656 lines
67 KiB
C#
656 lines
67 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Abstractions;
|
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
|
using Microsoft.AspNetCore.Mvc.Rendering;
|
|
using Microsoft.AspNetCore.Mvc.ViewEngines;
|
|
using Microsoft.AspNetCore.Mvc.ViewFeatures;
|
|
using Microsoft.AspNetCore.Routing;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.FileProviders;
|
|
using PlotLine.Controllers;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services;
|
|
using PlotLine.ViewModels;
|
|
|
|
// Isolated, loopback-only host: renders real compiled Razor chrome, never starts app workers or connects to a database.
|
|
internal static class ToolbarBrowserHost
|
|
{
|
|
private static readonly ParagraphManuscript readerFixture = ManuscriptReaderTests.Snapshot();
|
|
private static readonly ParagraphManuscript readerLongFixture = ManuscriptReaderTests.LongSnapshot();
|
|
private static readonly System.Collections.Concurrent.ConcurrentDictionary<(int User, int Chapter), ChapterGoal> writerGoals = new();
|
|
|
|
private static PlotLineWorkspaceData HealthFixture()
|
|
{
|
|
var f = new PlotHealthTests.Fixture();
|
|
f.Add(11, 1, "Introduced"); f.Add(11, 20, "Mentioned"); f.Add(11, 29, "Note");
|
|
f.Add(22, 1, "Developed");
|
|
return f.Data();
|
|
}
|
|
|
|
private static SceneEditViewModel SceneWorkspaceFixture()
|
|
{
|
|
// Optional read-only export for visual checks. This host never accesses the database.
|
|
var snapshot = Environment.GetEnvironmentVariable("PD_SCENE_VISUAL_FIXTURE");
|
|
if (!string.IsNullOrEmpty(snapshot))
|
|
return System.Text.Json.JsonSerializer.Deserialize<SceneEditViewModel>(File.ReadAllText(snapshot))!;
|
|
return new() {
|
|
SceneID = 101, SceneTitle = "Arrival at the harbour", ChapterID = 21, SceneNumber = 1,
|
|
Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour" },
|
|
Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" },
|
|
Chapter = new Chapter { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "The crossing" },
|
|
RevisionStatusID = 1, RevisionStatuses = [new SelectListItem("Planned", "1")],
|
|
POVCharacterID = 1, CharacterOptions = [new SelectListItem("Mara Vale", "1"), new SelectListItem("Elias", "2")],
|
|
RelativeTimeText = "Before dawn", Summary = "Mara reaches the harbour carrying a letter she cannot explain.",
|
|
ScenePurposeTypes = [new() { ScenePurposeTypeID = 1, PurposeName = "Setup" }], SelectedPurposeTypeIds = [1],
|
|
ScenePurposeNotes = "Establish the mystery", SceneOutcomeNotes = "Mara decides to stay",
|
|
Metrics = [new() { MetricName = "Tension", MinValue = 1, MaxValue = 10, Value = 7 }],
|
|
SceneCharacters = Enumerable.Range(1, 8).Select(i => new SceneCharacter { CharacterID = i, CharacterName = i == 1 ? "Mara Vale" : $"Harbour character {i}", RoleInSceneTypeName = i == 1 ? "POV" : "Supporting" }).ToList(),
|
|
ThreadEvents = [new() { EventTitle = "The letter", ThreadTitle = "Missing sender", PlotLineName = "Harbour mystery", EventDescription = "A clue at the water's edge." }],
|
|
Warnings = Enumerable.Range(1, 6).Select(i => new ContinuityWarning { ContinuityWarningID = i, WarningTypeName = "Location", Message = $"Review location evidence {i}." }).ToList(),
|
|
CharacterKnowledge = [new() { CharacterKnowledgeID = 1, CharacterID = 1, CharacterName = "Mara Vale", AssetName = "The letter", KnowledgeStateName = "Knows", Description = "Mara knows the letter was delivered before dawn. She has not yet discovered who sent it." }],
|
|
Notes = [new() { NoteTitle = "Atmosphere", NoteText = "Keep the harbour quiet." }, new() { NoteTitle = "Next draft", NoteText = "Let the letter carry the tension. Hold back the identity of the sender until the next chapter." }],
|
|
ChecklistItems = [new() { ItemText = "Check the tide", IsCompleted = false }]
|
|
};
|
|
|
|
}
|
|
|
|
private static SceneContinuityEditorViewModel SceneContinuityFixture()
|
|
{
|
|
var scene = SceneWorkspaceFixture();
|
|
return new() { Scene = scene, Dashboard = new WarningDashboardViewModel {
|
|
Project = scene.Project!, BookID = scene.Book?.BookID,
|
|
ProjectWarnings = scene.Warnings.Select(w => new ProjectWarningViewModel {
|
|
ContinuityWarningID = w.ContinuityWarningID, Source = "Persisted", WarningTypeDisplayName = w.WarningTypeName,
|
|
Message = w.Message, Severity = "Warning", SceneID = scene.SceneID
|
|
}).ToList()
|
|
}};
|
|
}
|
|
|
|
private static T FixtureProxy<T>(Func<string, object?[]?, object?> handler) where T : class
|
|
{
|
|
var proxy = System.Reflection.DispatchProxy.Create<T, StoryPointProxy>();
|
|
((StoryPointProxy)(object)proxy).Handler = handler;
|
|
return proxy;
|
|
}
|
|
|
|
private static Task SaveFixtureGoal(int userId, ChapterGoalEditViewModel model)
|
|
{
|
|
writerGoals[(userId, model.ChapterID)] = new() {
|
|
ChapterID = model.ChapterID, ChapterGoalID = model.ChapterGoalID,
|
|
GoalSummary = model.GoalSummary, EmotionalGoal = model.EmotionalGoal,
|
|
ReaderTakeaway = model.ReaderTakeaway, MustInclude = model.MustInclude, RisksOrConcerns = model.RisksOrConcerns
|
|
};
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private static WriterDashboardViewModel WriterFixture() => new() {
|
|
ProjectID = 7, BookID=12, Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"}, ProjectOptions = [new SelectListItem("The Glass Harbour", "7", true)],
|
|
WriteNext = [new() { ProjectID = 7, BookID = 12, BookTitle = "A Distant Shore", ChapterID = 21, ChapterNumber = 1, SceneID = 101, SceneNumber = 1, SceneTitle = "The crossing", RevisionStatusName = "Outlined", Summary = "A synthetic writing task." }]
|
|
};
|
|
|
|
private static WriterDashboardViewModel Writer3Fixture(HttpContext context)
|
|
{
|
|
var model = WriterFixture();
|
|
var book = int.TryParse(context.Request.Query["bookId"], out var requested) ? requested : 12;
|
|
model.BookID = book;
|
|
model.Book = new(){BookID=book,ProjectID=7,BookTitle=book==12?"A Distant Shore":"The Return",ChapterCount=book==12?2:0,SceneCount=book==12?2:0,CurrentWordCount=book==12?12400:0};
|
|
if(book==12){
|
|
model.ObjectiveChoices=[new(){ChapterID=21,ChapterTitle="The crossing",SceneID=31,SceneTitle="Arrival"},new(){ChapterID=22,ChapterTitle="The harbour",SceneID=32,SceneTitle="Departure"}];
|
|
if(context.Request.Query["objective"]=="true")model.Objective=new(){BookID=12,ChapterID=21,SceneID=31,Activity="Revising",ChapterTitle="The crossing",SceneTitle="Arrival"};
|
|
if(context.Request.Query["populated"]=="true")model.Activity=new(){BookID=12,Totals=new(){Added=120,Removed=30,HasAcceptedEvidence=true,RecordedEvents=2}};
|
|
}else model.WriteNext=[];
|
|
return model;
|
|
}
|
|
|
|
private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model)
|
|
{
|
|
context.Request.RouteValues["controller"] = controller;
|
|
context.Request.RouteValues["action"] = actionName;
|
|
var action = new ActionContext(context, new RouteData(context.Request.RouteValues), new ActionDescriptor());
|
|
var view = context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null, $"/Views/{controller}/{actionName}.cshtml", true);
|
|
if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations));
|
|
using var writer = new StringWriter();
|
|
await view.View.RenderAsync(new ViewContext(action, view.View,
|
|
new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model, ["WritingEmbedded"] = context.Request.Query["embedded"] == "true" },
|
|
new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>()), writer, new HtmlHelperOptions()));
|
|
context.Response.ContentType = "text/html; charset=utf-8";
|
|
await context.Response.WriteAsync(writer.ToString());
|
|
}
|
|
|
|
public static async Task RunAsync()
|
|
{
|
|
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") });
|
|
builder.Services.AddControllersWithViews().AddApplicationPart(typeof(ToolbarController).Assembly);
|
|
builder.Services.AddSignalR();
|
|
builder.Services.AddSingleton<IWordCompanionPresenceService, WordCompanionPresenceService>();
|
|
builder.Services.AddSingleton<IWritingWorkspacePresenceService, WritingWorkspacePresenceService>();
|
|
builder.Services.AddSingleton(FixtureProxy<IOnboardingRepository>((name, args) => throw new NotSupportedException(name)));
|
|
builder.Services.AddSingleton(FixtureProxy<IOnboardingBuildRepository>((name, args) => throw new NotSupportedException(name)));
|
|
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") : services.GetRequiredService<IHttpContextAccessor>().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture));
|
|
builder.Services.AddHttpContextAccessor();
|
|
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
|
|
builder.Services.AddScoped<ApplicationNavigation>(services => new ApplicationNavigation(
|
|
FixtureProxy<IProjectRepository>((name, args) => name == "GetForUserAsync"
|
|
? Task.FromResult<Project?>(new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" }) : throw new NotSupportedException(name)),
|
|
FixtureProxy<IBookRepository>((name, args) => name == "ListByProjectAsync"
|
|
? Task.FromResult<IReadOnlyList<Book>>([new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, new() { BookID = 13, ProjectID = 7, BookTitle = "The Return" }]) : throw new NotSupportedException(name)),
|
|
services.GetRequiredService<ICurrentUserService>()));
|
|
builder.Services.AddSingleton(FixtureProxy<IBookRepository>((name,args)=>name switch {
|
|
"ListByProjectAsync" => Task.FromResult<IReadOnlyList<Book>>([new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},new(){BookID=13,ProjectID=7,BookTitle="The Return"}]),
|
|
"GetAsync" => Task.FromResult<Book?>((int)args![0]! is 12 or 13 ? new(){BookID=(int)args[0]!,ProjectID=7,BookTitle=(int)args[0]! == 12?"A Distant Shore":"The Return"} : null),
|
|
_ => throw new NotSupportedException(name)
|
|
}));
|
|
builder.Services.AddSingleton(FixtureProxy<IProjectAccessService>((name,args)=>Task.FromResult(name=="CanAccessProjectAsync"?(int)args![0]! == 7:(int)args![1]! is 12 or 13)));
|
|
builder.Services.AddScoped<IWriterWorkspaceService>(services => FixtureProxy<IWriterWorkspaceService>((name, args) => name switch {
|
|
"GetDashboardAsync" => Task.FromResult(Writer3Fixture(services.GetRequiredService<IHttpContextAccessor>().HttpContext!)),
|
|
"GetChapterWorkflowAsync" => Task.FromResult<ChapterWorkflowViewModel?>(new() {
|
|
Project = new() { ProjectID = 7, ProjectName = "The Glass Harbour" },
|
|
Book = new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" },
|
|
Chapter = new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" },
|
|
Goal = writerGoals.GetOrAdd((services.GetRequiredService<ICurrentUserService>().UserId!.Value, 21), _ => new() { ChapterID = 21, GoalSummary = "Reveal the consequence" })
|
|
}),
|
|
"SaveChapterGoalAsync" => SaveFixtureGoal(services.GetRequiredService<ICurrentUserService>().UserId!.Value, (ChapterGoalEditViewModel)args![0]!),
|
|
_ => throw new NotSupportedException(name)
|
|
}));
|
|
builder.Services.AddSingleton(FixtureProxy<IWritingScheduleService>((name, args) => name switch {
|
|
"GetTodayDashboardAsync" => Task.FromResult(new WritingScheduleDashboardViewModel()),
|
|
"GetWritingPlansForManagementAsync" => Task.FromResult(new WritingPlansManagementViewModel()),
|
|
"GetSchedulePreviewAsync" => Task.FromResult(new WritingSchedulePreviewViewModel()),
|
|
"GetScheduleSetupAsync" => Task.FromResult(new WritingScheduleSetupViewModel()),
|
|
_ => throw new NotSupportedException(name)
|
|
}));
|
|
builder.Services.AddSingleton(FixtureProxy<ISubscriptionService>((name, args) => name == "GetEffectiveEntitlementAsync" ? Task.FromResult(new EffectiveEntitlement { UserID = 4, State = EntitlementState.ActivePaid }) : throw new NotSupportedException(name)));
|
|
builder.Services.AddSingleton(FixtureProxy<IFeatureRequestService>((name, args) => name == "CountAttentionForUserAsync" ? Task.FromResult(0) : throw new NotSupportedException(name)));
|
|
builder.Services.AddSingleton(FixtureProxy<IOnboardingService>((name, args) => name == "ShouldShowWordCompanionHeaderAsync" ? Task.FromResult(false) : throw new NotSupportedException(name)));
|
|
builder.Services.AddSingleton(FixtureProxy<IStoryIntelligenceGlobalProgressService>((name, args) => name == "GetForCurrentUserAsync" ? Task.FromResult(new StoryIntelligenceGlobalProgressViewModel()) : throw new NotSupportedException(name)));
|
|
builder.Services.AddSingleton<IHelpService, HelpService>();
|
|
builder.Services.AddSingleton<IWritingSolverRepository, WritingSolverFixtureRepository>();
|
|
builder.Services.AddSingleton<IWritingSolverWorkspaceContext, SolverWorkspaceFixture>();
|
|
builder.Services.AddMemoryCache();
|
|
builder.Services.AddSingleton<WritingSolverResultContext>();
|
|
builder.Services.AddScoped<WritingSolverReview>();
|
|
builder.Services.AddSingleton<WritingSolverReviewStore>();
|
|
builder.Services.AddSingleton(services=>new WritingSolverPayoff(Path.GetFullPath("PlotLine/Content/WritingSolver/Presentation/payoff-v1.json")));
|
|
builder.Services.AddAuthorization(options=>options.AddPolicy("AdminOnly",policy=>policy.RequireClaim(ClaimTypes.Role,"SolverReviewer")));
|
|
builder.Services.AddSingleton(new WritingProblemEditorial(Path.GetFullPath("PlotLine/Content/WritingSolver/Editorial/pages-v1.json")));
|
|
builder.Services.AddSingleton(new WritingSolverResults(Path.GetFullPath("PlotLine/Content/WritingSolver/Presentation/results-v1.json")));
|
|
builder.Services.AddSingleton<IHelpMarkdownRenderer, HelpMarkdownRenderer>();
|
|
builder.Services.AddScoped<ICurrentUserService>(services => new ToolbarTestUser(int.Parse(services.GetRequiredService<IHttpContextAccessor>().HttpContext!.User.FindFirstValue(ClaimTypes.NameIdentifier)!)));
|
|
builder.Services.AddAuthentication("ReviewFixture").AddCookie("ReviewFixture",options=>{options.Events.OnRedirectToLogin=c=>{c.Response.StatusCode=401;return Task.CompletedTask;};options.Events.OnRedirectToAccessDenied=c=>{c.Response.StatusCode=403;return Task.CompletedTask;};});
|
|
builder.Services.AddSingleton<IStoryCalendarService>(new StoryCalendarService(new FakeTimelineRepository(CalendarNavigationTests.Data())));
|
|
var app = builder.Build();
|
|
app.UseWritingSolverReviewBoundary();
|
|
app.MapGet("/writer2-fixture",async (HttpContext context)=>{
|
|
var model=WriterFixture();
|
|
model.Book = new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore",ChapterCount=3,SceneCount=7,CurrentWordCount=12400};
|
|
model.ObjectiveChoices=[new(){ChapterID=21,ChapterTitle="The crossing",SceneID=31,SceneTitle="Arrival"},new(){ChapterID=22,ChapterTitle="The harbour",SceneID=32,SceneTitle="Departure"}];
|
|
if(context.Request.Query["objective"]=="true") model.Objective=new(){BookID=12,ChapterID=21,SceneID=31,Activity="Revising",ChapterTitle="The crossing",SceneTitle="Arrival"};
|
|
if(context.Request.Query["populated"]=="true")
|
|
{
|
|
var now=DateTime.UtcNow;
|
|
model.Activity=new(){BookID=12,Totals=new(){Added=120,Removed=30,ActiveDays=2,RecordedEvents=3,AcceptedEvents=3,HasAcceptedEvidence=true,CoverageSinceUtc=now.AddDays(-2)},Days=[new(){Day=now.Date.AddDays(-1),Added=80,Removed=20,Changes=1},new(){Day=now.Date,Added=40,Removed=10,Changes=1}],Events=[new(){BookID=12,ReceivedUtc=now,Kind="Change",Source="WordCompanion",Added=40,Removed=10}]};
|
|
}
|
|
if(context.Request.Query["workOnly"]=="true"){model.Activity=null;model.Work=new(){BookID=12,Year=DateTime.UtcNow.Year,Month=DateTime.UtcNow.Month,Days=[new(){Day=DateTime.UtcNow.Date,Planning=1}]};}
|
|
model.Suggestions = new PlotLine.Services.Writer.WriterSuggestionProvider().Suggest(model);
|
|
if(context.Request.Query["journey"]=="true"){
|
|
model.Journey=true;
|
|
model.Work=new(){BookID=12,Year=2026,Month=11,Days=[new(){Day=new(2026,11,14),Added=2000,Removed=2000,Changes=4,Editing=1,EngagedSeconds=300},new(){Day=new(2026,11,15),AudioReview=1,PlaybackSeconds=600}]};
|
|
}
|
|
model.Workspace=context.Request.Query["workspace"].ToString() is "Revision"?"Revision":"WriteNext";
|
|
await RenderFullAsync(context,"Writer","Legacy",model);
|
|
});
|
|
app.Urls.Add(Environment.GetEnvironmentVariable("PD_BROWSER_FIXTURE_URL") ?? "http://127.0.0.1:5238");
|
|
app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.GetFullPath("PlotLine/wwwroot")) });
|
|
app.Use(async (context, next) =>
|
|
{
|
|
var user = context.Request.Cookies["fixture-user"] == "5" ? "5" : "4";
|
|
context.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user), new Claim(ClaimTypes.Name, "Fixture Author")], "Fixture"));
|
|
if(context.Request.Cookies["solver-reviewer"]=="true") ((ClaimsIdentity)context.User.Identity!).AddClaim(new Claim(ClaimTypes.Role,"SolverReviewer"));
|
|
if(context.Request.Cookies["solver-anonymous"]=="true") context.User=new ClaimsPrincipal(new ClaimsIdentity());
|
|
await next();
|
|
});
|
|
app.UseRouting();
|
|
app.UseAuthorization();
|
|
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
|
|
app.MapGet("/Projects", () => Results.Redirect("/fixture"));
|
|
app.MapGet("/map-story-fixture", () => {
|
|
var projection = MapStoryComposer.Compose(MapStoryTests.Fixture(), MapStoryTests.Plots(), 1);
|
|
projection.UserID=4;return Results.Json(projection);
|
|
});
|
|
app.MapGet("/plot-map-fixture", async context =>
|
|
{
|
|
var data = context.Request.Query["marketing"] == "true" ? PublicWebsiteFixtures.PlotMap()
|
|
: context.Request.Query["health"] == "true" || context.Request.Query["healthDetail"] == "true" ? HealthFixture() : PlotLineWorkspaceTests.Fixture();
|
|
var ids = context.Request.Query["focus"] == "true" ? new[] { 1 } : new[] { 1, 2, 3 };
|
|
var model = new PlotLineWorkspaceViewModel {
|
|
Project = new Project { ProjectID = 7 },
|
|
PlotLines = data.PlotLines.Where(l => ids.Contains(l.PlotLineID)).Select(l => new PlotLineWorkspaceLineViewModel { Line = l, IsSelected = true, Threads = data.Threads.Where(t => t.PlotLineID == l.PlotLineID).ToList() }).ToList(),
|
|
SelectedPlotLineIDs = ids,
|
|
Mode = ids.Length == 1 ? "Focus" : "Weave",
|
|
Scenes = PlotLineWorkspaceComposer.Compose(data, ids),
|
|
MapTargets = data.Targets,
|
|
AssociationScenes = data.AttributionScenes,
|
|
Health = new PlotHealthEvaluator().Evaluate(new(7, null, null, ids, data, data))
|
|
};
|
|
var action = new ActionContext(context, new RouteData(), new ActionDescriptor());
|
|
var view = context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null, context.Request.Query["healthDetail"] == "true" ? "/Views/PlotLineWorkspace/_Health.cshtml" : "/Views/PlotLineWorkspace/_NarrativeMap.cshtml", false);
|
|
if (!view.Success || view.View is null)
|
|
throw new InvalidOperationException($"Fixture view could not be resolved: {string.Join(", ", view.SearchedLocations)}");
|
|
using var writer = new StringWriter();
|
|
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model };
|
|
await view.View.RenderAsync(new ViewContext(action, view.View, viewData, new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>()), writer, new HtmlHelperOptions()));
|
|
context.Response.ContentType = "text/html; charset=utf-8";
|
|
if (context.Request.Query["healthDetail"] == "true" && context.Request.Query["marketing"] != "true") { await context.Response.WriteAsync(writer.ToString()); return; }
|
|
await context.Response.WriteAsync("<html data-app-theme='modern-dark' data-theme='dark'><head><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'></head><body class='app-layout'><form id='plot-workspace-form'><input type='hidden' name='projectId' value='7'><input id='plot-scene-search' type='search'></form>" + writer + "<div id='plot-inspector-backdrop' hidden></div><aside class='plot-inspector' id='plot-inspector' aria-hidden='true'><div id='plot-inspector-content'></div></aside><script src='/js/plot-line-workspace.js'></script></body></html>");
|
|
});
|
|
// Public QA renders the real views/layout with isolated models; no account, payment or DB calls.
|
|
app.MapGet("/public-fixture/{page}", async context =>
|
|
{
|
|
var page = context.Request.RouteValues["page"]?.ToString() ?? "home";
|
|
var (controller, viewName, viewModel) = page switch
|
|
{
|
|
"home" => ("Home", "Index", (object?)null),
|
|
"tour" => ("Public", "Features", (object?)null),
|
|
"login" => ("Account", "Login", (object?)new LoginViewModel { ReturnUrl = "/Projects" }),
|
|
"register" => ("Account", "Register", (object?)new RegisterViewModel()),
|
|
"pricing" => ("Pricing", "Index", (object?)new PricingViewModel { Plans = Enumerable.Range(0, 4).Select(i => new SubscriptionLevel {
|
|
SubscriptionLevelID = i + 1, DisplayName = new[] { "Draft Desk", "Writing Room", "Story Forge", "Author Studio" }[i],
|
|
RequiresStripeSubscription = i > 0, MonthlyPricePence = i == 0 ? null : i * 500, AnnualPricePence = i == 0 ? null : i * 5000,
|
|
MaxBooks = i + 1, MaxChaptersPerBook = (i + 1) * 50, MaxCharactersPerProject = (i + 1) * 50, MaxScenesPerBook = (i + 1) * 100, MaxStorageMB = (i + 1) * 250, MaxCollaborators = i
|
|
}).ToList() }),
|
|
_ => throw new InvalidOperationException("Unknown public fixture")
|
|
};
|
|
if (context.Request.Query["anonymous"] == "true") context.User = new ClaimsPrincipal(new ClaimsIdentity());
|
|
if (context.Request.Query.TryGetValue("theme", out var theme) && ApplicationAppearance.IsValid(theme.ToString()))
|
|
await context.RequestServices.GetRequiredService<IAppearanceRepository>().SaveThemeAsync(4, theme.ToString());
|
|
var route = new RouteData(); route.Values["controller"] = controller; route.Values["action"] = viewName;
|
|
var action = new ActionContext(context, route, new ActionDescriptor());
|
|
var view = context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null, $"/Views/{controller}/{viewName}.cshtml", true);
|
|
if (!view.Success) throw new InvalidOperationException(string.Join(",", view.SearchedLocations));
|
|
using var writer = new StringWriter();
|
|
var data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = viewModel };
|
|
await view.View.RenderAsync(new ViewContext(action, view.View, data, new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>()), writer, new HtmlHelperOptions()));
|
|
context.Response.ContentType = "text/html; charset=utf-8";
|
|
await context.Response.WriteAsync(writer.ToString());
|
|
});
|
|
app.MapGet("/writing-desk-fixture/{role}",async context=>
|
|
{
|
|
var role=context.Request.RouteValues["role"]?.ToString();var empty=context.Request.Query["empty"]=="true";
|
|
var scene=new SceneEditViewModel{SceneID=int.TryParse(context.Request.Query["sceneId"],out var selectedScene)?selectedScene:22,SceneTitle="A deliberately long scene title for a narrow reference screen",ChapterID=selectedScene==23?11:10,ScenePurposeNotes="Reveal the letter",Summary="Saved scene summary",Project=new Project{ProjectID=7,ProjectName="Fixture project"},Book=new Book{BookID=12,BookTitle="Fixture book"},Chapter=new Chapter{ChapterID=selectedScene==23?11:10,ChapterTitle=selectedScene==23?"Next chapter":"Opening",ChapterNumber=selectedScene==23?2:1}};
|
|
if(context.Request.Query["large"]=="true"){var index=Math.Max(0,scene.SceneID-22);scene.ChapterID=10+index/8;scene.Chapter=new(){ChapterID=scene.ChapterID,ChapterNumber=index/8+1,ChapterTitle="Chapter "+(index/8+1)};scene.SceneNumber=index%8+1;scene.SceneTitle="Scene "+(index+1);}
|
|
var story=new StoryContextViewModel{Position=new StoryPosition(7,12,scene.ChapterID,scene.SceneID),Scene=scene};
|
|
object model=role=="evidence"?new IntentAssessmentFrame(22,context.Request.Query["stale"]=="true"?"new-hash":"saved-hash",[new("purpose","Reveal the letter")],"Saved prose",new IntentAssessment{InputHash="saved-hash",CreatedUtc=DateTime.UtcNow,ResultsJson=System.Text.Json.JsonSerializer.Serialize(new[]{new IntentEvidence("purpose","partial","A qualified suggestion","Saved prose","Reveal the letter")}),DecisionsJson="{\"purpose\":\"deferred\"}"}):role=="context"?new WritingContextDisplayViewModel{Context=empty?null:story,SceneOptions=[new("Chapter one · first scene","22",scene.SceneID==22),new("Chapter two · next scene","23",scene.SceneID==23)]}:new WritingIntentDisplayViewModel{Context=empty?null:story};
|
|
if(model is WritingContextDisplayViewModel reference&&context.Request.Query["large"]=="true")reference.SceneOptions=Enumerable.Range(0,400).Select(i=>new SelectListItem($"Chapter {i/8+1} · Scene {i%8+1}",(i+22).ToString(),scene.SceneID==i+22)).ToArray();
|
|
if(role=="context"&&context.Request.Query["floor"]=="true"){
|
|
scene.PrimaryLocationID=77;scene.FloorPlanID=1;scene.InitialFloorPlanFloorID=8;
|
|
((WritingContextDisplayViewModel)model).FloorPlan=new(){FloorPlan=new(){FloorPlanID=1,Name="The inn"},Floors=[new(){FloorPlanFloorID=8,Name="Upper floor",GridWidth=20,GridHeight=10}],Blocks=[new(){FloorPlanFloorID=8,FloorPlanBlockID=9,LocationID=77,LocationName="Guest room",X=2,Y=2,WidthCells=4,HeightCells=3}]};
|
|
}
|
|
var writingRoute=new RouteData();writingRoute.Values["controller"]="Writing";var action=new ActionContext(context,writingRoute,new ActionDescriptor());var path=role=="evidence"?"/Views/Writing/_IntentAssessment.cshtml":role=="context"?"/Views/Writing/_WritingContextContent.cshtml":"/Views/Writing/_WritingIntentContent.cshtml";
|
|
var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,path,false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};
|
|
await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));
|
|
if(context.Request.Query["fragment"]=="true"){context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());return;}
|
|
context.Response.ContentType="text/html";await context.Response.WriteAsync("<html data-theme='light'><head><meta name='viewport' content='width=device-width'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/writing-context-plots.css'></head><body class='app-layout writing-embedded'><main class='writing-context-page'>"+writer+"</main><script src='/js/intent-assessment.js'></script></body></html>");
|
|
});
|
|
app.MapGet("/writing-context-component/{kind}",async context=>{
|
|
var kind=context.Request.RouteValues["kind"]?.ToString();var mapID=int.TryParse(context.Request.Query["mapId"],out var selectedMap)?selectedMap:1;var sceneId=int.TryParse(context.Request.Query["sceneId"],out var sid)?sid:22;
|
|
var scenes=new[]{new Scene{SceneID=22,ChapterID=10,SceneNumber=1,SceneTitle="Harbour arrival"},new Scene{SceneID=23,ChapterID=11,SceneNumber=1,SceneTitle="A room above the quay"}};
|
|
var mapFeature=Guid.Parse("11111111-1111-4111-8111-111111111111");var second=Guid.Parse("22222222-2222-4222-8222-222222222222");
|
|
object model=kind=="plots"?new PlotLineWorkspaceViewModel{Project=new(){ProjectID=7},SelectedBookID=12,PlotLines=[new(){Line=new(){PlotLineID=1,PlotLineName="The missing letter",Colour="#487b70"},IsSelected=true}],AssociationScenes=[new(){SceneID=22,SceneTitle=scenes[0].SceneTitle,ChapterNumber=1,SceneNumber=1,NarrativeOrder=0},new(){SceneID=23,SceneTitle=scenes[1].SceneTitle,ChapterNumber=2,SceneNumber=1,NarrativeOrder=1}],Scenes=[new(){SceneID=22,Memberships=[new(){PlotLineID=1,PlotLineName="The missing letter",Contributions=[new(){ThreadTitle="The arrival",CanonicalTitle="The letter changes hands"}]}]}]}:
|
|
kind=="metrics"?WritingContextMetrics.Build(new TimelineData{Project=new(){ProjectID=7},Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12,ChapterNumber=1},new(){ChapterID=11,BookID=12,ChapterNumber=2}],Scenes=scenes,MetricTypes=[new(){MetricTypeID=1,MetricName="Emotional intensity",MinValue=0,MaxValue=10,DefaultValue=5},new(){MetricTypeID=2,MetricName="Emotional direction",MinValue=-5,MaxValue=5}],MetricPoints=[new(){SceneID=22,MetricTypeID=1,Value=8},new(){SceneID=23,MetricTypeID=2,Value=0}]},[new(){SceneID=22,MetricTypeID=1,MetricName="Emotional intensity",MinValue=0,MaxValue=10,Value=8},new(){SceneID=23,MetricTypeID=2,MetricName="Emotional direction",MinValue=-5,MaxValue=5,Value=0}]):
|
|
new WritingContextMapViewModel{ProjectID=7,BookID=12,SceneID=sceneId,Maps=[new(){MapID=1,Name="Harbour map"},new(){MapID=2,Name="Neighbouring coast"}],Position=new(){FeatureID=sceneId==22?mapFeature:second,LocationID=77,LocationName="Saved harbour",Status="Mapped"},Document=context.Request.Query["empty"]=="true"?null:new(){Map=new(){MapID=mapID,ProjectID=7,Name="Harbour map"},Features=[new(){FeatureID=mapFeature,Name="Harbour",X=0,Y=0,LocationID=77,IsPlaced=true},new(){FeatureID=second,Name="Inn",X=500,Y=200,IsPlaced=true}],Relationships=[new(){SourceID=mapFeature,TargetID=second,Direction="NE",RelativeDistance="Close",TypicalTravelTime="Ten minutes"}]},Story=new(){Scenes=[new(){SceneID=22,PlotLineIDs=[1],Position=new(){FeatureID=mapFeature}}],Stops=[new(){SceneID=22,Position=new(){FeatureID=second}}]}};
|
|
if(context.Request.Query["large"]=="true"&&model is PlotLineWorkspaceViewModel large){
|
|
large.PlotLines=Enumerable.Range(1,10).Select(i=>new PlotLineWorkspaceLineViewModel{Line=new(){PlotLineID=i,PlotLineName="Plot line "+i,Colour=PlotLineColours.ForLine(i,null)},IsSelected=true}).ToArray();
|
|
large.AssociationScenes=Enumerable.Range(0,400).Select(i=>new PlotLineWorkspaceAttributionRow{SceneID=i+22,SceneTitle="Scene "+(i+1),ChapterNumber=i/8+1,SceneNumber=i%8+1,NarrativeOrder=i}).ToArray();
|
|
large.Scenes=Enumerable.Range(0,400).Select(i=>new PlotLineWorkspaceSceneViewModel{SceneID=i+22,Memberships=[new(){PlotLineID=i%10+1,PlotLineName="Plot line "+(i%10+1),Contributions=[new(){ThreadTitle="Saved thread",CanonicalTitle="Recorded development "+(i+1)}]}]}).ToArray();
|
|
}
|
|
if(kind=="plots"&&context.Request.Query["contextCases"]=="true") {
|
|
var ids=new[]{22,900,23,47,1001,35,4,61,88};
|
|
var positions=ids.Select((id,i)=>new PlotLineWorkspaceAttributionRow{SceneID=id,BookID=12,NarrativeOrder=i*3+1,ChapterNumber=i<2?1:i<5?3:i<6?4:i<8?9:12,SceneNumber=i==2?2.5m:i+1,SceneTitle="Saved scene "+id}).ToArray();
|
|
var lines=Enumerable.Range(1,7).Select(i=>new PlotLineWorkspaceLineViewModel{Line=new(){PlotLineID=i,PlotLineName="Saved line "+i,Description=i==6?null:"Saved description "+i,Colour=i==1?"#ba5365":"#487b70"}}).ToArray();
|
|
PlotLineWorkspaceSceneMembershipViewModel Member(int line,params string[] titles)=>new(){PlotLineID=line,PlotLineName="Saved line "+line,Contributions=titles.Select((title,i)=>new PlotLineWorkspaceContributionRow{ThreadEventID=line*10+i,ThreadTitle="Saved thread "+line,CanonicalTitle=title,CanonicalDescription=title.Length>0?"Saved detail for "+title:null}).ToArray()};
|
|
model=new PlotLineWorkspaceViewModel{AssociationScenes=positions,PlotLines=lines,Scenes=[
|
|
new(){SceneID=22,Memberships=[Member(1,"Earlier active development"),Member(2,"Previous only")]},
|
|
new(){SceneID=900,Memberships=[Member(4,"Before both")]},
|
|
new(){SceneID=23,Memberships=[Member(1,"Current first","Current second"),Member(5),Member(7,"")]},
|
|
new(){SceneID=4,Memberships=[Member(1,"Upcoming active development")]},
|
|
new(){SceneID=61,Memberships=[Member(4,"After both")]},
|
|
new(){SceneID=88,Memberships=[Member(3,"Future only")]}
|
|
]};
|
|
}
|
|
var path=kind=="plots"?"_WritingContextPlotLines":kind=="metrics"?"_WritingContextMetrics":"_WritingContextMap";
|
|
var route=new RouteData();route.Values["controller"]="Writing";var action=new ActionContext(context,route,new ActionDescriptor());
|
|
var view=context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null,"/Views/Writing/"+path+".cshtml",false);using var writer=new StringWriter();
|
|
await view.View!.RenderAsync(new ViewContext(action,view.View,new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model},new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));
|
|
context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());
|
|
});
|
|
app.MapGet("/book-recovery-fixture/{step}",async context=>{
|
|
var project=new Project{ProjectID=7,ProjectName="Harbour collection"};
|
|
var snapshot=new ProjectBackupExport{Project=project,Data=new(){Books=[new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore — long title with notes",SortOrder=1},new(){BookID=13,ProjectID=7,BookTitle="The archived sequel",IsArchived=true,SortOrder=2}]}};
|
|
var package=new BookBackupPackage{SourceProjectKey=Guid.NewGuid(),Snapshot=snapshot,Warnings=["Contains private manuscript prose. Downloading never deletes your books."]};var upload=Guid.NewGuid();
|
|
var model=new BookRecoveryPage{Projects=[project],ProjectID=7,BookID=context.Request.Query.ContainsKey("single")?12:null,Source=snapshot,Package=package,Upload=upload,UploadName="Harbour-books.plotdirector"};
|
|
var step=context.Request.RouteValues["step"]?.ToString()??"Backup";
|
|
if(step=="Preview")model.Preview=new(new(upload,[12,13],0,"Recovered harbour","",Guid.NewGuid(),DateTime.UtcNow.AddMinutes(20)),"fixture-confirmation",snapshot,12,5,context.Request.Query.ContainsKey("full")?0:4,package.Warnings);
|
|
await RenderFullAsync(context,"BookRecovery",step,step=="Complete"?new BookRecoveryReceipt{ProjectID=7,BooksCreated=2}:model);
|
|
});
|
|
app.MapGet("/Writing/Context", context => RenderFullAsync(context, "Writing", "Context", new WritingContextPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1);
|
|
app.MapGet("/Writing/Intent", context => RenderFullAsync(context, "Writing", "Intent", new WritingIntentPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1);
|
|
app.MapGet("/fixture", async context =>
|
|
{
|
|
if (context.Request.Query["page"] == "writer" && context.Request.Query["layout"] == "full")
|
|
{
|
|
await RenderFullAsync(context, "Writer", "Legacy", WriterFixture());
|
|
return;
|
|
}
|
|
var model = new ApplicationNavigationViewModel { ActiveSection = "Calendar", ShowCompanionPresence = true };
|
|
if (context.Request.Query["project"] != "none")
|
|
{
|
|
model.Project = new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = context.Request.Query["owner"] == "false" ? "Editor" : "Owner" };
|
|
model.Book = new Book { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore", BookNumber = 1 };
|
|
model.Books = [model.Book, new Book { BookID = 13, ProjectID = 7, BookTitle = "The Return", BookNumber = 2 }];
|
|
}
|
|
var fullLayout = context.Request.Query["layout"] == "full";
|
|
string? fullView = null;
|
|
object? fullModel = null;
|
|
string? recordLayout = null;
|
|
var writerScripts = "";
|
|
var dashboardPage = context.Request.Query["page"] == "dashboard";
|
|
var timelinePage = context.Request.Query["page"] == "timeline";
|
|
if (dashboardPage) model.ActiveSection = "Overview";
|
|
if (timelinePage) model.ActiveSection = "Timeline";
|
|
var appearance = await context.RequestServices.GetRequiredService<IAppearanceRepository>().GetAsync(int.Parse(context.User.FindFirstValue(ClaimTypes.NameIdentifier)!));
|
|
var route = new RouteData(); route.Values["controller"] = context.Request.Query["page"] == "relationships" ? "RelationshipMap" : dashboardPage ? "Projects" : "StoryCalendar"; route.Values["action"] = dashboardPage ? "Details" : "Index";
|
|
var action = new ActionContext(context, route, new ActionDescriptor());
|
|
async Task<string> Render(string name, object? viewModel = null)
|
|
{
|
|
if (fullLayout)
|
|
{
|
|
if (!name.StartsWith("Shared/") && !name.EndsWith("/_GraphScripts") && name != "Timeline/Settings")
|
|
{
|
|
fullView = name == "StoryCalendar/_StoryCalendarSurface" ? "StoryCalendar/Index" : name;
|
|
fullModel = viewModel ?? model;
|
|
}
|
|
return "";
|
|
}
|
|
var view = context.RequestServices.GetRequiredService<ICompositeViewEngine>().GetView(null, $"/Views/{name}.cshtml", false);
|
|
if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations));
|
|
using var writer = new StringWriter();
|
|
var data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = viewModel ?? model };
|
|
data["ApplicationAppearance"] = appearance;
|
|
var temp = new TempDataDictionary(context, context.RequestServices.GetRequiredService<ITempDataProvider>());
|
|
await view.View.RenderAsync(new ViewContext(action, view.View, data, temp, writer, new HtmlHelperOptions()));
|
|
if (name == "FloorPlans/Edit" && view.View is Microsoft.AspNetCore.Mvc.Razor.RazorView razorView
|
|
&& razorView.RazorPage.SectionWriters.TryGetValue("Scripts", out var scripts))
|
|
{
|
|
writer.Write("<script src='/lib/jquery/dist/jquery.min.js'></script>");
|
|
razorView.RazorPage.ViewContext.Writer = writer;
|
|
await scripts();
|
|
}
|
|
|
|
if (name == "Writer/Legacy" && view.View is Microsoft.AspNetCore.Mvc.Razor.RazorView writerView
|
|
&& writerView.RazorPage.SectionWriters.TryGetValue("Scripts", out var writerSection))
|
|
{
|
|
using var scriptWriter = new StringWriter();
|
|
writerView.RazorPage.ViewContext.Writer = scriptWriter;
|
|
await writerSection();
|
|
writerScripts = scriptWriter.ToString();
|
|
}
|
|
return writer.ToString();
|
|
}
|
|
if (context.Request.Query["page"] == "scene-edit" && context.Request.Query.TryGetValue("editor", out var requestedEditor))
|
|
{
|
|
var editors = new Dictionary<string, string> { ["purpose"] = "Purpose", ["relationships"] = "Relationships", ["characters"] = "Characters", ["metrics"] = "Metrics", ["threads"] = "Threads", ["dependencies"] = "Dependencies", ["locations"] = "Locations", ["assets"] = "Assets", ["notes"] = "Notes", ["checklist"] = "Checklist", ["workflow"] = "Workflow", ["attachments"] = "Attachments", ["warnings"] = "Continuity", ["scene-details"] = "Details", ["knowledge"] = "Knowledge", ["attributes"] = "CharacterAttributes", ["suggestions"] = "Suggestions" };
|
|
if (!editors.TryGetValue(requestedEditor.ToString(), out var editorName)) { context.Response.StatusCode = 404; return; }
|
|
context.Response.ContentType = "text/html";
|
|
await context.Response.WriteAsync(await Render($"Shared/SceneInspectorV2/_Scene{editorName}Editor", editorName == "Continuity" ? SceneContinuityFixture() : SceneWorkspaceFixture()));
|
|
return;
|
|
}
|
|
if (context.Request.Query["page"] == "scene-edit")
|
|
{
|
|
var scene = SceneWorkspaceFixture();
|
|
model.Project = scene.Project;
|
|
model.Book = scene.Book;
|
|
model.Books = scene.Book is null ? [] : [scene.Book];
|
|
}
|
|
if (context.Request.Query["page"] == "maps") { model.ActiveSection = "Maps"; route.Values["controller"] = "Maps"; }
|
|
if (context.Request.Query["page"] == "writer") { model.ActiveSection = "Writer"; route.Values["controller"] = "Writer"; }
|
|
var menu = await Render("Shared/_ApplicationShell");
|
|
var toolbar = "";
|
|
var calendar = new StoryCalendarViewModel { Project = model.Project ?? new(), SelectedBookID = model.Book?.BookID,
|
|
SelectedMonth = new DateOnly(2026, 10, 1), EarliestStoryDate = new DateOnly(2026, 10, 3), LatestStoryDate = new DateOnly(2026, 10, 3),
|
|
BookOptions = [new SelectListItem("A Distant Shore", "12"), new SelectListItem("The Return", "13")],
|
|
MonthOptions = [new SelectListItem("October 2026", "2026-10")],
|
|
DatedScenes = [new StoryCalendarSceneViewModel { Title = "Arrival", StoryDate = new DateOnly(2026, 10, 3) }],
|
|
Weeks = Enumerable.Range(0, 5).Select(week => new StoryCalendarWeekViewModel {
|
|
Days = Enumerable.Range(0, 7).Select(day => new StoryCalendarDayViewModel { Date = new DateOnly(2026, 9, 28).AddDays(week * 7 + day), IsInSelectedMonth = week * 7 + day >= 3 }).ToList()
|
|
}).ToList()
|
|
};
|
|
if (context.Request.Query["page"] == "calendar-test")
|
|
calendar = (await context.RequestServices.GetRequiredService<IStoryCalendarService>().GetAsync(7, null, null, null))!;
|
|
if (context.Request.Query["marketing"] == "true")
|
|
{
|
|
calendar.DatedScenes = PublicWebsiteFixtures.CalendarScenes();
|
|
foreach (var day in calendar.Weeks.SelectMany(w => w.Days))
|
|
day.Scenes = calendar.DatedScenes.Where(scene => scene.StoryDate == day.Date).ToList();
|
|
calendar.EarliestStoryDate = new DateOnly(2026, 10, 3);
|
|
calendar.LatestStoryDate = new DateOnly(2026, 10, 24);
|
|
}
|
|
var surface = dashboardPage || context.Request.Query["page"] == "writer" || context.Request.Query["page"] == "relationships" || context.Request.Query["page"] == "maps" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar);
|
|
if (context.Request.Query["page"] == "calendar-test")
|
|
surface = "<div data-story-calendar-root>" + surface + "</div><script src='/js/story-calendar.js'></script>";
|
|
if (timelinePage)
|
|
{
|
|
surface = """
|
|
<div class="workspace-heading"><form class="timeline-filter"><button class="btn btn-outline-primary">View</button></form><div class="button-row"><button class="btn btn-outline-primary">Validate project</button><button class="btn btn-outline-secondary">Warnings</button><button class="btn btn-outline-secondary">Story health</button><button class="btn btn-outline-secondary">Timeline Settings</button><button class="btn btn-outline-primary">Create Scenario</button><button class="btn btn-outline-secondary">Archived Items</button></div></div>
|
|
<section class="timeline-control-panel"><details class="timeline-filter-drawer"><summary>Filters</summary></details><details class="timeline-control-group"><summary>View</summary></details><details class="timeline-control-group"><summary>Jump</summary></details><details class="timeline-control-group"><summary>Saved views</summary></details></section>
|
|
<details class="timeline-drag-palette"><summary>Drag sources</summary><span class="drag-chip">Mara Vale</span></details>
|
|
<div class="workspace-layout"><main class="timeline-workspace"><section class="timeline-shell"><div class="timeline-section-header">Scene timeline</div><div class="timeline-project-title">The Glass Harbour</div><div class="timeline-book-title"><strong>A Distant Shore</strong><span>Book one</span></div><div class="timeline-chapter"><div class="timeline-chapter-title"><strong>Chapter 1</strong><span>The crossing</span></div><a class="timeline-scene-card"><strong>Arrival</strong><span class="scene-summary">Mara reaches the harbour before dawn.</span><span class="scene-pov-label">Mara</span><span class="location-pill">North Pier</span><span class="purpose-chip">Inciting event</span></a><a class="timeline-scene-card focus-dim"><strong>Departure</strong><span class="scene-summary">The ship leaves at dusk.</span></a></div><div class="lane-board-heading">Story asset lanes</div><div class="asset-lane-label"><strong>Brass key</strong><span>Object / 8</span></div><div class="asset-lane-slot"><a class="asset-marker">Found</a></div><div class="metric-shape-controls"><div class="metric-toggle-row"><label class="metric-toggle-pill" style="--metric-colour:#2f6f63"><input type="checkbox" checked><span>Overall Intensity</span></label><label class="metric-toggle-pill" style="--metric-colour:#b35f3b"><input type="checkbox"><span>Tension</span></label></div><span class="timeline-metric-edit-status">Select a single metric to edit its curve.</span></div><div class="timeline-minimap"><button class="is-active">Chapter 1</button></div></section></main><aside class="scene-inspector-panel"><div class="inspector-header"><div><p class="eyebrow">Scene inspector</p><h2>Arrival</h2></div><a class="btn btn-outline-secondary">Close</a></div><div class="scene-inspector-body">Scene details</div></aside></div>
|
|
""";
|
|
}
|
|
if (context.Request.Query["page"] == "timeline-render")
|
|
{
|
|
var scenes = new List<Scene> {
|
|
new() { SceneID = 101, ChapterID = 21, SceneNumber = 1, SceneTitle = "Arrival", Summary = "The crossing begins." },
|
|
new() { SceneID = 102, ChapterID = 21, SceneNumber = 2, SceneTitle = "Departure", Summary = "The crossing ends." }
|
|
};
|
|
var scenario = context.Request.Query["scenario"] == "true";
|
|
if (scenario) scenes.Reverse();
|
|
surface = await Render("Timeline/Index", new TimelineViewModel {
|
|
Project = model.Project!, SelectedBookID = 12,
|
|
Settings = new ProjectTimelineSettings { ShowPlotLines = true, ShowSceneCards = true, ShowMetricShape = false, ShowStoryAssets = false },
|
|
Filter = new TimelineFilterViewModel { ProjectID = 7, PlotLineID = 1, FocusType = "plotline", FocusID = 1 },
|
|
Books = [new() { Book = model.Book!, Chapters = [new() { Chapter = new Chapter { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "The crossing" }, Scenes = scenes }] }],
|
|
OrderedScenes = scenes, MatchingSceneIDs = new HashSet<int> { 101 }, FocusSceneIDs = new HashSet<int> { 101 }, FocusLabel = "Harbour mystery",
|
|
ScenePlotSearchText = new Dictionary<int,string> { [101] = "Harbour mystery First clues Revelation" },
|
|
PlotLineOptions = [new SelectListItem("Harbour mystery", "1", true)],
|
|
PlotThreadOptions = [new SelectListItem("First clues", "11")]
|
|
});
|
|
surface += await Render("Timeline/Settings", new TimelineSettingsViewModel { ProjectID = 7, ProjectName = "The Glass Harbour" });
|
|
|
|
}
|
|
if (dashboardPage)
|
|
{
|
|
surface = await Render("Projects/Details", new ProjectDetailViewModel {
|
|
Project = model.Project ?? new(),
|
|
Summary = new() { TotalBooks = 2, DraftingBooks = 1, PlanningBooks = 1, TotalWords = 68420, CharacterCount = 18, LocationCount = 12, ActivePlotThreadCount = 7, ContinuityWarningCount = 3 },
|
|
SeriesProgress = new() { Percentage = 42, SupportingLine = "68,420 of 160,000 planned words", CalculationLabel = "Word count" },
|
|
Books = [new() { BookID = 12, BookNumber = 1, BookTitle = "A Distant Shore", Subtitle = "The Glass Harbour · Book One", Status = "Drafting", CurrentWordCount = 68420, TargetWordCount = 80000, ProgressPercentage = 85.5m, ChapterCount = 24, SceneCount = 72, UpdatedDate = new DateTime(2026,10,28) }],
|
|
RecentActivity = [new() { ActivityType = "Updated", EntityType = "Scene", EntityName = "An unexpected arrival", Description = "Chapter 12 · A change of direction", TimeLabel = "Today", UserLabel = "Fixture Author", IconLabel = "Scene" }],
|
|
NeedsAttention = new() { Warnings = [new() { SeverityName = "Review", WarningTypeName = "Chronology", Message = "Check the order of events at the harbour.", LocationLabel = "Book 1 · Chapter 12" }] }
|
|
});
|
|
}
|
|
if (context.Request.Query["page"] == "projects")
|
|
{
|
|
route.Values["controller"] = "Projects";
|
|
route.Values["action"] = "Index";
|
|
surface = await Render("Projects/Index", new ProjectIndexViewModel {
|
|
ActiveProjects = [
|
|
new() { ProjectID = 7, ProjectName = "With cover", CoverThumbnailPaths = ["/images/placeholders/book-cover.svg"] },
|
|
new() { ProjectID = 8, ProjectName = "Without cover" }
|
|
]
|
|
});
|
|
}
|
|
var desktopPage = context.Request.Query["desktop"].ToString();
|
|
if (!string.IsNullOrEmpty(desktopPage))
|
|
{
|
|
var project = model.Project ?? new Project { ProjectID = 7, ProjectName = "Fixture project" };
|
|
if (context.Request.Query["owner"] == "false") project.AccessRole = "Editor";
|
|
object pageModel = desktopPage switch
|
|
{
|
|
"ManuscriptImport" => new OnboardingWizardViewModel { CurrentStep = OnboardingSteps.NextPathPreview, WritingSoftware = WritingSoftwareValues.MicrosoftWord, SelectedProjectName = "The Glass Harbour", SelectedBookTitle = "A Distant Shore", ProjectID = 7, BookID = 12 },
|
|
"StoryBible" => new StoryBibleViewModel { Project = project, Query = context.Request.Query["q"] },
|
|
"Books" => new BookDetailViewModel { Project = project, Book = model.Book!, Chapters = [
|
|
new() { ChapterID = 21, ChapterNumber = 1, ChapterTitle = "Drowning in Silence", RevisionStatusName = "Planned", IsLinkedToManuscript = true, Summary = "A quiet opening." },
|
|
new() { ChapterID = 22, ChapterNumber = 2, ChapterTitle = "A deliberately long chapter title about an unexpected journey beyond the distant northern mountains", RevisionStatusName = "Draft", ChapterPurposeName = "Turning point", Summary = "A longer summary remains available on small screens.", IsLinkedToManuscript = false }
|
|
] },
|
|
"Chapters" => new ChapterDetailViewModel { Project = project, Book = model.Book!, Chapter = new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing", Summary = "A synthetic chapter." }, Scenes = [new() { SceneID = 101, ChapterID = 21, SceneNumber = 1, SceneTitle = "Arrival", Summary = "A synthetic scene." }] },
|
|
"Characters" => new CharacterListViewModel { Project = project, Characters = context.Request.Query["context"] == "objects" ? [new Character { CharacterID = 71, CharacterName = "Context A" }, new Character { CharacterID = 72, CharacterName = "Context B" }] : [] },
|
|
"Locations" => new LocationListViewModel { Project = project, Locations = [
|
|
new() { LocationID = 1, ProjectID = 7, LocationName = "Room", LocationPath = "Room" },
|
|
new() { LocationID = 3, ProjectID = 7, LocationName = "Cupboard", ParentLocationID = 1, ParentLocationName = "Room", Depth = 1, LocationPath = "Room / Cupboard" },
|
|
new() { LocationID = 2, ProjectID = 7, LocationName = "Building", LocationPath = "Building" },
|
|
new() { LocationID = 4, ProjectID = 7, LocationName = "Annex", ParentLocationID = 2, ParentLocationName = "Building", Depth = 1, LocationPath = "Building / Annex" }
|
|
] },
|
|
"FloorPlans" => new FloorPlanListViewModel { Project = project },
|
|
"PlotLineWorkspace" => new PlotLineWorkspaceViewModel { Project = project },
|
|
"Warnings" => new WarningDashboardViewModel { Project = project },
|
|
"Archives" => new ArchivedItemsViewModel { ProjectID = project.ProjectID, Items = context.Request.Query["context"] == "objects" ? [new ArchivedItem { EntityType = "Character", EntityID = 71, DisplayName = "Archived context fixture", UpdatedDate = DateTime.UtcNow }] : [] },
|
|
"PlotThreads" => new PlotThreadListViewModel { Project = project },
|
|
"StoryCalendar" => calendar,
|
|
"StoryPoint" => new StoryPointViewModel { Project = project },
|
|
"ProjectMetrics" => new ProjectSceneMetricsViewModel { Project = project },
|
|
"Analytics" => new AnalyticsViewModel { Project = project },
|
|
"Dynamics" => new StoryDynamicsViewModel { Project = project },
|
|
"ReviewCentre" => new StoryIntelligenceProgressViewModel { ProjectID = 7, BookID = 12 },
|
|
"ProjectEdit" => new ProjectEditViewModel { ProjectID = 7, ProjectName = project.ProjectName },
|
|
"WritingPlans" => new WritingPlansManagementViewModel(),
|
|
"SchedulePreview" => new WritingSchedulePreviewViewModel(),
|
|
_ => throw new InvalidOperationException("Unknown desktop fixture")
|
|
};
|
|
var viewController = desktopPage switch { "ManuscriptImport" or "ReviewCentre" => "Onboarding", "ProjectEdit" => "Projects", "WritingPlans" or "SchedulePreview" => "Writer", _ => desktopPage };
|
|
var viewAction = desktopPage switch { "ManuscriptImport" => "Index", "ReviewCentre" => "StoryIntelligenceReviewCentre", "ProjectEdit" => "Edit", "WritingPlans" or "SchedulePreview" => desktopPage, "Dynamics" => "Story", "Books" or "Chapters" => "Details", _ => "Index" };
|
|
route.Values["controller"] = viewController;
|
|
route.Values["action"] = viewAction;
|
|
model.ActiveSection = desktopPage switch { "StoryBible" => "Story Bible", "PlotLineWorkspace" => "Plot Lines", "PlotThreads" => "Threads", "StoryCalendar" => "Calendar", "StoryPoint" => "At This Point", "ProjectMetrics" => "Metrics", "Analytics" or "Dynamics" => "Health", _ => desktopPage };
|
|
surface = await Render($"{viewController}/{viewAction}", pageModel);
|
|
menu = await Render("Shared/_ApplicationShell");
|
|
}
|
|
var record = context.Request.Query["record"].ToString();
|
|
if (!string.IsNullOrEmpty(record))
|
|
{
|
|
recordLayout = record is "Projects" or "ProjectMetrics" ? "compact" : "wide";
|
|
var project = model.Project!;
|
|
object recordModel = record switch {
|
|
"Projects" => new ProjectEditViewModel { ProjectID = 7, ProjectName = project.ProjectName },
|
|
"Books" => new BookEditViewModel { BookID = 12, BookNumber = 1, ProjectID = 7, BookTitle = model.Book!.BookTitle, StatusOptions = [new SelectListItem("Planning", "Planning", true)], Project = project },
|
|
"Chapters" => new ChapterEditViewModel { ChapterID = 21, BookID = 12, ChapterTitle = "The crossing", Book = model.Book },
|
|
"Characters" => new CharacterEditViewModel { CharacterID = 71, ProjectID = 7, CharacterName = "Mara Vale", Project = project },
|
|
"Locations" => new LocationEditViewModel { LocationID = 81, ProjectID = 7, LocationName = "The harbour", Project = project },
|
|
"StoryAssets" => new StoryAssetEditViewModel { StoryAssetID = 91, ProjectID = 7, AssetName = "The letter", Project = project },
|
|
"PlotLines" => new PlotLineEditViewModel { PlotLineID = 1, ProjectID = 7, PlotLineName = "The missing letter", Project = project },
|
|
"PlotThreads" => new PlotThreadEditViewModel { PlotThreadID = 2, ProjectID = 7, ThreadTitle = "Arrival", Project = project },
|
|
"ProjectMetrics" => new SceneMetricTypeEditViewModel { ProjectID = 7 },
|
|
_ => throw new InvalidOperationException("Unknown record fixture")
|
|
};
|
|
route.Values["controller"] = record; route.Values["action"] = "Edit";
|
|
surface = await Render($"{record}/Edit", recordModel);
|
|
surface += "<script src='/lib/jquery/dist/jquery.min.js'></script><script src='/lib/jquery-validation/dist/jquery.validate.min.js'></script><script src='/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js'></script>";
|
|
menu = await Render("Shared/_ApplicationShell");
|
|
}
|
|
if (context.Request.Query["page"] == "scene-edit")
|
|
{
|
|
surface = await Render("Scenes/Edit", SceneWorkspaceFixture());
|
|
// The fixture renders a partial page; include its normal Scripts section explicitly.
|
|
surface += "<script src='/js/scene-inspector-v2.js'></script>";
|
|
}
|
|
if (context.Request.Query["page"] == "relationships")
|
|
{
|
|
var relationships = await RelationshipWorkspaceTests.Fixture();
|
|
surface = await Render("RelationshipMap/Index", relationships);
|
|
surface += await Render("RelationshipMap/_GraphScripts", relationships);
|
|
}
|
|
if (context.Request.Query["page"] == "maps")
|
|
{
|
|
var map = new StoryMap { MapID = 1, ProjectID = 7, Name = "Working geography", Kind = "Region" };
|
|
surface = await Render("Maps/Index", context.Request.Query["story"] == "true" ? MapStoryTests.Workspace() : new MapsViewModel {
|
|
Project = model.Project!, Maps = [map], Document = new MapDocument { Map = map },
|
|
Locations = context.Request.Query["settlements"]=="true"
|
|
? [new(){LocationID=11,ProjectID=7,LocationName="Rubery"},new(){LocationID=12,ProjectID=7,LocationName="Maggie's flat",ParentLocationID=11},new(){LocationID=13,ProjectID=7,LocationName="Beth's flat",ParentLocationID=11}]
|
|
: [new LocationItem { LocationID = 11, ProjectID = 7, LocationName = "Harbour town" }, new LocationItem { LocationID = 12, ProjectID = 7, LocationName = "Hill village" }]
|
|
});
|
|
surface += "<script src='/js/application-dialogs.js'></script><script src='/js/workspace-surface.js'></script><script src='/js/maps-symbols.js'></script><script src='/js/workspace-bridge.js'></script><script src='/js/maps-engine.js'></script><script src='/js/maps-topology-engine.js'></script><script src='/js/maps-appearance-engine.js'></script><script src='/js/maps-geography-engine.js'></script><script src='/js/maps-workspace.js'></script><script src='/js/maps-appearance.js'></script><script src='/js/maps-story-engine.js'></script><script src='/js/maps-story.js'></script>";
|
|
}
|
|
if (context.Request.Query["page"] == "floorplans")
|
|
{
|
|
route.Values["controller"] = "FloorPlans"; route.Values["action"] = "Edit";
|
|
model.ActiveSection = "Floor Plans";
|
|
surface = await Render("FloorPlans/Edit", new FloorPlanEditorViewModel {
|
|
Project = model.Project!,
|
|
FloorPlan = new() { ProjectID = 7, FloorPlanID = 31, Name = "Fixture building" },
|
|
Floors = [new() { FloorPlanFloorID = 41, FloorPlanID = 31, Name = "Ground floor" }],
|
|
Blocks = [new() { FloorPlanBlockID = 51, FloorPlanFloorID = 41, LocationName = "Study", X = 2, Y = 2, WidthCells = 3, HeightCells = 2 }]
|
|
});
|
|
}
|
|
if (context.Request.Query["page"] == "writer")
|
|
surface = await Render("Writer/Legacy", WriterFixture());
|
|
if (fullLayout)
|
|
{
|
|
if (fullView is null || fullModel is null) throw new InvalidOperationException("Full-layout fixture requires a page model.");
|
|
var selected = fullView.Split('/');
|
|
await RenderFullAsync(context, selected[0], selected[1], fullModel);
|
|
return;
|
|
}
|
|
surface += await Render("Shared/_ConfirmationDialog");
|
|
var initialTheme = appearance.ThemeKey ?? "warm-light";
|
|
var appearanceScript = "<script>window.plotdirectorAppearance=" + System.Text.Json.JsonSerializer.Serialize(new { theme = initialTheme, migrate = false, collapsed = appearance.RibbonCollapsed }) + ";</script>";
|
|
using var contributionWriter = new StringWriter();
|
|
PlotLine.TagHelpers.RibbonContributionTagHelper.Snapshot(context).WriteTo(contributionWriter, System.Text.Encodings.Web.HtmlEncoder.Default);
|
|
var contributions = contributionWriter.ToString();
|
|
context.Response.ContentType = "text/html; charset=utf-8";
|
|
await context.Response.WriteAsync("<!doctype html><html lang='en' data-app-theme='" + initialTheme + "' data-theme='" + (initialTheme.EndsWith("dark") ? "dark" : "light") + "'><head><script src='/js/application-display-mode.js'></script><link rel='manifest' href='/site.webmanifest'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'><link rel='stylesheet' href='/css/application-navigation.css'><link rel='stylesheet' href='/css/application-shell.css'><link rel='stylesheet' href='/css/record-workspace.css'><link rel='stylesheet' href='/css/application-context-menu.css'><link rel='stylesheet' href='/css/plot-line-workspace.css'><link rel='stylesheet' href='/css/onboarding.css'></head><body data-pd-user-id='1' data-pd-project-id='7' class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><template data-pwa-initial-contributions>" + contributions + "</template><script src='/js/application-page-context.js'></script><div class='plotline-help-main'><div class='container-fluid plotline-shell " + (recordLayout is null ? "pd-dashboard-shell" : $"pd-record-canvas pd-record-canvas--{recordLayout}") + "'><main data-pwa-page-content class='pb-3'>" + surface + "</main><script>window.PlotDirectorPageContext?.activate();</script></div></div><script src='/lib/bootstrap/dist/js/bootstrap.bundle.min.js'></script><script src='/js/application-navigation.js'></script><script src='/js/application-toolbar.js'></script>" + appearanceScript + "<script src='/js/application-shell.js'></script><script src='/js/application-theme-sync.js'></script><script src='/js/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script>" + writerScripts + "</body></html>");
|
|
});
|
|
app.MapHub<PlotLine.Hubs.WordCompanionFollowHub>("/hubs/word-companion-follow");
|
|
await app.RunAsync();
|
|
}
|
|
}
|
|
|
|
internal sealed class WritingSolverFixtureRepository(IHttpContextAccessor accessor) : IWritingSolverRepository
|
|
{
|
|
private readonly Lazy<string?> candidateSnapshot = new(() =>
|
|
{
|
|
var path=Environment.GetEnvironmentVariable("PD_WRITING_SOLVER_CANDIDATE");
|
|
if(string.IsNullOrEmpty(path)) return null;
|
|
var graph=WritingSolverRepository.Parse(File.ReadAllText(path));
|
|
foreach(var page in graph.Solutions.Cast<PlotLine.Models.WritingSolver.SolverPage>().Concat(graph.Features)) page.Index=Environment.GetEnvironmentVariable("PD_SOLVER_TEST_INDEXING")=="true";
|
|
return System.Text.Json.JsonSerializer.Serialize(graph,WritingSolverRepository.JsonOptions);
|
|
});
|
|
public Task<PlotLine.Models.WritingSolver.SolverGraph> GetAsync()
|
|
{
|
|
var snapshot=candidateSnapshot.Value;
|
|
var graph=snapshot is null
|
|
? WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/demo.json"))
|
|
: System.Text.Json.JsonSerializer.Deserialize<PlotLine.Models.WritingSolver.SolverGraph>(snapshot,WritingSolverRepository.JsonOptions)!;
|
|
if (snapshot is null && accessor.HttpContext?.Request.Query["curated"].ToString() == "true")
|
|
{
|
|
graph.IsDemo = false;
|
|
foreach(var page in graph.Solutions.Cast<PlotLine.Models.WritingSolver.SolverPage>().Concat(graph.Features)) page.Index = true;
|
|
}
|
|
return Task.FromResult(graph);
|
|
}
|
|
public Task PublishAsync(string json,string editor) => throw new NotSupportedException("Read-only fixture");
|
|
}
|
|
|
|
internal sealed class SolverWorkspaceFixture : IWritingSolverWorkspaceContext
|
|
{
|
|
public Task<IReadOnlyList<Project>> ProjectsAsync()=>Task.FromResult<IReadOnlyList<Project>>([new(){ProjectID=77,ProjectName="Fixture novel"}]);
|
|
public Task<IReadOnlyList<Character>> CharactersAsync(int projectId)=>Task.FromResult<IReadOnlyList<Character>>([new(){CharacterID=88,ProjectID=77,CharacterName="Fixture character"}]);
|
|
}
|