Add persistent author activity planning with List Board and Schedule views

This commit is contained in:
Nick Beckley 2026-11-18 21:19:13 +00:00
parent c26a67bec7
commit fb537cd4e8
10 changed files with 177 additions and 8 deletions

View File

@ -0,0 +1,27 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Controllers;
[Authorize]
public sealed class WriterActivitiesController(WriterActivityRepository activities,WriterObjectiveRepository objectives,IBookRepository books):Controller
{
int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
[HttpGet]public async Task<IActionResult> Panel(int bookId,string view="list")=>await Guard(async()=>PartialView("~/Views/Writer/_ActivityPlanner.cshtml",new WriterActivityPage(bookId,view is "board" or "schedule"?view:"list",await activities.Read(Actor,bookId),await activities.Entities(Actor,bookId))));
[HttpPost,ValidateAntiForgeryToken]public Task<IActionResult> Save(WriterActivity item)=>Guard(async()=>{
if(!ModelState.IsValid||item.ID==Guid.Empty||!WriterActivity.Kinds.Contains(item.Kind)||!WriterActivity.Statuses.Contains(item.Status))return BadRequest(new{message="Choose a title, activity type and status. Your text is retained."});
string? entityKind=null;int? entityID=null;if(!string.IsNullOrEmpty(item.EntityKey)){var entity=(await activities.Entities(Actor,item.BookID)).SingleOrDefault(e=>e.Key==item.EntityKey);if(entity==null)return BadRequest(new{message="Choose an available related entity."});entityKind=entity.EntityKind;entityID=entity.EntityID;}
await activities.Execute(new{Action="save",UserID=Actor,item.BookID,item.ID,item.Version,item.Title,item.Kind,item.Notes,EntityKind=entityKind,EntityID=entityID,item.Status,item.TargetDate});return Ok(new{saved=true});});
[HttpPost,ValidateAntiForgeryToken]public Task<IActionResult> Change(int bookId,Guid id,int version,string operation,string status="Next",int direction=0,bool confirm=false)=>Guard(async()=>{
if(operation is not("status" or "archive" or "restore" or "move")||operation=="archive"&&!confirm)return BadRequest();
await activities.Execute(new{Action=operation,UserID=Actor,BookID=bookId,ID=id,Version=version,Status=status,Direction=direction});return Ok();});
[HttpPost,ValidateAntiForgeryToken]public Task<IActionResult> Start(int bookId,Guid id,int version)=>Guard(async()=>{
var row=(await activities.Read(Actor,bookId)).SingleOrDefault(x=>x.ID==id&&!x.IsArchived&&x.Version==version);if(row==null)return Conflict(new{message="This activity changed. Reload the planner."});
if(row.EntityID.HasValue&&row.EntityTitle==null)return Conflict(new{message="The linked entity is unavailable. Edit the activity to select another."});
var book=await books.GetAsync(bookId);if(book==null)return NotFound();
if(row.ChapterID.HasValue)await objectives.Save(Actor,new(){BookID=bookId,ChapterID=row.ChapterID,SceneID=row.SceneID,Activity=row.Kind is "Editing" or "Review" or "AudioReview"?"Revising":row.Kind=="Research"?"Researching":"Drafting",Intention=row.Title});
return row.Kind is "Review" or "AudioReview"?RedirectToAction("Review","Writer",new{bookId,chapterId=row.ChapterID}):row.EntityKind=="Character"?RedirectToAction("Edit","Characters",new{id=row.EntityID}):row.EntityKind=="Location"?RedirectToAction("Edit","Locations",new{id=row.EntityID}):row.EntityKind is "PlotLine" or "Thread"||row.Kind=="Plot"?RedirectToAction("Index","PlotLineWorkspace",new{projectId=book.ProjectID,bookId}):RedirectToAction("Write","Writer",new{bookId});
});
async Task<IActionResult> Guard(Func<Task<IActionResult>> action){Response.Headers.CacheControl="no-store";try{return await action();}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number is 51000 or 51002){return StatusCode(e.Number==51002?409:404,new{message="The activity or book is unavailable or changed. Your entered text is retained; reload before retrying."});}}
}

View File

@ -0,0 +1,10 @@
using System.Data;
using Dapper;
using PlotLine.Models;
namespace PlotLine.Data;
public sealed class WriterActivityRepository(ISqlConnectionFactory factory)
{
public async Task<IReadOnlyList<WriterActivity>> Read(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync<WriterActivity>("dbo.WriterActivities_Manage",new{Action="read",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task<IReadOnlyList<WriterActivityEntity>> Entities(int user,int book){using var db=factory.CreateConnection();return(await db.QueryAsync<WriterActivityEntity>("dbo.WriterActivities_Manage",new{Action="entities",UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();}
public async Task Execute(object args){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterActivities_Manage",args,commandType:CommandType.StoredProcedure);}
}

View File

@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace PlotLine.Models;
public sealed class WriterActivity
{
public Guid ID{get;set;} public int BookID{get;set;} public int Version{get;set;}
[Required,StringLength(200)]public string Title{get;set;}="";
[Required]public string Kind{get;set;}="Planning";
[StringLength(10000)]public string? Notes{get;set;}
public string? EntityKind{get;set;} public int? EntityID{get;set;} public string? EntityTitle{get;set;} public int? ChapterID{get;set;}public int? SceneID{get;set;}
public string Status{get;set;}="Next";public int SortOrder{get;set;}public DateTime? TargetDate{get;set;} public bool IsArchived{get;set;}
public DateTime CreatedUtc{get;set;}public DateTime UpdatedUtc{get;set;}
public string? EntityKey{get;set;}
public static readonly string[] Statuses=["Next","In progress","Completed","Deferred"];
public static readonly string[] Kinds=["Writing","Editing","Planning","Research","Character","Plot","Review","AudioReview"];
}
public sealed class WriterActivityEntity{public string EntityKind{get;set;}="";public int EntityID{get;set;}public string Title{get;set;}="";public int? ChapterID{get;set;}public int? SceneID{get;set;}public string Key=>$"{EntityKind}:{EntityID}";}
public sealed record WriterActivityPage(int BookID,string View,IReadOnlyList<WriterActivity> Activities,IReadOnlyList<WriterActivityEntity> Entities);

View File

@ -210,6 +210,7 @@ public class Program
builder.Services.AddScoped<WriterObjectiveRepository>();
builder.Services.AddScoped<WriterWorkRepository>();
builder.Services.AddScoped<WriterPlanningRepository>();
builder.Services.AddScoped<WriterActivityRepository>();
builder.Services.AddSingleton<PlotLine.Services.Writer.IWriterSuggestionProvider, PlotLine.Services.Writer.WriterSuggestionProvider>();
builder.Services.AddHostedService<PlotLine.Services.WritingActivity.WritingActivityRetention>();
builder.Services.AddScoped<IOnboardingRepository, OnboardingRepository>();

View File

@ -0,0 +1,74 @@
-- Author intentions only: no sessions, canonical prose or schedule engine is mutated.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID('dbo.WriterActivities','U') IS NULL
BEGIN
CREATE TABLE dbo.WriterActivities(ID uniqueidentifier NOT NULL PRIMARY KEY,UserID int NOT NULL,BookID int NOT NULL,
Title nvarchar(200) NOT NULL,Kind varchar(30) NOT NULL,Notes nvarchar(max) NULL,EntityKind varchar(20) NULL,EntityID int NULL,
Status varchar(20) NOT NULL DEFAULT 'Next',SortOrder int NOT NULL DEFAULT 0,TargetDate date NULL,IsArchived bit NOT NULL DEFAULT 0,Version int NOT NULL DEFAULT 1,
CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),UpdatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME(),
CONSTRAINT FK_WriterActivities_User FOREIGN KEY(UserID) REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE,
CONSTRAINT FK_WriterActivities_Book FOREIGN KEY(BookID) REFERENCES dbo.Books(BookID) ON DELETE CASCADE,
CONSTRAINT CK_WriterActivities_Status CHECK(Status IN('Next','In progress','Completed','Deferred')),
CONSTRAINT CK_WriterActivities_Entity CHECK((EntityKind IS NULL AND EntityID IS NULL) OR (EntityKind IN('Chapter','Scene','Character','Location','PlotLine','Thread') AND EntityID>0)));
CREATE INDEX IX_WriterActivities_Book ON dbo.WriterActivities(UserID,BookID,IsArchived,SortOrder,ID);
END;
GO
CREATE OR ALTER PROCEDURE dbo.WriterActivities_Manage @Action varchar(15),@UserID int,@BookID int,@ID uniqueidentifier=NULL,@Version int=0,
@Title nvarchar(200)=NULL,@Kind varchar(30)=NULL,@Notes nvarchar(max)=NULL,@EntityKind varchar(20)=NULL,@EntityID int=NULL,@Status varchar(20)='Next',@TargetDate date=NULL,@Direction int=0
AS
BEGIN
SET NOCOUNT ON; SET XACT_ABORT ON;
DECLARE @Project int;
SELECT @Project=b.ProjectID FROM dbo.Books b 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;
IF @Project IS NULL THROW 51000,'Book access unavailable',1;
DECLARE @Entities TABLE(EntityKind varchar(20),EntityID int,Title nvarchar(500),ChapterID int NULL,SceneID int NULL);
INSERT @Entities
SELECT 'Chapter',ChapterID,ChapterTitle,ChapterID,NULL FROM dbo.Chapters WHERE BookID=@BookID AND IsArchived=0
UNION ALL SELECT 'Scene',s.SceneID,s.SceneTitle,c.ChapterID,s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID AND c.IsArchived=0 AND s.IsArchived=0
UNION ALL SELECT 'Character',CharacterID,CharacterName,NULL,NULL FROM dbo.Characters WHERE ProjectID=@Project AND IsArchived=0
UNION ALL SELECT 'Location',LocationID,LocationName,NULL,NULL FROM dbo.Locations WHERE ProjectID=@Project AND IsArchived=0
UNION ALL SELECT 'PlotLine',PlotLineID,PlotLineName,NULL,NULL FROM dbo.PlotLines WHERE ProjectID=@Project AND (BookID IS NULL OR BookID=@BookID) AND IsArchived=0
UNION ALL SELECT 'Thread',t.PlotThreadID,t.ThreadTitle,NULL,NULL FROM dbo.PlotThreads t JOIN dbo.PlotLines p ON p.PlotLineID=t.PlotLineID WHERE p.ProjectID=@Project AND (p.BookID IS NULL OR p.BookID=@BookID) AND p.IsArchived=0 AND t.IsArchived=0;
IF @Action='entities' BEGIN SELECT * FROM @Entities ORDER BY EntityKind,Title;RETURN;END;
IF @Action='read' BEGIN SELECT a.*,e.Title EntityTitle,e.ChapterID,e.SceneID FROM dbo.WriterActivities a LEFT JOIN @Entities e ON e.EntityKind=a.EntityKind AND e.EntityID=a.EntityID WHERE a.UserID=@UserID AND a.BookID=@BookID ORDER BY a.SortOrder,a.CreatedUtc,a.ID;RETURN;END;
IF @Action NOT IN('save','status','archive','restore','move') OR @ID IS NULL THROW 51000,'Invalid planner action',1;
BEGIN TRANSACTION;
IF @Action='save'
BEGIN
IF LEN(COALESCE(@Notes,''))>10000 OR LEN(TRIM(COALESCE(@Title,'')))=0 OR @Kind NOT IN('Writing','Editing','Planning','Research','Character','Plot','Review','AudioReview') OR @Status NOT IN('Next','In progress','Completed','Deferred') THROW 51000,'Choose a title, activity and status',1;
IF (@EntityID IS NULL AND @EntityKind IS NOT NULL) OR (@EntityID IS NOT NULL AND NOT EXISTS(SELECT 1 FROM @Entities WHERE EntityKind=@EntityKind AND EntityID=@EntityID)) THROW 51000,'Related entity is not in this book or project',1;
IF @Version=0
BEGIN
IF EXISTS(SELECT 1 FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID)
BEGIN
IF NOT EXISTS(SELECT 1 FROM dbo.WriterActivities WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND Title=@Title AND Kind=@Kind AND ISNULL(Notes,'')=ISNULL(@Notes,'') AND ISNULL(EntityKind,'')=ISNULL(@EntityKind,'') AND ISNULL(EntityID,0)=ISNULL(@EntityID,0) AND Status=@Status AND ISNULL(TargetDate,'00010101')=ISNULL(@TargetDate,'00010101')) THROW 51002,'Activity changed; reload before retrying',1;
END
ELSE BEGIN
DECLARE @Order int=(SELECT ISNULL(MAX(SortOrder),0)+10 FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID);
INSERT dbo.WriterActivities(ID,UserID,BookID,Title,Kind,Notes,EntityKind,EntityID,Status,TargetDate,SortOrder) VALUES(@ID,@UserID,@BookID,@Title,@Kind,@Notes,@EntityKind,@EntityID,@Status,@TargetDate,@Order);
END;
END
ELSE BEGIN
UPDATE dbo.WriterActivities SET Title=@Title,Kind=@Kind,Notes=@Notes,EntityKind=@EntityKind,EntityID=@EntityID,Status=@Status,TargetDate=@TargetDate,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND Version=@Version;
IF @@ROWCOUNT<>1 THROW 51002,'Activity changed; reload before retrying',1;
END;
END
ELSE BEGIN
DECLARE @Sort int;SELECT @Sort=SortOrder FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE ID=@ID AND UserID=@UserID AND BookID=@BookID AND Version=@Version;
IF @Sort IS NULL THROW 51002,'Activity changed; reload before retrying',1;
IF @Action='status' AND @Status NOT IN('Next','In progress','Completed','Deferred') THROW 51000,'Invalid status',1;
IF @Action='move'
BEGIN
IF @Direction NOT IN(-1,1) THROW 51000,'Invalid order',1;
DECLARE @Other uniqueidentifier,@OtherSort int;
IF @Direction=-1 SELECT TOP(1) @Other=ID,@OtherSort=SortOrder FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID AND IsArchived=0 AND SortOrder<@Sort ORDER BY SortOrder DESC;
ELSE SELECT TOP(1) @Other=ID,@OtherSort=SortOrder FROM dbo.WriterActivities WITH(UPDLOCK,HOLDLOCK) WHERE UserID=@UserID AND BookID=@BookID AND IsArchived=0 AND SortOrder>@Sort ORDER BY SortOrder;
IF @Other IS NOT NULL BEGIN UPDATE dbo.WriterActivities SET SortOrder=@Sort,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@Other;UPDATE dbo.WriterActivities SET SortOrder=@OtherSort,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID;END;
END
ELSE UPDATE dbo.WriterActivities SET Status=CASE WHEN @Action='status' THEN @Status ELSE Status END,IsArchived=CASE WHEN @Action='archive' THEN 1 WHEN @Action='restore' THEN 0 ELSE IsArchived END,Version=Version+1,UpdatedUtc=SYSUTCDATETIME() WHERE ID=@ID;
END;
COMMIT;
END;
GO

View File

@ -0,0 +1,12 @@
@model PlotLine.Models.WriterActivity
<article class="writer21-task" data-activity-id="@Model.ID">
<h4>@Model.Title</h4><p>@Model.Kind · @Model.Status · @(Model.EntityTitle??(Model.EntityID.HasValue?"Unavailable reference":"Across this book")) @if(Model.TargetDate.HasValue){<time>· @Model.TargetDate.Value.ToString("d MMM yyyy")</time>}</p>
@if(!string.IsNullOrWhiteSpace(Model.Notes)){<p>@Model.Notes</p>}
<small>Updated @Model.UpdatedUtc.ToString("d MMM yyyy HH:mm") UTC</small>
<div class="button-row"><form asp-controller="WriterActivities" asp-action="Start" method="post" data-activity-start><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@Model.ID"/><input type="hidden" name="version" value="@Model.Version"/><button class="btn btn-primary">Start working</button></form>
<form asp-controller="WriterActivities" asp-action="Change" method="post" data-activity-change><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@Model.ID"/><input type="hidden" name="version" value="@Model.Version"/><input type="hidden" name="operation" value="status"/><label>Status <select name="status" class="form-select">@foreach(var status in PlotLine.Models.WriterActivity.Statuses){<option selected="@(status==Model.Status)">@status</option>}</select></label><button class="btn btn-outline-secondary">Update status</button></form>
@foreach(var direction in new[]{-1,1}){<form asp-controller="WriterActivities" asp-action="Change" method="post" data-activity-change><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@Model.ID"/><input type="hidden" name="version" value="@Model.Version"/><input type="hidden" name="operation" value="move"/><input type="hidden" name="direction" value="@direction"/><button class="btn btn-outline-secondary" aria-label="@(direction<0?"Move up":"Move down") @Model.Title">@(direction<0?"↑":"↓")</button></form>}
</div>
<details><summary>Edit activity</summary><partial name="~/Views/Writer/_ActivityEditor.cshtml" model="Model" /></details>
<details><summary>Archive activity</summary><p>Keep this record in the archive and remove it from active views.</p><form asp-controller="WriterActivities" asp-action="Change" method="post" data-activity-change><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@Model.ID"/><input type="hidden" name="version" value="@Model.Version"/><input type="hidden" name="operation" value="archive"/><label><input type="checkbox" name="confirm" value="true" required/> Archive this activity</label><button class="btn btn-outline-secondary">Archive</button></form></details>
</article>

View File

@ -0,0 +1,12 @@
@model PlotLine.Models.WriterActivity
@{var choices=(IReadOnlyList<PlotLine.Models.WriterActivityEntity>)ViewData["ActivityEntities"]!;var key="activity-"+Model.ID;}
<form asp-controller="WriterActivities" asp-action="Save" method="post" data-activity-save>
<input type="hidden" name="BookID" value="@Model.BookID"/><input type="hidden" name="ID" value="@Model.ID"/><input type="hidden" name="Version" value="@Model.Version"/>
<label for="@key-title">Title</label><input id="@key-title" class="form-control" name="Title" value="@Model.Title" maxlength="200" required/>
<label for="@key-kind">Activity</label><select id="@key-kind" class="form-select" name="Kind">@foreach(var kind in PlotLine.Models.WriterActivity.Kinds){<option selected="@(kind==Model.Kind)">@kind</option>}</select>
<label for="@key-notes">Notes (optional)</label><textarea id="@key-notes" class="form-control" name="Notes" rows="3" maxlength="10000">@Model.Notes</textarea>
<label for="@key-entity">Related chapter, scene or story entity (optional)</label><select id="@key-entity" class="form-select" name="EntityKey"><option value="">Across this book</option>@foreach(var entity in choices){<option value="@entity.Key" selected="@(entity.EntityKind==Model.EntityKind&&entity.EntityID==Model.EntityID)">@entity.EntityKind · @entity.Title</option>}</select>
<label for="@key-status">Status</label><select id="@key-status" class="form-select" name="Status">@foreach(var status in PlotLine.Models.WriterActivity.Statuses){<option selected="@(status==Model.Status)">@status</option>}</select>
<label for="@key-date">Target date (optional)</label><input id="@key-date" type="date" name="TargetDate" class="form-control" value="@Model.TargetDate?.ToString("yyyy-MM-dd")"/>
<p data-activity-error role="alert"></p><button type="submit" class="btn btn-primary">Save activity</button>
</form>

View File

@ -0,0 +1,14 @@
@model PlotLine.Models.WriterActivityPage
@{ViewData["ActivityEntities"]=Model.Entities;var active=Model.Activities.Where(x=>!x.IsArchived).ToArray();}
<div class="writer21-planner" data-planner-view="@Model.View">
<div class="writer21-tabs" role="tablist" aria-label="Activity views">@foreach(var view in new[]{"list","board","schedule"}){<button type="button" role="tab" aria-selected="@(Model.View==view?"true":"false")" data-planner-tab="@view">@System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToTitleCase(view)</button>}</div>
<p data-planner-message role="status"></p><details><summary>Add planned activity</summary><partial name="~/Views/Writer/_ActivityEditor.cshtml" model="new PlotLine.Models.WriterActivity{ID=Guid.NewGuid(),BookID=Model.BookID}" /></details>
@if(active.Length==0){<p>No planned activities yet. Add one when it helps you organise your work.</p>}
@if(Model.View=="board"){<div class="writer21-board">@foreach(var status in PlotLine.Models.WriterActivity.Statuses){<section><h3>@status</h3>@foreach(var item in active.Where(x=>x.Status==status)){<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />}</section>}</div>}
else if(Model.View=="schedule"){
<h3>Dated activities</h3>@foreach(var item in active.Where(x=>x.TargetDate.HasValue).OrderBy(x=>x.TargetDate)){<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />}
<h3>Undated activities</h3>@foreach(var item in active.Where(x=>!x.TargetDate.HasValue)){<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />}
<p>Existing allocated writing time and schedules are shown below. Target dates do not reserve writing time or generate sessions.</p>
}else{@foreach(var item in active){<partial name="~/Views/Writer/_ActivityCard.cshtml" model="item" />}}
<details><summary>Archived activities (@Model.Activities.Count(x=>x.IsArchived))</summary>@foreach(var item in Model.Activities.Where(x=>x.IsArchived)){<article><h4>@item.Title</h4><p>@item.Notes</p><form asp-controller="WriterActivities" asp-action="Change" method="post" data-activity-change><input type="hidden" name="bookId" value="@Model.BookID"/><input type="hidden" name="id" value="@item.ID"/><input type="hidden" name="version" value="@item.Version"/><input type="hidden" name="operation" value="restore"/><button class="btn btn-outline-secondary">Restore</button></form></article>}</details>
</div>

View File

@ -1,13 +1,8 @@
@model WriterDashboardViewModel
<div class="writer3-workspace writer2-single" aria-label="Writing priorities">
<section class="writer3-panel writer3-main" data-writer-focus data-book-id="@Model.BookID" data-focus-url="@Url.Action("Focus","Writer",new{bookId=Model.BookID})">
<h2>Next activities</h2><p>Choose what deserves your attention next. Dates and schedules are optional.</p>
@if(Model.Work?.Current is {} recording && recording.StartedUtc>DateTime.UtcNow.AddHours(-12)){<section class="writer3-inset"><h3>Recording in progress</h3><p>@recording.Kind · @(recording.ChapterTitle??"Across the book")</p><a asp-action="Write" asp-route-bookId="@Model.BookID">Return to your session</a><p class="writer3-caption">This actual recording is separate from your intended next work.</p></section>}
<section class="writer3-inset"><h3>Your next intended work</h3><div data-focus-summary>
@if(Model.Objective is {} focus){<p><strong>@focus.Activity · @(focus.SceneTitle??focus.ChapterTitle??"Across the book")</strong></p>@if(!string.IsNullOrWhiteSpace(focus.Intention)){<p class="review-recorded">@focus.Intention</p>}<a class="btn btn-primary" asp-action="Write" asp-route-bookId="@Model.BookID">Continue this work</a>}
else{<p>Start with one piece of work you would like to continue. It does not need a deadline.</p>}
</div><a class="btn btn-outline-secondary" asp-action="Write" asp-route-bookId="@Model.BookID" asp-route-setup="true" data-change-focus>@(Model.Objective==null?"Choose next work":"Change next work")</a>
<div id="objective-setup" hidden></div><p class="writer3-caption">This is your saved writing focus, not a completed task or a recorded session.</p></section>
<section class="writer3-panel writer3-main">
<h2>Planned activities</h2><p>What you intend to accomplish. Starting work is separate from recording a session.</p>
<div data-activity-planner data-book="@Model.BookID" data-url="@Url.Action("Panel","WriterActivities",new{bookId=Model.BookID})"><p>Loading your activities…</p></div>
@if(Model.PlannedActivities.Count>0){<h3>Scheduled writing activities</h3><ol class="writer2-activities">@foreach(var item in Model.PlannedActivities.Take(12)){<li><time>@item.ScheduledDate.ToString("ddd d MMM")</time><strong>@item.Kind · @item.Title</strong><span>@item.Status · @item.Minutes planned minutes</span>@if(item.SceneID.HasValue){<a asp-controller="Scenes" asp-action="Edit" asp-route-id="@item.SceneID">Work on this scene</a>}else{<a asp-action="Chapter" asp-route-id="@item.ChapterID">Work on this chapter</a>}</li>}</ol>}
else{<h3>Writing time ahead</h3><partial name="_WriterUpcoming" model="Model" />}
<details class="writer3-inset"><summary>Schedule and completed work</summary><p>@Model.WritingSchedule.CompletedTasks completed · @Model.WritingSchedule.SkippedTasks skipped · @Model.WritingSchedule.RemainingTasks outstanding scheduled tasks. These are recorded task states, not measured manuscript progress.</p>

View File

@ -0,0 +1,7 @@
(()=>{const root=document.querySelector('[data-activity-planner]');if(!root)return;let view=new URLSearchParams(location.search).get('view')||'list',busy=false,dirty=false,allow=false;
async function load(){const url=new URL(root.dataset.url,location.href);url.searchParams.set('view',view);const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw Error('The planner could not load. Reload when connected.');const doc=new DOMParser().parseFromString(await r.text(),'text/html'),panel=doc.querySelector('[data-planner-view]');if(!panel)throw Error('Sign in to resume your planner.');root.replaceChildren(panel);dirty=false;}
root.addEventListener('input',()=>dirty=true);
root.addEventListener('click',async event=>{const tab=event.target.closest('[data-planner-tab]');if(!tab||busy)return;if(dirty&&!confirm('Leave unsaved activity edits?'))return;view=tab.dataset.plannerTab;try{await load();}catch(e){root.querySelector('[data-planner-message]').textContent=e.message;}});
root.addEventListener('submit',async event=>{const form=event.target;if(form.matches('[data-activity-start]')){if(form.dataset.pending==='true'||dirty&&!confirm('Leave unsaved activity edits and start this work?')){event.preventDefault();return;}form.dataset.pending='true';allow=true;return;}if(!form.matches('[data-activity-change],[data-activity-save]'))return;event.preventDefault();if(busy)return;busy=true;const button=event.submitter;button.disabled=true;let committed=false;const message=form.querySelector('[data-activity-error]')||root.querySelector('[data-planner-message]');message.textContent='Saving…';try{const r=await fetch(form.action,{method:'POST',body:new FormData(form)});if(!r.ok){const data=await r.json().catch(()=>null);throw Error(data?.message||'Save not confirmed. Your text is retained. Reload before retrying.');}committed=true;dirty=false;await load();}catch(e){message.textContent=committed?'Saved, but the refreshed planner could not load. Reload the page before making another change.':e.message;}finally{busy=false;button.disabled=committed&&form.isConnected;}});
window.addEventListener('beforeunload',e=>{if((dirty||busy)&&!allow){e.preventDefault();e.returnValue='';}});load().catch(e=>{root.textContent=e.message;});
})();