Protect unsaved Writer chapter goals during navigation

This commit is contained in:
Nick Beckley 2026-11-03 22:24:22 +00:00
parent 81833c6b0d
commit 408ea95a09
7 changed files with 203 additions and 8 deletions

View File

@ -12,9 +12,9 @@
## Durable queue
1. CURRENT: verify Writer connection-recovery repair and repeated full-layout navigation; inspect chapter-goal unsaved navigation.
2. Verify Writer commands and repeated entry/exit, legitimate unsaved-change guards and cancelled/saved/discarded navigation.
3. Repair Writer spacing after functional repair or explicit deferral.
1. COMPLETE: Writer connection recovery and distinct window identities; commit 81833c6.
2. COMPLETE: Writer command/re-entry and chapter-goal unsaved navigation tests; urgent Development checkpoint being prepared.
3. NEXT: repair Writer spacing after the verified functional checkpoint and documented live-acceptance deferral.
4. Build rendered page inventory covering all requested areas/modes/themes; capture and inspect screenshots; repair evidenced shared spacing defects.
5. Distinguish Maps/Floor Plans navigation icons.
6. Replace Locations segments with conventional icon/label ribbon commands and depressed active styling.
@ -58,3 +58,21 @@ Also corrected false success feedback when a popup is blocked and protected role
Verification: solution build passed (0 warnings/errors); full executable harness passed (405 checks); full-layout Writer browser/PWA regression passed. It exercises one failed real negotiation followed by recovery, terminal stop/reconnect, actual Context and Intent Razor windows, three distinct IDs, reload stability, focus reuse, popup denial feedback, three leave/return cycles per mode, project Focus submission, Writing Plans/Schedule Setup/Schedule Preview real controller/view routes, and unsupported display-detection fallback. No whole-page blocking overlay was observed in these fixtures. Live authenticated PWA acceptance remains unperformed.
Next functional item: chapter-goal editing has no beforeunload/navigation guard. Probe confirmed that leaving Writer is not intercepted after typing. Browser back-cache may retain the draft temporarily; it is not a save or a reliable protection against closing/reloading the page. Add save/discard/cancel protection using the established application dialog and explicit save acknowledgement before visual work.
### Writer chapter-goal unsaved protection — browser verified, broader gate running
Probe established that editing chapter goals did not register a navigation/unload guard. Leaving the page proceeded without save/discard/cancel; browser back-cache could temporarily retain the form but did not persist it. Added an explicit opt-in form guard to this editable Writer workflow using the established PlotDirector application dialog. Native browser unload protection remains; if dialog assets are unavailable the browser unload guard supplies the fallback instead of trapping navigation.
Save and leave requires explicit successful JSON acknowledgement from the existing authorised/antiforgery-protected Writer action. Ordinary non-AJAX saves retain their redirect. Failed/redirected/malformed responses retain the draft; newer edits are not cleared by an older acknowledgement. Discard restores the last acknowledged field values; Keep editing preserves them. The guard resets its navigation permission on pageshow so browser back-cache cannot silently disable future protection.
Verification: build passed (0 warnings/errors). Real-layout browser/PWA tests passed for cancelled navigation, explicit discard, normal Save, Save and leave, failed Save/retry, Unicode payload comparison across actual controller/antiforgery and isolated in-memory service boundary, and unload-guard state. The Writer recovery/identity/re-entry test passed again. These are fixture/in-process Hub checks, not live authenticated Development or SQL round trips. Broader harness running.
The exact reported whole-page PWA navigation lock has not been reproduced separately in the available full-layout fixture. Live authenticated acceptance is deferred because no user session is available; no claim that a blocking overlay was found or removed. Connection recovery and opener-ID collision were independently reproduced and repaired. Proceed with independently verifiable programme work after this checkpoint.
### Chapter-goal guard verification complete
- Build: passed, zero warnings/errors. Full harness: 405 PASS, exit 0.
- Writer recovery/full-window/repeated-navigation suite: passed again.
- Chapter-goal browser/PWA suite: passed, including a held older save request followed by newer edits. An older acknowledgement leaves the newer draft guarded until its own successful save.
- Existing authorised save action retains its normal redirect for non-AJAX callers; the new JSON acknowledgement follows the awaited service save. Verified the repository saves goals by ChapterID, so repeated AJAX saves do not depend on a refreshed generated goal ID.
- Read-only Development restart gate verified database identity and found no active background work. Preparing an early verified Writer deployment before the longer visual/data-transfer audits; the gate will be checked again immediately before restart.

View File

@ -21,7 +21,8 @@
"test:relationship-focus": "node relationship-focus-stability.cjs",
"test:maps": "node maps-engine.cjs && node maps-workspace.cjs",
"test:maps-story": "node maps-story-engine.cjs && node maps-story.cjs",
"test:writer": "node writer-workspace.cjs"
"test:writer": "node writer-workspace.cjs",
"test:writer-goals": "node writer-goal-navigation.cjs"
},
"devDependencies": {
"@microsoft/signalr": "8.0.7",

View File

@ -0,0 +1,52 @@
const {chromium}=require('playwright');
const fs=require('node:fs');
const assert=require('node:assert/strict');
const base='http://127.0.0.1:5238';
(async()=>{const browser=await chromium.launch();try{
for(const pwa of [false,true]){
const context=await browser.newContext({viewport:{width:1500,height:1000}});
if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))}));
const page=await context.newPage(),errors=[];page.on('pageerror',error=>errors.push(error.message));
const goal=page.locator('[name=GoalSummary]');
const modal=page.locator('#pdApplicationDialog');
const guarded=()=>page.evaluate(()=>{const event=new Event('beforeunload',{cancelable:true});window.dispatchEvent(event);return event.defaultPrevented;});
const leave=async()=>{await page.getByRole('tab',{name:'Project',exact:true}).click();await page.getByRole('link',{name:'Writer',exact:true}).first().click();await modal.waitFor();};
await page.goto(base+'/Writer/Chapter/21');
const original=await goal.inputValue();
const draft=original+' — “Δοκιμή / 日本語”';
await goal.fill(draft);
assert(await guarded(),'Unsaved chapter intent protects browser unload');
await leave();await modal.getByRole('button',{name:'Keep editing',exact:true}).click();await modal.waitFor({state:'hidden'});
assert.equal(new URL(page.url()).pathname,'/Writer/Chapter/21');assert.equal(await goal.inputValue(),draft);
await page.getByRole('button',{name:'Save chapter goals',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('[data-unsaved-form] [role=status]')?.textContent==='Saved');
assert.equal(await guarded(),false,'Only acknowledged saves clear protection');
const check=await context.newPage();await check.goto(base+'/Writer/Chapter/21');assert.equal(await check.locator('[name=GoalSummary]').inputValue(),draft,'Actual controller/service boundary receives Unicode content');await check.close();
await goal.fill(draft+' discarded');await leave();await modal.getByRole('button',{name:'Discard and leave',exact:true}).click();await page.waitForURL(url=>url.pathname==='/Writer');
await page.goto(base+'/Writer/Chapter/21');assert.equal(await goal.inputValue(),draft,'Discard never writes the draft');
const savedDraft=draft+' saved on navigation';await goal.fill(savedDraft);await leave();await modal.getByRole('button',{name:'Save and leave',exact:true}).click();await page.waitForURL(url=>url.pathname==='/Writer');
await page.goto(base+'/Writer/Chapter/21');assert.equal(await goal.inputValue(),savedDraft);
let reject=true;
await page.route('**/Writer/SaveChapterGoal',route=>reject?(reject=false,route.fulfill({status:503,json:{message:'Synthetic save failure'}})):route.continue());
const retryDraft=savedDraft+' retry';await goal.fill(retryDraft);await leave();await modal.getByRole('button',{name:'Save and leave',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('[data-dialog-error]')?.textContent==='Synthetic save failure');
assert.equal(new URL(page.url()).pathname,'/Writer/Chapter/21');assert.equal(await goal.inputValue(),retryDraft);assert(await guarded());
await modal.getByRole('button',{name:'Save and leave',exact:true}).click();await page.waitForURL(url=>url.pathname==='/Writer');
await page.goto(base+'/Writer/Chapter/21');assert.equal(await goal.inputValue(),retryDraft);
let release;
const held=new Promise(resolve=>release=resolve);let first=true;
await page.route('**/Writer/SaveChapterGoal',async route=>{if(first){first=false;await held;}await route.continue();});
await goal.fill(retryDraft+' older request');
const started=page.waitForRequest('**/Writer/SaveChapterGoal');
await page.getByRole('button',{name:'Save chapter goals',exact:true}).click();await started;
const newer=retryDraft+' newer edit';await goal.fill(newer);release();
await page.waitForFunction(()=>document.querySelector('[data-unsaved-form] [role=status]')?.textContent.includes('newer edits'));
assert(await guarded(),'An older acknowledgement does not clear newer text changes');
await page.getByRole('button',{name:'Save chapter goals',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('[data-unsaved-form] [role=status]')?.textContent==='Saved');
assert.equal(await guarded(),false);
assert.deepEqual(errors,[]);await context.close();
}
console.log('PASS Writer chapter-goal unsaved guard, cancelled/discarded navigation, real antiforgery/controller saves, Unicode persistence, save-and-leave failure/retry and concurrent edits in browser/PWA');
}finally{await browser.close();}})().catch(error=>{console.error(error);process.exitCode=1;});

View File

@ -19,6 +19,8 @@ using PlotLine.ViewModels;
// Isolated, loopback-only host: renders real compiled Razor chrome, never starts app workers or connects to a database.
internal static class ToolbarBrowserHost
{
private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new();
private static PlotLineWorkspaceData HealthFixture()
{
var f = new PlotHealthTests.Fixture();
@ -73,6 +75,16 @@ internal static class ToolbarBrowserHost
return proxy;
}
private static Task SaveFixtureGoal(int userId, ChapterGoalEditViewModel model)
{
writerGoals[(userId, model.ChapterID)] = new() {
ChapterID = model.ChapterID, ChapterGoalID = model.ChapterGoalID,
GoalSummary = model.GoalSummary, EmotionalGoal = model.EmotionalGoal,
ReaderTakeaway = model.ReaderTakeaway, MustInclude = model.MustInclude, RisksOrConcerns = model.RisksOrConcerns
};
return Task.CompletedTask;
}
private static WriterDashboardViewModel WriterFixture() => new() {
ProjectID = 7, ProjectOptions = [new SelectListItem("The Glass Harbour", "7", true)],
WriteNext = [new() { ProjectID = 7, BookID = 12, BookTitle = "A Distant Shore", ChapterID = 21, ChapterNumber = 1, SceneID = 101, SceneNumber = 1, SceneTitle = "The crossing", RevisionStatusName = "Outlined", Summary = "A synthetic writing task." }]
@ -113,15 +125,15 @@ internal static class ToolbarBrowserHost
FixtureProxy<IBookRepository>((name, args) => name == "ListByProjectAsync"
? Task.FromResult<IReadOnlyList<Book>>([new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }]) : throw new NotSupportedException(name)),
services.GetRequiredService<ICurrentUserService>()));
builder.Services.AddSingleton(FixtureProxy<IWriterWorkspaceService>((name, args) => name switch {
builder.Services.AddScoped<IWriterWorkspaceService>(services => FixtureProxy<IWriterWorkspaceService>((name, args) => name switch {
"GetDashboardAsync" => Task.FromResult(WriterFixture()),
"GetChapterWorkflowAsync" => Task.FromResult<ChapterWorkflowViewModel?>(new() {
Project = new() { ProjectID = 7, ProjectName = "The Glass Harbour" },
Book = new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" },
Chapter = new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" },
Goal = new() { ChapterID = 21, GoalSummary = "Reveal the consequence" }
Goal = writerGoals.GetOrAdd((services.GetRequiredService<ICurrentUserService>().UserId!.Value, 21), _ => new() { ChapterID = 21, GoalSummary = "Reveal the consequence" })
}),
"SaveChapterGoalAsync" => Task.CompletedTask,
"SaveChapterGoalAsync" => SaveFixtureGoal(services.GetRequiredService<ICurrentUserService>().UserId!.Value, (ChapterGoalEditViewModel)args![0]!),
_ => throw new NotSupportedException(name)
}));
builder.Services.AddSingleton(FixtureProxy<IWritingScheduleService>((name, args) => name switch {

View File

@ -298,6 +298,8 @@ public sealed class WriterController(
public async Task<IActionResult> SaveChapterGoal(ChapterGoalEditViewModel model)
{
await writerWorkspace.SaveChapterGoalAsync(model);
if (string.Equals(Request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.OrdinalIgnoreCase))
return Json(new { ok = true });
return RedirectToAction(nameof(Chapter), new { id = model.ChapterID });
}

View File

@ -47,7 +47,7 @@
<h2>Chapter Goals <help-icon key="workspace.chapterGoals" /></h2>
</div>
</div>
<form asp-action="SaveChapterGoal" method="post" class="story-bible-card chapter-goal-form">
<form asp-action="SaveChapterGoal" method="post" class="story-bible-card chapter-goal-form" data-unsaved-form>
<input type="hidden" name="ChapterGoalID" value="@Model.Goal.ChapterGoalID" />
<input type="hidden" name="ChapterID" value="@Model.Chapter.ChapterID" />
<label class="form-label">Goal summary</label>
@ -99,3 +99,7 @@
}
</div>
</section>
@section Scripts {
<script src="~/js/form-navigation-guard.js" asp-append-version="true"></script>
}

View File

@ -0,0 +1,106 @@
(() => {
const forms = [...document.querySelectorAll('form[data-unsaved-form]')];
if (!forms.length) return;
const serialise = data => JSON.stringify([...data.entries()].filter(([name]) => name !== '__RequestVerificationToken').map(([name, value]) => [name, typeof value === 'string' ? value : value.name]));
const snapshot = form => serialise(new FormData(form));
const states = forms.map(form => {
const status = document.createElement('p');
status.className = 'form-text mb-0'; status.hidden = true; status.setAttribute('role', 'status');
form.append(status);
return { form, status, baseline: snapshot(form), pending: null };
});
let leaving = false, choosing = false;
const dirty = state => snapshot(state.form) !== state.baseline;
const hasChanges = () => states.some(state => dirty(state) || state.pending);
const showStatus = (state, message, failed = false) => {
state.status.hidden = !message;
state.status.textContent = message;
state.status.classList.toggle('text-danger', failed);
state.status.setAttribute('role', failed ? 'alert' : 'status');
};
const save = state => {
if (state.pending) return state.pending;
const data = new FormData(state.form), sent = serialise(data);
const buttons = [...state.form.querySelectorAll('button[type=submit], input[type=submit]')].map(button => [button, button.disabled]);
buttons.forEach(([button]) => button.disabled = true);
showStatus(state, 'Saving…');
state.pending = (async () => {
try {
const response = await fetch(state.form.action, {
method: 'POST', body: data, credentials: 'same-origin',
headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
});
if (response.redirected) throw new Error('Your session or subscription needs attention. Open your account in another tab; your changes remain here.');
const result = await response.json().catch(() => null);
if (!response.ok || result?.ok !== true) throw new Error(result?.message || 'Unable to save. Your changes remain here; please try again.');
state.baseline = sent;
showStatus(state, dirty(state) ? 'Earlier changes saved; newer edits remain unsaved.' : 'Saved');
} catch (error) {
showStatus(state, error.message || 'Unable to save. Your changes remain here.', true);
throw error;
} finally {
buttons.forEach(([button, disabled]) => button.disabled = disabled);
state.pending = null;
}
})();
return state.pending;
};
const discard = state => {
const values = new Map();
for (const [name, value] of JSON.parse(state.baseline)) {
if (!values.has(name)) values.set(name, []);
values.get(name).push(value);
}
for (const field of state.form.elements) {
if (!field.name || field.name === '__RequestVerificationToken' || field.matches('button, input[type=submit]')) continue;
const original = values.get(field.name) || [];
if (field.matches('input[type=checkbox], input[type=radio]')) field.checked = original.includes(field.value);
else if (field.matches('select[multiple]')) [...field.options].forEach(option => option.selected = original.includes(option.value));
else if (field.type === 'file') field.value = '';
else field.value = original[0] ?? '';
}
showStatus(state, 'Changes discarded');
};
for (const state of states) {
state.form.addEventListener('input', () => { if (!state.pending) showStatus(state, dirty(state) ? 'Unsaved changes' : ''); });
state.form.addEventListener('change', () => { if (!state.pending) showStatus(state, dirty(state) ? 'Unsaved changes' : ''); });
state.form.addEventListener('submit', event => { event.preventDefault(); void save(state).catch(() => {}); });
}
window.addEventListener('beforeunload', event => {
if (leaving || !hasChanges()) return;
event.preventDefault(); event.returnValue = '';
});
window.addEventListener('pageshow', () => leaving = false);
document.addEventListener('click', async event => {
if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey || !hasChanges()) return;
const link = event.target.closest('a[href]');
if (!link || link.hasAttribute('download') || (link.target && link.target !== '_self')) return;
const url = new URL(link.href, location.href);
if (!['http:', 'https:'].includes(url.protocol) || link.getAttribute('href').startsWith('#')
|| (url.origin === location.origin && url.pathname === location.pathname && url.search === location.search && url.hash)) return;
if (!window.PlotDirectorDialogs || !window.bootstrap?.Modal || !document.getElementById('pdApplicationDialogTemplate')) {
// The browser's beforeunload protection remains available if dialog assets fail.
states.filter(dirty).forEach(state => showStatus(state, 'Save your changes before leaving this page.', true));
return;
}
event.preventDefault();
if (choosing) return;
choosing = true;
try {
const result = await window.PlotDirectorDialogs.choose({
title: 'Unsaved changes', message: 'Save your changes before leaving this page?',
failureMessage: 'Changes remain unsaved. Save again or keep editing.',
actions: [
{ label: 'Save and leave', value: 'save', className: 'btn-primary', run: async () => {
for (const state of states.filter(state => dirty(state) || state.pending)) await save(state);
return !hasChanges();
} },
{ label: 'Discard and leave', value: 'discard', className: 'btn-outline-danger' },
{ label: 'Keep editing', value: 'cancel' }
]
});
if (result?.value === 'discard') states.forEach(discard);
if (result?.value === 'save' || result?.value === 'discard') { leaving = true; location.assign(url.href); }
} finally { choosing = false; }
}, true);
})();