Share the Story Elements palette across Context and Writer

This commit is contained in:
Codex 2026-12-04 11:36:14 +00:00
parent ae7dc97f87
commit 8597d458b2
10 changed files with 223 additions and 11 deletions

View File

@ -1,4 +1,4 @@
// Backend palette milestone only. This does not certify the unfinished Intent UI.
// Scoped Story Elements reads and Context palette controls.
'use strict';
const assert = require('node:assert/strict');
const {open} = require('./dev-acceptance.cjs');
@ -58,6 +58,24 @@ let session, stage = 'login';
assert.deepEqual(scoped.entries[0].sources,[{sceneID:first,provenance:'Scene location'}]);
assert.deepEqual((await read({sceneID:second})).entries.map(e=>e.key),['location:'+literal]);
assert.deepEqual(new Set((await read()).entries.map(e=>e.key)),new Set(['location:'+place,'location:'+literal]));
stage='Context palette chapter and scene browsing';
const contextUrl = '/Writing/Context?' + new URLSearchParams({
projectId:project, bookId:book, chapterId:chapter, sceneId:first, pinned:true
});
assert.equal((await session.goto(contextUrl)).status(),200);
await session.page.locator('[data-context-tab]').first().selectOption('intent');
const panel=session.page.locator('[data-context-intent]');
await panel.locator('[data-entity-key="location:'+literal+'"]').waitFor();
await panel.getByLabel('Current scene only').check();
const search=panel.getByRole('searchbox',{name:'Search story'});
await panel.getByText('Scene location',{exact:false}).first().waitFor();
await panel.locator('[data-entity-key="location:'+literal+'"]').waitFor({state:'detached'});
await search.fill('SHARED NAME');
await panel.locator('[data-entity-key="character:'+person+'"]').waitFor();
assert.equal(await search.evaluate(input=>input===document.activeElement),true);
assert.equal(session.page.url().endsWith(contextUrl),true,'Palette browsing preserves Context position');
await panel.getByText('Story Elements',{exact:true}).click();
assert.equal(await panel.locator('details').evaluate(details=>details.open),false);
stage='invalid and mismatched scope denial';
stage='chapter/book mismatch denial';await read({chapterID:otherChapter},403);
stage='book/chapter mismatch denial';await read({bookID:otherBook},403);
@ -74,12 +92,13 @@ let session, stage = 'login';
const editor=session.page.locator('form[data-scene-editor-form]');
assert.equal(await editor.locator('[name=PrimaryLocationID]').inputValue(),String(place),'Source location');
assert.equal(await editor.locator('[name=SceneTitle]').inputValue(),'Palette first scene','Source title');
console.log(JSON.stringify({passed:true,milestone:'palette read path only',checks:[
console.log(JSON.stringify({passed:true,milestone:'Context Story Elements palette',checks:[
'chapter without prose or scenes','canonical identity separation and hidden-label ambiguity',
'case-insensitive wider search and literal percent','chapter and optional scene associations/provenance',
'Context chapter and scene browsing, search, collapse and focus',
'book/chapter/scene mismatch denial and query limits','fresh login reads authoritative saved sources'
],featureUrl:'https://dev.plotdirector.com/Writing/Context/Intent/Palette?'+new URLSearchParams(base),
limitations:['interactive checklist/palette component and candidate fixture acceptance remain outstanding']}));
limitations:['interactive checklist, docked Writer and candidate fixture acceptance remain outstanding']}));
} catch(error) {
console.error('Intent palette acceptance failed at '+stage+' ('+error.name+'). No credentials logged.');
if(error.name==='AssertionError') console.error(error.message);

View File

@ -12,6 +12,18 @@ public sealed class ContextIntentController(ContextIntentPalette palette) : Cont
{
// 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.
[HttpGet("Panel")]
public IActionResult Panel(int projectId, int bookId, int chapterId, int? sceneId)
{
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.
return PartialView("~/Views/Writing/_ContextIntentPanel.cshtml",
new IntentPaletteScope(projectId, bookId, chapterId, sceneId));
}
[HttpGet("Palette")]
public async Task<IActionResult> Palette([FromQuery] IntentPaletteQuery query)
{

View File

@ -32,6 +32,7 @@
@if(Model.Destination=="Review"){<link rel="stylesheet" href="~/css/writer-review-layout.css" asp-append-version="true" /><script src="~/js/writer-review-layout.js" asp-append-version="true"></script><script src="~/js/manuscript-reader.js" asp-append-version="true"></script><script src="~/js/review-authoring.js" asp-append-version="true"></script><script src="~/js/writer-review.js" asp-append-version="true"></script><script src="~/js/narrative-focus-review.js" asp-append-version="true"></script><script src="~/js/writer-work.js" asp-append-version="true"></script>}
@if(Model.Destination is "Write" or "Plan"){
<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>
<script src="~/js/writer-objective.js" asp-append-version="true"></script>

View File

@ -46,4 +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/_ContextIntentPalette.cshtml"
model="@(new PlotLine.Services.Context.IntentPaletteScope(0, Model.BookID, Model.ChapterID, Model.SceneID))" />
</template>

View File

@ -5,6 +5,7 @@
ViewData["Title"] = "Context";
var position = Model.Display?.Context?.Position;
var tabs = new[] {
new { id = "intent", displayName = "Intent", endpoint = Url.Action("Panel", "ContextIntent"), scope = "Chapter", contentRefresh = "relevant-scope", lifecycle = "intent", refreshGuard = "defer-while-dirty-or-busy", actions = Array.Empty<string>() },
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>() },
@ -85,6 +86,7 @@
<script src="~/js/context-assets.js" asp-append-version="true"></script>
<script src="~/js/context-calendar-model.js" asp-append-version="true"></script>
<script src="~/js/context-calendar.js" asp-append-version="true"></script>
<script src="~/js/context-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>
<script src="~/js/context-windows.js" asp-append-version="true"></script>

View File

@ -0,0 +1,15 @@
@model PlotLine.Services.Context.IntentPaletteScope
<details open class="border rounded p-2" data-intent-palette
data-url="@Url.Action("Palette", "ContextIntent")" data-project-id="@Model.ProjectID"
data-book-id="@Model.BookID" data-chapter-id="@Model.ChapterID" data-scene-id="@Model.SceneID">
<summary class="fw-semibold">Story Elements</summary>
<label class="mt-2" data-palette-scene-choice hidden="@(!Model.SceneID.HasValue)">
<input type="checkbox" data-palette-scene /> Current scene only
</label>
<label class="d-block mt-2">Search story
<input type="search" maxlength="200" class="form-control form-control-sm" data-palette-search />
</label>
<label class="d-block"><input type="checkbox" data-palette-wider /> Include wider story</label>
<p class="small text-body-secondary mb-1" role="status" data-palette-status></p>
<ul class="list-group list-group-flush" data-palette-rows></ul>
</details>

View File

@ -0,0 +1,6 @@
@model PlotLine.Services.Context.IntentPaletteScope
@{ Layout = null; }
<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/_ContextIntentPalette.cshtml" model="Model" />
</div>

View File

@ -0,0 +1,144 @@
(() => {
'use strict';
const instances = new WeakMap();
function mount(root) {
if (instances.has(root)) return instances.get(root);
const search = root.querySelector('[data-palette-search]');
const scene = root.querySelector('[data-palette-scene]');
const sceneChoice = root.querySelector('[data-palette-scene-choice]');
const wider = root.querySelector('[data-palette-wider]');
const rows = root.querySelector('[data-palette-rows]');
const status = root.querySelector('[data-palette-status]');
const events = new AbortController();
const projectId = Number(root.dataset.projectId) ||
Number(root.closest('[data-writer-destination]')?.dataset.projectId);
const wired = new WeakSet();
let pending;
let debounce;
function render(frame) {
const entries = frame.entries.map(entry => {
const row = document.createElement('li');
row.className = 'list-group-item px-0';
row.dataset.entityKey = entry.key;
const name = document.createElement('strong');
name.textContent = entry.name;
const details = document.createElement('div');
details.className = 'small text-body-secondary';
const provenance = [...new Set(entry.sources.map(source => source.provenance))];
if (entry.isCandidate && !provenance.includes('Candidate')) provenance.push('Candidate');
if (!entry.inScope) provenance.push('Wider story');
if (entry.possiblyAmbiguous) provenance.push('Shared name or alias');
details.textContent = [entry.kind, ...provenance].join(' · ');
row.append(name, details);
const aliases = entry.aliases.filter(alias => alias !== entry.name);
if (aliases.length) {
const aliasList = document.createElement('div');
aliasList.className = 'small text-body-secondary';
aliasList.textContent = 'Aliases ' + aliases.join(', ');
row.append(aliasList);
}
return row;
});
rows.replaceChildren(...entries);
status.textContent = frame.hasMore ? 'Showing the first 200 elements. Refine your search.'
: entries.length ? '' : 'No Story Elements found.';
}
async function refresh() {
clearTimeout(debounce);
pending?.abort();
if (!root.open || !root.isConnected) return;
const controller = new AbortController();
pending = controller;
const url = new URL(root.dataset.url, location.origin);
url.searchParams.set('bookID', root.dataset.bookId);
url.searchParams.set('chapterID', root.dataset.chapterId);
if (scene.checked) url.searchParams.set('sceneID', root.dataset.sceneId);
url.searchParams.set('widerStory', String(wider.checked || !!search.value.trim()));
url.searchParams.set('search', search.value);
status.textContent = 'Loading Story Elements…';
try {
const response = await fetch(url, { signal: controller.signal, cache: 'no-store' });
if (!response.ok || response.redirected) throw new Error();
const frame = await response.json();
if (controller.signal.aborted || !root.isConnected) return;
if (projectId && frame.scope.projectID !== projectId) throw new Error();
render(frame);
} catch {
if (controller.signal.aborted || !root.isConnected) return;
rows.replaceChildren();
status.textContent = 'Story Elements are unavailable. Reopen the palette to retry.';
}
}
search.addEventListener('input', () => {
pending?.abort();
clearTimeout(debounce);
debounce = setTimeout(refresh, 250);
}, { signal: events.signal });
root.addEventListener('toggle', refresh, { signal: events.signal });
scene.addEventListener('change', refresh, { signal: events.signal });
wider.addEventListener('change', refresh, { signal: events.signal });
function wireWriter(connection) {
if (!connection || wired.has(connection)) return;
wired.add(connection);
const invalidate = hint => {
if (!hint?.projectId || Number(hint.projectId) === projectId) void refresh();
};
connection.on('ContextInvalidated', invalidate);
events.signal.addEventListener('abort', () => connection.off('ContextInvalidated', invalidate), { once: true });
}
if (root.closest('[data-writer-destination]')) {
document.addEventListener('pd-presence-connection', event => wireWriter(event.detail), { signal: events.signal });
wireWriter(window.PlotDirectorPresenceConnection);
}
const instance = {
refresh,
setScene(sceneId) {
root.dataset.sceneId = sceneId || '';
sceneChoice.hidden = !sceneId;
if (!sceneId) scene.checked = false;
void refresh();
},
dispose() {
clearTimeout(debounce);
pending?.abort();
events.abort();
instances.delete(root);
}
};
instances.set(root, instance);
void refresh();
return instance;
}
const palette = node => node.querySelector('[data-intent-palette]');
window.PlotDirectorIntentPalette = {
mountWithin(node) { node.querySelectorAll('[data-intent-palette]').forEach(mount); },
disposeWithin(node) {
node.querySelectorAll('[data-intent-palette]').forEach(root => instances.get(root)?.dispose());
}
};
window.PlotDirectorContextLifecycles = {
...window.PlotDirectorContextLifecycles,
intent: {
mount(node) { mount(palette(node)); },
dispose(node) { instances.get(palette(node))?.dispose(); },
onPosition(node, next, previous) {
if (next.chapterId !== previous.chapterId) return false;
instances.get(palette(node))?.setScene(next.sceneId);
return true;
},
onInvalidation(node) {
void instances.get(palette(node))?.refresh();
return true;
}
}
};
})();

View File

@ -96,6 +96,10 @@
dispose(pane.host.contextRecord);pane.host.contextRecord=null;pane.host.replaceChildren();
pane.host.removeAttribute('aria-busy');pane.status.textContent='No verified current scene. Choose a saved scene to browse.';return;
}
if(tab.scope==='Chapter'&&!position.chapterId){
dispose(pane.host.contextRecord);pane.host.contextRecord=null;pane.host.replaceChildren();
pane.host.removeAttribute('aria-busy');pane.status.textContent='Choose a saved chapter to browse.';return;
}
const request=++pane.revision, epoch=generation;
pane.status.textContent=record.node?'Updating saved information…':'Loading saved information…';pane.host.setAttribute('aria-busy','true');
try {
@ -120,24 +124,24 @@
const scopeChanged = (tab,before,after) => {
const level=scopes.indexOf(tab.scope);
if(level<=0)return false;
const count=level===1?2:level===2?3:level===3?4:5;
const count=tab.id==='intent'?4:level+1;
return fields.slice(0,count).some(field=>before[field]!==after[field]);
};
const affectedPanels = {
overview:['overview'], maps:['maps'], floorplans:['floorplans'], locations:['overview','locations','maps','floorplans','assets'],
spatial:['locations','maps','floorplans'], names:['names'],
characters:['overview','characters','relationships','names','locations','maps','floorplans','assets'],
overview:['overview'], maps:['maps'], floorplans:['floorplans'], locations:['overview','locations','maps','floorplans','assets','intent'],
spatial:['locations','maps','floorplans'], names:['names','intent'],
characters:['overview','characters','relationships','names','locations','maps','floorplans','assets','intent'],
relationships:['overview','characters','relationships'],
warnings:['warnings'], dates:['overview','calendar','warnings'], intent:['overview','intent'],
plotlines:['overview','intent','plotlines','threads'], threads:['overview','intent','threads'],
metrics:['overview','metrics'], assets:['overview','assets','maps','floorplans']
metrics:['overview','metrics'], assets:['overview','assets','maps','floorplans','intent']
};
function inScope(hint) {
return !(hint.projectId&&scope.projectId&&Number(hint.projectId)!==scope.projectId) &&
!(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['dates','structure','assets','locations','characters'].includes(hint.kind));
}
function affects(tab,hint) {
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['calendar','warnings','assets'].includes(tab.id))return false;
if(hint.bookId&&scope.bookId&&Number(hint.bookId)!==scope.bookId&&!['calendar','warnings','assets','intent'].includes(tab.id))return false;
return tab.contentRefresh!=='none' && (!affectedPanels[hint.kind] || affectedPanels[hint.kind].includes(tab.id));
}
function invalidate(hint={}) {

View File

@ -6,6 +6,13 @@
let allowLeave=false;const dirty=()=>[...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)return;
window.PlotDirectorIntentPalette?.disposeWithin(references);
references.replaceChildren(template.content.cloneNode(true));
window.PlotDirectorIntentPalette?.mountWithin(references);
}
function bind(container){
window.PlotLineHelpIcons?.init(container);
for(const form of container.querySelectorAll('[data-authoring-form]')){
@ -31,7 +38,7 @@
committed=true;form.dataset.dirty='false';const doc=await read();const isAdd=card.dataset.kind.startsWith('Add');replaceCard(card,doc);
const preview=root.querySelector('.writer3-reminder-preview'),freshPreview=doc.querySelector('.writer3-reminder-preview');if(preview&&freshPreview)preview.replaceWith(freshPreview.cloneNode(true));
const next=root.querySelector('[data-authoring-next-area]'),freshNext=doc.querySelector('[data-authoring-next-area]');if(next&&freshNext){const clone=freshNext.cloneNode(true);next.replaceWith(clone);bind(clone);}
const refs=document.querySelector('[data-authoring-references]'),template=doc.querySelector('[data-authoring-companion]');if(refs&&template)refs.replaceChildren(template.content.cloneNode(true));
replaceReferences(doc.querySelector('[data-authoring-companion]'));
if(isAdd){for(const fresh of doc.querySelectorAll('[data-authoring-card]'))if(!root.querySelector(`[data-key="${CSS.escape(fresh.dataset.key)}"]`)){const clone=fresh.cloneNode(true);root.querySelector('[data-authoring-new-records]')?.append(clone);bind(clone.parentElement);}}
}catch{error.textContent=committed?'Saved, but the refreshed record could not load. Your text is retained. Reload the recorded version.':'Save was not confirmed. Your text is retained. Reload the recorded version to check before trying again.';error.hidden=false;form.querySelector('[data-authoring-reload]').hidden=false;}
finally{form.dataset.busy='false';save.disabled=committed&&form.isConnected;cancel.disabled=committed&&form.isConnected;reload.disabled=false;}
@ -43,7 +50,7 @@
function replaceCard(card,doc){if(!card.isConnected)return;const fresh=doc.querySelector(`[data-key="${CSS.escape(card.dataset.key)}"]`);if(!fresh)throw Error('Saved record is not available');const clone=fresh.cloneNode(true),parent=card.parentElement;card.replaceWith(clone);bind(parent);clone.querySelector('[data-authoring-status]').textContent='Saved.';clone.querySelector('[data-authoring-edit]')?.focus();}
async function read(){const response=await fetch(root.dataset.inspectUrl,{cache:'no-store'});if(!response.ok)throw Error('Recorded information is unavailable');const doc=new DOMParser().parseFromString(await response.text(),'text/html');if(!doc.querySelector('[data-authoring-content]'))throw Error('Authorisation or recorded information is unavailable');return doc;}
let loadEpoch=0;
async function load(){const mine=++loadEpoch;if(!root.dataset.inspectUrl){root.hidden=true;root.replaceChildren();return;}root.hidden=false;const pending=document.createElement('p');pending.textContent='Loading the selected chapter and scene notes…';root.replaceChildren(pending);try{const doc=await read();if(mine!==loadEpoch)return;root.replaceChildren(...doc.body.childNodes);bind(root);const references=document.querySelector('[data-authoring-references]'),template=root.querySelector('[data-authoring-companion]');if(references&&template)references.replaceChildren(template.content.cloneNode(true));}
async function load(){const mine=++loadEpoch;if(!root.dataset.inspectUrl){root.hidden=true;root.replaceChildren();return;}root.hidden=false;const pending=document.createElement('p');pending.textContent='Loading the selected chapter and scene notes…';root.replaceChildren(pending);try{const doc=await read();if(mine!==loadEpoch)return;root.replaceChildren(...doc.body.childNodes);bind(root);replaceReferences(root.querySelector('[data-authoring-companion]'));}
catch{if(mine!==loadEpoch)return;root.replaceChildren();const p=document.createElement('p');p.textContent='Recorded information could not load. Your current work and existing editors remain available.';const retry=document.createElement('button');retry.type='button';retry.className='btn btn-outline-secondary';retry.textContent='Try again';retry.addEventListener('click',load);root.append(p,retry);}}
window.addEventListener('beforeunload',e=>{if(dirty()&&!allowLeave){e.preventDefault();e.returnValue='';}});
function guard(e){if(!dirty())return;const target=e.target.closest('a,form,[data-plan-focus]');if(!target||target.matches('[data-authoring-form],[data-work-start]')||target.target==='_blank'||target.hasAttribute('download'))return;if(target.tagName==='A'&&new URL(target.href,location.href).pathname===location.pathname&&new URL(target.href,location.href).search===location.search&&target.hash)return;if(!confirm(root.querySelector('[data-busy="true"]')?'A save is in progress and may finish after you leave. Leave this page?':'Leave without saving your inline edits?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}