PlotDirector/PlotLine.Tests/ToolbarBrowserHost.cs

373 lines
35 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 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()
}};
}
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.AddSingleton<IToolbarPreferenceRepository, ToolbarMemoryPreferences>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<IAppearanceRepository, AppearanceMemoryPreferences>();
builder.Services.AddScoped<ApplicationNavigation>(_ => new ApplicationNavigation(null!, null!, null!));
builder.Services.AddSingleton<IHelpService, HelpService>();
builder.Services.AddSingleton<IWritingSolverRepository, WritingSolverFixtureRepository>();
builder.Services.AddSingleton<IWritingSolverWorkspaceContext, SolverWorkspaceFixture>();
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)!)));
var app = builder.Build();
app.Urls.Add("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-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("/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);
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'></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("/fixture", async context =>
{
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 }];
}
string? recordLayout = null;
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)
{
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()));
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];
}
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["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"] == "relationships" ? "" : await Render("StoryCalendar/_StoryCalendarSurface", calendar);
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" }] }
});
}
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 }
] },
"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 },
"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" => "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);
}
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 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/site.js'></script><script src='/js/application-pwa.js'></script><script src='/js/application-context-menu.js'></script></body></html>");
});
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=false;
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"}]);
}