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 = ReviewSnapshot(); private static ParagraphManuscript ReviewSnapshot(){var state=ManuscriptReaderTests.Snapshot();var scene=Guid.NewGuid();state.Scenes=[new(){Id=scene,CanonicalId=31,ChapterId=21}];foreach(var p in state.Paragraphs.Where(p=>p.ChapterId==21&&p.Story))p.SceneId=scene;return state;} private static readonly ParagraphManuscript readerFocusFixture=ManuscriptReaderTests.FocusSnapshot(); private static readonly ParagraphManuscript readerSameChapterUnmapped=SameChapterUnmapped(); private static ParagraphManuscript SameChapterUnmapped(){var state=PlotLine.Services.Manuscript.ParagraphManuscriptEngine.Clone(readerFocusFixture);var target=state.Scenes.Single(s=>s.CanonicalId==101).Id;foreach(var p in state.Paragraphs.Where(p=>p.SceneId==target))p.SceneId=null;state.Revision++;return state;} private static readonly ParagraphManuscript readerUnmappedFixture=ManuscriptReaderTests.FocusSnapshot(true); 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(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(Func handler) where T : class { var proxy = System.Reflection.DispatchProxy.Create(); ((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=context.Request.Query["chapterOnly"]=="true"?null: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=[]; model.NarrativeFocus=context.RequestServices.GetRequiredService().Read(context.RequestServices.GetRequiredService().UserId!.Value,7,book).GetAwaiter().GetResult(); return model; } private static async Task RenderFullAsync(HttpContext context, string controller, string actionName, object model, Dictionary? extras=null) { 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().GetView(null, $"/Views/{controller}/{actionName}.cshtml", true); if (!view.Success) throw new Exception(string.Join(",", view.SearchedLocations)); using var writer = new StringWriter(); var fullData=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model,["WritingEmbedded"]=true}; if(extras!=null)foreach(var item in extras)fullData[item.Key]=item.Value; await view.View.RenderAsync(new ViewContext(action, view.View, fullData, new TempDataDictionary(context, context.RequestServices.GetRequiredService()), 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 { EnvironmentName = "Development", ApplicationName = typeof(ToolbarController).Assembly.FullName, ContentRootPath = Path.GetFullPath("PlotLine") }); builder.Services.AddControllersWithViews(options=>options.Filters.Add()).AddApplicationPart(typeof(ToolbarController).Assembly); builder.Services.AddSignalR(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddMemoryCache(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(); builder.Services.AddSingleton(FixtureProxy((name,args)=>Task.FromResult((int)args![0]! is 12 or 13?new(){BookId=(int)args[0]!,Chapters=[new(){ChapterId=10,Scenes=[new(){SceneId=22}]},new(){ChapterId=11,Scenes=[new(){SceneId=23}]}]}:null))); builder.Services.AddSingleton(FixtureProxy((name,args)=>name switch{"GetCharacterAsync"=>Task.FromResult((int)args![0]! is >=1 and <=120?new(){CharacterID=(int)args[0]!,ProjectID=7,CharacterName="Fixture participant"}:null),"GetRelationshipAsync"=>Task.FromResult((int)args![0]! is >=1 and <=300?new(){CharacterRelationshipID=(int)args[0]!,ProjectID=7}:null),_=>throw new NotSupportedException(name)})); builder.Services.AddSingleton(FixtureProxy((name,args)=>name=="GetAsync"?Task.FromResult((int)args![0]! ==77?new(){LocationID=77,ProjectID=7,LocationName="Saved room"}:null):throw new NotSupportedException(name))); builder.Services.AddSingleton(); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name,args)=>{ if(name!="GetAsync")throw new NotSupportedException(name); var filter=(TimelineFilterViewModel)args![0]!; IReadOnlyList scenes=[new(){SceneID=31,ChapterID=21,SceneNumber=1,SortOrder=1,SceneTitle="Arrival"},new(){SceneID=101,ChapterID=21,SceneNumber=2,SortOrder=2,SceneTitle="Second scene"},new(){SceneID=32,ChapterID=22,SceneNumber=1,SortOrder=1,SceneTitle="Departure"}]; return Task.FromResult(new(){Project=new(){ProjectID=7,ProjectName="The Glass Harbour"},SelectedBookID=filter.BookID,SelectedSceneID=filter.SelectedSceneID,SelectedScene=filter.SelectedSceneID is int selectedScene?new(){SceneID=selectedScene,ChapterID=scenes.First(s=>s.SceneID==selectedScene).ChapterID,SceneTitle=scenes.First(s=>s.SceneID==selectedScene).SceneTitle}:null,Filter=filter, Settings=new(){ShowSceneCards=true},OrderedScenes=scenes,MatchingSceneIDs=scenes.Select(s=>s.SceneID).ToHashSet(), Books=[new(){Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},Chapters=[new(){Chapter=new(){ChapterID=21,BookID=12,ChapterNumber=1,ChapterTitle="The crossing"},Scenes=scenes.Where(s=>s.ChapterID==21).ToArray()},new(){Chapter=new(){ChapterID=22,BookID=12,ChapterNumber=2,ChapterTitle="The harbour"},Scenes=scenes.Where(s=>s.ChapterID==22).ToArray()}]}]}); })); builder.Services.AddSingleton(FixtureProxy((name,args)=>{ if(name!="GetDetailAsync")throw new NotSupportedException(name); var id=(int)args![0]!;return Task.FromResult(new(){Project=new(){ProjectID=7,ProjectName="The Glass Harbour"},Book=new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},Chapter=new(){ChapterID=id,BookID=12,ChapterNumber=id==21?1:2,ChapterTitle="Focused chapter"},Scenes=(id==21?new[]{31,101}:new[]{32}).Select(scene=>new Scene{SceneID=scene,ChapterID=id,SceneTitle="Scene "+scene,SceneNumber=scene==101?2:1}).ToArray()}); })); builder.Services.AddSingleton(); builder.Services.AddScoped(services => ManuscriptReaderTests.FixtureService(() => services.GetRequiredService().HttpContext!.Request.Query["reader-error"] == "true" ? throw new TimeoutException("Synthetic unavailable manuscript") : services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="same-chapter-unmapped"?readerSameChapterUnmapped:services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="mapped"?readerFocusFixture:services.GetRequiredService().HttpContext!.Request.Cookies["fixture-focus-reader"]=="unmapped"?readerUnmappedFixture:services.GetRequiredService().HttpContext!.Request.Query["reader-long"] == "true" ? readerLongFixture : readerFixture,allowSecondBook:true)); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(services => new ApplicationNavigation( FixtureProxy((name, args) => name == "GetForUserAsync" ? Task.FromResult(new Project { ProjectID = 7, ProjectName = "The Glass Harbour", AccessRole = "Owner" }) : throw new NotSupportedException(name)), FixtureProxy((name, args) => name == "ListByProjectAsync" ? Task.FromResult>([new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, new() { BookID = 13, ProjectID = 7, BookTitle = "The Return" }]) : throw new NotSupportedException(name)), services.GetRequiredService(), services.GetRequiredService())); builder.Services.AddSingleton(FixtureProxy((name,args)=>name switch { "ListByProjectAsync" => Task.FromResult>([new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore"},new(){BookID=13,ProjectID=7,BookTitle="The Return"}]), "GetAsync" => Task.FromResult((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((name,args)=>Task.FromResult(name=="CanAccessProjectAsync"?(int)args![0]! == 7:(int)args![1]! is 12 or 13 or 21 or 22 or 31 or 32))); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(services => FixtureProxy((name, args) => name switch { "GetDashboardAsync" => Task.FromResult(Writer3Fixture(services.GetRequiredService().HttpContext!)), "GetChapterWorkflowAsync" => Task.FromResult(new() { Project = new() { ProjectID = 7, ProjectName = "The Glass Harbour" }, Book = new() { BookID = 12, ProjectID = 7, BookTitle = "A Distant Shore" }, Chapter = new() { ChapterID = (int)args![0]!, BookID = 12, ChapterNumber = (int)args[0]! ==21?1:2, ChapterTitle = "The crossing" }, Goal = writerGoals.GetOrAdd((services.GetRequiredService().UserId!.Value, 21), _ => new() { ChapterID = 21, GoalSummary = "Reveal the consequence" }) }), "SaveChapterGoalAsync" => SaveFixtureGoal(services.GetRequiredService().UserId!.Value, (ChapterGoalEditViewModel)args![0]!), _ => throw new NotSupportedException(name) })); builder.Services.AddSingleton(FixtureProxy((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((name, args) => name == "GetEffectiveEntitlementAsync" ? Task.FromResult(new EffectiveEntitlement { UserID = 4, State = EntitlementState.ActivePaid }) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "CountAttentionForUserAsync" ? Task.FromResult(0) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "ShouldShowWordCompanionHeaderAsync" ? Task.FromResult(false) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((name, args) => name == "GetForCurrentUserAsync" ? Task.FromResult(new StoryIntelligenceGlobalProgressViewModel()) : throw new NotSupportedException(name))); builder.Services.AddSingleton(FixtureProxy((_,_)=>throw new NotSupportedException())); builder.Services.AddSingleton(FixtureProxy((_,_)=>throw new NotSupportedException())); builder.Services.AddSingleton(FixtureProxy((_,_)=>throw new NotSupportedException())); builder.Services.AddSingleton(FixtureProxy((name,_)=>name=="GetCurrentForCharacterAsync"?Task.FromResult(null):throw new NotSupportedException(name))); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddMemoryCache(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); 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(); builder.Services.AddScoped(services => new ToolbarTestUser(int.Parse(services.GetRequiredService().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(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("/Scenes/Edit/{id:int}", async (HttpContext context, int id) => { var model=SceneWorkspaceFixture(); model.SceneID=id;model.ChapterID=id==32?22:21;model.SceneNumber=id==101?2:1; model.SceneTitle=$"Fixture scene {id}"; model.Chapter!.ChapterID=model.ChapterID;model.Chapter.ChapterNumber=id==32?2:1; if(context.Request.Query["retainNarrativeFocus"]!="true"&&id is not (22 or 23)) await context.RequestServices.GetRequiredService().Open(context.RequestServices.GetRequiredService().UserId!.Value,null,id); await RenderFullAsync(context,"Scenes","Edit",model); }).WithOrder(-1); app.MapGet("/Characters",async (HttpContext context)=>await RenderFullAsync(context,"Characters","Index",new CharacterListViewModel{Project=new(){ProjectID=7,ProjectName="Fixture project",AccessRole="Owner"},Characters=[new(){CharacterID=5,ProjectID=7,CharacterName="Fixture participant",CharacterImportance=6}]})).WithOrder(-1); 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().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()), 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("
" + writer + ""); }); // 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().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().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()), 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/_WritingContextOverview.cshtml":"/Views/Writing/_WritingIntentPlan.cshtml"; var view=context.RequestServices.GetRequiredService().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()),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("
"+writer+"
"); }); 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().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()),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", async context => { context.Request.RouteValues["controller"] = "Writing"; var pinned=context.Request.Query["pinned"]=="true"; var sceneId=int.TryParse(context.Request.Query["sceneId"],out var selected)?selected:22; var page=new WritingContextPageViewModel { ProjectID=7, BookID=12, ChapterID=10, SceneID=sceneId, Display=new(){SceneOptions=[new("Chapter one · scene one","22",sceneId==22),new("Chapter two · scene two","23",sceneId==23)]} }; await RenderFullAsync(context,"Writing","Context",page,new Dictionary { ["NativeSnapshot"]=pinned }); }).WithOrder(-1); app.MapGet("/Writing/Intent",context=>{context.Response.Redirect("/Writing/Context"+context.Request.QueryString);return Task.CompletedTask;}).WithOrder(-1); app.MapGet("/context-family-index-fixture",context=>{ var fixture=ContextFamilyTests.Fixture(context.Request.Query["large"]=="true",int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:22,context.Request.Query["many"]=="true"); if(context.Request.Query["split"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Where(r=>!(r.CharacterAID is 3 or 4 && r.CharacterBID==5)).ToList()); if(context.Request.Query["merge"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList()); return context.Response.WriteAsJsonAsync(PlotLine.Services.Context.ContextFamilyExploration.Index(fixture.Structure,fixture.Scene)); }); app.MapGet("/context-family-tree-fixture",context=>{ var fixture=ContextFamilyTests.Fixture(context.Request.Query["large"]=="true",int.TryParse(context.Request.Query["sceneId"],out var scene)?scene:22,context.Request.Query["many"]=="true");var focus=int.TryParse(context.Request.Query["focusId"],out var fid)?fid:5; if(context.Request.Query["split"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Where(r=>!(r.CharacterAID is 3 or 4 && r.CharacterBID==5)).ToList()); if(context.Request.Query["merge"]=="true")fixture.Structure=new(fixture.Structure.Seeds,fixture.Structure.Links.Append(new(){CharacterRelationshipID=500,CharacterAID=8,CharacterBID=22,RelationshipTypeName="Spouse",RelationshipCategoryName="Romantic / Sexual"}).ToList()); var expanded=context.Request.Query["expanded"].Select(s=>int.Parse(s!)).ToArray();var topology=new PlotLine.Services.Context.ContextFamilyTopology(fixture.Structure.Links);(int[] People,int[] Links,IReadOnlyList Branches,bool Truncated) visible; try{visible=topology.Visible(focus,expanded);}catch(ArgumentException){context.Response.StatusCode=400;return context.Response.WriteAsJsonAsync(new{message="Choose branches within the selected family."});} var graph=PlotLine.Services.Context.ContextRelationshipLenses.Compose(new(new(){Books=[new(){BookID=12}],Chapters=[new(){ChapterID=10,BookID=12}],Scenes=[new(){SceneID=fixture.Scene.SceneID,ChapterID=10}],Characters=fixture.Structure.Seeds.Where(c=>visible.People.Contains(c.CharacterID)).ToList(),Relationships=fixture.Structure.Links.Where(r=>visible.Links.Contains(r.CharacterRelationshipID)).ToList()},focus,visible.Truncated),"family",fixture.Scene,context.Request.Query["readonly"]!="true"); return context.Response.WriteAsJsonAsync(new PlotLine.Services.Context.ContextFamilyTree(topology.Key(focus),graph,visible.Branches,topology.Warnings(visible.People))); }); app.MapGet("/relationship-evolution-fixture",async context=>{int count=int.TryParse(context.Request.Query["count"],out var n)?n:1;var model=new RelationshipEvolutionViewModel{Project=new(){ProjectID=7,ProjectName="Evolution fixture"},Relationship=CharacterWorkspaceBrowserFixture.Relationship(),ReturnCharacterID=5,CanEdit=context.Request.Query["viewer"]!="true",Events=Enumerable.Range(1,count).Select(i=>new PlotLine.Models.RelationshipProgressionPoint{RelationshipEventID=i,CharacterRelationshipID=9,SceneID=i,SceneNumber=i,BookTitle="Recorded book",ChapterNumber=1,SceneTitle="Canonical scene "+i,GlobalSceneIndex=i*3,Intensity=i==2?null:Math.Min(10,i+2),RelationshipStateName="Recorded state "+i,Description="Canonical event description",TotalRecords=count}).ToArray()};await RenderFullAsync(context,"Dynamics","Relationship",model);}); app.MapGet("/character-workspace-fixture",async context=>{ var id=int.TryParse(context.Request.Query["id"],out var cid)?cid:5;var profile=CharacterWorkspaceBrowserFixture.Header(id,context.Request.Query["viewer"]=="true");profile.WorkspaceTab=context.Request.Query["tab"].FirstOrDefault();if(profile.WorkspaceTab!=null)profile.WorkspacePage=CharacterWorkspaceBrowserFixture.Page(id,new(){Tab=profile.WorkspaceTab},context.Request.Query["viewer"]=="true");await RenderFullAsync(context,"Characters","Details",profile); }); app.MapGet("/character-workspace-tab-fixture",async context=>{ int? Number(string key)=>int.TryParse(context.Request.Query[key],out var value)?value:null;var q=new CharacterWorkspaceQuery{Tab=context.Request.Query["Tab"].FirstOrDefault()??"overview",Page=Number("Page")??1,SceneID=Number("SceneID"),BookID=Number("BookID"),RelationshipID=Number("RelationshipID"),Search=context.Request.Query["Search"],Category=context.Request.Query["Category"]};var model=CharacterWorkspaceBrowserFixture.Page(Number("id")??5,q,context.Request.Query["viewer"]=="true",context.Request.Query["removed"]=="true",context.Request.Query["notes"].FirstOrDefault());await WorkspacePartial(context,"_WorkspaceTab",model); }); app.MapGet("/character-workspace-operation-fixture",async context=>{ var action=context.Request.Query["operation"].FirstOrDefault()??"definition";var model=CharacterWorkspaceBrowserFixture.Operation(5,action,int.TryParse(context.Request.Query["relationshipId"],out var r)?r:9,int.TryParse(context.Request.Query["eventId"],out var e)?e:null,context.Request.Query["protected"]=="true");if(context.Request.Query["invalid"]=="true"){context.Response.StatusCode=400;model.Notes=context.Request.Query["notes"].FirstOrDefault()??model.Notes;context.Items["WorkspaceValidation"]="The record changed. Your draft is retained.";}await WorkspacePartial(context,"_WorkspaceOperation",model); }); app.MapGet("/character-workspace-family-fixture",context=>{var expanded=context.Request.Query["expanded"].Select(v=>int.Parse(v!)).ToArray();return context.Response.WriteAsJsonAsync(CharacterWorkspaceBrowserFixture.Family(int.TryParse(context.Request.Query["focusId"],out var f)?f:5,expanded,context.Request.Query["removed"]=="true"));}); static async Task WorkspacePartial(HttpContext context,string partial,object model){var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Characters/"+partial+".cshtml",false);using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model};if(context.Items["WorkspaceValidation"] is string error)data.ModelState.AddModelError("",error);await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString());} app.MapGet("/context-edit-fixture",async context=>{ var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextCharacterEdit.cshtml",false); var model=new PlotLine.Services.Context.ContextCharacterEditForm{BookID=12,SceneID=22,CharacterID=5,Field=context.Request.Query["field"].ToString(),CharacterName="Fixture participant",Label="Focused correction",Value="Saved value",Fingerprint="fixture-fingerprint"}; if(model.Field=="life-status"){model.Value=null;model.Options=[new("Unrecorded",""),new("Living","false"),new("Deceased","true")];} if(model.Field is "classification" or "location")model.Options=[new("Recorded option","Saved value"),new("Other option","Other")]; using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; if(context.Request.Query["invalid"]=="true"){data.ModelState.AddModelError("Value","Synthetic validation: draft retained.");model.Value="Entered draft";} await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); }); app.MapGet("/context-relationship-edit-fixture",async context=>{ var action=new ActionContext(context,new RouteData(),new ActionDescriptor());var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextRelationshipEdit.cshtml",false); var model=new PlotLine.Services.Context.ContextRelationshipForm{BookID=12,SceneID=22,RelationshipID=9,Mode="scene",SourceID=5,TargetID=6,TypeID=1,StateID=1,Label="Relationship development at selected scene",Notes="Saved scene note",Fingerprint="fixture",Characters=[new("Fixture participant","5"),new("Other character","6")],Types=[new("Family · Parent","1")],States=[new("Established","1")]}; 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()),writer,new HtmlHelperOptions()));context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); }); app.MapGet("/context-lenses-fixture",(HttpContext context)=>Results.Json(ContextRelationshipBrowserFixture.Graph(context))); app.MapGet("/context-lenses-lookup-fixture",()=>Results.Json(new[]{new{id=7,name="An established relative with a deliberately long name 7",archived=false}})); app.MapGet("/context-names-fixture/{part}",ContextNamesBrowserFixture.Render); app.MapGet("/context-tab-fixture/{tool}",async context=> { var sceneId=int.TryParse(context.Request.Query["sceneId"],out var id)?id:22; var scene=new SceneEditViewModel { SceneID=sceneId, ChapterID=sceneId==23?11:10, SceneTitle="Scene "+sceneId+" · A deliberately long scene title for a narrow reference screen", Summary="Saved scene summary and provenance",ScenePurposeNotes="Reveal the letter",SceneOutcomeNotes="A decision changes the plan", Project=new(){ProjectID=7,ProjectName="Fixture project"},Book=new(){BookID=12,BookTitle="Fixture book"},Chapter=new(){ChapterID=10,ChapterNumber=1,ChapterTitle="Opening"}, SceneCharacters=[new(){CharacterID=5,CharacterName="Fixture participant",RoleInSceneTypeName="Observer",EmotionalState="Uncertain",PhysicalCondition="Tired",LocationName="Saved room",EntryLocationName="Hall",ExitLocationName="Garden"}] }; var model=new WritingContextDisplayViewModel { Context=new(){Position=new(7,12,scene.ChapterID,sceneId),Scene=scene} }; scene.POVCharacterID=5; var catalogue=Enumerable.Range(5,12).Select(id=>new Character{CharacterID=id,ProjectID=7,CharacterName=id==5?"Fixture participant":"A long established character name "+id,CharacterImportance=id==5?6:2}).ToList(); scene.SceneCharacters=catalogue.Select(c=>new SceneCharacter{SceneCharacterID=c.CharacterID,CharacterID=c.CharacterID,SceneID=sceneId,CharacterName=c.CharacterName,PresenceTypeName=c.CharacterID==6?"Mentioned Only":"Present",RoleInSceneTypeName="Observer",EmotionalState=c.CharacterID==5?"Uncertain":null,PhysicalCondition="Tired",LocationID=77}).ToList(); model=new WritingContextDisplayViewModel { Context=new(){Position=new(7,12,scene.ChapterID,sceneId),Scene=scene,Narrative=new(){Chapters=[new(){ChapterID=10,BookID=12},new(){ChapterID=11,BookID=12}],Scenes=[new(){SceneID=21,ChapterID=10,SceneTitle="Earlier"},new(){SceneID=22,ChapterID=10,SceneTitle="Current"},new(){SceneID=23,ChapterID=11,SceneTitle="Following"}]}} }; var appearances=scene.SceneCharacters.Concat(new SceneCharacter[]{new(){CharacterID=5,SceneID=21,PresenceTypeName="Present",LocationID=78},new(){CharacterID=5,SceneID=23,PresenceTypeName="Present",LocationID=79}}).ToList(); model.CharacterExplorer=PlotLine.Services.Context.ContextCharacterPanels.Compose(model,catalogue,appearances,[new(){LocationID=77,LocationName="Saved room"},new(){LocationID=78,LocationName="Earlier hall"},new(){LocationID=79,LocationName="Following garden"}],true); model.ContextRelationshipCanEdit=true; model.RelationshipMap=new(){Relationships=[new(){CharacterRelationshipID=9,CharacterAID=5,CharacterBID=6,CharacterAName="Fixture participant",CharacterBName="A long established character name 6",RelationshipCategoryName="Family",RelationshipTypeName="Parent",CurrentStateName="Established",InitialStateEditable=true,Notes="Explicit recorded family note",History=[new(){SceneID=22,Label="Current scene",StateName="Established",Notes="An explicit development"}]},new(){CharacterRelationshipID=10,CharacterAID=5,CharacterBID=7,CharacterAName="Fixture participant",CharacterBName="Another character",RelationshipCategoryName="Social",RelationshipTypeName="Friend",CurrentStateName="Trusting",IsReciprocal=true}]}; model.NamePanel=ContextNamesBrowserFixture.Panel(); var action=new ActionContext(context,new RouteData(),new ActionDescriptor()); var view=context.RequestServices.GetRequiredService().GetView(null,"/Views/Writing/_ContextTab.cshtml",false); using var writer=new StringWriter();var data=new ViewDataDictionary(new EmptyModelMetadataProvider(),new ModelStateDictionary()){Model=model}; data["ContextTabPartial"]=context.Request.RouteValues["tool"]?.ToString()switch{"characters"=>"_WritingContextPeople","names"=>"_ContextNames","relationships"=>"_ContextRelationships",_=>"_WritingContextOverview"}; await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService()),writer,new HtmlHelperOptions())); context.Response.ContentType="text/html";await context.Response.WriteAsync(writer.ToString()); }); app.MapGet("/scenario-fixture/{view}", async (HttpContext context, string view) => { var project = new Project { ProjectID = 7, ProjectName = "Scenario visual qualification" }; var scenario = new Scenario { ScenarioID = 17, ProjectID = 7, BookID = 12, ScenarioName = "Alternative reveal order with a long descriptive title", Description = "Explore the consequences of moving the discovery later while preserving canonical story structure." }; var empty = context.Request.Query["empty"] == "true"; var warnings = empty ? Array.Empty() : new[] { new ScenarioWarning { SeverityName = "Warning", WarningTypeName = "Knowledge order", Message = "A scene uses information before its introduction.", Details = "Review the proposed order; the main timeline is unaffected." } }; var chapters = Enumerable.Range(1, 5).Select(i => new Chapter { ChapterID = i, ChapterNumber = i, ChapterTitle = $"Chapter {i}: An unexpectedly long chapter heading that should wrap" }).ToArray(); var scenes = empty ? Array.Empty() : Enumerable.Range(1, 15).Select(i => new ScenarioScene { ScenarioID = 17, SceneID = i, ProposedChapterID = (i - 1) / 3 + 1, ProposedSortOrder = i, SceneNumber = i, SceneTitle = $"Scene {i}: The unexpected discovery and its consequences", Summary = "A difficult decision changes the direction of the investigation and reveals a hidden connection.", RevisionStatusName = "Draft", TimeLabel = "20 November · 09:30", ThreadLabels = "The missing letter", CharacterLabels = "Alex, Sam", LocationLabel = "Station", AssetLabels = "Letter", WarningCount = i == 1 ? 1 : 0 }).ToArray(); object model = view switch { "Timeline" => new ScenarioTimelineViewModel { Project = project, Scenario = scenario, Chapters = chapters, Scenes = scenes, Warnings = warnings }, "Compare" => new ScenarioCompareViewModel { Project = project, Scenario = scenario, ScenarioWarnings = warnings, MovedScenes = empty ? [] : [new() { SceneID = 1, SceneTitle = scenes[0].SceneTitle, MainPosition = "Chapter 1 · Scene 1", ScenarioPosition = "Chapter 3 · Scene 7", HasMoved = true }] }, "Create" => new ScenarioCreateViewModel { ProjectID = 7 }, "Index" => new ScenarioListViewModel { Project = project, Scenarios = empty ? [] : [scenario] }, _ => throw new ArgumentException("Unknown scenario fixture view") }; await RenderFullAsync(context, "Scenarios", view, model); }); 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 }]; if(context.Request.Query["page"]=="scene-edit") await context.RequestServices.GetRequiredService().Open(context.RequestServices.GetRequiredService().UserId!.Value,null,SceneWorkspaceFixture().SceneID); model.NarrativeFocus=await context.RequestServices.GetRequiredService().Read(context.RequestServices.GetRequiredService().UserId!.Value,7,12); } 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().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 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().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()); 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(""); 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 { ["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().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 = "
" + surface + "
"; if (timelinePage) { surface = """
Filters
View
Jump
Saved views
Drag sourcesMara Vale
Scene timeline
The Glass Harbour
A Distant ShoreBook one
Story asset lanes
Brass keyObject / 8
Select a single metric to edit its curve.
"""; } if (context.Request.Query["page"] == "timeline-render") { var scenes = new List { 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 { 101 }, FocusSceneIDs = new HashSet { 101 }, FocusLabel = "Harbour mystery", ScenePlotSearchText = new Dictionary { [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,SelectedBookID=12,PlotLines=[new(){Line=new(){PlotLineID=1,PlotLineName="Fixture line",Colour="#487b70"},IsSelected=true}],AssociationScenes=[new(){SceneID=31,BookID=12,SceneTitle="Arrival",ChapterNumber=1,SceneNumber=1,NarrativeOrder=1}],Scenes=[new(){SceneID=31,SceneTitle="Arrival",ChapterNumber=1,SceneNumber=1,Memberships=[new(){PlotLineID=1,PlotLineName="Fixture line",Colour="#487b70",Contributions=[new(){ThreadTitle="Fixture thread",CanonicalTitle="Fixture contribution"}]}]}] }, "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, Books=[model.Book!], Chapters=[new(){ChapterID=21,BookID=12,ChapterNumber=1,ChapterTitle="The crossing"},new(){ChapterID=22,BookID=12,ChapterNumber=2,ChapterTitle="The harbour"}], Scenes=[new(){SceneID=31,ChapterID=21,SceneNumber=1,SceneTitle="Arrival"},new(){SceneID=101,ChapterID=21,SceneNumber=2,SceneTitle="Second scene"},new(){SceneID=32,ChapterID=22,SceneNumber=1,SceneTitle="Departure"}] }, "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); if(desktopPage=="PlotLineWorkspace")writerScripts+=""; if(desktopPage=="StoryPoint")writerScripts+=""; 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 += ""; 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 += ""; } 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 += ""; } 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" }, OccupancyScenes=[new(){SceneID=31,Label="Chapter 1 · Scene 1: Arrival"},new(){SceneID=101,Label="Chapter 1 · Scene 2: Second scene"},new(){SceneID=32,Label="Chapter 2 · Scene 1: Departure"}], 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 = ""; 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("
" + menu + toolbar + "
" + surface + "
" + appearanceScript + "" + writerScripts + ""); }); app.MapHub("/hubs/story-intelligence"); app.MapHub("/hubs/native-companion"); app.MapHub("/hubs/word-companion-follow"); await app.RunAsync(); } } internal sealed class WritingSolverFixtureRepository(IHttpContextAccessor accessor) : IWritingSolverRepository { private readonly Lazy 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().Concat(graph.Features)) page.Index=Environment.GetEnvironmentVariable("PD_SOLVER_TEST_INDEXING")=="true"; return System.Text.Json.JsonSerializer.Serialize(graph,WritingSolverRepository.JsonOptions); }); public Task GetAsync() { var snapshot=candidateSnapshot.Value; var graph=snapshot is null ? WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/demo.json")) : System.Text.Json.JsonSerializer.Deserialize(snapshot,WritingSolverRepository.JsonOptions)!; if (snapshot is null && accessor.HttpContext?.Request.Query["curated"].ToString() == "true") { graph.IsDemo = false; foreach(var page in graph.Solutions.Cast().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> ProjectsAsync()=>Task.FromResult>([new(){ProjectID=77,ProjectName="Fixture novel"}]); public Task> CharactersAsync(int projectId)=>Task.FromResult>([new(){CharacterID=88,ProjectID=77,CharacterName="Fixture character"}]); }