Refine Context Threads history and scene link editing

This commit is contained in:
Codex 2026-12-05 00:34:50 +00:00
parent 0060c19109
commit c0d2afdbaf
9 changed files with 210 additions and 23 deletions

View File

@ -18,9 +18,9 @@ const script = fs.readFileSync(path.resolve(__dirname, '../../PlotLine/wwwroot/j
];
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),
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)
? [{ chapterNumber: 1, chapterTitle: 'Opening', sceneNumber: 1, sceneTitle: 'Earlier scene' }] : [] })) };
? [{ chapterID: 1, sceneID: 11, chapterNumber: 1, chapterTitle: 'Opening', sceneNumber: 1, sceneTitle: 'Earlier scene' }] : [] })) };
}
await context.route('http://context.test/**', async route => {
const url = new URL(route.request().url());
@ -32,6 +32,12 @@ const script = fs.readFileSync(path.resolve(__dirname, '../../PlotLine/wwwroot/j
for (const id of body.threadIDs) links.get(body.sceneID).add(id);
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>' });
});
@ -53,7 +59,7 @@ const script = fs.readFileSync(path.resolve(__dirname, '../../PlotLine/wwwroot/j
if (!readonly) await page.waitForFunction(pane => !document.querySelector(`[data-test-pane="${pane}"] [data-thread-add]`).disabled, pane);
}
await mount(11);
assert.equal(await page.getByText('Journey / A <saved> question', { exact: true }).count(), 1);
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 dialog = page.getByRole('dialog');
@ -81,9 +87,9 @@ const script = fs.readFileSync(path.resolve(__dirname, '../../PlotLine/wwwroot/j
reject = false;
await dialog.getByRole('button', { name: 'Add to scene', exact: true }).click();
await dialog.waitFor({ state: 'detached' });
await page.getByText('Ch 1: Opening · Scene 1: Earlier scene', { exact: true }).waitFor();
await page.getByRole('link', {name: 'Scene 1: Earlier scene'}).waitFor();
await mount(22); // Reload saved state through a fresh lifecycle.
await page.getByText('Ch 1: Opening · Scene 1: Earlier scene', { exact: true }).waitFor();
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();
@ -100,7 +106,26 @@ const script = fs.readFileSync(path.resolve(__dirname, '../../PlotLine/wwwroot/j
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;
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'});
assert.deepEqual(errors, []);
console.log('PASS Context Threads nested search, parent context, linked state, multi-select, explicit target, guards, failure recovery, history, reload, split panes and read-only state (isolated fixtures)');
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; });

View File

@ -13,5 +13,33 @@ const script=fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/shar
await page.evaluate(()=>{conn.state='Connected';conn.connectionId='second';lifecycle.reconnected();document.dispatchEvent(new Event('pd-presence-ready'));respond(1,{version:4,sceneID:40});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===4&&document.querySelector('button').disabled===false);assert.equal(await page.evaluate(()=>window.moves.length),moves,'held recovery must retain local position');assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),30);
await page.getByRole('button',{name:'Resume',exact:true}).press('Enter');await page.waitForFunction(()=>reads.length===3);await page.evaluate(()=>respond(2,{version:5,sceneID:50}));await page.waitForFunction(()=>PlotDirectorSharedFocus.local.sceneID===50&&!PlotDirectorSharedFocus.held);assert.equal(await page.evaluate(()=>posts.length),1,'only held reference validation posts; release cannot publish');assert(await page.evaluate(()=>posts.every(p=>!p.url.endsWith('/Publish'))));assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).getAttribute('aria-pressed'),'false');console.log('PASS reconnect preserves Hold; keyboard Release catches latest without publication');
await page.evaluate(()=>{void PlotDirectorSharedFocus.refresh();conn.state='Reconnecting';lifecycle.reconnecting();conn.state='Connected';conn.connectionId='third';lifecycle.reconnected();respond(3,{version:99,sceneID:99});respond(4,{version:6,sceneID:60});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===6);assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),60,'abandoned transport cannot overwrite new connection');console.log('PASS disconnected read cancellation and new group recovery');
// A new pinned entry in the same tab must override the previous saved reference.
const snapshots=await browser.newPage();
await snapshots.route('https://snapshot.invalid/**',route=>{
const scene=Number(new URL(route.request().url()).searchParams.get('sceneId'));
return route.fulfill({contentType:'text/html',body:`<body><main data-context-workspace data-follow-mode="snapshot" data-user="7" data-scope-project-id="3" data-scope-book-id="12" data-chapter-id="1" data-scene-id="${scene}"></main></body>`});
});
async function snapshot(scene){
await snapshots.goto('https://snapshot.invalid/?sceneId='+scene);
await snapshots.evaluate(scene=>{
document.querySelector('main').contextController={windowId:'a0000000-0000-4000-8000-000000000001',position:{projectID:3,bookID:12,chapterID:1,sceneID:scene}};
},scene);
await snapshots.addScriptTag({content:script});
return snapshots.evaluate(()=>[PlotDirectorSharedFocus.held,PlotDirectorSharedFocus.local.sceneID]);
}
assert.deepEqual(await snapshot(10),[true,10]);
await snapshots.evaluate(()=>{
document.body.insertAdjacentHTML('beforeend','<input name="__RequestVerificationToken" value="fixture">');
window.fetch=async url=>{
assertResolve(url);
return {ok:true,json:async()=>({projectID:3,bookID:12,chapterID:1,sceneID:15})};
};
function assertResolve(url){if(!url.endsWith('/Resolve'))throw Error('Snapshot must resolve locally');}
return PlotDirectorSharedFocus.navigate({sceneID:15});
});
assert.deepEqual(await snapshot(10),[true,15],'reload of same entry retains local browsing');
assert.deepEqual(await snapshot(20),[true,20],'new explicit scene overrides the old held reference');
await snapshots.close();
console.log('PASS pinned Context reload preserves browsing and a new scene URL selects its own target');
const partial=fs.readFileSync(path.join(__dirname,'../../PlotLine/Views/Shared/_FocusFollowControl.cshtml'),'utf8');assert(!partial.includes('data-shared-focus-status'));assert(!partial.includes('Following'));assert(partial.includes('disabled'));const ribbon=fs.readFileSync(path.join(__dirname,'../../PlotDirector.NativeCompanion/Vsto/Ribbon.xml'),'utf8');assert(!ribbon.includes('PlotDirectorFocusState'));assert(ribbon.includes('getEnabled="CanHoldFocus"'));console.log('PASS concise accessible toggle and no adjacent state controls');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});

View File

@ -10,7 +10,7 @@ internal static class ContextThreadsTests
{
public static void Run()
{
var scope = new SpatialScope { ProjectID = 7, BookID = 12, SceneID = 90 };
var scope = new SpatialScope { ProjectID = 7, BookID = 12, SceneID = 90, CanEdit = true };
var data = new PlotLineWorkspaceData
{
PlotLines = [new() { PlotLineID = 1, ProjectID = 7, BookID = 12, PlotLineName = "Main" },
@ -31,12 +31,14 @@ internal static class ContextThreadsTests
var panel = ContextThreads.Build(scope, data, links);
Check(panel.Threads.Count == 3, "Exclude other books and projects; include project-wide lines.");
var question = panel.Threads.Single(t => t.PlotThreadID == 10);
Check(question.Linked, "A direct scene link needs no event.");
Check(question.Linked && question.CanRemove, "A direct scene link needs no event.");
Check(question.PreviousScenes.Select(s => s.SceneID).SequenceEqual([15, 7]), "Keep every previous pickup in narrative order; deduplicate events, milestones and direct links; exclude future/other-book scenes.");
Check(panel.Threads.Single(t => t.PlotThreadID == 11).Linked, "An actual resolution is a recorded association.");
Check(panel.Threads.Single(t => t.PlotThreadID == 11) is { Linked: true, CanRemove: false }, "A resolution stays linked and cannot be removed as a direct scene link.");
Check(!panel.Threads.Single(t => t.PlotThreadID == 14).Linked, "A planned resolution alone is not an actual pickup.");
var earlier = ContextThreads.Build(new() { ProjectID = 7, BookID = 12, SceneID = 7 }, data, links);
Check(earlier.Threads.Single(t => t.PlotThreadID == 10).PreviousScenes.Single().SceneID == 15, "History follows the selected scene, not IDs or latest saved scene.");
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 backup = new ProjectBackupExport
{
Project = new() { ProjectID = 7 },

View File

@ -28,4 +28,12 @@ public sealed class ContextThreadsController(ContextThreads threads) : Controlle
await threads.Add(input);
return Json(new { saved = true });
});
[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();
await threads.Remove(input);
return Json(new { saved = true });
});
}

View File

@ -7,9 +7,10 @@ using PlotLine.Models;
namespace PlotLine.Services.Context;
public sealed record ContextThreadRow(int PlotThreadID, int PlotLineID, string Title, string PlotLineName,
bool Linked, IReadOnlyList<PlotLineWorkspaceAttributionRow> PreviousScenes);
bool Linked, bool CanRemove, IReadOnlyList<PlotLineWorkspaceAttributionRow> PreviousScenes);
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 class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRepository workspace,
ISqlConnectionFactory connections, ICurrentUserService user, ContextWorkspaceNotifications notifications)
@ -29,9 +30,9 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep
var scenes = data.AttributionScenes.Where(s => s.BookID == scope.BookID).ToDictionary(s => s.SceneID);
if (!scenes.TryGetValue(scope.SceneID, out var current)) throw new ArgumentException("Scene order is unavailable.");
var lines = data.PlotLines.Where(l => l.ProjectID == scope.ProjectID && (l.BookID == null || l.BookID == scope.BookID)).ToDictionary(l => l.PlotLineID);
var associations = links.Select(l => (l.PlotThreadID, l.SceneID))
.Concat(data.Contributions.Where(c => c.BookID == scope.BookID).Select(c => (c.PlotThreadID, c.SceneID)))
.ToHashSet();
var directLinks = links.Select(l => (l.PlotThreadID, l.SceneID)).ToHashSet();
var associations = directLinks.ToHashSet();
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.
foreach (var thread in data.Threads)
@ -42,6 +43,7 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep
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 && directLinks.Contains((t.PlotThreadID, scope.SceneID)),
scenes.Values.Where(s => s.NarrativeOrder < current.NarrativeOrder && associations.Contains((t.PlotThreadID, s.SceneID)))
.OrderBy(s => s.NarrativeOrder).ToArray())).OrderBy(t => t.PlotLineName).ThenBy(t => t.Title).ToArray();
return new(scope, rows);
@ -58,4 +60,14 @@ public sealed class ContextThreads(ContextSpatial spatial, IPlotLineWorkspaceRep
// 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");
}
public async Task Remove(ContextThreadRemoval input)
{
var userId = user.UserId ?? throw new UnauthorizedAccessException();
using var db = connections.CreateConnection();
var project = await db.QuerySingleAsync<int>("dbo.SceneThread_Remove",
new { input.BookID, input.SceneID, UserID = userId, input.ThreadID },
commandType: CommandType.StoredProcedure);
await notifications.Invalidate(userId, projectId: project, bookId: input.BookID, kind: "threads");
}
}

View File

@ -0,0 +1,41 @@
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.SceneThread_Remove
@BookID int, @SceneID int, @UserID int, @ThreadID int
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
-- Serialize with SceneThread_Add for this scene.
DECLARE @LockedSceneID int, @ProjectID int;
SELECT @LockedSceneID = SceneID
FROM dbo.Scenes WITH (UPDLOCK, HOLDLOCK)
WHERE SceneID = @SceneID;
EXEC dbo.SpatialContext_Scope @UserID, @BookID, @SceneID, 0;
SELECT @ProjectID = ProjectID FROM dbo.Books WITH (HOLDLOCK) WHERE BookID = @BookID;
IF NOT EXISTS (
SELECT 1 FROM dbo.ProjectUserAccess WITH (HOLDLOCK)
WHERE ProjectID = @ProjectID AND UserID = @UserID AND IsActive = 1
AND AccessRole IN (N'Owner', N'Collaborator')
)
THROW 51010, 'Editing unavailable.', 1;
DELETE FROM dbo.SceneThreads WHERE SceneID = @SceneID AND PlotThreadID = @ThreadID;
COMMIT;
SELECT @ProjectID;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK;
THROW;
END CATCH;
END;
GO

View File

@ -1,9 +1,10 @@
@{ Layout = null; }
@model PlotLine.Services.Context.SpatialScope
<div data-context-tab-fragment data-context-threads data-project-id="@Model.ProjectID" data-book-id="@Model.BookID" data-chapter-id="@Model.ChapterID" data-scene-id="@Model.SceneID">
<h2 class="h5">Threads · @Model.Label</h2>
<h2 class="h5">Threads</h2>
<p><strong>Current scene</strong><br />@Model.Label</p>
<form hidden>@Html.AntiForgeryToken()</form>
<button type="button" class="btn btn-outline-primary btn-sm" data-thread-add disabled>Add thread</button>
<p role="alert" class="text-danger" data-thread-error></p>
<div data-thread-rows><p>Loading saved threads…</p></div>
<div class="d-grid gap-2" data-thread-rows><p>Loading saved threads…</p></div>
</div>

View File

@ -11,7 +11,7 @@
const node = el('button', text, 'btn btn-outline-secondary btn-sm');
node.type = 'button'; node.addEventListener('click', action); return node;
};
const sceneLabel = s => `Ch ${s.chapterNumber}: ${s.chapterTitle} · Scene ${s.sceneNumber}: ${s.sceneTitle}`;
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);
@ -32,21 +32,79 @@
if (!alive || version !== readVersion) return;
data = result;
const linked = data.threads.filter(t => t.linked);
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) {
const article = el('article', null, 'writing-context-card');
article.append(el('h3', `${thread.plotLineName} / ${thread.title}`, 'h6'));
if (!thread.previousScenes.length) article.append(el('p', 'First picked up here.'));
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 {
article.append(el('p', 'Previously picked up in:'));
const list = el('ol');
for (const scene of thread.previousScenes) list.append(el('li', sceneLabel(scene)));
article.append(list);
const chapters = new Map();
const lastPickup = thread.previousScenes.at(-1);
for (const scene of thread.previousScenes) {
const key = `${thread.plotThreadID}:${scene.chapterID}`;
if (!chapters.has(key)) {
const group = el('details', null, 'small mb-1');
group.dataset.threadChapter = key;
group.open = openChapters.get(key) ?? true;
const summary = el('summary', `Ch ${scene.chapterNumber}: ${scene.chapterTitle}`, 'fw-semibold');
summary.dataset.threadFocus = `chapter:${key}`;
const list = el('ul', null, 'mb-1');
group.append(summary, list);
chapters.set(key, list);
article.append(group);
}
const item = el('li');
const link = el('a', sceneLabel(scene));
link.href = `/Scenes/Edit/${scene.sceneID}?retainNarrativeFocus=true`;
link.target = '_blank'; link.rel = 'noopener';
link.dataset.contextNarrative = 'author';
link.dataset.threadFocus = `scene:${thread.plotThreadID}:${scene.sceneID}`;
item.append(link);
if (scene === lastPickup) item.append(el('strong', 'Last pickup', 'ms-2'));
chapters.get(key).append(item);
}
}
if (thread.canRemove) {
const remove = button('Remove from scene', () => removeLink(thread.plotThreadID));
remove.dataset.threadFocus = `remove:${thread.plotThreadID}`;
remove.setAttribute('aria-label', `Remove ${thread.title} from scene`);
article.append(remove);
}
rows.append(article);
}
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) {
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 })
});
if (!response.ok || response.redirected) {
const body = await response.json().catch(() => null);
throw Error(body?.message || 'The thread link could not be removed. Review access and try again.');
}
window.PlotDirector?.toast?.success('Thread link removed');
try { await read(); }
catch { error.textContent = 'The link was removed. Refresh saved data to reload the scene.'; }
} catch (e) { fail(e); }
finally {
if (alive) {
guard(false, true);
node.closest('[data-context-workspace]')?.contextController?.invalidate({ bookId: bookID, kind: 'threads' });
}
}
}
function picker() {
if (!alive || busy || !data?.scope.canEdit) return;

View File

@ -1,5 +1,17 @@
// One user/book/canonical-manuscript focus stream over the window's existing presence connection.
(()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,connected=false,authoritative=false,readFlight=null,readAbort=null,readyKey=null,generation=0,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null,heldRecent=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence,heldRecent}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;heldRecent=data?.heldRecent||null;}catch{held=false;}}
(()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,connected=false,authoritative=false,readFlight=null,readAbort=null,readyKey=null,generation=0,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null,heldRecent=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');// Snapshot URLs explicitly select a reference. Restore in-window browsing only on the same entry.
const snapshotEntry = context?.dataset.followMode === 'snapshot'
? [project, book, context.dataset.chapterId, context.dataset.sceneId].join('/') : null;
function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence,heldRecent,snapshotEntry}));}catch{}}
function restore(){
let data;
try{data=JSON.parse(sessionStorage.getItem(key())||'null');}catch{}
sequence=data?.sequence||0;
const saved = snapshotEntry && data?.snapshotEntry !== snapshotEntry ? null : data;
held=saved?.held??Boolean(snapshotEntry);
local=saved?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});
heldRecent=saved?.heldRecent||null;
}
const traceEnabled=new URLSearchParams(location.search).get('focusDiagnostics')==='1',traceRows=[];function trace(stage,outcome,p=latest){if(!traceEnabled)return;traceRows.push({stage,outcome,source:context?'Context':'Review',windowID:id,bookID:book,chapterID:p?.chapterID,sceneID:p?.sceneID,paragraphID:p?.paragraphID,version:p?.version,held});if(traceRows.length>128)traceRows.shift();let panel=document.querySelector('[data-focus-diagnostics]');if(!panel){panel=document.createElement('pre');panel.dataset.focusDiagnostics='';document.body.append(panel);}panel.textContent=JSON.stringify(traceRows,null,2);}
let lastNotice='';function status(message=''){const available=!!book&&connected&&authoritative&&!disconnected;buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?(b.dataset.focusHeldLabel||'Resume'):'Hold';const icon=b.querySelector('[data-focus-mode-icon]');if(icon)icon.setAttribute('d',held?'M8 4l12 8-12 8z':'M8 4v16 M16 4v16');b.setAttribute('aria-pressed',String(held));b.disabled=!available;b.classList.toggle('active',held);b.title=!available?(book?'Shared focus is connecting. Your local position is retained.':'Select a book first.'):(held?'Catch up to the latest shared manuscript position.':'Hold this window at its local manuscript position.');});outputs.forEach(n=>{n.textContent=message;n.hidden=!message;});document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';if(message&&message!==lastNotice){lastNotice=message;window.PlotDirector?.toast?.warning?.(message);}if(!message)lastNotice='';}function apply(position,reason){local=normal(position);save();trace('reconcile',reason,local);window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false,metadata=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&next.version<latest.version){trace('reconcile','stale-revision',next);return false;}if(latest&&!force&&next.version===latest.version){if(metadata&&latest.isValid!==next.isValid){latest={...latest,isValid:next.isValid};if(!held)status(next.isValid?'':'Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');}return false;}latest=next;if(publishing&&queuedTarget)return true;if(!held&&next.isValid&&next.chapterID&&(force||positionKey(local)!==positionKey(next)))apply(next,next.originWindowID===id&&selectionPublishing?'selection':'shared');else if(!held&&next.isValid&&next.chapterID)status();else if(!next.isValid&&!held)status('Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');return true;}
async function request(action,target={}){trace('request',action,normal(target));const token=document.querySelector('[name=__RequestVerificationToken]')?.value;if(!token)throw Error('Refresh this authenticated window before changing focus.');const body=new URLSearchParams({projectID:project,bookID:book,windowID:id,sequence:++sequence,__RequestVerificationToken:token});for(const[k,v]of Object.entries(target))if(v!=null&&['chapterID','sceneID','paragraphID','manuscriptID','direction'].includes(k))body.set(k,v);save();const response=await fetch('/NarrativeFocus/Shared/'+action,{method:'POST',body,cache:'no-store'});const packet=await response.json().catch(()=>null);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);}