Refresh accepted Reader chapters safely and retain focus across navigation

This commit is contained in:
Nick Beckley 2026-11-13 20:21:10 +00:00
parent 0c9aa9b257
commit 7855ff1ac1
11 changed files with 571 additions and 31 deletions

View File

@ -0,0 +1,43 @@
# Manuscript Reader — live updates and persistent Focus Reading
This extends Phase 1 without changing the accepted manuscript store, Word Companion, reconciliation, installers, SQL schema or Maps.
## Change detection and server overhead
An authenticated GET to `/manuscript/reader/changes` checks immediately on opening a selected chapter and every **12 seconds** while visible. It carries book/chapter IDs, the last observed accepted book revision and chapter fingerprint. Existing `ParagraphManuscript` status, `Book_Get` and `Chapter_Get` stored procedures enforce book access and validate the active chapter. Stable polls perform three small stored-procedure reads and transfer only a small JSON response; they do not retrieve paragraph JSON or prose.
When the accepted book revision differs, the service uses the existing read-only projection to compute a SHA-256 fingerprint over the selected chapter's ordered paragraph GUIDs, exact text and heading flags, with length-delimited encoding. The returned revision is the revision of the snapshot actually read. A preference revision, unchanged successful synchronisation or another chapter's update does not replace the selected chapter when its fingerprint is unchanged. Pending/rejected submissions never enter the committed source.
Only a changed chapter fingerprint causes the browser to GET `/manuscript/reader/chapter`, which returns that chapter's JSON paragraphs and accurately sourced timestamps. Both new GET endpoints retain authentication, access checks, no-store responses, safe generic errors and no-index headers. Browser rendering uses `textContent`, never manuscript HTML insertion. Revisions travel as decimal strings to avoid JavaScript integer precision loss.
The existing storage API still reads/deserialises the book aggregate on the server to calculate a chapter fingerprint after a revision change and to retrieve a changed chapter. This happens on candidate changes, not every polling interval; a genuine selected-chapter change can therefore cause two aggregate reads. There is no new SQL projection, persistent cache, database object or browser book preload. The normal metadata-only path is approximately 15 small stored-procedure calls per minute per visible Reader tab. No polling occurs while hidden.
## Reading session behaviour
Updates preserve a visible paragraph GUID and its vertical screen offset, using nearby surviving GUIDs or exact paragraph text when needed. Scroll restoration is instantaneous (including under themes that enable smooth scrolling). Replacements retain Focus Reading. If no usable anchor survives, the page offers an explicit update instead of forcibly resetting the reading session.
A non-collapsed browser selection defers both full chapter retrieval and DOM replacement. Metadata checks can continue tracking the newest accepted version, but the page does not repeatedly fetch or replace the deferred chapter. Clearing the selection fetches the latest accepted chapter. A second selection/pause check after the full fetch protects selections made while that request was running.
**Pause automatic updates while listening** retains the current text and offers **Show updated chapter**. The latter is an explicit user action and may clear selection to display the pending chapter. No proprietary text-to-speech API or reliable extension-playback detection exists. Extensions without a browser selection should use the pause control; interruption-free third-party playback cannot be guaranteed during an automatic replacement.
There is one serial polling loop. Hidden pages suspend polling and abort outstanding requests, visible/online pages check promptly, transient errors retain prose and retry, and access/authentication failures stop polling with an unobtrusive message. Requests are cancelled/ignored on navigation. Reinitialisation disposes the old timer and listeners. Browsers restoring a Reader from the back/forward cache rearm its loop.
## Focus Reading navigation
Focus Reading is a Reader viewing preference carried by the Reader URL (`focus=true`), chapter links and chapter form. The server renders the focused state, and CSS applies it before the deferred script executes. Next, Previous, the chapter selector and Reader refresh links preserve it. Explicit exit/Escape removes it; navigating away does not apply focus to other workspaces. No manuscript state or browser prose storage is involved.
Each newly navigated chapter starts at its beginning; automatic updates within the same chapter preserve position. Normal navigation and first/last chapter boundaries are unchanged.
## Verification
- Application build, full executable regression harness and the original 24-combination Reader browser suite.
- Focused service tests cover initial/stable metadata-only checks, genuine accepted content, unchanged successful synchronisation, another chapter's update, pending/rejected isolation, chapter/account access and timestamp provenance.
- `PlotLine.Tests/Browser/manuscript-reader-live.cjs` covers actual controller/cache/access boundaries plus simulated accepted updates: no page reload, normal/focused paragraph anchors, deferred/latest version while selected, listening pause/manual action, hidden/visible lifecycle, offline/recovery, reinitialisation/single loop, in-flight navigation, Next/Previous/dropdown focus persistence, top-of-new-chapter and first/last boundaries. It runs desktop/mobile, ordinary browser/simulated PWA, with all four themes checked. It does not write a database or drive real Word.
Example browser invocation against the isolated fixture host:
```sh
PD_BROWSER_FIXTURE_URL=http://127.0.0.1:5249 node PlotLine.Tests/Browser/manuscript-reader-live.cjs
```
The author reports Word-to-server acceptance and manual-refresh Reader visibility were verified before this task. This task's synchronisation-change browser fixtures are simulations, not evidence of another real Word run. Actual installed Windows PWA and text-to-speech extension playback must be qualified on Windows.

View File

@ -1,5 +1,7 @@
# Manuscript Reader — Phase 1
For the subsequent automatic-update and Focus Reading navigation behaviour, see [LiveUpdates.md](LiveUpdates.md). The original delivery evidence below describes the initial release.
The read-only Reader is available from **Read manuscript** in a book's Chapters list, each chapter's details, and the application Book menu. The installed PWA uses the same authenticated workspace. It requires no local Word installation.
## Implementation and data contract

View File

@ -0,0 +1,158 @@
const assert = require('node:assert/strict');
const { chromium } = require('playwright');
const base = process.env.PD_BROWSER_FIXTURE_URL || 'http://127.0.0.1:5249';
const settle = () => new Promise(resolve => setTimeout(resolve, 120));
(async () => {
const browser = await chromium.launch();
try {
// Real controller checks: per-request access/cache rules and server-rendered focus state.
const api = await browser.newContext();
const chapter = await (await api.request.get(`${base}/manuscript/reader/chapter?bookId=12&chapterId=21`)).json();
const unchanged = await api.request.get(`${base}/manuscript/reader/changes?bookId=12&chapterId=21&knownRevision=${chapter.revision}&knownVersion=${chapter.version}`);
assert.equal(unchanged.status(),200); assert.equal((await unchanged.json()).changed,false);
assert.match(unchanged.headers()['cache-control'],/no-store/);
assert.match(unchanged.headers()['x-robots-tag'],/noindex/);
for(const path of ['chapter','changes']) {
assert.equal((await api.request.get(`${base}/manuscript/reader/${path}?bookId=12&chapterId=999`)).status(),404);
assert.equal((await api.request.post(`${base}/manuscript/reader/${path}?bookId=12&chapterId=21`)).status(),405);
}
await api.addCookies([{name:'fixture-user',value:'5',url:base}]);
for(const path of ['chapter','changes']) assert.equal((await api.request.get(`${base}/manuscript/reader/${path}?bookId=12&chapterId=21`)).status(),404);
await api.close();
for(const pwa of [false,true]) for(const width of [390,1440]) for(const initiallyFocused of [false,true]) {
const context = await browser.newContext({viewport:{width,height:900}});
if(pwa) await context.addInitScript(() => Object.defineProperty(navigator,'standalone',{value:true}));
const page = await context.newPage();
await page.clock.install();
let current, checks=0, chapters=0, hold=false, release, disconnected=false;
await page.route('**/manuscript/reader/changes?**', async route => {
const request = new URL(route.request().url());
if(request.searchParams.get('chapterId')!=='21') return route.fallback();
checks++;
if(disconnected) return route.abort("internetdisconnected");
if(!current) current = {revision:request.searchParams.get('knownRevision'),version:request.searchParams.get('knownVersion')};
await route.fulfill({json:{revision:current.revision,version:current.version,changed:current.version!==request.searchParams.get('knownVersion')}});
});
await page.route('**/manuscript/reader/chapter?**', async route => {
if(new URL(route.request().url()).searchParams.get('chapterId')!=='21') return route.fallback();
chapters++;
const snapshot = structuredClone(current);
if(hold) await new Promise(resolve => { release=resolve; });
await route.fulfill({json:snapshot}).catch(()=>{});
});
await page.goto(`${base}/manuscript/reader?bookId=12&chapterId=21&focus=${initiallyFocused}&reader-long=true`);
await settle();
const initial = await page.evaluate(() => {
const root=document.querySelector('.manuscript-reader');
window.readerDocumentSentinel=42;
window.firstReaderNode=root.querySelector('.reader-paragraph');
return {bookId:12,chapterId:21,revision:root.dataset.revision,version:root.dataset.version,title:'The crossing',
lastSuccessfulSyncUtc:'2026-11-13T10:12:13Z',snapshotCapturedUtc:'2026-11-13T10:11:12Z',
paragraphs:[...root.querySelectorAll('.reader-paragraph')].map(p=>({id:p.dataset.paragraphId,text:p.textContent,isHeading:p.matches('h2,h3')}))};
});
current=structuredClone(initial);
assert.ok(checks>=1,'Immediate initial check'); assert.equal(chapters,0,'No chapter transfer on initial/unchanged check');
assert.equal(await page.locator('.manuscript-reader').evaluate(n=>getComputedStyle(n).position),initiallyFocused?'fixed':'static');
for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']) {
await page.evaluate(theme=>PlotDirectorApplyApplicationTheme(theme),theme);
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),String(initiallyFocused));
}
// A successful unchanged synchronisation advances the book revision, not chapter prose.
current.revision='1'; const before=checks;
await page.clock.fastForward(12000); await settle();
assert.ok(checks>before); assert.equal(chapters,0);
assert.equal(await page.evaluate(()=>window.firstReaderNode===document.querySelector('.reader-paragraph')),true);
const anchor = await page.locator('.reader-paragraph').nth(25).evaluate(row=>{
row.scrollIntoView({behavior:"instant"});
const root=document.querySelector('.manuscript-reader');
if(root.dataset.focus==='true') root.scrollTop-=100; else window.scrollBy({top:-100,behavior:"instant"});
return {id:row.dataset.paragraphId,top:row.getBoundingClientRect().top};
});
current.revision='2';current.version='accepted-change-2';
current.paragraphs.splice(1,0,{id:'new-synthetic-id',text:'Inserted accepted prose <script>unsafe()</script>.\n'.repeat(40),isHeading:false});
await page.clock.fastForward(12000);await settle();
await page.waitForFunction(()=>document.querySelector('.manuscript-reader').dataset.version==='accepted-change-2');
assert.equal(chapters,1);assert.equal(await page.locator('.reader-page script').count(),0);assert.equal(await page.evaluate(()=>window.readerDocumentSentinel),42,'No page reload');
const after=await page.locator(`[data-paragraph-id="${anchor.id}"]`).evaluate(n=>n.getBoundingClientRect().top);
assert.ok(Math.abs(after-anchor.top)<3,`Paragraph anchor drift ${after-anchor.top}, focused=${initiallyFocused}, width=${width}, pwa=${pwa}`);
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),String(initiallyFocused));
// A selection defers full fetches and replacements while metadata follows the latest accepted version.
await page.locator(`[data-paragraph-id="${anchor.id}"]`).evaluate(row=>{
const range=document.createRange();range.selectNodeContents(row);getSelection().removeAllRanges();getSelection().addRange(range);
});
current.revision='3';current.version='accepted-change-3';current.paragraphs[3].text+=' Selection deferred.';
await page.clock.fastForward(12000);await settle();
assert.equal(chapters,1);assert.match(await page.locator('#reader-update-status').textContent(),/selection/);
current.revision='4';current.version='accepted-change-4';current.paragraphs[3].text+=' Latest accepted version.';
for(let i=0;i<3;i++){await page.clock.fastForward(12000);await settle();}
assert.equal(chapters,1,'No repeated full transfer while update is deferred');
assert.equal(await page.evaluate(()=>getSelection().isCollapsed),false);
await page.evaluate(()=>getSelection().removeAllRanges());await settle();
await page.waitForFunction(()=>document.querySelector('.manuscript-reader').dataset.version==='accepted-change-4');
assert.equal(chapters,2,'Only latest pending version retrieved after selection clears');
// Listening pause offers explicit update without claiming extension playback detection.
await page.locator('#reader-pause').check();
current.revision='5';current.version='accepted-change-5';current.paragraphs[3].text+=' Listening pause.';
await page.clock.fastForward(12000);await settle();assert.equal(chapters,2);
await page.locator('#reader-apply-update').click();await settle();
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-version'),'accepted-change-5');
// Hidden lifecycle: suspend requests, then perform an immediate visible check.
await page.evaluate(()=>{Object.defineProperty(document,'hidden',{configurable:true,value:true});document.dispatchEvent(new Event('visibilitychange'));});
const hiddenChecks=checks;await page.clock.fastForward(60000);await settle();assert.equal(checks,hiddenChecks);
await page.evaluate(()=>{Object.defineProperty(document,'hidden',{configurable:true,value:false});document.dispatchEvent(new Event('visibilitychange'));});await settle();assert.equal(checks,hiddenChecks+1);
// Network loss retains prose and recovers automatically.
disconnected=true;await context.setOffline(true);await page.clock.fastForward(12000);await settle();
assert.match(await page.locator('#reader-update-status').textContent(),/temporarily unavailable/);
assert.equal(await page.locator('.reader-paragraph').count(),initial.paragraphs.length+1);
disconnected=false;await context.setOffline(false);await settle();
assert.doesNotMatch(await page.locator('#reader-update-status').textContent(),/temporarily unavailable/);
// Script reinitialisation disposes prior timer/listeners; there is exactly one polling loop.
await page.addScriptTag({url:base+'/js/manuscript-reader.js'});await settle();const single=checks;
await page.clock.fastForward(12000);await settle();assert.equal(checks,single+1);
await page.clock.fastForward(12000);await settle();assert.equal(checks,single+2);
// No surviving anchor: offer a manual update instead of forcing the reader elsewhere.
current.revision='6';current.version='accepted-change-6';
current.paragraphs=current.paragraphs.map((p,i)=>({...p,id:'replacement-'+i,text:'Replacement synthetic paragraph '+i+' with unrelated accepted text.'}));
await page.clock.fastForward(12000);await settle();
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-version'),'accepted-change-5');
assert.equal(await page.locator('#reader-pause').isChecked(),true);
await page.locator('#reader-apply-update').click();await settle();
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-version'),'accepted-change-6');
// Selection beginning while a full request is running is checked again before replacement.
hold=true;current.revision='7';current.version='accepted-change-7';current.paragraphs[2].text+=' Deferred after request starts.';
await page.clock.fastForward(12000);await settle();
await page.locator('.reader-paragraph').nth(2).evaluate(row=>{
const range=document.createRange();range.selectNodeContents(row);getSelection().removeAllRanges();getSelection().addRange(range);
});
release();hold=false;await settle();
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-version'),'accepted-change-6');
await page.evaluate(()=>getSelection().removeAllRanges());await settle();
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-version'),'accepted-change-7');
if(!initiallyFocused) await page.getByRole('button',{name:'Focus reading',exact:true}).click();
// A chapter fetch in flight cannot overwrite a subsequent chapter navigation.
hold=true;current.revision='8';current.version='accepted-change-8';current.paragraphs[3].text+=' In flight.';
await page.clock.fastForward(12000);await settle();assert.equal(typeof release,'function');
await page.getByRole('link',{name:'Next chapter →',exact:true}).click();await page.waitForURL(/chapterId=22/);
release();await settle();hold=false;
assert.match(await page.locator('.reader-page').textContent(),/Another chapter only/);
assert.doesNotMatch(await page.locator('.reader-page').textContent(),/In flight|Inserted accepted/);
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),'true');
assert.equal(await page.locator('.manuscript-reader').evaluate(n=>n.scrollTop),0);
// Stop synthetic updates for chapter-navigation checks, which use real server-rendered pages.
await page.unroute('**/manuscript/reader/changes?**');await page.unroute('**/manuscript/reader/chapter?**');
await page.getByRole('link',{name:'← Previous chapter',exact:true}).click();await page.waitForURL(/chapterId=21/);
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),'true');
assert.equal(await page.getByRole('link',{name:'← Previous chapter',exact:true}).count(),0);
await page.getByLabel('Chapter',{exact:true}).selectOption('23');await page.getByRole('button',{name:'Read',exact:true}).click();await page.waitForURL(/chapterId=23/);
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),'true');
assert.equal(await page.locator('.manuscript-reader').evaluate(n=>n.scrollTop),0);
assert.equal(await page.getByRole('link',{name:'Next chapter →',exact:true}).count(),0);
await page.getByRole('button',{name:'Exit focus reading',exact:true}).click();
await page.getByRole('link',{name:'← Previous chapter',exact:true}).click();await page.waitForURL(/chapterId=22/);
assert.equal(await page.locator('.manuscript-reader').getAttribute('data-focus'),'false');
await context.close();
}
console.log('PASS Reader live updates: accepted fingerprint/no-op sync, no reload, paragraph position, selection deferral/latest version, listening pause, hidden resume, offline recovery, single loop, stale navigation response, focus Next/Previous/selector/top/boundaries, access/cache rules; desktop/mobile and simulated PWA. Synchronisations simulated, no Word or database writes.');
}finally{await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});

View File

@ -32,23 +32,40 @@ internal static class ManuscriptReaderTests
]
};
}
internal static ManuscriptReaderService FixtureService(Func<ParagraphManuscript?>? snapshot = null)
internal static ManuscriptReaderService FixtureService(Func<ParagraphManuscript?>? snapshot = null, Action? onRead = null)
{
var fixture = Snapshot();
var repository = NativeWorkflowTests.Proxy<IParagraphManuscriptRepository>((name, args) => {
if (name != "Get") throw new Exception("Reader attempted manuscript mutation: " + name);
if (name is not ("Get" or "Status")) throw new Exception("Reader attempted manuscript mutation: " + name);
if ((int)args![0]! != 4 || (int)args[1]! != 12) throw new UnauthorizedAccessException();
return Task.FromResult(snapshot is null ? Snapshot() : snapshot());
if (name == "Get") onRead?.Invoke();
var current = snapshot is null ? fixture : snapshot();
return name == "Get" ? Task.FromResult(current) : Task.FromResult(current is null ? null : new ParagraphSyncStatus { Revision = current.Revision });
});
var books = NativeWorkflowTests.Proxy<IBookRepository>((name, _) => name == "GetAsync"
? Task.FromResult<Book?>(new() { BookID = 12, BookTitle = "A Distant Shore", ProjectID = 7 }) : throw new Exception(name));
var chapters = NativeWorkflowTests.Proxy<IChapterRepository>((name, _) => name == "ListByBookAsync"
? Task.FromResult<IReadOnlyList<Chapter>>(Chapters) : throw new Exception(name));
var chapters = NativeWorkflowTests.Proxy<IChapterRepository>((name, args) => name switch {
"ListByBookAsync" => Task.FromResult<IReadOnlyList<Chapter>>(Chapters),
"GetAsync" => Task.FromResult(Chapters.FirstOrDefault(c => c.ChapterID == (int)args![0]!)),
_ => throw new Exception(name)
});
return new(repository, books, chapters);
}
internal static ParagraphManuscript LongSnapshot()
{
var state = Snapshot();
state.Paragraphs.AddRange(Enumerable.Range(0,80).Select(i => new StoryParagraph {
ChapterId = 21, Story = true,
Occurrence = new() { Id = Guid.NewGuid(), Ordinal = i + 10, Outline = 10,
Text = $"Synthetic reading paragraph {i + 1}. " + string.Join(" ", Enumerable.Repeat("This is selectable captured prose used only for browser verification.", 5)) }
}));
return state;
}
public static async Task Run()
{
void Check(bool value, string message) { if (!value) throw new Exception(message); }
var state = Snapshot(); var service = FixtureService(() => state);
var state = Snapshot(); var reads = 0; var service = FixtureService(() => state, () => reads++);
var first = (await service.Read(4, 12, null))!;
Check(first.Chapters.Count == 3 && first.Chapter!.ChapterID == 21, "Book context and canonical chapter ordering");
Check(first.PreviousId is null && first.NextId == 22, "First chapter navigation");
@ -66,9 +83,23 @@ internal static class ManuscriptReaderTests
windows.Paragraphs.Insert(2, new() { Occurrence = new() { Id = Guid.NewGuid(), Text = " ", Ordinal = 1 } });
var complete = ManuscriptReaderService.Project(first.Book, Chapters, Chapters[0], windows);
Check(complete.Paragraphs.Count == 4 && complete.Paragraphs.Any(p => p.Text == " "), "Heading windows preserve unassigned blank paragraphs and scene separators");
var baseline = first.ContentVersion;
Check(!(await service.Check(4,12,21,state.Revision,baseline))!.Changed, "Initial poll checks accepted metadata without a false update");
Check(reads == 3, "Unchanged poll never transfers the paragraph aggregate");
state.Revision++;
state.ChapterCheckpoints[0].LastSuccessfulSyncUtc = DateTime.UtcNow;
Check(!(await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Successful unchanged synchronisation does not change the chapter fingerprint");
state.Paragraphs.Single(p => p.ChapterId == 22).Occurrence.Text = "Other chapter accepted change";
state.Revision++;
Check(!(await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Another chapter revision does not rerender the selected chapter");
Check(await service.Check(4,12,999,state.Revision,baseline) is null, "Poll rejects a chapter outside the book even on unchanged revision");
try { await service.Check(5,12,21,state.Revision,baseline); throw new Exception("Foreign poll allowed"); } catch (UnauthorizedAccessException) { }
var pending = ParagraphManuscriptEngine.Clone(state); pending.Paragraphs[2].Occurrence.Text = "Pending change";
Check((await service.Read(4, 12, 21))!.Paragraphs[1].Text != "Pending change", "Uncommitted or rejected submissions cannot enter Reader");
pending.Revision++;
Check(!(await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Pending or rejected text is absent from change checks");
state = pending;
Check((await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Genuine accepted chapter change has a different fingerprint");
Check((await service.Read(4, 12, 21))!.Paragraphs[1].Text == "Pending change", "Next read sees newly committed snapshot without cache");
var empty = await FixtureService(() => null).Read(4, 12, 21);
Check(empty!.Paragraphs.Count == 0 && empty.SnapshotCapturedUtc is null, "Missing accepted snapshot remains empty without bootstrap");

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 ParagraphManuscript readerFixture = ManuscriptReaderTests.Snapshot();
private static readonly ParagraphManuscript readerLongFixture = ManuscriptReaderTests.LongSnapshot();
private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new();
private static PlotLineWorkspaceData HealthFixture()
@ -119,7 +121,7 @@ internal static class ToolbarBrowserHost
builder.Services.AddSingleton<IToolbarPreferenceRepository, ToolbarMemoryPreferences>();
builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() =>
services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-error"] == "true"
? throw new TimeoutException("Synthetic unavailable manuscript") : ManuscriptReaderTests.Snapshot()));
? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture));
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
builder.Services.AddScoped<ApplicationNavigation>(services => new ApplicationNavigation(

View File

@ -13,7 +13,7 @@ public sealed class ManuscriptReaderController(ManuscriptReaderService reader, I
ILogger<ManuscriptReaderController> logger) : Controller
{
[HttpGet]
public async Task<IActionResult> Index(int bookId, int? chapterId = null)
public async Task<IActionResult> Index(int bookId, int? chapterId = null, bool focus = false)
{
Response.Headers["X-Robots-Tag"] = "noindex, nofollow, noarchive";
if (currentUser.UserId is not int user) return Challenge();
@ -21,7 +21,9 @@ public sealed class ManuscriptReaderController(ManuscriptReaderService reader, I
try
{
var model = await reader.Read(user, bookId, chapterId);
return model is null ? NotFound() : View(model);
if (model is null) return NotFound();
model.FocusReading = focus;
return View(model);
}
catch (UnauthorizedAccessException) { return NotFound(); }
catch (SqlException e) when (e.Number == 51000) { return NotFound(); }
@ -33,4 +35,41 @@ public sealed class ManuscriptReaderController(ManuscriptReaderService reader, I
return View("Unavailable", new { BookId = bookId, ChapterId = chapterId });
}
}
[HttpGet("changes")]
public Task<IActionResult> Changes(int bookId, int chapterId, long knownRevision, string? knownVersion = null) => Poll(async user =>
{
if (bookId <= 0 || chapterId <= 0 || knownVersion is null || knownVersion.Length != 64) return NotFound();
var change = await reader.Check(user, bookId, chapterId, knownRevision, knownVersion);
return change is null ? NotFound() : Json(new { revision = change.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture), changed = change.Changed, version = change.Version });
});
[HttpGet("chapter")]
public Task<IActionResult> Chapter(int bookId, int chapterId) => Poll(async user =>
{
if (bookId <= 0 || chapterId <= 0) return NotFound();
var model = await reader.Read(user, bookId, chapterId);
return model is null ? NotFound() : Json(new
{
bookId, chapterId, revision = model.Revision.ToString(System.Globalization.CultureInfo.InvariantCulture),
version = model.ContentVersion, title = model.Chapter!.ChapterTitle,
paragraphs = model.Paragraphs.Select(p => new { id = p.Id, text = p.Text, isHeading = p.IsHeading }),
lastSuccessfulSyncUtc = model.LastSuccessfulSyncUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
snapshotCapturedUtc = model.SnapshotCapturedUtc?.ToString("yyyy-MM-ddTHH:mm:ssZ")
});
});
private async Task<IActionResult> Poll(Func<int, Task<IActionResult>> read)
{
Response.Headers["X-Robots-Tag"] = "noindex, nofollow, noarchive";
if (currentUser.UserId is not int user) return Challenge();
try { return await read(user); }
catch (UnauthorizedAccessException) { return NotFound(); }
catch (SqlException e) when (e.Number == 51000) { return NotFound(); }
catch (Exception e) when (e is SqlException or TimeoutException or System.Text.Json.JsonException)
{
logger.LogWarning("Manuscript Reader check unavailable ({FailureKind}).", e.GetType().Name);
return StatusCode(503, new { message = "Manuscript updates are temporarily unavailable." });
}
}
}

View File

@ -1,3 +1,5 @@
using System.Security.Cryptography;
using System.Text;
using PlotLine.Data;
using PlotLine.Models;
@ -6,6 +8,26 @@ namespace PlotLine.Services.Manuscript;
public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading);
public sealed class ManuscriptReaderModel
{
public long Revision { get; init; } = -1;
public bool FocusReading { get; set; }
public string ContentVersion => Fingerprint(Paragraphs);
public static string Fingerprint(IReadOnlyList<ReaderParagraph> paragraphs)
{
using var buffer = new MemoryStream();
using (var writer = new BinaryWriter(buffer, Encoding.UTF8, leaveOpen: true))
{
writer.Write(paragraphs.Count);
foreach (var paragraph in paragraphs)
{
writer.Write(paragraph.Id.ToByteArray());
writer.Write(paragraph.Text);
writer.Write(paragraph.IsHeading);
}
}
return Convert.ToHexString(SHA256.HashData(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)));
}
public required Book Book { get; init; }
public required IReadOnlyList<Chapter> Chapters { get; init; }
public Chapter? Chapter { get; init; }
@ -33,6 +55,20 @@ public sealed class ManuscriptReaderService(
return Project(book, ordered, selected, state);
}
public async Task<ReaderChange?> Check(int user, int bookId, int chapterId, long knownRevision, string knownVersion)
{
// Status transfers only metadata. Accepted prose changes always advance Revision; checkpoint
// validation without changed prose may update metadata in place, which needs no rerender.
var status = await manuscripts.Status(user, bookId);
var book = await books.GetAsync(bookId);
var chapter = await chapters.GetAsync(chapterId);
if (book is null || book.IsArchived || chapter is null || chapter.IsArchived || chapter.BookID != bookId) return null;
var revision = status?.Revision ?? -1;
if (revision == knownRevision) return new(revision, false, knownVersion);
var model = await Read(user, bookId, chapterId);
return model is null ? null : new(model.Revision, model.ContentVersion != knownVersion, model.ContentVersion);
}
public static ManuscriptReaderModel Project(Book book, IReadOnlyList<Chapter> ordered, Chapter? selected, ParagraphManuscript? state)
{
var index = selected is null ? -1 : ordered.ToList().FindIndex(c => c.ChapterID == selected.ChapterID);
@ -63,6 +99,7 @@ public sealed class ManuscriptReaderService(
var checkpoint = state?.ChapterCheckpoints.FirstOrDefault(c => c.ChapterId == selected?.ChapterID);
return new()
{
Revision = state?.Revision ?? -1,
Book = book, Chapters = ordered, Chapter = selected, Paragraphs = rows,
PreviousId = index > 0 ? ordered[index - 1].ChapterID : null,
NextId = index >= 0 && index + 1 < ordered.Count ? ordered[index + 1].ChapterID : null,
@ -71,3 +108,5 @@ public sealed class ManuscriptReaderService(
};
}
}
public sealed record ReaderChange(long Revision, bool Changed, string Version);

View File

@ -4,7 +4,10 @@
ViewData["DesktopLayout"] = "details";
}
<link rel="stylesheet" href="~/css/manuscript-reader.css" asp-append-version="true" />
<div class="manuscript-reader">
<div class="manuscript-reader" data-focus="@(Model.FocusReading ? "true" : "false")"
data-book-id="@Model.Book.BookID" data-chapter-id="@Model.Chapter?.ChapterID" data-chapter-number="@Model.Chapter?.ChapterNumber"
data-revision="@Model.Revision" data-version="@Model.ContentVersion"
data-check-url="@Url.Action("Changes")" data-chapter-url="@Url.Action("Chapter")">
<nav data-pwa-identity class="breadcrumb-trail" aria-label="Breadcrumb">
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">@Model.Book.BookTitle · Chapters</a>
<span>Manuscript Reader</span>
@ -14,9 +17,10 @@
</header>
<nav class="reader-controls" aria-label="Chapter navigation">
@if (Model.PreviousId is int previous)
{ <a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@previous" rel="prev">← Previous chapter</a> }
{ <a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@previous" asp-route-focus="@Model.FocusReading" rel="prev">← Previous chapter</a> }
else { <span class="btn btn-outline-secondary disabled" aria-disabled="true">← Previous chapter</span> }
<form method="get" asp-action="Index">
<input type="hidden" name="focus" value="@Model.FocusReading.ToString().ToLowerInvariant()" />
<input type="hidden" name="bookId" value="@Model.Book.BookID" />
<label for="reader-chapter">Chapter</label>
<select id="reader-chapter" name="chapterId" class="form-select">
@ -26,24 +30,30 @@
<button class="btn btn-outline-secondary" type="submit">Read</button>
</form>
@if (Model.NextId is int next)
{ <a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@next" rel="next">Next chapter →</a> }
{ <a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@next" asp-route-focus="@Model.FocusReading" rel="next">Next chapter →</a> }
else { <span class="btn btn-outline-secondary disabled" aria-disabled="true">Next chapter →</span> }
<button type="button" class="btn btn-outline-secondary" id="reader-focus" aria-pressed="false" hidden>Focus reading</button>
<button type="button" class="btn btn-outline-secondary" id="reader-focus" aria-pressed="@Model.FocusReading.ToString().ToLowerInvariant()" hidden>Focus reading</button>
</nav>
<p class="reader-status" role="status" id="reader-loading" hidden>Loading chapter…</p>
<div class="reader-status muted">
<div class="reader-status reader-live-controls" hidden>
<label><input type="checkbox" id="reader-pause" /> Pause automatic updates while listening</label>
<span role="status" aria-live="polite" id="reader-update-status"></span>
<button type="button" id="reader-apply-update" class="btn btn-outline-secondary btn-sm" hidden>Show updated chapter</button>
</div>
<div class="reader-status muted" id="reader-timestamps">
@if (Model.LastSuccessfulSyncUtc is DateTime sync)
{ <p>Last successful chapter synchronisation: <time datetime="@sync.ToString("yyyy-MM-ddTHH:mm:ssZ")">@sync.ToString("dd MMM yyyy HH:mm:ss") UTC</time></p> }
else { <p>No successful chapter synchronisation timestamp is recorded.</p> }
@if (Model.SnapshotCapturedUtc is DateTime captured)
{ <p>Accepted manuscript snapshot captured: <time datetime="@captured.ToString("yyyy-MM-ddTHH:mm:ssZ")">@captured.ToString("dd MMM yyyy HH:mm:ss") UTC</time></p> }
<p>Showing the latest accepted server text. Refresh to read newly synchronised changes.</p>
<p>Showing accepted server text. Changes are checked automatically while this page is visible.</p>
</div>
<div id="reader-content">
@if (Model.Paragraphs.Count == 0)
{
<section class="reader-empty" role="status"><h2>@(Model.Chapter?.ChapterTitle ?? "No chapters yet")</h2>
<p>No accepted manuscript text is available for this chapter. Save and successfully synchronise it using Word Companion, then refresh this page.</p>
<a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID">Refresh manuscript</a>
<a class="btn btn-outline-secondary" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-focus="@Model.FocusReading">Refresh manuscript</a>
</section>
}
else
@ -56,9 +66,10 @@
<partial name="_Paragraphs" model="Model.Paragraphs" />
</article>
}
</div>
<footer class="reader-status muted"><p>Captured paragraph text and headings are preserved. Word formatting such as bold, italics, images and page layout is not available in this capture.</p>
<a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">Return to Chapters</a>
<a asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID">Refresh manuscript</a>
<a asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter?.ChapterID" asp-route-focus="@Model.FocusReading">Refresh manuscript</a>
</footer>
</div>
<script src="~/js/manuscript-reader.js" asp-append-version="true" defer></script>

View File

@ -3,9 +3,9 @@
{
var paragraph = Model[index];
if (paragraph.IsHeading && index == 0)
{ <h2 class="reader-paragraph reader-heading">@paragraph.Text</h2> }
{ <h2 class="reader-paragraph reader-heading" data-paragraph-id="@paragraph.Id">@paragraph.Text</h2> }
else if (paragraph.IsHeading)
{ <h3 class="reader-paragraph reader-heading">@paragraph.Text</h3> }
{ <h3 class="reader-paragraph reader-heading" data-paragraph-id="@paragraph.Id">@paragraph.Text</h3> }
else
{ <p class="reader-paragraph">@paragraph.Text</p> }
{ <p class="reader-paragraph" data-paragraph-id="@paragraph.Id">@paragraph.Text</p> }
}

View File

@ -10,7 +10,11 @@
.reader-page header { margin-bottom: 2rem; }
.reader-paragraph { white-space: pre-wrap; tab-size: 4; min-height: 1em; margin: 0 0 1.15em; }
.reader-heading { font-size: 1.3em; line-height: 1.5; margin-block: 1.7em 1em; }
body.reader-focused .manuscript-reader { position: fixed; inset: 0; z-index: 2000; overflow-y: auto; background: var(--plotline-paper); padding: 1rem clamp(1rem, 4vw, 3rem); }
body.reader-focused { overflow: hidden; }
body.reader-focused .manuscript-reader .page-heading, body.reader-focused .breadcrumb-trail { display: none; }
.manuscript-reader[data-focus="true"] { position: fixed; inset: 0; z-index: 2000; overflow-y: auto; background: var(--plotline-paper); padding: 1rem clamp(1rem, 4vw, 3rem); }
body:has(.manuscript-reader[data-focus="true"]) { overflow: hidden; }
.manuscript-reader[data-focus="true"] .page-heading, .manuscript-reader[data-focus="true"] .breadcrumb-trail { display: none; }
@media (max-width: 600px) { .reader-controls form { order: -1; flex-basis: 100%; } .reader-page { margin-block: 1rem; } }
.reader-live-controls { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; color: var(--plotline-muted); }
.reader-live-controls[hidden] { display: none; }
.reader-paragraph { overflow-anchor: none; }

View File

@ -1,15 +1,226 @@
(() => {
const focus = document.getElementById('reader-focus');
if (!focus) return;
focus.hidden = false;
const root = document.querySelector('.manuscript-reader');
if (!root) return;
root.readerCleanup?.();
const listeners = new AbortController();
const on = (node, name, handler) => node.addEventListener(name, handler, { signal: listeners.signal });
const focus = root.querySelector('#reader-focus');
const content = root.querySelector('#reader-content');
const message = root.querySelector('#reader-update-status');
const apply = root.querySelector('#reader-apply-update');
const pause = root.querySelector('#reader-pause');
const loading = root.querySelector('#reader-loading');
const bookId = root.dataset.bookId;
const chapterId = root.dataset.chapterId;
let revision = root.dataset.revision;
let displayedVersion = root.dataset.version;
let observedVersion = displayedVersion;
let timer, request, busy = false, stopped = false, blocked = false, resumePending = false;
const interval = 12000;
const setFocus = enabled => {
root.dataset.focus = String(enabled);
document.body.classList.toggle('reader-focused', enabled);
focus.setAttribute('aria-pressed', String(enabled));
focus.textContent = enabled ? 'Exit focus reading' : 'Focus reading';
root.querySelector('input[name="focus"]').value = String(enabled);
root.querySelectorAll('a').forEach(link => {
const url = new URL(link.href);
if (url.origin === location.origin && url.pathname.replace(/\/$/, '').toLowerCase() === location.pathname.replace(/\/$/, '').toLowerCase()) {
if (enabled) url.searchParams.set('focus', 'true'); else url.searchParams.delete('focus');
link.href = url.href;
}
});
// Keep the current Reader URL consistent for reload/back without persisting focus outside it.
const url = new URL(location.href);
if (enabled) url.searchParams.set('focus', 'true'); else url.searchParams.delete('focus');
history.replaceState(history.state, '', url);
};
focus.addEventListener('click', () => setFocus(focus.getAttribute('aria-pressed') !== 'true'));
document.addEventListener('keydown', event => { if (event.key === 'Escape') setFocus(false); });
const loading = document.getElementById('reader-loading');
document.querySelector('.reader-controls form')?.addEventListener('submit', () => { loading.hidden = false; });
window.addEventListener('pageshow', () => { loading.hidden = true; });
focus.hidden = false;
setFocus(root.dataset.focus === 'true');
on(focus, 'click', () => setFocus(root.dataset.focus !== 'true'));
on(document, 'keydown', event => { if (event.key === 'Escape') setFocus(false); });
on(root.querySelector('.reader-controls form'), 'submit', () => { loading.hidden = false; stop(); });
on(root, 'click', event => {
if (event.target.closest('a') && !event.ctrlKey && !event.metaKey && !event.shiftKey && event.button === 0) stop();
});
const hasSelection = () => {
const selection = window.getSelection();
// A selection anywhere on the page is a reason to defer; extensions may select outside prose.
return selection && !selection.isCollapsed;
};
const pending = () => observedVersion !== displayedVersion;
const indicate = () => {
apply.hidden = !pending();
if (!pending()) message.textContent = pause.checked ? "Automatic updates paused." : "Checking for accepted chapter changes automatically.";
else message.textContent = hasSelection()
? 'Updated chapter available. It will appear after you clear the text selection.'
: pause.checked ? 'Updated chapter available. Automatic updates are paused.' : 'Updated chapter available.';
};
const viewportTop = () => root.dataset.focus === 'true' ? root.getBoundingClientRect().top : 0;
const rememberPosition = () => {
const top = viewportTop();
const rows = [...content.querySelectorAll('[data-paragraph-id]')];
const index = rows.findIndex(row => row.getBoundingClientRect().bottom > top);
if (index < 0) return null;
// Keep neighbours in case the currently visible paragraph is deleted by the accepted update.
return rows.slice(Math.max(0, index - 2), index + 3).map(row => ({
id: row.dataset.paragraphId, text: row.textContent, offset: row.getBoundingClientRect().top - top,
primary: row === rows[index]
})).sort((a, b) => Number(b.primary) - Number(a.primary));
};
const restorePosition = anchors => {
if (!anchors) return;
const rows = [...content.querySelectorAll('[data-paragraph-id]')];
for (const anchor of anchors) {
const row = rows.find(p => p.dataset.paragraphId === anchor.id) || rows.find(p => p.textContent === anchor.text);
if (!row) continue;
const delta = row.getBoundingClientRect().top - viewportTop() - anchor.offset;
if (root.dataset.focus === 'true') root.scrollBy({ top: delta, behavior: 'instant' });
else window.scrollBy({ top: delta, behavior: 'instant' });
break;
}
};
const fetchJson = async url => {
request = new AbortController();
const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal: request.signal });
if (response.redirected || [401, 403, 404].includes(response.status)) {
blocked = true;
throw new Error('access');
}
if (!response.ok) throw new Error('network');
return response.json();
};
const urlFor = endpoint => {
const url = new URL(endpoint, location.href);
url.searchParams.set('bookId', bookId); url.searchParams.set('chapterId', chapterId);
return url;
};
const render = data => {
const fragment = document.createDocumentFragment();
const article = document.createElement(data.paragraphs.length ? 'article' : 'section');
article.className = data.paragraphs.length ? 'reader-page' : 'reader-empty';
if (data.paragraphs.length) {
article.setAttribute('aria-label', 'Chapter manuscript');
// Preserve the existing canonical chapter identification and title when no captured heading exists.
const oldHeader = content.querySelector('.reader-page header');
const header = oldHeader ? oldHeader.cloneNode(true) : document.createElement('header');
if (!oldHeader) {
const label = document.createElement('p'); label.className = 'eyebrow';
label.textContent = 'Chapter ' + root.dataset.chapterNumber; header.append(label);
}
header.querySelector('h2')?.remove();
if (!data.paragraphs[0].isHeading) {
const title = document.createElement('h2'); title.textContent = data.title; header.append(title);
}
article.append(header);
data.paragraphs.forEach((paragraph, index) => {
const node = document.createElement(paragraph.isHeading ? index === 0 ? 'h2' : 'h3' : 'p');
node.className = 'reader-paragraph' + (paragraph.isHeading ? ' reader-heading' : '');
node.dataset.paragraphId = paragraph.id;
node.textContent = paragraph.text;
article.append(node);
});
} else {
article.setAttribute('role', 'status');
const title = document.createElement('h2'); title.textContent = data.title;
const text = document.createElement('p'); text.textContent = 'No accepted manuscript text is available for this chapter. Save and successfully synchronise it using Word Companion.';
article.append(title, text);
}
fragment.append(article);
return fragment;
};
const timestamps = data => {
const area = root.querySelector('#reader-timestamps');
const nodes = [];
for (const [label, value] of [['Last successful chapter synchronisation', data.lastSuccessfulSyncUtc], ['Accepted manuscript snapshot captured', data.snapshotCapturedUtc]]) {
const p = document.createElement('p');
if (value) {
p.append(label + ': ');
const time = document.createElement('time'); time.dateTime = value;
time.textContent = new Date(value).toLocaleString('en-GB', { timeZone: 'UTC', hour12: false }) + ' UTC';
p.append(time);
} else if (label.startsWith('Last')) p.textContent = 'No successful chapter synchronisation timestamp is recorded.';
else continue;
nodes.push(p);
}
area.replaceChildren(...nodes);
};
const update = async (force = false) => {
if (!pending() || pause.checked || hasSelection() || stopped || document.hidden) return;
const data = await fetchJson(urlFor(root.dataset.chapterUrl));
if (stopped || document.hidden || String(data.bookId) !== bookId || String(data.chapterId) !== chapterId) return;
revision = data.revision;
observedVersion = data.version;
if (!pending()) { apply.hidden = true; message.textContent = ''; return; }
if (pause.checked || hasSelection()) { indicate(); return; }
const anchors = rememberPosition();
// If no surviving anchor can preserve the reading session, offer the update instead.
if (!force && anchors && !anchors.some(a => data.paragraphs.some(p => p.id === a.id || p.text === a.text))) {
pause.checked = true; indicate(); return;
}
const fragment = render(data);
content.replaceChildren(fragment);
timestamps(data);
displayedVersion = data.version;
root.dataset.version = displayedVersion;
root.dataset.revision = revision;
restorePosition(anchors);
apply.hidden = true;
message.textContent = 'Chapter updated.';
};
const schedule = () => {
clearTimeout(timer);
if (!stopped && !blocked && !document.hidden && chapterId) timer = setTimeout(check, interval);
};
const finish = () => {
busy = false; request = null;
if (resumePending && !stopped && !document.hidden) { resumePending = false; void check(); }
else schedule();
};
const check = async () => {
if (busy || stopped || blocked || document.hidden || !chapterId) return;
clearTimeout(timer); busy = true;
try {
const url = urlFor(root.dataset.checkUrl);
url.searchParams.set('knownRevision', revision); url.searchParams.set('knownVersion', observedVersion);
const data = await fetchJson(url);
if (stopped || document.hidden) return;
revision = data.revision; observedVersion = data.version;
indicate();
await update();
} catch (error) {
if (error.name !== 'AbortError' && !stopped) message.textContent = blocked
? 'Updates stopped. Sign in again or reopen this chapter to check access.'
: 'Updates temporarily unavailable. Your chapter is retained; retrying automatically.';
} finally { finish(); }
};
const tryUpdate = async (force = false) => {
if (busy || stopped || blocked || document.hidden) return;
clearTimeout(timer); busy = true;
try { await update(force); }
catch (error) { if (error.name !== 'AbortError') message.textContent = 'Update could not be loaded. Retrying automatically.'; }
finally { finish(); }
};
const stop = () => { stopped = true; clearTimeout(timer); request?.abort(); };
root.readerCleanup = () => { stop(); listeners.abort(); };
on(document, 'selectionchange', () => { if (pending() && !hasSelection()) void tryUpdate(); });
on(pause, 'change', () => { indicate(); if (!pause.checked) void tryUpdate(); });
on(apply, 'click', () => { pause.checked = false; window.getSelection()?.removeAllRanges(); void tryUpdate(true); });
on(document, 'visibilitychange', () => {
clearTimeout(timer);
if (document.hidden) request?.abort();
else if (busy) resumePending = true; else void check();
});
on(window, 'online', () => { if (!busy) void check(); });
on(window, 'pagehide', stop);
on(window, 'pageshow', event => {
loading.hidden = true;
if (event.persisted) { stopped = false; root.scrollTop = 0; window.scrollTo({ top: 0, behavior: 'instant' }); void check(); }
});
if (chapterId) {
root.querySelector('.reader-live-controls').hidden = false;
void check();
}
})();