Add read-only chapter manuscript reader using accepted snapshots
This commit is contained in:
parent
ec5cf67596
commit
e67c6f9fb5
62
Docs/ManuscriptReader/Phase1.md
Normal file
62
Docs/ManuscriptReader/Phase1.md
Normal file
@ -0,0 +1,62 @@
|
||||
# Manuscript Reader — Phase 1
|
||||
|
||||
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
|
||||
|
||||
- GET `/manuscript/reader?bookId={id}&chapterId={id}`; chapterId is optional and defaults to the first active chapter.
|
||||
- `ManuscriptReaderService` separates retrieval/projection from the Razor paragraph partial and navigation controls. It calls the existing `IParagraphManuscriptRepository.Get(user, book)` / `dbo.ParagraphManuscript` get operation. That procedure checks active project access before any book metadata is fetched. Unknown/foreign books and cross-book chapter IDs return 404.
|
||||
- Only committed `BookParagraphManuscripts.Payload` is read. No preview, pending capture, live Word position, reconciliation operation, bootstrap or write method is invoked. A rejected transfer leaves this existing accepted snapshot visible. Position verification is intentionally not required for reading: it concerns live Word coordinates, not validity of saved prose.
|
||||
- Active chapters use existing `Chapter_ListByBook` ordering. Paragraphs use accepted heading windows and occurrence ordinal, retaining blank paragraphs and scene separators as well as prose. Canonical-zero section boundaries keep excluded sections outside chapter windows. Older or inconsistent boundary metadata falls back to explicit ChapterId assignments and the mapped heading; no boundaries are guessed. GUIDs remain in the projection for future reuse without appearing in the interface.
|
||||
- Only the selected chapter is rendered/sent to the browser. This phase reuses the existing whole-book JSON read on the server; large books still incur aggregate transfer/deserialization for each request. There is no browser preloading of the book, speculative caching, second manuscript store, new database object or schema migration.
|
||||
- Razor encodes prose as ordinary HTML text. Paragraphs retain captured whitespace with `white-space: pre-wrap`. Formatting absent from capture (emphasis, images, page layout and other Word objects) is not reconstructed. The captured opening chapter heading is retained verbatim without duplicating the title in the reading column.
|
||||
- GET-only controller, existing authentication, no-store responses and `X-Robots-Tag: noindex, nofollow, noarchive`. Database/JSON/timeout errors produce a generic 503 page with retry, without payloads or exception messages. No offline manuscript storage is provided.
|
||||
|
||||
## Timestamp meanings
|
||||
|
||||
**Last successful chapter synchronisation** comes directly from the selected chapter's persisted `ChapterCheckpoints[].LastSuccessfulSyncUtc`. The existing chapter validation contract records this after successful evidence acceptance, including unchanged-text validation. It is not a claim that the prose changed at that moment. If absent, the Reader explicitly says it is not recorded.
|
||||
|
||||
**Accepted manuscript snapshot captured** comes from persisted `ParagraphManuscript.UpdatedUtc`, set by bootstrap/full snapshot or chapter reconciliation. It is a book-snapshot capture time, not an invented chapter-specific sync time or the database row's UpdatedUtc (which also changes for preferences). Chapter-only unchanged validation may update its checkpoint without changing this capture time. All displayed times explicitly use UTC, to the second. A failed/pending transfer cannot supply either displayed value.
|
||||
|
||||
## Verification
|
||||
|
||||
Run serially:
|
||||
|
||||
```sh
|
||||
dotnet build PlotLine.slnx
|
||||
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj
|
||||
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --chapter-sync
|
||||
```
|
||||
|
||||
Focused Reader tests are also available with `--manuscript-reader`.
|
||||
|
||||
For browser checks, start the existing isolated fixture host (synthetic manuscript, no database connection):
|
||||
|
||||
```sh
|
||||
PD_BROWSER_FIXTURE_URL=http://127.0.0.1:5249 dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --toolbar-browser-host
|
||||
PD_BROWSER_FIXTURE_URL=http://127.0.0.1:5249 node PlotLine.Tests/Browser/manuscript-reader.cjs
|
||||
```
|
||||
|
||||
The browser suite exercises the real controller and compiled Razor, three viewport widths (390/800/1440), all four application themes, browser and simulated installed-PWA modes, safe HTML-like text, DOM text selection, navigation/selector, empty state, UTC timestamps, focus/Escape, account/book isolation, private headers, GET-only routing and generic error/retry. PWA simulation does not constitute a Windows installed-app acceptance test. Tests use normal DOM Range selection; ElevenReader itself is not integrated or tested.
|
||||
|
||||
### Results — 13 November 2026
|
||||
|
||||
- Solution build: passed, zero warnings/errors. Full executable regression harness: passed, including Reader and existing paragraph synchronisation workflows.
|
||||
- Dedicated chapter synchronisation regression: passed.
|
||||
- Chromium suite: passed all 24 viewport/theme/browser-or-PWA combinations, plus isolation and error/retry checks. Desktop and phone screenshots were visually inspected during development.
|
||||
- Read-only live Development check: verified the effective database, retrieved first/middle/last chapters (537 paragraphs) from an existing accepted manuscript, refused an unrelated account, and confirmed the accepted revision and snapshot hash were unchanged. An earlier check traversed all 48 chapters. No author prose was exported or database state modified.
|
||||
- Actual Word editing/saving and a real installed Windows PWA were unavailable on Atlas. The end-to-end scenario below remains unverified.
|
||||
|
||||
## Windows Word-to-Reader acceptance still required
|
||||
|
||||
1. On Windows, open the existing bound manuscript in Word using the current Companion; no new installer is required for Reader use.
|
||||
2. Add a small identifiable phrase within an existing chapter, save, and wait for a successful Companion acknowledgement. Record the acknowledged chapter and UTC time.
|
||||
3. On a separate browser/device, open the same book and choose **Read manuscript**, then the changed chapter. Refresh if already open. Confirm the exact phrase and paragraph position.
|
||||
4. Compare the chapter synchronisation timestamp with the successful acceptance (including seconds/UTC); the separately labelled snapshot capture time has the meaning described above.
|
||||
5. Drag-select multiple paragraphs and copy/paste them into a plain-text document. Optionally try the author's normal reading extension. Confirm paragraph order and literal angle-bracket text where present.
|
||||
6. Use previous/next and the chapter selector, then return. Repeat on mobile and the installed desktop PWA in the desired theme.
|
||||
7. Confirm Word text and Companion accepted revision remain unchanged by Reader navigation. Do not use the Reader to trigger sync; it has no mutation action.
|
||||
|
||||
## Deployment
|
||||
|
||||
Normal development application deployment is needed to expose the new route and assets. No SQL migration, configuration change or Companion installer is needed. This implementation does not deploy or change Production.
|
||||
61
PlotLine.Tests/Browser/manuscript-reader.cjs
Normal file
61
PlotLine.Tests/Browser/manuscript-reader.cjs
Normal file
@ -0,0 +1,61 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { chromium } = require('playwright');
|
||||
const base = process.env.PD_BROWSER_FIXTURE_URL || 'http://127.0.0.1:5238';
|
||||
(async () => {
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
for (const pwa of [false, true]) for (const width of [390, 800, 1440]) {
|
||||
const context = await browser.newContext({viewport:{width,height:1000}});
|
||||
if(pwa) await context.addInitScript(() => Object.defineProperty(navigator, 'standalone', {value:true}));
|
||||
const page = await context.newPage();
|
||||
for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']) {
|
||||
const response = await page.goto(`${base}/manuscript/reader?bookId=12&chapterId=21`);
|
||||
assert.equal(response.status(),200);
|
||||
assert.match(response.headers()['cache-control'],/no-store/);
|
||||
assert.match(response.headers()['x-robots-tag'],/noindex/);
|
||||
await page.evaluate(theme => PlotDirectorApplyApplicationTheme(theme), theme);
|
||||
const paragraphs = page.locator('.reader-paragraph');
|
||||
assert.equal(await paragraphs.count(),3);
|
||||
assert.match(await paragraphs.nth(1).textContent(), /First paragraph: <script>unsafe\(\)<\/script>/);
|
||||
assert.equal(await page.locator('.reader-page script').count(),0);
|
||||
assert.match(await paragraphs.nth(2).textContent(),/Second paragraph/);
|
||||
assert.equal(await page.locator('.reader-page').evaluate(node => getComputedStyle(node).userSelect),'auto');
|
||||
const selected = await page.locator('.reader-page').evaluate(node => {
|
||||
const range = document.createRange(); range.selectNodeContents(node);
|
||||
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); return selection.toString();
|
||||
});
|
||||
assert.match(selected,/First paragraph/); assert.match(selected,/Second paragraph/);
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'No horizontal overflow');
|
||||
const box = await page.locator('.reader-page').boundingBox(); assert.ok(box.width <= 740,'Reading column bounded');
|
||||
assert.ok(await page.locator('time').first().getAttribute('datetime') === '2026-11-13T10:12:13Z');
|
||||
await page.getByRole('button',{name:'Focus reading',exact:true}).click();
|
||||
assert.equal(await page.locator('body').evaluate(n=>n.classList.contains('reader-focused')),true);
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.getByRole('button',{name:'Focus reading',exact:true}).getAttribute('aria-pressed'),'false');
|
||||
await page.getByRole('link',{name:'Next chapter →',exact:true}).click();
|
||||
await page.waitForURL(/chapterId=22/);
|
||||
assert.match(await page.locator('.reader-page').textContent(),/Another chapter only/);
|
||||
assert.doesNotMatch(await page.locator('.reader-page').textContent(),/First paragraph/);
|
||||
await page.getByLabel('Chapter',{exact:true}).selectOption('23');
|
||||
await page.getByRole('button',{name:'Read',exact:true}).click();
|
||||
await page.waitForURL(/chapterId=23/);
|
||||
assert.match(await page.locator('.reader-empty').textContent(),/No accepted manuscript text/);
|
||||
assert.equal(await page.getByRole('link',{name:'Next chapter →',exact:true}).count(),0);
|
||||
await page.getByRole('link',{name:'← Previous chapter',exact:true}).click();
|
||||
await page.waitForURL(/chapterId=22/);
|
||||
}
|
||||
await context.addCookies([{name:'fixture-user',value:'5',url:base}]);
|
||||
assert.equal((await page.goto(`${base}/manuscript/reader?bookId=12&chapterId=21`)).status(),404);
|
||||
await context.clearCookies();
|
||||
assert.equal((await page.goto(`${base}/manuscript/reader?bookId=13&chapterId=21`)).status(),404);
|
||||
assert.equal((await page.goto(`${base}/manuscript/reader?bookId=12&chapterId=999`)).status(),404);
|
||||
const unavailable = await page.goto(`${base}/manuscript/reader?bookId=12&chapterId=21&reader-error=true`);
|
||||
assert.equal(unavailable.status(),503);
|
||||
assert.equal(await page.getByRole('link',{name:'Retry',exact:true}).count(),1);
|
||||
assert.doesNotMatch(await page.locator('body').textContent(),/First paragraph|Synthetic unavailable/);
|
||||
const post = await context.request.post(`${base}/manuscript/reader?bookId=12`); assert.equal(post.status(),405);
|
||||
await context.close();
|
||||
}
|
||||
console.log('PASS Manuscript Reader: real Razor/controller, escaped selectable text, chapter navigation, empty state, timestamps, private headers, account isolation, GET-only, focus, 3 widths × 4 themes × browser/PWA');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => { console.error(error);process.exitCode=1; });
|
||||
84
PlotLine.Tests/ManuscriptReaderTests.cs
Normal file
84
PlotLine.Tests/ManuscriptReaderTests.cs
Normal file
@ -0,0 +1,84 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using PlotDirector.Companion.Protocol.Manuscript;
|
||||
|
||||
internal static class ManuscriptReaderTests
|
||||
{
|
||||
internal static readonly Chapter[] Chapters = [
|
||||
new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" },
|
||||
new() { ChapterID = 22, BookID = 12, ChapterNumber = 2, ChapterTitle = "Arrival" },
|
||||
new() { ChapterID = 23, BookID = 12, ChapterNumber = 3, ChapterTitle = "Unwritten" }
|
||||
];
|
||||
internal static ParagraphManuscript Snapshot()
|
||||
{
|
||||
var heading = Guid.NewGuid();
|
||||
return new() {
|
||||
BookId = 12, UpdatedUtc = new DateTime(2026, 11, 13, 10, 11, 12, DateTimeKind.Utc),
|
||||
Chapters = [new() { CanonicalId = 21, HeadingId = heading }],
|
||||
ChapterCheckpoints = [new() { ChapterId = 21, LastSuccessfulSyncUtc = new DateTime(2026, 11, 13, 10, 12, 13, DateTimeKind.Utc) }],
|
||||
Paragraphs = [
|
||||
new() { ChapterId = 21, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 2, Text = "Second paragraph.\r", Outline = 10 } },
|
||||
new() { ChapterId = 21, Story = false, Occurrence = new() { Id = heading, Ordinal = 0, Text = "The crossing\r", Outline = 1 } },
|
||||
new() { ChapterId = 21, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 1, Text = "First paragraph: <script>unsafe()</script> & <b>plain text</b>.\r", Outline = 10 } },
|
||||
new() { ChapterId = 22, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 3, Text = "Another chapter only.\r", Outline = 10 } },
|
||||
new() { ChapterId = null, Story = false, Occurrence = new() { Ordinal = 4, Text = "Excluded section." } }
|
||||
]
|
||||
};
|
||||
}
|
||||
internal static ManuscriptReaderService FixtureService(Func<ParagraphManuscript?>? snapshot = null)
|
||||
{
|
||||
var repository = NativeWorkflowTests.Proxy<IParagraphManuscriptRepository>((name, args) => {
|
||||
if (name != "Get") 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());
|
||||
});
|
||||
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));
|
||||
return new(repository, books, chapters);
|
||||
}
|
||||
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 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");
|
||||
Check(first.Paragraphs.Select(p => p.Text).SequenceEqual(state.Paragraphs.OrderBy(p => p.Occurrence.Ordinal).Take(3).Select(p => p.Occurrence.Text)), "Exact accepted paragraph order, heading and boundaries");
|
||||
Check(first.Paragraphs.All(p => p.Id != Guid.Empty), "Paragraph identities retained internally");
|
||||
Check(first.LastSuccessfulSyncUtc == state.ChapterCheckpoints[0].LastSuccessfulSyncUtc && first.SnapshotCapturedUtc == state.UpdatedUtc, "Distinct exact timestamp sources");
|
||||
var last = (await service.Read(4, 12, 23))!;
|
||||
Check(last.PreviousId == 22 && last.NextId is null && last.Paragraphs.Count == 0, "Last chapter navigation and empty state");
|
||||
Check(await service.Read(4, 12, 999) is null, "Cross-book or unknown chapter rejected");
|
||||
try { await service.Read(5, 12, 21); throw new Exception("Foreign account retrieved manuscript"); } catch (UnauthorizedAccessException) { }
|
||||
try { await service.Read(4, 13, 21); throw new Exception("Foreign book retrieved manuscript"); } catch (UnauthorizedAccessException) { }
|
||||
var windows = Snapshot();
|
||||
windows.Paragraphs = windows.Paragraphs.OrderBy(p => p.Occurrence.Ordinal).Take(4).ToList();
|
||||
windows.Chapters.Add(new() { CanonicalId = 22, HeadingId = windows.Paragraphs[3].Occurrence.Id });
|
||||
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 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");
|
||||
state = pending;
|
||||
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");
|
||||
var user = NativeWorkflowTests.Proxy<ICurrentUserService>((_, _) => 5);
|
||||
var controller = new ManuscriptReaderController(service, user, NullLogger<ManuscriptReaderController>.Instance) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } };
|
||||
Check(await controller.Index(12, 21) is NotFoundResult, "Controller does not leak unauthorised book existence");
|
||||
Check(typeof(ManuscriptReaderController).IsDefined(typeof(AuthorizeAttribute), true), "Reader requires authentication");
|
||||
var cache = (ResponseCacheAttribute)System.Attribute.GetCustomAttribute(typeof(ManuscriptReaderController), typeof(ResponseCacheAttribute))!;
|
||||
Check(cache.NoStore && cache.Location == ResponseCacheLocation.None, "Private manuscript responses cannot be cached");
|
||||
Check(controller.Response.Headers["X-Robots-Tag"] == "noindex, nofollow, noarchive", "Manuscript indexing disabled");
|
||||
Console.WriteLine("PASS Manuscript Reader: scoped read-only retrieval, ordering, navigation, empty snapshot, accepted updates, pending isolation and accurate timestamps");
|
||||
}
|
||||
}
|
||||
@ -18,6 +18,7 @@ using PlotLine.ViewModels;
|
||||
if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev")||args.Contains("--chapter-incremental-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;}
|
||||
if(args.Contains("--manuscript-reader")){await ManuscriptReaderTests.Run();return;}
|
||||
#pragma warning disable CS8321
|
||||
|
||||
if (args.Contains("--word-marker-security"))
|
||||
@ -154,6 +155,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Release triage and browser-only onboarding preserve author decisions", ReleaseSprintTests.Run),
|
||||
("Approved native import source and confirmation remain safe", () => NativeImportTests.Run().GetAwaiter().GetResult()),
|
||||
("Native installation renewal and revocation remain account/security scoped", () => NativeInstallationTests.Run().GetAwaiter().GetResult()),
|
||||
("Manuscript Reader", () => ManuscriptReaderTests.Run().GetAwaiter().GetResult()),
|
||||
("Paragraph manuscript identity, evidence and exact-session synchronisation", () => { ParagraphManuscriptTests.Run();ParagraphWorkflowTests.Run().GetAwaiter().GetResult(); }),
|
||||
("Native wizard capture is scoped, durable and independent of Word", () => NativeManuscriptCaptureTests.Run().GetAwaiter().GetResult()),
|
||||
("Native tray presence and PWA review remain scoped, expiring and non-destructive", () => NativeTrayIntegrationTests.Run().GetAwaiter().GetResult()),
|
||||
|
||||
@ -117,6 +117,9 @@ internal static class ToolbarBrowserHost
|
||||
builder.Services.AddSingleton(FixtureProxy<IManuscriptScanPreviewStore>((name, args) => throw new NotSupportedException(name)));
|
||||
|
||||
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()));
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
|
||||
builder.Services.AddScoped<ApplicationNavigation>(services => new ApplicationNavigation(
|
||||
|
||||
36
PlotLine/Controllers/ManuscriptReaderController.cs
Normal file
36
PlotLine/Controllers/ManuscriptReaderController.cs
Normal file
@ -0,0 +1,36 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Services.Manuscript;
|
||||
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
[Route("manuscript/reader")]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
public sealed class ManuscriptReaderController(ManuscriptReaderService reader, ICurrentUserService currentUser,
|
||||
ILogger<ManuscriptReaderController> logger) : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Index(int bookId, int? chapterId = null)
|
||||
{
|
||||
Response.Headers["X-Robots-Tag"] = "noindex, nofollow, noarchive";
|
||||
if (currentUser.UserId is not int user) return Challenge();
|
||||
if (bookId <= 0 || chapterId is <= 0) return NotFound();
|
||||
try
|
||||
{
|
||||
var model = await reader.Read(user, bookId, chapterId);
|
||||
return model is null ? NotFound() : View(model);
|
||||
}
|
||||
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)
|
||||
{
|
||||
// Log neither SQL error text nor payloads: manuscripts are private content.
|
||||
logger.LogWarning("Manuscript Reader unavailable ({FailureKind}).", e.GetType().Name);
|
||||
Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
return View("Unavailable", new { BookId = bookId, ChapterId = chapterId });
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -113,6 +113,7 @@ public class Program
|
||||
builder.Services.AddHostedService<PlotLine.Services.NativeCompanion.NativeCaptureExpiry>();
|
||||
builder.Services.AddScoped<IManuscriptCaptureRepository, ManuscriptCaptureRepository>();
|
||||
builder.Services.AddScoped<IParagraphManuscriptRepository,ParagraphManuscriptRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Manuscript.ManuscriptReaderService>();
|
||||
builder.Services.AddScoped<IChapterSyncRepository,ChapterSyncRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Manuscript.ChapterSyncService>();
|
||||
builder.Services.AddScoped<PlotLine.Services.Manuscript.ParagraphManuscriptService>();
|
||||
|
||||
@ -15,7 +15,7 @@ public sealed class ApplicationNavigation(IProjectRepository projects, IBookRepo
|
||||
var controller = request.RouteValues["controller"]?.ToString() ?? string.Empty;
|
||||
var result = new ApplicationNavigationViewModel { ActiveSection = section ?? controller switch
|
||||
{
|
||||
"Projects" or "Books" or "Chapters" or "Scenes" => "Overview",
|
||||
"Projects" or "Books" or "Chapters" or "Scenes" or "ManuscriptReader" => "Overview",
|
||||
"StoryCalendar" => "Calendar", "StoryPoint" => "At This Point",
|
||||
"RelationshipMap" => "Relationships", "StoryAssets" => "Assets",
|
||||
"FloorPlans" => "Floor Plans", "PlotThreads" => "Threads", "PlotLineWorkspace" => "Plot Lines",
|
||||
|
||||
73
PlotLine/Services/Manuscript/ManuscriptReaderService.cs
Normal file
73
PlotLine/Services/Manuscript/ManuscriptReaderService.cs
Normal file
@ -0,0 +1,73 @@
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models;
|
||||
|
||||
namespace PlotLine.Services.Manuscript;
|
||||
|
||||
public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading);
|
||||
public sealed class ManuscriptReaderModel
|
||||
{
|
||||
public required Book Book { get; init; }
|
||||
public required IReadOnlyList<Chapter> Chapters { get; init; }
|
||||
public Chapter? Chapter { get; init; }
|
||||
public int? PreviousId { get; init; }
|
||||
public int? NextId { get; init; }
|
||||
public IReadOnlyList<ReaderParagraph> Paragraphs { get; init; } = [];
|
||||
public DateTime? LastSuccessfulSyncUtc { get; init; }
|
||||
public DateTime? SnapshotCapturedUtc { get; init; }
|
||||
}
|
||||
|
||||
// Read only: deliberately bypasses the manuscript workspace, which may bootstrap tracking.
|
||||
public sealed class ManuscriptReaderService(
|
||||
IParagraphManuscriptRepository manuscripts, IBookRepository books, IChapterRepository chapters)
|
||||
{
|
||||
public async Task<ManuscriptReaderModel?> Read(int user, int bookId, int? chapterId)
|
||||
{
|
||||
// This existing stored procedure checks active ProjectUserAccess before returning any data,
|
||||
// even when no paragraph snapshot exists. Never fetch book metadata before this check.
|
||||
var state = await manuscripts.Get(user, bookId);
|
||||
var book = await books.GetAsync(bookId);
|
||||
if (book is null || book.IsArchived) return null;
|
||||
var ordered = (await chapters.ListByBookAsync(bookId)).Where(c => !c.IsArchived).ToArray();
|
||||
var selected = chapterId.HasValue ? ordered.FirstOrDefault(c => c.ChapterID == chapterId) : ordered.FirstOrDefault();
|
||||
if (chapterId.HasValue && selected is null) return null;
|
||||
return Project(book, ordered, selected, state);
|
||||
}
|
||||
|
||||
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);
|
||||
var heading = state?.Chapters.FirstOrDefault(c => c.CanonicalId == selected?.ChapterID)?.HeadingId;
|
||||
// Accepted assignments, not live Word positions, govern reading. Position verification may
|
||||
// expire or need review without invalidating the last committed prose.
|
||||
IEnumerable<StoryParagraph> source = state?.Paragraphs.Where(p =>
|
||||
selected is not null && (p.ChapterId == selected.ChapterID || p.Occurrence.Id == heading)) ?? [];
|
||||
if (state is not null && selected is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Exact accepted heading windows also retain unassigned blank paragraphs and
|
||||
// scene separators. Excluded sections have their own canonical-zero boundary.
|
||||
var part = ChapterCheckpointEngine.Parts(state).FirstOrDefault(p => p.Chapter.CanonicalId == selected.ChapterID);
|
||||
if (part is not null && !part.Rows.Any(p => p.ChapterId > 0 && p.ChapterId != selected.ChapterID))
|
||||
source = part.Rows;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Older accepted snapshots can lack reversible heading windows. Use only their
|
||||
// explicit chapter assignments; never guess boundaries from prose or Word offsets.
|
||||
}
|
||||
}
|
||||
var rows = source.OrderBy(p => p.Occurrence.Ordinal)
|
||||
.Select(p => new ReaderParagraph(p.Occurrence.Id, p.Occurrence.Text, p.Occurrence.Id == heading || p.Occurrence.Outline is >= 1 and <= 6))
|
||||
.ToArray();
|
||||
var checkpoint = state?.ChapterCheckpoints.FirstOrDefault(c => c.ChapterId == selected?.ChapterID);
|
||||
return new()
|
||||
{
|
||||
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,
|
||||
LastSuccessfulSyncUtc = checkpoint?.LastSuccessfulSyncUtc > DateTime.MinValue ? checkpoint.LastSuccessfulSyncUtc : null,
|
||||
SnapshotCapturedUtc = state?.UpdatedUtc > DateTime.MinValue ? state.UpdatedUtc : null
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -178,6 +178,7 @@
|
||||
|
||||
<section class="list-section">
|
||||
<h2>Chapters <help-icon key="books.chapters" /></h2>
|
||||
<a class="btn btn-outline-secondary" asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@Model.Book.BookID">Read manuscript</a>
|
||||
@if (!Model.Chapters.Any())
|
||||
{
|
||||
<p class="muted">No chapters yet.</p>
|
||||
@ -212,6 +213,7 @@
|
||||
<td role="cell" class="chapter-manuscript"><span class="status-pill">@(chapter.IsLinkedToManuscript ? "🔗 Linked" : "📝 Planned")</span></td>
|
||||
<td role="cell" class="chapter-summary">@chapter.Summary</td>
|
||||
<td role="cell" class="chapter-actions text-end">
|
||||
<a class="btn btn-outline-secondary btn-sm" asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@chapter.ChapterID">Read manuscript</a>
|
||||
<a class="btn btn-outline-secondary btn-sm" asp-controller="Chapters" asp-action="Edit" asp-route-id="@chapter.ChapterID">Edit</a>
|
||||
<form asp-controller="Chapters" asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this chapter? This will hide it from active lists and timelines, but the data will be kept and can be restored later.">
|
||||
<input type="hidden" name="id" value="@chapter.ChapterID" />
|
||||
|
||||
@ -30,6 +30,7 @@
|
||||
/ <a asp-controller="Books" asp-action="Details" asp-route-id="@Model.Book.BookID">@Model.Book.BookTitle</a>
|
||||
</p>
|
||||
<h1>Chapter @Model.Chapter.ChapterNumber: @Model.Chapter.ChapterTitle <help-icon key="chapters.overview" /></h1>
|
||||
<a class="btn btn-outline-secondary" asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@Model.Book.BookID" asp-route-chapterId="@Model.Chapter.ChapterID">Read manuscript</a>
|
||||
<span class="status-pill">@(Model.Chapter.IsLinkedToManuscript ? "🔗 Linked" : "📝 Planned")</span>
|
||||
@if (!string.IsNullOrWhiteSpace(Model.Chapter.ChapterPurposeName))
|
||||
{
|
||||
|
||||
64
PlotLine/Views/ManuscriptReader/Index.cshtml
Normal file
64
PlotLine/Views/ManuscriptReader/Index.cshtml
Normal file
@ -0,0 +1,64 @@
|
||||
@model PlotLine.Services.Manuscript.ManuscriptReaderModel
|
||||
@{
|
||||
ViewData["Title"] = $"Manuscript Reader · {Model.Book.BookTitle}";
|
||||
ViewData["DesktopLayout"] = "details";
|
||||
}
|
||||
<link rel="stylesheet" href="~/css/manuscript-reader.css" asp-append-version="true" />
|
||||
<div class="manuscript-reader">
|
||||
<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>
|
||||
</nav>
|
||||
<header data-pwa-header class="page-heading">
|
||||
<div><p class="eyebrow">@Model.Book.BookTitle</p><h1>Manuscript Reader</h1><span class="status-pill">Read only</span></div>
|
||||
</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> }
|
||||
else { <span class="btn btn-outline-secondary disabled" aria-disabled="true">← Previous chapter</span> }
|
||||
<form method="get" asp-action="Index">
|
||||
<input type="hidden" name="bookId" value="@Model.Book.BookID" />
|
||||
<label for="reader-chapter">Chapter</label>
|
||||
<select id="reader-chapter" name="chapterId" class="form-select">
|
||||
@foreach (var chapter in Model.Chapters)
|
||||
{ <option value="@chapter.ChapterID" selected="@(chapter.ChapterID == Model.Chapter?.ChapterID)">@chapter.ChapterNumber: @chapter.ChapterTitle</option> }
|
||||
</select>
|
||||
<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> }
|
||||
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>
|
||||
</nav>
|
||||
<p class="reader-status" role="status" id="reader-loading" hidden>Loading chapter…</p>
|
||||
<div class="reader-status muted">
|
||||
@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>
|
||||
</div>
|
||||
@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>
|
||||
</section>
|
||||
}
|
||||
else
|
||||
{
|
||||
<article class="reader-page" aria-label="Chapter manuscript">
|
||||
<header><p class="eyebrow">Chapter @Model.Chapter?.ChapterNumber</p>
|
||||
@if (!Model.Paragraphs[0].IsHeading)
|
||||
{ <h2>@Model.Chapter?.ChapterTitle</h2> }
|
||||
</header>
|
||||
<partial name="_Paragraphs" model="Model.Paragraphs" />
|
||||
</article>
|
||||
}
|
||||
<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>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="~/js/manuscript-reader.js" asp-append-version="true" defer></script>
|
||||
9
PlotLine/Views/ManuscriptReader/Unavailable.cshtml
Normal file
9
PlotLine/Views/ManuscriptReader/Unavailable.cshtml
Normal file
@ -0,0 +1,9 @@
|
||||
@{
|
||||
ViewData["Title"] = "Manuscript Reader unavailable";
|
||||
}
|
||||
<section class="list-section" role="alert">
|
||||
<h1>Manuscript could not be loaded</h1>
|
||||
<p>The server could not retrieve the accepted text. Please try again.</p>
|
||||
<a class="btn btn-primary" href="@Context.Request.Path@Context.Request.QueryString">Retry</a>
|
||||
<a class="btn btn-outline-secondary" asp-controller="Projects" asp-action="Index">Projects</a>
|
||||
</section>
|
||||
11
PlotLine/Views/ManuscriptReader/_Paragraphs.cshtml
Normal file
11
PlotLine/Views/ManuscriptReader/_Paragraphs.cshtml
Normal file
@ -0,0 +1,11 @@
|
||||
@model IReadOnlyList<PlotLine.Services.Manuscript.ReaderParagraph>
|
||||
@for (var index = 0; index < Model.Count; index++)
|
||||
{
|
||||
var paragraph = Model[index];
|
||||
if (paragraph.IsHeading && index == 0)
|
||||
{ <h2 class="reader-paragraph reader-heading">@paragraph.Text</h2> }
|
||||
else if (paragraph.IsHeading)
|
||||
{ <h3 class="reader-paragraph reader-heading">@paragraph.Text</h3> }
|
||||
else
|
||||
{ <p class="reader-paragraph">@paragraph.Text</p> }
|
||||
}
|
||||
@ -51,12 +51,13 @@
|
||||
@if (project is not null)
|
||||
{
|
||||
<li class="nav-item dropdown">
|
||||
<button class="nav-link dropdown-toggle @(controller is "Books" or "Chapters" or "Scenes" ? "active" : null)" type="button" id="appBookMenu" data-bs-toggle="dropdown" aria-expanded="false" title="@(book?.BookDisplayTitle ?? "Book")">
|
||||
<button class="nav-link dropdown-toggle @(controller is "Books" or "Chapters" or "Scenes" or "ManuscriptReader" ? "active" : null)" type="button" id="appBookMenu" data-bs-toggle="dropdown" aria-expanded="false" title="@(book?.BookDisplayTitle ?? "Book")">
|
||||
<span class="app-context-label app-book-label" data-app-book-label>@(book?.BookDisplayTitle ?? "Book")</span>
|
||||
</button>
|
||||
<ul class="dropdown-menu app-book-menu" aria-labelledby="appBookMenu">
|
||||
<li><h2 class="dropdown-header" data-app-book-heading>@(book?.BookDisplayTitle ?? "Books in this project")</h2></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-book-url="@Url.Action("Details", "Books", new { id = (int?)null })" asp-controller="Books" asp-action="Details" asp-route-id="@book?.BookID">Book overview</a></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-book-url="@Url.Action("Index", "ManuscriptReader")" data-app-book-param="bookId" asp-controller="ManuscriptReader" asp-action="Index" asp-route-bookId="@book?.BookID">Read manuscript</a></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-book-url="@Url.Action("Edit", "Books", new { id = (int?)null })" asp-controller="Books" asp-action="Edit" asp-route-id="@book?.BookID">Edit book</a></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-book-url="@Url.Action("Create", "Chapters", new { id = (int?)null })" data-app-book-param="bookId" asp-controller="Chapters" asp-action="Create" asp-route-bookId="@book?.BookID">Add chapter</a></li>
|
||||
<li hidden="@(book is null)" data-app-book-action><a class="dropdown-item" data-app-review-link data-review-url="@Url.Action("StoryIntelligenceBookReviewCentre", "Onboarding", new { bookId = 0 })" asp-controller="Onboarding" asp-action="StoryIntelligenceBookReviewCentre" asp-route-bookId="@book?.BookID">Review Centre</a></li>
|
||||
|
||||
16
PlotLine/wwwroot/css/manuscript-reader.css
Normal file
16
PlotLine/wwwroot/css/manuscript-reader.css
Normal file
@ -0,0 +1,16 @@
|
||||
.manuscript-reader { color: var(--plotline-ink); }
|
||||
.reader-controls { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; margin-block: 1.5rem; }
|
||||
.reader-controls form { display: flex; align-items: center; flex-wrap: wrap; gap: .5rem; flex: 1; }
|
||||
.reader-controls select { width: auto; max-width: 100%; flex: 1; min-width: 10rem; }
|
||||
.reader-status { font-size: .9rem; margin-block: 1.5rem; }
|
||||
.reader-status p { margin-block: .35rem; }
|
||||
.reader-status a { display: inline-block; margin-inline-end: 1rem; }
|
||||
.reader-page, .reader-empty { max-width: 46rem; margin: 2rem auto; padding: clamp(1rem, 4vw, 3rem); background: var(--plotline-panel); border: 1px solid var(--plotline-line); border-radius: .6rem; }
|
||||
.reader-page { font-family: Georgia, 'Times New Roman', serif; font-size: clamp(1.1rem, 1rem + .35vw, 1.25rem); line-height: 1.85; overflow-wrap: anywhere; }
|
||||
.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; }
|
||||
@media (max-width: 600px) { .reader-controls form { order: -1; flex-basis: 100%; } .reader-page { margin-block: 1rem; } }
|
||||
15
PlotLine/wwwroot/js/manuscript-reader.js
Normal file
15
PlotLine/wwwroot/js/manuscript-reader.js
Normal file
@ -0,0 +1,15 @@
|
||||
(() => {
|
||||
const focus = document.getElementById('reader-focus');
|
||||
if (!focus) return;
|
||||
focus.hidden = false;
|
||||
const setFocus = enabled => {
|
||||
document.body.classList.toggle('reader-focused', enabled);
|
||||
focus.setAttribute('aria-pressed', String(enabled));
|
||||
focus.textContent = enabled ? 'Exit focus reading' : 'Focus reading';
|
||||
};
|
||||
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; });
|
||||
})();
|
||||
Loading…
x
Reference in New Issue
Block a user