PlotDirector/PlotLine.Tests/ToolbarBrowserHost.cs

112 lines
12 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
{
public static async Task RunAsync()
{
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(ToolbarController).Assembly.FullName });
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.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"));
await next();
});
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
app.MapGet("/Projects", () => Results.Redirect("/fixture"));
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 = "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 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"] = 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();
}
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()
};
var surface = dashboardPage ? "" : 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">Plot line lanes</div><div class="plot-lane-row lane-dim" style="--plot-colour:#4f8bc9"><a class="plot-lane-label"><strong>Harbour mystery</strong></a><div class="plot-lane-slot"><a class="thread-marker">Revelation</a></div></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="lane-board-heading">Character appearances</div><div class="character-lane-label"><strong>Mara Vale</strong></div><div class="character-lane-slot"><a class="character-marker">POV</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="future-lane-placeholder">Add characters to scenes to see appearance lanes.</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 (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 initialTheme = appearance.ThemeKey ?? "warm-light";
var appearanceScript = "<script>window.plotdirectorAppearance=" + System.Text.Json.JsonSerializer.Serialize(new { theme = initialTheme, migrate = false, collapsed = appearance.RibbonCollapsed }) + ";</script>";
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><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'></head><body class='app-layout'><header class='pd-application-header'>" + menu + toolbar + "</header><main class='plotline-help-main container-fluid plotline-shell pd-dashboard-shell'>" + surface + "</main><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-pwa.js'></script></body></html>");
});
await app.RunAsync();
}
}