Integrate editorial annotations and direct notes in Review and consolidate Reflect history

This commit is contained in:
Nick Beckley 2026-11-18 21:19:13 +00:00
parent fb537cd4e8
commit 9d397c0ae3
14 changed files with 174 additions and 60 deletions

View File

@ -20,16 +20,18 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
return model is null ? NotFound() : View("Edit", model);
}
public async Task<IActionResult> Edit(int id)
public async Task<IActionResult> Edit(int id,string? returnUrl=null)
{
ViewData["ReturnUrl"]=Url.IsLocalUrl(returnUrl)?returnUrl:null;
var model = await chapters.GetEditAsync(id);
return model is null ? NotFound() : View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Save(ChapterEditViewModel model)
public async Task<IActionResult> Save(ChapterEditViewModel model,string? returnUrl=null)
{
ViewData["ReturnUrl"]=Url.IsLocalUrl(returnUrl)?returnUrl:null;
if (!ModelState.IsValid)
{
return View("Edit", model);
@ -57,7 +59,7 @@ public sealed class ChaptersController(IChapterService chapters) : Controller
return View("Edit", createModel);
}
return RedirectToAction(nameof(Details), new { id = chapterId });
return Url.IsLocalUrl(returnUrl)?LocalRedirect(returnUrl!):RedirectToAction(nameof(Details), new { id = chapterId });
}
[HttpPost]

View File

@ -13,12 +13,17 @@ public sealed class ReviewObservation
public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;}public string? AnchorHash{get;set;}public int? SceneID{get;set;}
public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open";public int Version{get;set;}public DateTime CreatedUtc{get;set;}public DateTime UpdatedUtc{get;set;}
public string AnchorState{get;set;}="Chapter";
public string? Scope{get;set;}public string? Classification{get;set;}
public string EffectiveScope=>Scope??(StartParagraph.HasValue?"Passage":"Chapter");
public string EffectiveClassification=>Classification??"Observation";
}
public sealed class ReviewSave
{
public int BookID{get;set;}public int ChapterID{get;set;}public Guid ID{get;set;}public int Version{get;set;}
public string ContentVersion{get;set;}="";public Guid? StartParagraph{get;set;}public Guid? EndParagraph{get;set;}public int? StartOffset{get;set;}public int? EndOffset{get;set;}
public string Observation{get;set;}="";public string? Decision{get;set;}public string Status{get;set;}="Open";
public string Scope{get;set;}="";public string Classification{get;set;}="Observation";public int? SceneID{get;set;}
public static readonly string[] Classifications=["Observation","Revision needed","Continuity","Research","Character","Plot","Pacing","Reminder","General note"];
}
public sealed record ReviewPanel(WriterAuthoringPage Intentions,IReadOnlyList<ReviewObservation> Observations,int Page,bool HasMore,string ReferenceMessage);
public interface IWriterReviewService
@ -29,7 +34,7 @@ public interface IWriterReviewService
public sealed class WriterReviewService(ISqlConnectionFactory factory,ManuscriptReaderService reader,IWriterAuthoringService intentions):IWriterReviewService
{
public static string Hash(IEnumerable<ReaderParagraph> paragraphs){using var buffer=new MemoryStream();using(var writer=new BinaryWriter(buffer,Encoding.UTF8,true))foreach(var p in paragraphs){writer.Write(p.Id.ToByteArray());writer.Write(p.Text);}return Convert.ToHexString(SHA256.HashData(buffer.ToArray()));}
public static string Validate(ReviewSave r)=>r.ID==Guid.Empty||r.Version<0?"Choose a valid observation.":r.Status is not("Open" or "Working" or "Resolved")?"Choose a valid observation state.":string.IsNullOrWhiteSpace(r.Observation)?"Record what you noticed before saving.":r.Observation.Length>10000||(r.Decision?.Length??0)>10000?"Keep each observation and decision within 10,000 characters.":"";
public static string Validate(ReviewSave r)=>r.ID==Guid.Empty||r.Version<0?"Choose a valid observation.":!ReviewSave.Classifications.Contains(r.Classification)?"Choose an annotation classification.":r.Status is not("Open" or "Working" or "Resolved" or "Dismissed")?"Choose a valid observation state.":string.IsNullOrWhiteSpace(r.Observation)?"Record what you noticed before saving.":r.Observation.Length>10000||(r.Decision?.Length??0)>10000?"Keep each observation and decision within 10,000 characters.":"";
public static ReaderParagraph[] Anchor(ManuscriptReaderModel model,Guid? first,Guid? last,int? start,int? end){
if(first==null&&last==null&&start==null&&end==null)return [];
var rows=model.Paragraphs.ToArray();var from=Array.FindIndex(rows,p=>p.Id==first);var to=Array.FindIndex(rows,p=>p.Id==last);
@ -55,8 +60,13 @@ public sealed class WriterReviewService(ISqlConnectionFactory factory,Manuscript
public async Task<ReviewObservation> Save(int actor,ReviewSave r){
var error=Validate(r);if(error.Length>0)throw new ArgumentException(error);
ManuscriptReaderModel? source=null;ReaderParagraph[] rows=[];
if(r.Version==0){source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();if(r.ContentVersion!=source.ContentVersion)throw new AuthoringConflictException("The accepted chapter changed. Your observation text is retained. Refresh the manuscript before choosing its reference again.");rows=Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);}
int? scene=rows.Length>0&&rows[0].SceneID.HasValue&&rows.All(p=>p.SceneID==rows[0].SceneID)?rows[0].SceneID:null;
using var db=factory.CreateConnection();try{return await db.QuerySingleAsync<ReviewObservation>("dbo.WriterReview_Observations",new{Action=r.Version==0?"create":"update",UserID=actor,r.BookID,r.ChapterID,r.ID,r.Version,ManuscriptID=source?.ManuscriptID,SnapshotRevision=source?.Revision,ContentVersion=source?.ContentVersion,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset,AnchorHash=rows.Length>0?Hash(rows):null,SceneID=scene,r.Observation,r.Decision,r.Status},commandType:CommandType.StoredProcedure);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){throw new AuthoringConflictException("The observation or accepted manuscript changed. Your text is retained. Reload the recorded observations before retrying.",e);}
if(r.Version==0){source=await reader.Read(actor,r.BookID,r.ChapterID)??throw new KeyNotFoundException();if(r.ContentVersion!=source.ContentVersion)throw new AuthoringConflictException("The accepted chapter changed. Your observation text is retained. Refresh the manuscript before choosing its reference again.");if(r.Scope=="")r.Scope=r.StartParagraph.HasValue?"Passage":"Chapter";
if(r.Scope is not("Chapter" or "Scene" or "Passage"))throw new ArgumentException("Choose an annotation scope.");
if(r.Scope=="Passage")rows=Anchor(source,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset);
else if(r.StartParagraph.HasValue||r.EndParagraph.HasValue)throw new ArgumentException("Choose the reference explicitly for this scope.");
if(r.Scope=="Passage"&&rows.Length==0)throw new ArgumentException("Select an accepted passage first.");
if(r.Scope=="Scene"&&(!r.SceneID.HasValue||!source.Paragraphs.Any(p=>p.SceneID==r.SceneID)))throw new ArgumentException("Select a paragraph with a verified scene before adding a scene annotation.");}
int? scene=r.Version==0&&r.Scope=="Scene"?r.SceneID:rows.Length>0&&rows[0].SceneID.HasValue&&rows.All(p=>p.SceneID==rows[0].SceneID)?rows[0].SceneID:null;
using var db=factory.CreateConnection();try{return await db.QuerySingleAsync<ReviewObservation>("dbo.WriterReview_Observations",new{Action=r.Version==0?"create":"update",UserID=actor,r.BookID,r.ChapterID,r.ID,r.Version,ManuscriptID=source?.ManuscriptID,SnapshotRevision=source?.Revision,ContentVersion=source?.ContentVersion,r.StartParagraph,r.EndParagraph,r.StartOffset,r.EndOffset,AnchorHash=rows.Length>0?Hash(rows):null,SceneID=scene,r.Observation,r.Decision,r.Status,r.Scope,r.Classification},commandType:CommandType.StoredProcedure);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51002){throw new AuthoringConflictException("The observation or accepted manuscript changed. Your text is retained. Reload the recorded observations before retrying.",e);}
}
}

View File

@ -0,0 +1,47 @@
-- Extend existing editorial observations without rewriting existing records or anchors.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF COL_LENGTH('dbo.WriterReviewObservations','Scope') IS NULL ALTER TABLE dbo.WriterReviewObservations ADD Scope varchar(10) NULL,Classification varchar(30) NULL;
GO
IF EXISTS(SELECT 1 FROM sys.check_constraints WHERE name='CK_WriterReview_Status') ALTER TABLE dbo.WriterReviewObservations DROP CONSTRAINT CK_WriterReview_Status;
ALTER TABLE dbo.WriterReviewObservations ADD CONSTRAINT CK_WriterReview_Status CHECK(Status IN('Open','Working','Resolved','Dismissed'));
GO
CREATE OR ALTER PROCEDURE dbo.WriterReview_Observations @Action varchar(12),@UserID int,@BookID int,@ChapterID int,@ID uniqueidentifier=NULL,@Version int=0,
@ManuscriptID uniqueidentifier=NULL,@SnapshotRevision bigint=NULL,@ContentVersion char(64)=NULL,
@StartParagraph uniqueidentifier=NULL,@EndParagraph uniqueidentifier=NULL,@StartOffset int=NULL,@EndOffset int=NULL,@AnchorHash char(64)=NULL,@SceneID int=NULL,
@Observation nvarchar(max)=NULL,@Decision nvarchar(max)=NULL,@Status varchar(16)='Open',@Page int=1,@Scope varchar(10)=NULL,@Classification varchar(30)='Observation'
AS
BEGIN
SET NOCOUNT ON;SET XACT_ABORT ON;
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.ChapterID=@ChapterID AND c.IsArchived=0 JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID AND b.IsArchived=0) THROW 51000,'Review scope unavailable',1;
IF @Action='list' BEGIN
IF @Page<1 OR @Page>100000 THROW 51000,'Invalid review page',1;
SELECT * FROM dbo.WriterReviewObservations WHERE UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID ORDER BY CreatedUtc DESC,ID OFFSET ((@Page-1)*50) ROWS FETCH NEXT 51 ROWS ONLY;RETURN;
END;
IF @Action NOT IN('create','update') OR @ID IS NULL OR @Status NOT IN('Open','Working','Resolved','Dismissed') OR LEN(TRIM(COALESCE(@Observation,N'')))=0 OR LEN(@Observation)>10000 OR LEN(COALESCE(@Decision,N''))>10000 THROW 51000,'Invalid observation',1;
IF @Classification NOT IN('Observation','Revision needed','Continuity','Research','Character','Plot','Pacing','Reminder','General note') THROW 51000,'Invalid classification',1;
SET @Scope=COALESCE(NULLIF(@Scope,''),CASE WHEN @StartParagraph IS NULL THEN 'Chapter' ELSE 'Passage' END);
IF @Action='create' AND (@Scope NOT IN('Chapter','Scene','Passage') OR (@Scope='Scene' AND @SceneID IS NULL) OR (@Scope='Passage' AND @StartParagraph IS NULL) OR (@Scope<>'Passage' AND @StartParagraph IS NOT NULL)) THROW 51000,'Invalid annotation scope',1;
IF @Action='create' AND @Scope='Scene' AND NOT EXISTS(SELECT 1 FROM dbo.Scenes WHERE SceneID=@SceneID AND ChapterID=@ChapterID AND IsArchived=0) THROW 51000,'Scene unavailable',1;
BEGIN TRANSACTION;
IF @Action='create'
BEGIN
IF EXISTS(SELECT 1 FROM dbo.WriterReviewObservations WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID)
BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.WriterReviewObservations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND Observation=@Observation AND ISNULL(Decision,N'')=ISNULL(@Decision,N'') AND ContentVersion=@ContentVersion AND Status=@Status AND ISNULL(Classification,'Observation')=@Classification AND ISNULL(Scope,CASE WHEN StartParagraph IS NULL THEN 'Chapter' ELSE 'Passage' END)=@Scope AND ISNULL(SceneID,0)=ISNULL(@SceneID,0) AND ISNULL(CONVERT(varchar(36),StartParagraph),'')=ISNULL(CONVERT(varchar(36),@StartParagraph),'') AND ISNULL(CONVERT(varchar(36),EndParagraph),'')=ISNULL(CONVERT(varchar(36),@EndParagraph),'') AND ISNULL(StartOffset,-1)=ISNULL(@StartOffset,-1) AND ISNULL(EndOffset,-1)=ISNULL(@EndOffset,-1)) THROW 51002,'This observation changed; reload before retrying',1;
END ELSE BEGIN
DECLARE @CurrentRevision bigint,@CurrentManuscript uniqueidentifier;
SELECT @CurrentRevision=Revision,@CurrentManuscript=ManuscriptID FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
IF ISNULL(@CurrentRevision,-1)<>@SnapshotRevision OR ISNULL(@CurrentManuscript,'00000000-0000-0000-0000-000000000000')<>ISNULL(@ManuscriptID,'00000000-0000-0000-0000-000000000000') THROW 51002,'Accepted manuscript changed; your text has been retained',1;
INSERT dbo.WriterReviewObservations(ID,UserID,BookID,ChapterID,ManuscriptID,SnapshotRevision,ContentVersion,StartParagraph,EndParagraph,StartOffset,EndOffset,AnchorHash,SceneID,Observation,Decision,Status,Scope,Classification)
VALUES(@ID,@UserID,@BookID,@ChapterID,@ManuscriptID,@SnapshotRevision,@ContentVersion,@StartParagraph,@EndParagraph,@StartOffset,@EndOffset,@AnchorHash,@SceneID,@Observation,@Decision,@Status,@Scope,@Classification);
END;
END ELSE BEGIN
UPDATE dbo.WriterReviewObservations SET Observation=@Observation,Decision=@Decision,Status=@Status,Classification=@Classification,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID AND Version=@Version;
IF @@ROWCOUNT<>1 THROW 51002,'Another window changed this observation; your text has been retained',1;
END;
SELECT * FROM dbo.WriterReviewObservations WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND ChapterID=@ChapterID;
COMMIT;
END;
GO

View File

@ -12,7 +12,9 @@
<a class="btn btn-outline-secondary" asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Back to book</a>
</div>
@if(ViewData["ReturnUrl"] is string back){<a href="@back" class="btn btn-outline-secondary">Return to Review</a>}
<form asp-action="Save" method="post" class="edit-panel pd-record-form">
<input type="hidden" name="returnUrl" value="@ViewData["ReturnUrl"]" />
<input asp-for="ChapterID" type="hidden" />
<input asp-for="BookID" type="hidden" />
<input asp-for="OriginalDerivedPOVCharacterID" type="hidden" />

View File

@ -1,11 +1,11 @@
@model WriterDashboardViewModel
@{
ViewData["Title"] = Model.Destination == "Dashboard" ? "Writing Dashboard" : $"Writer · {Model.Destination}";
ViewData["Title"] = Model.Destination == "Dashboard" ? "Writing Dashboard" : $"{Model.Destination}{(Model.Book == null ? "" : " · " + Model.Book.BookDisplayTitle)}";
ViewData["ProjectSection"] = "Writer";
ViewData["ShellClass"] = "pd-writer writer3-shell";
}
<link rel="stylesheet" href="~/css/writer-work.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/writer3.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/writer3.css" asp-append-version="true" /><link rel="stylesheet" href="~/css/writer21.css" asp-append-version="true" />
<div class="writer3 writer3-destination" data-writer-destination="@Model.Destination" data-review-chapters="@string.Join(",",Model.ObjectiveChoices.Select(x=>x.ChapterID).Distinct())" data-layout-owner="@User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value" data-writing-workspace-launcher data-compact-writer="true" data-project-id="@Model.ProjectID" data-book-id="@Model.BookID">
<partial name="_Writer3Header" model="Model" />
@if(!Model.BookID.HasValue && Model.Destination != "Explore"){
@ -22,13 +22,16 @@
}
</div>
@section Scripts {
<script src="~/js/writer21.js" asp-append-version="true"></script>
<script src="~/js/writer2-workspaces.js" asp-append-version="true"></script>
<script src="~/js/writer3-workspace.js" asp-append-version="true"></script>
<script src="~/js/writing-workspace.js" asp-append-version="true"></script>
<script src="~/js/writing-workspace-launcher.js" asp-append-version="true"></script>
@if(Model.Destination=="Review"){<script src="~/js/manuscript-reader.js" asp-append-version="true"></script><script src="~/js/writer-review.js" asp-append-version="true"></script><script src="~/js/writer-word.js" asp-append-version="true"></script><script src="~/js/writer-work.js" asp-append-version="true"></script>}
@if(Model.Destination=="Plan"){<script src="~/js/writer-planner.js" asp-append-version="true"></script>}
@if(Model.Destination=="Explore"){<script src="~/js/writer-explore.js" asp-append-version="true"></script>}
@if(Model.Destination=="Review"){<script src="~/js/manuscript-reader.js" asp-append-version="true"></script><script src="~/js/review-authoring.js" asp-append-version="true"></script><script src="~/js/writer-review.js" asp-append-version="true"></script><script src="~/js/writer-work.js" asp-append-version="true"></script>}
@if(Model.Destination is "Write" or "Plan"){
<script src="~/js/writer-word.js" asp-append-version="true"></script>
<script src="~/js/writer-authoring.js" asp-append-version="true"></script>
<script src="~/js/writer-focus.js" asp-append-version="true"></script>
<script src="~/js/writer-objective.js" asp-append-version="true"></script>

View File

@ -6,9 +6,6 @@
<div class="writer-month-grid">@foreach(var name in new[]{"Mon","Tue","Wed","Thu","Fri","Sat","Sun"}){<strong>@name</strong>}@for(var i=0;i<offset;i++){<span></span>}@for(var date=first;date.Month==first.Month;date=date.AddDays(1)){days.TryGetValue(date,out var day);<a class="work-level-@Level(day) @(work.Day?.Date==date?"writer-day-selected":"")" asp-action="@(Model.Destination=="Reflect"?"Reflect":"Journey")" asp-route-bookId="@work.BookID" asp-route-year="@date.Year" asp-route-month="@date.Month" asp-route-day="@date.ToString("yyyy-MM-dd")" aria-label="@date.ToString("d MMMM yyyy"): @Description(day)"><strong>@date.Day</strong>@if(day!=null){<small>+@day.Added / −@day.Removed words</small>@if(day.Writing>0||day.Editing>0){<small>Writing / editing</small>}@if(day.EngagedSeconds>=60){<small>@Math.Floor(day.EngagedSeconds/60d) browser-engaged min</small>}@if(day.Planning>0){<small>Planning</small>}@if(day.Reading>0){<small>Reading review</small>}@if(day.AudioReview>0){<small>Audio review · @Math.Floor(day.PlaybackSeconds/60) observed min</small>}}</a>}</div>
<details><summary>@work.Year year overview</summary><div class="writer-year-grid">@for(var date=new DateTime(work.Year,1,1);date.Year==work.Year;date=date.AddDays(1)){days.TryGetValue(date,out var day);<a class="work-level-@Level(day)" asp-action="@(Model.Destination=="Reflect"?"Reflect":"Journey")" asp-route-bookId="@work.BookID" asp-route-year="@date.Year" asp-route-month="@date.Month" asp-route-day="@date.ToString("yyyy-MM-dd")" aria-label="@date.ToString("d MMM yyyy"): @Description(day)" title="@date.ToString("d MMM"): @Description(day)"></a>}</div></details>
@if(work.Day is {} selected){days.TryGetValue(selected.Date,out var observed);<h3 class="mt-3">@selected.ToString("d MMMM yyyy")</h3>@if(observed==null){<p>No retained observation for this day. This does not establish that no work took place.</p>}else{<p>@observed.Changes accepted changes · +@observed.Added / −@observed.Removed words · @(observed.Added-observed.Removed) net.</p><p>@Math.Floor(observed.EngagedSeconds/60d) browser-engaged minutes · @Math.Floor(observed.PlaybackSeconds/60) observed playback minutes. These may overlap and are not added.</p>}<a asp-controller="WritingActivity" asp-action="Index" asp-route-bookId="@work.BookID" asp-route-day="@selected.ToString("yyyy-MM-dd")">Accepted-change evidence</a>}
<h3 class="mt-3">@(work.Day.HasValue?"Sessions on this day":"Recent sessions")</h3>
@foreach(var session in work.Sessions.Take(20)){<article class="writer-reminder"><strong>@session.Kind · @(session.ChapterTitle??"Across the book")</strong><p>@session.StartedUtc.ToString("d MMM yyyy HH:mm") · @(session.EndedUtc.HasValue?Math.Round((session.EndedUtc.Value-session.StartedUtc).TotalMinutes)+" minutes elapsed":"Session open")</p>@if(!string.IsNullOrWhiteSpace(session.Note)){<p class="review-recorded">@session.Note</p>}<details><summary>Recording details</summary><p>This session was started explicitly. Elapsed time is not active time. @Math.Floor(session.EngagedSeconds/60d) browser-engaged minutes and @Math.Floor(session.PlaybackSeconds/60) observed playback minutes may overlap and are not added. Dates use UTC.</p>@if(session.ChangesDuringSession>0){<p>@session.ChangesDuringSession accepted manuscript changes were recorded during this interval; this association does not establish what caused them.</p>}</details></article>}
<a asp-controller="WriterWork" asp-action="Export" asp-route-bookId="@work.BookID" asp-route-day="@work.Day?.ToString("yyyy-MM-dd")">Export recent session evidence (up to 50)</a>
</section>
@if(Model.WritingSchedule.UpcomingTasks.Count>0||Model.PlannedActivities.Count>0){<section class="writer-card"><h2>Planned work ahead</h2><ul>@foreach(var task in Model.WritingSchedule.UpcomingTasks){<li>@task.ScheduledDate.ToString("d MMM") · <a asp-controller="Scenes" asp-action="Edit" asp-route-id="@task.SceneID">@task.SceneTitle</a> · @task.TaskType</li>}@foreach(var task in Model.PlannedActivities){<li>@task.ScheduledDate.ToString("d MMM") · @if(task.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@task.SceneID">@task.Title</a>}else{<a asp-action="Chapter" asp-route-id="@task.ChapterID">@task.Title</a>} · @task.Kind · @task.Minutes planned minutes</li>}</ul></section>}

View File

@ -1,25 +1,24 @@
@model PlotLine.Services.Writer.ReviewPanel
@{var data=Model.Intentions;var goal=data.Sections.First(x=>x.Kind=="Goals");var scene=data.Sections.FirstOrDefault(x=>x.Kind=="Scene");string Compact(string value)=>value.Length>360?value[..360]+"…":value;}
<div data-review-panel><p class="writer3-caption">@Model.ReferenceMessage</p>
<section class="writer3-inset" data-review-intentions><h3>Chapter and scene intentions</h3>
@if(scene!=null){<h4>@data.Scene?.SceneTitle</h4><p class="review-recorded">@(string.IsNullOrWhiteSpace(scene.Value("ScenePurposeNotes"))?"No scene intention recorded.":Compact(scene.Value("ScenePurposeNotes")))</p><p class="review-recorded">@Compact(scene.Value("SceneOutcomeNotes"))</p><p class="writer3-caption">Recorded scene state: @data.Scene?.RevisionStatusName</p>}
<p class="review-recorded">@(string.IsNullOrWhiteSpace(goal.Value("GoalSummary"))?"No chapter intention recorded. You can review without one.":Compact(goal.Value("GoalSummary")))</p>
<details><summary>Chapter details, reminders &amp; editing</summary>
@foreach(var section in data.Sections.Where(x=>x.Kind is "Chapter" or "Goals")){@foreach(var field in section.Fields){var value=section.Value(field.Name);if(field.Type=="purpose"&&!string.IsNullOrWhiteSpace(value))value=section.Purposes.FirstOrDefault(p=>p.Value==value).Label??"Recorded purpose is unavailable";@if(!string.IsNullOrWhiteSpace(value)){<p><strong>@field.Label</strong><span class="review-recorded">@value</span></p>}}}
@foreach(var note in data.Sections.Where(x=>x.Kind=="Note"&&x.Value("IsResolved")!="true"||x.Kind=="Checklist"&&x.Value("IsCompleted")!="true").Take(10)){<p class="review-recorded">@(note.Kind=="Note"?note.Value("NoteText"):note.Value("ItemText"))</p>}
@{var flow=data.Sections.FirstOrDefault(x=>x.Kind=="Workflow");}@if(flow!=null){<p>Priority: @flow.Value("Priority"). @flow.Value("BlockedReason")</p>}
<a asp-controller="Chapters" asp-action="Edit" asp-route-id="@data.ChapterID" target="_blank" rel="noopener">Edit chapter intentions in the existing editor</a>
@if(data.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@data.SceneID" target="_blank" rel="noopener">Edit scene intentions, notes and working details</a>}
</details></section>
<section class="writer3-inset"><div class="writer3-authoring-heading"><h3>Your observations</h3><button type="button" class="btn btn-sm btn-link" data-review-reload>Reload</button></div>
@if(Model.Observations.Count==0){<p>No observations on this page. Record something when it helps your review.</p>}
@foreach(var row in Model.Observations){
<article class="writer3-authoring-card" data-observation data-id="@row.ID" data-version="@row.Version" data-first="@row.StartParagraph" data-anchor="@row.AnchorState">
<p class="writer3-focus-kind">@(row.Status=="Open"?"Needs attention":row.Status=="Working"?"Working on it":"Resolved")</p>
<p class="review-recorded" data-observation-text>@row.Observation</p><p class="review-recorded" data-decision-text>@row.Decision</p>
<p class="writer3-caption">@row.AnchorState reference · @(row.SnapshotRevision<0?"No accepted version at capture":"Accepted version "+row.SnapshotRevision) · created @row.CreatedUtc.ToString("dd MMM yyyy HH:mm:ss") UTC · updated @row.UpdatedUtc.ToString("dd MMM yyyy HH:mm:ss") UTC</p>
<div class="button-row"><button type="button" class="btn btn-sm btn-outline-secondary" data-review-edit data-state="@row.Status">Edit / change decision</button>@if(row.StartParagraph.HasValue){<button type="button" class="btn btn-sm btn-outline-secondary" data-review-revisit>Revisit reference</button>}</div>
@{var data=Model.Intentions;}
<div data-review-panel data-selected-scene="@data.SceneID">
<div data-review-intentions>
<p>@data.Chapter.ChapterTitle</p>
@foreach(var section in data.Sections.Where(x=>x.Kind is "Chapter" or "Goals")){<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="section" />}
<a asp-controller="Chapters" asp-action="Edit" asp-route-id="@data.ChapterID" asp-route-returnUrl="@Url.Action("Review","Writer",new{bookId=data.BookID,chapterId=data.ChapterID})">Structural chapter properties</a>
</div>
<div data-review-scene-intentions>
<p>@Model.ReferenceMessage</p>
@if(data.SceneID.HasValue){<h3>@data.Scene?.SceneTitle</h3>@foreach(var section in data.Sections.Where(x=>x.Kind is "Scene" or "Note" or "Checklist" or "AddNote" or "AddChecklist")){<partial name="~/Views/Writer/_AuthoringSection.cshtml" model="section" />}}
else{<p>No verified scene selected. Select an accepted paragraph with an assigned scene. No association is guessed.</p>}
</div>
<section class="writer3-inset" data-review-observations><div class="writer3-authoring-heading"><h3>Editorial annotations</h3><button type="button" class="btn btn-sm btn-link" data-review-reload>Reload</button></div>
<label>Filter classification <select data-annotation-filter="classification" class="form-select"><option value="">All classifications</option>@foreach(var kind in PlotLine.Services.Writer.ReviewSave.Classifications){<option>@kind</option>}</select></label><label>Filter status <select data-annotation-filter="status" class="form-select"><option value="">All statuses</option><option value="Open">Open</option><option value="Working">In progress</option><option value="Resolved">Resolved</option><option value="Dismissed">Dismissed</option></select></label>
@if(Model.Observations.Count==0){<p>No annotations on this page.</p>}
@foreach(var row in Model.Observations){<article class="writer3-authoring-card" data-observation data-id="@row.ID" data-version="@row.Version" data-first="@row.StartParagraph" data-anchor="@row.AnchorState" data-scope="@row.EffectiveScope" data-classification="@row.EffectiveClassification" data-status="@row.Status" data-scene="@row.SceneID">
<h4>@row.EffectiveScope · @row.EffectiveClassification</h4><p>@(row.Status=="Working"?"In progress":row.Status)</p>
<p class="review-recorded" data-observation-text>@row.Observation</p><p class="review-recorded" data-decision-text>@row.Decision</p><p class="writer3-caption">@row.AnchorState reference · accepted revision @row.SnapshotRevision · updated @row.UpdatedUtc.ToString("d MMM yyyy HH:mm") UTC</p>
<button type="button" class="btn btn-outline-secondary" data-review-edit data-state="@row.Status">Edit / change status</button>@if(row.StartParagraph.HasValue){<button type="button" class="btn btn-outline-secondary" data-review-revisit>Revisit reference</button>}
</article>}
<div class="button-row">@if(Model.Page>1){<button type="button" class="btn btn-sm btn-link" data-review-page="@(Model.Page-1)">Previous observations</button>}@if(Model.HasMore){<button type="button" class="btn btn-sm btn-link" data-review-page="@(Model.Page+1)">More observations</button>}</div>
<div class="button-row">@if(Model.Page>1){<button type="button" data-review-page="@(Model.Page-1)">Previous annotations</button>}@if(Model.HasMore){<button type="button" data-review-page="@(Model.Page+1)">More annotations</button>}</div>
</section>
</div>

View File

@ -0,0 +1,8 @@
@model WriterDashboardViewModel
@{var work=Model.Work??new PlotLine.Models.WriterWorkPage{BookID=Model.BookID??0};}
<label>Filter sessions <input type="search" data-session-filter class="form-control" placeholder="Activity, chapter or note" /></label><div class="writer21-bounded" data-session-history>
<h3 class="mt-3">@(work.Day.HasValue?"Sessions on this day":"Recent sessions")</h3>
@foreach(var session in work.Sessions.Take(20)){<article class="writer-reminder"><strong>@session.Kind · @(session.ChapterTitle??"Across the book")</strong><p>@session.StartedUtc.ToString("d MMM yyyy HH:mm") · @(session.EndedUtc.HasValue?Math.Round((session.EndedUtc.Value-session.StartedUtc).TotalMinutes)+" minutes elapsed":"Session open")</p>@if(!string.IsNullOrWhiteSpace(session.Note)){<p class="review-recorded">@session.Note</p>}<details><summary>Recording details</summary><p>This session was started explicitly. Elapsed time is not active time. @Math.Floor(session.EngagedSeconds/60d) browser-engaged minutes and @Math.Floor(session.PlaybackSeconds/60) observed playback minutes may overlap and are not added. Dates use UTC.</p>@if(session.ChangesDuringSession>0){<p>@session.ChangesDuringSession accepted manuscript changes were recorded during this interval; this association does not establish what caused them.</p>}</details></article>}
<a asp-controller="WriterWork" asp-action="Export" asp-route-bookId="@work.BookID" asp-route-day="@work.Day?.ToString("yyyy-MM-dd")">Export recent session evidence (up to 50)</a>
</div>

View File

@ -2,9 +2,9 @@
<div class="writer3-workspace writer2-single" aria-label="Writing reflection"><section class="writer3-panel writer3-main">
@if(Model.ActivityIsPrivate){<p>Recorded activity is private to the book owner. Your chapter and scene tools remain available.</p>}
else{
<h2>Your writing journey</h2><p>Look back at recorded work, explore a day, or notice how your writing has changed over time.</p>
<div data-workspace-tabs><div class="writer21-tabs" role="tablist" aria-label="Reflection"><button type="button" role="tab" aria-selected="true" data-tab="calendar">Calendar</button><button type="button" role="tab" aria-selected="false" data-tab="sessions">Sessions &amp; activity</button></div><div data-pane="calendar">
@if(Model.Work?.Days.Any(x=>x.Intensity>0)!=true&&Model.Work?.Sessions.Count==0){<p>Your journey will grow as writing sessions and manuscript changes are recorded. Quiet days here do not mean you did no writing.</p><div class="button-row"><a class="btn btn-primary" asp-action="Write" asp-route-bookId="@Model.BookID">Continue writing or record a session</a></div>}
<partial name="_JourneyCalendar" model="Model" />
<partial name="_JourneyCalendar" model="Model" /></div><div data-pane="sessions" hidden><partial name="_SessionHistory" model="Model" /></div></div>
<details class="writer3-inset"><summary>Recorded manuscript progress</summary><partial name="_WriterProgress" model="Model" /></details>
}
</section></div>

View File

@ -1,30 +1,30 @@
@model WriterDashboardViewModel
@{var reader=Model.ReviewReader;var word=new WriterDashboardViewModel{BookID=Model.BookID,ProjectID=Model.ProjectID,WordNavigationContext="review",Objective=reader?.Chapter==null?null:new(){ChapterID=reader.Chapter.ChapterID,ChapterTitle=reader.Chapter.ChapterTitle,Activity="Revising"}};}
<div class="writer3-workspace" aria-label="Manuscript review">
<section class="writer3-panel writer3-main" tabindex="0" aria-label="Accepted manuscript">
@if(reader?.Chapter!=null){<details class="writer2-chapter-context" open><summary>Chapter intentions and verified scene context</summary><div data-review-intentions-slot><p>Loading recorded intentions…</p></div></details>}
@if(reader!=null){<partial name="~/Views/ManuscriptReader/_Reader.cshtml" model="reader" />}
else{<h2>Read the accepted manuscript</h2><p>Select a book with chapters to review your accepted writing.</p><a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Open your book</a>}
</section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Review intentions and observations">
<div class="writer3-authoring-heading"><h2>Notice &amp; decide</h2><help-icon key="writer3.reviewing" /></div>
@if(reader?.Chapter!=null){
<section class="writer3-panel writer3-main" tabindex="0" aria-label="Editorial review">
<div class="button-row"><button type="button" class="btn btn-outline-secondary" data-editorial-toggle="review-chapter-notes" aria-expanded="true">Chapter notes</button><button type="button" class="btn btn-outline-secondary" data-editorial-toggle="review-scene-notes" aria-expanded="true">Scene notes</button></div>
<div class="writer21-editorial">
<section class="writer21-notes" id="review-chapter-notes" aria-label="Chapter notes"><h2>Chapter notes</h2><button type="button" class="btn btn-outline-primary" data-review-scope-new="Chapter">Add chapter annotation</button><div data-review-intentions-slot><p>Loading chapter notes…</p></div><div data-chapter-annotations></div></section>
<section class="writer21-manuscript" aria-label="Accepted manuscript">@if(reader!=null){<partial name="~/Views/ManuscriptReader/_Reader.cshtml" model="reader" />}else{<p>Select a book with chapters to review.</p>}</section>
<section class="writer21-notes" id="review-scene-notes" aria-label="Scene notes"><h2>Scene notes</h2><div data-review-scene-context></div>
@if(reader?.Chapter!=null){
<div data-writer-review data-book="@Model.BookID" data-chapter="@reader.Chapter.ChapterID" data-panel-url="@Url.Action("Panel","WriterReview")">
<p data-review-reference>Chapter observation · select text or a paragraph for a passage reference.</p><p data-review-message role="status"></p>
<button type="button" class="btn btn-sm btn-outline-primary" data-review-new>Something here needs attention</button>
<button type="button" class="btn btn-sm btn-outline-primary" data-review-new>Add annotation</button>
<form asp-controller="WriterReview" asp-action="Save" method="post" data-review-form hidden>
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID" value="@reader.Chapter.ChapterID"/><input type="hidden" name="ID"/><input type="hidden" name="Version" value="0"/><input type="hidden" name="ContentVersion"/>
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ChapterID" value="@reader.Chapter.ChapterID"/><input type="hidden" name="ID"/><input type="hidden" name="Version" value="0"/><input type="hidden" name="ContentVersion"/><input type="hidden" name="SceneID"/>
<input type="hidden" name="StartParagraph"/><input type="hidden" name="EndParagraph"/><input type="hidden" name="StartOffset"/><input type="hidden" name="EndOffset"/>
<div class="writer3-inline-field"><label for="review-observation">What have you noticed?</label><textarea id="review-observation" name="Observation" class="form-control" maxlength="10000" rows="4" required></textarea></div>
<div class="writer3-inline-field"><label for="review-decision">What would you like to change? (optional)</label><textarea id="review-decision" name="Decision" class="form-control" maxlength="10000" rows="3"></textarea></div>
<label for="review-status">Your decision</label><select name="Status" id="review-status" class="form-select"><option value="Open">Needs attention</option><option value="Working">Working on it</option><option value="Resolved">Resolved</option></select>
<label for="review-scope">Scope</label><select id="review-scope" name="Scope" class="form-select"><option value="Chapter">Whole chapter</option><option value="Scene">Verified scene</option><option value="Passage">Selected accepted passage</option></select><p class="writer3-caption">Saved references stay attached to their original accepted version. Create another annotation to choose a different reference.</p>
<label for="review-classification">Classification</label><select id="review-classification" name="Classification" class="form-select">@foreach(var classification in PlotLine.Services.Writer.ReviewSave.Classifications){<option>@classification</option>}</select>
<label for="review-status">Your decision</label><select name="Status" id="review-status" class="form-select"><option value="Open">Needs attention</option><option value="Working">Working on it</option><option value="Resolved">Resolved</option><option value="Dismissed">Dismissed</option></select>
<p data-review-error role="alert" hidden></p><div class="button-row"><button class="btn btn-primary" type="submit" data-review-save>Save observation</button><button type="button" class="btn btn-outline-secondary" data-review-cancel>Cancel</button></div>
</form>
<button type="button" class="btn btn-sm btn-link" data-review-chapter>Use a chapter-level reference</button>
<div data-review-context aria-live="polite"><p>Loading recorded intentions and observations…</p></div>
</div>
<details class="writer3-authoring-details"><summary>Return to Word</summary><partial name="_WriterWord" model="word" /></details>
}
<details class="writer3-authoring-details"><summary>Saved assessments &amp; other tools</summary><p>Author observations above are separate from automated findings. Opening Review runs no analysis.</p><div class="writer3-link-list"><button type="button" data-open-writing-intent>Open Intent &amp; saved assessment evidence</button><button type="button" data-open-writing-context>Open standalone Context</button><a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Open the book’s saved analysis and review tools</a><a asp-action="Write" asp-route-projectId="@Model.ProjectID" asp-route-bookId="@Model.BookID">Return to saved writing focus</a></div><p data-writing-workspace-message role="status"></p></details>
</aside>
}
</section></div></section>
<aside class="writer3-panel writer3-reference" tabindex="0" aria-label="Word Companion"><partial name="_WriterWord" model="word" /><details><summary>Saved assessments &amp; story tools</summary><p>Annotations remain separate from automated findings. Opening Review runs no analysis.</p><a asp-controller="Books" asp-action="Details" asp-route-id="@Model.BookID">Saved analysis and review tools</a></details></aside>
</div>

View File

@ -0,0 +1,26 @@
/* Workspace composition uses existing theme tokens and natural manuscript scrolling. */
.writer3-destination{padding-block-start:.6rem}
.writer21-tabs{display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:1rem;border-bottom:1px solid var(--bs-border-color)}
.writer21-tabs button{border:0;background:transparent;color:inherit;padding:.6rem .9rem;border-bottom:3px solid transparent}
.writer21-tabs button[aria-selected=true]{border-bottom-color:var(--bs-primary);font-weight:700}
.writer21-bounded{max-height:32rem;overflow-y:auto;overscroll-behavior:contain;padding:.3rem}
.writer21-bounded article{padding:.75rem 0;border-bottom:1px solid var(--bs-border-color)}
.writer3-workspace:has([data-explore-investigation]){grid-template-columns:minmax(0,1fr) minmax(0,1fr)}
.writer3-workspace.writer21-investigating{grid-template-columns:minmax(0,1fr) minmax(0,3fr)}
.investigation-journey{display:grid;grid-template-columns:minmax(0,2fr) minmax(12rem,1fr);gap:1rem}
.investigation-journey>.writer3-panel{padding:.7rem;min-width:0}
.writer21-editorial{display:flex;gap:1rem;align-items:flex-start}
.writer21-editorial>.writer21-notes{flex:1 1 24%;min-width:0}
.writer21-editorial>.writer21-manuscript{flex:2 1 50%;min-width:0;margin-inline:auto}
.writer21-editorial .reader-document{margin-inline:auto}
.writer21-board{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:1rem}
.writer21-planner form textarea{max-width:60ch}
.writer21-task{padding:1rem;border:1px solid var(--bs-border-color);border-radius:.5rem;margin-block:.7rem}
.writer21-task form{display:inline-block;margin:.2rem}
.writer21-task p{white-space:pre-wrap}
@media(max-width:1150px){.investigation-journey{grid-template-columns:1fr}.writer21-editorial{flex-wrap:wrap}.writer21-editorial>.writer21-manuscript{order:-1;flex-basis:100%}.writer21-board{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:800px){.writer3-workspace:has([data-explore-investigation]),.writer3-workspace.writer21-investigating{grid-template-columns:minmax(0,1fr)}.writer21-editorial>.writer21-notes{flex-basis:100%}.writer21-board{grid-template-columns:1fr}}
body:has(.manuscript-reader[data-focus=true]) .writer21-notes,body:has(.manuscript-reader[data-focus=true]) [data-editorial-toggle]{display:none!important}
body:has(.manuscript-reader[data-reading=true]) .writer21-notes{display:none}
.writer21-manuscript .reader-page{margin-inline:auto;max-width:72ch}

View File

@ -0,0 +1,10 @@
// Inline compatibility editors retain canonical chapter/scene note records and field tokens.
(()=>{const editorial=document.querySelector('.writer21-editorial');if(!editorial)return;let busy=false;
const cardOf=node=>node.closest('[data-authoring-card]');
editorial.addEventListener('input',event=>{const form=event.target.closest('[data-authoring-form]');if(form)form.dataset.dirty='true';});
editorial.addEventListener('change',async event=>{const card=cardOf(event.target);if(!card)return;const form=card.querySelector('form');if(event.target.matches('[data-checklist-toggle]')){if(busy){event.target.checked=!event.target.checked;return;}form.querySelector('[name=IsCompleted]').checked=event.target.checked;await save(form);}else if(event.target.closest('form'))form.dataset.dirty='true';});
editorial.addEventListener('click',event=>{const card=cardOf(event.target);if(!card)return;const form=card.querySelector('form'),display=card.querySelector('[data-authoring-display]');if(event.target.closest('[data-authoring-edit]')){form.hidden=false;display.hidden=true;form.querySelector('textarea,input:not([type=hidden])')?.focus();}if(event.target.closest('[data-authoring-cancel]')&&!busy){form.reset();form.dataset.dirty='false';form.hidden=true;display.hidden=false;}if(event.target.closest('[data-authoring-reload]')&&confirm('Reload recorded notes? Copy any text to keep first.')){form.dataset.dirty='false';window.dispatchEvent(new Event('review:notes-saved'));}});
editorial.addEventListener('submit',event=>{const form=event.target;if(!form.matches('[data-authoring-form]'))return;event.preventDefault();void save(form);});
async function save(form){if(busy)return;busy=true;const card=cardOf(form),status=card.querySelector('[data-authoring-status]'),data=new FormData(form);for(const box of form.querySelectorAll('input[type=checkbox]'))data.set(box.name,String(box.checked));status.textContent='Saving…';form.dataset.busy='true';let committed=false;try{const response=await fetch(form.action,{method:'POST',body:data});const result=await response.json().catch(()=>null);if(!response.ok||result?.success!==true)throw Error(result?.message||'Save was not confirmed. Reload the recorded version before retrying.');committed=true;form.dataset.dirty='false';status.textContent='Saved.';window.dispatchEvent(new Event('review:notes-saved'));}catch(error){status.textContent=error.message;form.hidden=false;form.dataset.dirty='true';form.querySelector('[data-authoring-reload]').hidden=false;}finally{form.dataset.busy='false';busy=false;if(committed)form.querySelector('[data-authoring-save]').disabled=true;}}
window.addEventListener('beforeunload',event=>{if(busy||editorial.querySelector('[data-authoring-form][data-dirty=true]')){event.preventDefault();event.returnValue='';}});
})();

View File

@ -1,29 +1,35 @@
// Author actions only. Selection never navigates Word, creates a record or changes working/session focus.
(()=>{'use strict';const root=document.querySelector('[data-writer-review]'),reader=document.querySelector('.manuscript-reader');if(!root||!reader)return;
const form=root.querySelector('[data-review-form]'),context=root.querySelector('[data-review-context]'),message=root.querySelector('[data-review-message]'),reference=root.querySelector('[data-review-reference]'),error=root.querySelector('[data-review-error]'),newButton=root.querySelector('[data-review-new]');
const editorial=root.closest('.writer21-editorial')||root;const form=root.querySelector('[data-review-form]'),context=root.querySelector('[data-review-context]'),message=root.querySelector('[data-review-message]'),reference=root.querySelector('[data-review-reference]'),error=root.querySelector('[data-review-error]'),newButton=root.querySelector('[data-review-new]');
let anchor=null,selected=null,page=1,dirty=false,busy=false,loading=false,allowLeave=false,pauseBefore=false,controller=null,generation=0,selectionTimer=null,lastContext='';
const field=n=>form.elements.namedItem(n),readerContent=reader.querySelector('#reader-content'),word=document.querySelector('[data-writer-word]');
const nodeParagraph=n=>(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest('[data-paragraph-id]');
function capture(){const s=getSelection();if(!s||s.isCollapsed||s.rangeCount!==1)return null;const r=s.getRangeAt(0),first=nodeParagraph(r.startContainer),last=nodeParagraph(r.endContainer);if(!first||!last||!readerContent.contains(first)||!readerContent.contains(last))return null;const before=document.createRange();before.selectNodeContents(first);before.setEnd(r.startContainer,r.startOffset);const after=document.createRange();after.selectNodeContents(last);after.setEnd(r.endContainer,r.endOffset);return{StartParagraph:first.dataset.paragraphId,EndParagraph:last.dataset.paragraphId,StartOffset:before.toString().length,EndOffset:after.toString().length};}
function wordReference(id){if(!word)return;word.dataset.paragraphId=id||'';word.dataset.acceptedRevision=reader.dataset.revision;window.dispatchEvent(new Event('review-reference-changed'));}
function queueContext(){clearTimeout(selectionTimer);selectionTimer=setTimeout(()=>void load(false),180);}
async function load(force=true){clearTimeout(selectionTimer);const key=[selected,anchor?.EndParagraph,reader.dataset.version,page].join(':');if(!force&&key===lastContext)return;const mine=++generation;controller?.abort();controller=new AbortController();loading=true;const url=new URL(root.dataset.panelUrl,location.href);url.search=new URLSearchParams({bookId:root.dataset.book,chapterId:root.dataset.chapter,version:reader.dataset.version,page:String(page),...(selected?{paragraphId:selected,endParagraphId:anchor?.EndParagraph||selected}:{})});try{const response=await fetch(url,{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const doc=new DOMParser().parseFromString(await response.text(),'text/html'),panel=doc.querySelector('[data-review-panel]');if(!panel)throw Error();if(mine===generation){context.replaceChildren(panel);const slot=document.querySelector('[data-review-intentions-slot]');if(slot&&panel.querySelector('[data-review-intentions]'))slot.replaceChildren(panel.querySelector('[data-review-intentions]'));lastContext=key;}}catch(e){if(e.name!=='AbortError'&&mine===generation){message.textContent='Recorded review information could not load. Your observation text is retained.';}}finally{if(mine===generation)loading=false;}}
async function load(force=true){if(editorial.querySelector('[data-authoring-form][data-dirty="true"]')){message.textContent="Save or Cancel your chapter/scene note editor before changing review context.";return;}clearTimeout(selectionTimer);const key=[selected,anchor?.EndParagraph,reader.dataset.version,page].join(':');if(!force&&key===lastContext)return;const mine=++generation;controller?.abort();controller=new AbortController();loading=true;const url=new URL(root.dataset.panelUrl,location.href);url.search=new URLSearchParams({bookId:root.dataset.book,chapterId:root.dataset.chapter,version:reader.dataset.version,page:String(page),...(selected?{paragraphId:selected,endParagraphId:anchor?.EndParagraph||selected}:{})});try{const response=await fetch(url,{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error();const doc=new DOMParser().parseFromString(await response.text(),'text/html'),panel=doc.querySelector('[data-review-panel]');if(!panel)throw Error();if(mine===generation){context.replaceChildren(panel);const slot=document.querySelector('[data-review-intentions-slot]');if(slot&&panel.querySelector('[data-review-intentions]'))slot.replaceChildren(panel.querySelector('[data-review-intentions]'));
const sceneSlot=document.querySelector('[data-review-scene-context]');if(sceneSlot)sceneSlot.replaceChildren(panel.querySelector('[data-review-scene-intentions]'));
const chapterAnnotations=document.querySelector('[data-chapter-annotations]');if(chapterAnnotations){chapterAnnotations.replaceChildren();for(const note of panel.querySelectorAll('[data-observation][data-scope="Chapter"]'))chapterAnnotations.append(note);}
const sceneID=panel.dataset.selectedScene||'';if(word){word.dataset.sceneId=sceneID;window.dispatchEvent(new Event('review-reference-changed'));}
for(const note of panel.querySelectorAll('[data-observation]'))if(note.dataset.scope==='Scene')note.hidden=note.dataset.scene!==sceneID;
window.dispatchEvent(new Event('review:context-loaded'));lastContext=key;}}catch(e){if(e.name!=='AbortError'&&mine===generation){message.textContent='Recorded review information could not load. Your observation text is retained.';}}finally{if(mine===generation)loading=false;}}
function pause(enabled){const input=reader.querySelector('#reader-pause');if(enabled){pauseBefore=input.checked;input.checked=true;}else input.checked=pauseBefore;input.dispatchEvent(new Event('change'));}
function showEditor(){if(reader.dataset.focus==='true'){const restore=reader.readerPreserveView?.();reader.querySelector('#reader-focus').click();restore?.();}const aside=root.closest('.writer3-reference');if(aside.hidden)document.querySelector('[data-writer-companion-toggle]')?.click();form.hidden=false;newButton.hidden=true;field('Observation').focus();}
function begin(){if(busy)return;if(dirty){field('Observation').focus();return;}anchor=capture()||anchor;selected=anchor?.StartParagraph||null;wordReference(selected);void load();field('ID').value=crypto.randomUUID();field('Version').value='0';field('ContentVersion').value=reader.dataset.version;for(const n of['StartParagraph','EndParagraph','StartOffset','EndOffset'])field(n).value=anchor?.[n]??'';field('Observation').value='';field('Decision').value='';field('Status').value='Open';error.hidden=true;pause(true);dirty=true;reference.textContent=anchor?'Observation linked to the selected accepted paragraph(s).':'Chapter-level observation; no exact passage is claimed.';showEditor();}
function showEditor(){if(reader.dataset.focus==='true'){const restore=reader.readerPreserveView?.();reader.querySelector('#reader-focus').click();restore?.();}const aside=root.closest('.writer21-notes')||root.closest('.writer3-reference');if(aside?.hidden)document.querySelector('[data-editorial-toggle=review-scene-notes]')?.click();form.hidden=false;newButton.hidden=true;field('Observation').focus();}
function begin(){if(busy)return;if(dirty){field('Observation').focus();return;}anchor=capture()||anchor;selected=anchor?.StartParagraph||null;wordReference(selected);void load();field('ID').value=crypto.randomUUID();field('Version').value='0';field('ContentVersion').value=reader.dataset.version;for(const n of['StartParagraph','EndParagraph','StartOffset','EndOffset'])field(n).value=anchor?.[n]??'';field('Observation').value='';field('Decision').value='';field('Status').value='Open';field('Scope').disabled=false;field('Scope').value=anchor?'Passage':'Chapter';field('Classification').value='Observation';field('SceneID').value=document.querySelector('[data-review-panel]')?.dataset.selectedScene||'';error.hidden=true;pause(true);dirty=true;reference.textContent=anchor?'Observation linked to the selected accepted paragraph(s).':'Chapter-level observation; no exact passage is claimed.';showEditor();}
reader.querySelector('#reader-focus').addEventListener('click',e=>{if(dirty&&reader.dataset.focus!=='true'){e.preventDefault();e.stopImmediatePropagation();message.textContent='Save or Cancel the observation before entering Focused Reading.';}},true);
function finish(){form.hidden=true;newButton.hidden=false;dirty=false;error.hidden=true;pause(false);newButton.focus();}
newButton.addEventListener('click',begin);document.querySelector('[data-review-record]')?.addEventListener('click',begin);
const markDirty=()=>{if(!form.hidden&&!busy)dirty=true;};form.addEventListener('input',markDirty);form.addEventListener('change',markDirty);root.querySelector('[data-review-cancel]').addEventListener('click',()=>{if(!busy){finish();message.textContent='Observation cancelled; no changes saved.';}});
root.querySelector('[data-review-chapter]').addEventListener('click',()=>{if(busy)return;if(dirty&&Number(field('Version').value)>0){message.textContent='A saved observation keeps its original reference. Create a new chapter observation instead.';return;}anchor=null;selected=null;wordReference(null);for(const n of['StartParagraph','EndParagraph','StartOffset','EndOffset'])field(n).value='';reference.textContent='Chapter-level reference; no exact passage is claimed.';if(!dirty)void load();});
form.addEventListener('submit',async e=>{e.preventDefault();if(busy)return;const data=new FormData(form),creating=Number(field('Version').value)===0;busy=true;for(const input of form.querySelectorAll('textarea,select'))input.disabled=true;const button=root.querySelector('[data-review-save]'),cancel=root.querySelector('[data-review-cancel]');button.disabled=true;cancel.disabled=true;error.hidden=true;try{const response=await fetch(form.action,{method:'POST',body:data,headers:{'X-Requested-With':'XMLHttpRequest'}});const result=await response.json().catch(()=>null);if(!response.ok||result?.success!==true){error.textContent=result?.message||'Save was not confirmed. Your text is retained. Reload observations to check before retrying.';error.hidden=false;return;}finish();if(creating)page=1;message.textContent='Observation saved. Manuscript and scene revision state are unchanged.';await load();}catch{error.textContent='Save was not confirmed. Your text is retained; reload recorded observations before retrying.';error.hidden=false;}finally{busy=false;for(const input of form.querySelectorAll('textarea,select'))input.disabled=false;button.disabled=false;cancel.disabled=false;}});
root.addEventListener('click',e=>{const row=e.target.closest('[data-observation]');if(e.target.closest('[data-review-reload]')){if(dirty){message.textContent='Save or Cancel the editor before reloading observations.';return;}void load();}const pager=e.target.closest('[data-review-page]');if(pager){if(dirty){message.textContent='Save or Cancel before changing observation pages.';return;}page=Number(pager.dataset.reviewPage);void load();}
if(!row)return;if(e.target.closest('[data-review-edit]')){if(dirty){message.textContent='Save or Cancel your current observation first.';return;}field('ContentVersion').value=reader.dataset.version;field('ID').value=row.dataset.id;field('Version').value=row.dataset.version;field('Observation').value=row.querySelector('[data-observation-text]').textContent;field('Decision').value=row.querySelector('[data-decision-text]').textContent;field('Status').value=row.querySelector('[data-review-edit]').dataset.state;pause(true);dirty=true;reference.textContent='Editing a recorded observation; its original accepted-version reference is retained.';showEditor();}
form.addEventListener('submit',async e=>{e.preventDefault();if(busy)return;const data=new FormData(form);data.set('Scope',field('Scope').value);if(Number(field('Version').value)===0&&field('Scope').value!=='Passage')for(const name of ['StartParagraph','EndParagraph','StartOffset','EndOffset'])data.set(name,'');const creating=Number(field('Version').value)===0;busy=true;for(const input of form.querySelectorAll('textarea,select'))input.disabled=true;const button=root.querySelector('[data-review-save]'),cancel=root.querySelector('[data-review-cancel]');button.disabled=true;cancel.disabled=true;error.hidden=true;try{const response=await fetch(form.action,{method:'POST',body:data,headers:{'X-Requested-With':'XMLHttpRequest'}});const result=await response.json().catch(()=>null);if(!response.ok||result?.success!==true){error.textContent=result?.message||'Save was not confirmed. Your text is retained. Reload observations to check before retrying.';error.hidden=false;return;}finish();if(creating)page=1;message.textContent='Observation saved. Manuscript and scene revision state are unchanged.';await load();}catch{error.textContent='Save was not confirmed. Your text is retained; reload recorded observations before retrying.';error.hidden=false;}finally{busy=false;for(const input of form.querySelectorAll('textarea,select'))input.disabled=false;field('Scope').disabled=Number(field('Version').value)>0;button.disabled=false;cancel.disabled=false;}});
editorial.addEventListener('click',e=>{const row=e.target.closest('[data-observation]');if(e.target.closest('[data-review-reload]')){if(dirty){message.textContent='Save or Cancel the editor before reloading observations.';return;}void load();}const pager=e.target.closest('[data-review-page]');if(pager){if(dirty){message.textContent='Save or Cancel before changing observation pages.';return;}page=Number(pager.dataset.reviewPage);void load();}
if(!row)return;if(e.target.closest('[data-review-edit]')){if(dirty){message.textContent='Save or Cancel your current observation first.';return;}field('ContentVersion').value=reader.dataset.version;field('ID').value=row.dataset.id;field('Version').value=row.dataset.version;field('Observation').value=row.querySelector('[data-observation-text]').textContent;field('Decision').value=row.querySelector('[data-decision-text]').textContent;field('Status').value=row.querySelector('[data-review-edit]').dataset.state;field('Classification').value=row.dataset.classification;field('Scope').value=row.dataset.scope;field('SceneID').value=row.dataset.scene||'';field('Scope').disabled=true;pause(true);dirty=true;reference.textContent='Editing a recorded observation; its original accepted-version reference is retained.';showEditor();}
if(e.target.closest('[data-review-revisit]')){if(dirty){message.textContent='Save or Cancel before revisiting another reference.';return;}const target=readerContent.querySelector(`[data-paragraph-id="${CSS.escape(row.dataset.first)}"]`);if(!target){wordReference(null);message.textContent='The original paragraph is missing. Its reference is retained; use the verified chapter action in Word.';return;}target.scrollIntoView({block:'center'});selected=row.dataset.first;anchor=null;wordReference(row.dataset.anchor==='Current'?selected:null);message.textContent=row.dataset.anchor==='Current'?'Original paragraph reference selected. Word has not moved.':'The referenced paragraph changed. Its original reference is retained; exact Word handoff is unavailable. Use the chapter action.';void load();}});
editorial.addEventListener('change',event=>{if(!event.target.matches('[data-annotation-filter]'))return;const type=root.querySelector('[data-annotation-filter=classification]')?.value,status=root.querySelector('[data-annotation-filter=status]')?.value;for(const note of editorial.querySelectorAll('[data-observation]'))note.hidden=!!(type&&note.dataset.classification!==type||status&&note.dataset.status!==status||note.dataset.scope==='Scene'&&note.dataset.scene!==document.querySelector('[data-review-panel]')?.dataset.selectedScene);});
readerContent.addEventListener('click',e=>{if(dirty||busy)return;const p=e.target.closest('[data-paragraph-id]');if(!p)return;anchor=capture()||{StartParagraph:p.dataset.paragraphId,EndParagraph:p.dataset.paragraphId,StartOffset:0,EndOffset:p.textContent.length};selected=anchor.StartParagraph;reference.textContent='Accepted paragraph selected; nothing is saved until you record an observation.';wordReference(selected);queueContext();});
readerContent.addEventListener('keyup',()=>{if(dirty||busy)return;const choice=capture();if(choice){anchor=choice;selected=choice.StartParagraph;wordReference(selected);queueContext();}});
reader.addEventListener('reader:metadata',()=>{if(!dirty)wordReference(selected);});
reader.addEventListener('reader:updated',()=>{if(dirty)return;if(selected&&!readerContent.querySelector(`[data-paragraph-id="${CSS.escape(selected)}"]`)){selected=null;anchor=null;wordReference(null);message.textContent='The selected paragraph is no longer in the accepted chapter. Original observation references remain recorded.';}else wordReference(selected);void load();});
function guard(e){if(!dirty&&!busy)return;const target=e.target.closest('a,form');if(!target||target===form||target.matches('[data-work-start]')||target.target==='_blank'||target.matches('.plotline-help-more')&&window.PlotLineHelpDrawer)return;if(!confirm(busy?'An observation save may still finish. Leave this Review page?':'Leave without saving your review observation?')){e.preventDefault();e.stopImmediatePropagation();}else allowLeave=true;}
document.addEventListener('click',e=>{if(e.target.closest('a'))guard(e);},true);document.addEventListener('submit',guard,true);window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});window.addEventListener('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});window.addEventListener('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});void load();
document.addEventListener('click',e=>{if(e.target.closest('a'))guard(e);},true);document.addEventListener('submit',guard,true);window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allowLeave){e.preventDefault();e.returnValue='';}});window.addEventListener('pageshow',e=>{allowLeave=false;if(e.persisted&&!dirty)void load();});window.addEventListener('pagehide',()=>{clearTimeout(selectionTimer);controller?.abort();});for(const b of document.querySelectorAll('[data-review-scope-new]'))b.addEventListener('click',()=>{begin();field('Scope').value=b.dataset.reviewScopeNew;});window.addEventListener('review:notes-saved',()=>void load());void load();
})();

View File

@ -0,0 +1,4 @@
(()=>{for(const root of document.querySelectorAll('[data-workspace-tabs]'))for(const button of root.querySelectorAll('[data-tab]'))button.addEventListener('click',()=>{for(const b of root.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b===button));for(const panel of root.querySelectorAll('[data-pane]'))panel.hidden=panel.dataset.pane!==button.dataset.tab;});
document.querySelector('[data-session-filter]')?.addEventListener('input',event=>{for(const row of document.querySelectorAll('[data-session-history] article'))row.hidden=!row.textContent.toLowerCase().includes(event.target.value.toLowerCase());});
for(const button of document.querySelectorAll('[data-editorial-toggle]'))button.addEventListener('click',()=>{const panel=document.getElementById(button.dataset.editorialToggle);panel.hidden=!panel.hidden;button.setAttribute('aria-expanded',String(!panel.hidden));});
})();