Renders themed pages as swappable sections with path-mirrored template scopes and a Razor fallback

This commit is contained in:
BinaryAlley committed 2026-08-20 06:50:17 -07:00
1 parent f17e685239
commit e37bb3ecc6
24 files changed
+351 -187

No files matched your search

@@ -2,12 +2,17 @@
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -19,18 +24,32 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.B
/// </summary>
public class BooksIndexViewEndpoint : BaseEndpoint<GetBooksViewRequest, IResult>
{
// the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it
// with the configured ResourcesPath, so "Lumina.Presentation.Web.Views.X" resolves to the embedded
// "Lumina.Presentation.Web.Core.Resources.Views.X" resource; including "Core" here would insert it twice
private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.WrittenContentLibrary.BookLibrary.Books.Index";
private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web";
// the page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope
private const string VIEW_PAGE_KEY = "library/written-content-library/book-library/books/index";
private readonly IApiHttpClient _apiHttpClient;
private readonly IUrlService _urlService;
private readonly ThemePageRenderer _themePageRenderer;
private readonly IStringLocalizer _localizer;
/// <summary>
/// Initializes a new instance of the <see cref="BooksIndexViewEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
public BooksIndexViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService)
/// <param name="themePageRenderer">Injected service for rendering themed pages.</param>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the view resources.</param>
public BooksIndexViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService, ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory)
{
_apiHttpClient = apiHttpClient;
_urlService = urlService;
_themePageRenderer = themePageRenderer;
_localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION);
}
/// <summary>
@@ -46,7 +65,7 @@ public class BooksIndexViewEndpoint : BaseEndpoint<GetBooksViewRequest, IResult>
}
/// <summary>
/// Displays the books browsing view.
/// Displays the books browsing view, rendered by the active theme with a fallback to the Razor view.
/// </summary>
/// <param name="request">The request containing the Id of the media library whose books are browsed.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
@@ -55,6 +74,25 @@ public class BooksIndexViewEndpoint : BaseEndpoint<GetBooksViewRequest, IResult>
if (request.LibraryId is null)
return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!);
LibraryDto library = await _apiHttpClient.GetAsync<LibraryDto>(ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", request.LibraryId.Value.ToString()), cancellationToken).ConfigureAwait(false);
return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml", library);
ThemePageDto pageModel = new()
{
PageKey = VIEW_PAGE_KEY,
Title = library.Title ?? string.Empty,
Description = string.Empty,
PageData = new Dictionary<string, object?>
{
["libraryId"] = library.Id?.ToString() ?? request.LibraryId.Value.ToString(),
["itemsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS) ?? string.Empty,
["settingsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS) ?? string.Empty,
["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer)
}
};
Result<ThemePageRenderResultDto> renderResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false);
if (renderResult.IsFailure)
return View("/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml", library);
return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(renderResult.Value.Content, renderResult.Value.Script, pageModel.AssetBase));
}
}
@@ -52,7 +52,7 @@ public class ThemeAssetsEndpoint : BaseEndpoint<GetThemeAssetRequest, IResult>
return Results.Problem(statusCode: StatusCodes.Status400BadRequest, detail: "The theme id and the asset path are required.");
BlobDataDto blob = await _apiHttpClient.GetBlobAsync(
ApiRoutes.Themes.GET_THEME_ASSET.Replace("{themeId}", request.ThemeId).Replace("{assetPath}", request.Path), cancellationToken).ConfigureAwait(false);
ApiRoutes.Themes.GET_THEME_ASSET.Replace("{themeId}", request.ThemeId).Replace("{*assetPath}", request.Path), cancellationToken).ConfigureAwait(false);
return Results.File(blob.Data, blob.ContentType);
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.Extensions.Localization;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Core.Themes;
/// <summary>
/// Builds the page data entries that the themed endpoints expose to their templates.
/// </summary>
public static class ThemePageDataFactory
{
/// <summary>
/// Creates the localized strings of a page from the provided localizer, keyed by their resource names.
/// </summary>
/// <param name="localizer">The localizer of the page resources.</param>
/// <returns>The localized strings keyed by their resource names.</returns>
public static Dictionary<string, object?> CreateLocalizedStrings(IStringLocalizer localizer)
{
Dictionary<string, object?> strings = [];
foreach (LocalizedString localizedString in localizer.GetAllStrings(includeParentCultures: true))
strings[localizedString.Name] = localizedString.Value;
return strings;
}
}
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using System;
using Lumina.Presentation.Web.Common.Services;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -11,7 +11,7 @@ namespace Lumina.Presentation.Web.Core.Themes;
/// <summary>
/// Renders a theme template against a page model, populating the theme metadata before rendering.
/// </summary>
public sealed class ThemePageRenderer
public class ThemePageRenderer
{
private readonly ThemeService _themeService;
private readonly ThemeTemplateEngine _templateEngine;
@@ -28,22 +28,20 @@ public sealed class ThemePageRenderer
}
/// <summary>
/// Renders the page model with the theme selected for the requested theme identifier.
/// Renders the page model with the theme selected for the requested theme identifier, producing the content and script sections of the page.
/// </summary>
/// <param name="model">The page model to render.</param>
/// <param name="requestedThemeId">The optional unique identifier of the theme to render with, falling back to the current theme when <see langword="null"/>.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the rendered HTML, or an error.</returns>
public async Task<Result<string>> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default)
/// <returns>An <see cref="Result{TValue}"/> containing either the rendered page, or an error.</returns>
public virtual async Task<Result<ThemePageRenderResultDto>> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default)
{
ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(model.PageKey, requestedThemeId, cancellationToken);
model.ThemeId = document.Theme.Id;
model.ThemeName = document.Theme.Name;
model.ThemeVersion = document.Theme.Version;
model.AssetBase = $"/theme-assets/{document.Theme.Id}/assets";
model.CurrentYear = DateTime.UtcNow.Year;
model.ScriptId = ScriptIdentifierHelper.GenerateScriptId();
return _templateEngine.Render(document.Template, model);
return _templateEngine.RenderPage(document.Template, model);
}
}
@@ -110,7 +110,7 @@ public sealed class ThemeService
themeId = requestedThemeId;
ThemeTemplateResponseDto response = await _apiHttpClient.GetAsync<ThemeTemplateResponseDto>(
ApiRoutes.Themes.GET_THEME_TEMPLATE.Replace("{themeId}", themeId).Replace("{pageKey}", pageKey), cancellationToken).ConfigureAwait(false);
ApiRoutes.Themes.GET_THEME_TEMPLATE.Replace("{themeId}", themeId).Replace("{*pageKey}", pageKey), cancellationToken).ConfigureAwait(false);
return new ThemeRenderDocumentDto(ToThemeInfo(response.Theme), response.Template);
}
@@ -26,28 +26,12 @@ public sealed class ThemeTemplateEngine
RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>
/// Validates the structure and expressions of a theme template.
/// </summary>
/// <param name="template">The template source to validate.</param>
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public Result<Success> Validate(string template)
{
ArgumentNullException.ThrowIfNull(template);
int cursor = 0;
Result<IReadOnlyList<ThemeTemplateNodeDto>> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0);
if (parseResult.IsFailure)
return parseResult.Errors;
return Result.Success;
}
/// <summary>
/// Renders a theme template against the provided model.
/// Renders a theme template against the provided model, splitting the reserved top-level <c>scripts</c> section from the page content.
/// </summary>
/// <param name="template">The template source to render.</param>
/// <param name="model">The model the template expressions resolve against.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the rendered output, or an error.</returns>
public Result<string> Render(string template, object model)
/// <returns>An <see cref="Result{TValue}"/> containing either the rendered page, or an error.</returns>
public Result<ThemePageRenderResultDto> RenderPage(string template, object model)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(model);
@@ -57,12 +41,38 @@ public sealed class ThemeTemplateEngine
if (parseResult.IsFailure)
return parseResult.Errors;
StringBuilder output = new(Math.Min(template.Length * 2, 256 * 1024));
Result<Success> renderResult = RenderNodes(parseResult.Value, new ThemeRenderScopeDto(model, Parent: null), output);
if (renderResult.IsFailure)
return renderResult.Errors;
// the reserved top-level 'scripts' section holds the script of the page and is rendered separately, mirroring the
// 'Scripts' section of a Razor view, so that the layout can host it in the scripts container of the navigator;
// every other top-level node is the content of the page section
List<ThemeTemplateNodeDto> contentNodes = [];
ThemeSectionNodeDto? scriptsSection = null;
foreach (ThemeTemplateNodeDto node in parseResult.Value)
{
if (node is ThemeSectionNodeDto { Inverted: false } section
&& scriptsSection is null
&& string.Equals(section.Expression, "scripts", StringComparison.OrdinalIgnoreCase))
{
scriptsSection = section;
continue;
}
return output.ToString();
contentNodes.Add(node);
}
StringBuilder contentOutput = new(Math.Min(template.Length * 2, 256 * 1024));
Result<Success> contentResult = RenderNodes(contentNodes, new ThemeRenderScopeDto(model, Parent: null), contentOutput);
if (contentResult.IsFailure)
return contentResult.Errors;
StringBuilder scriptOutput = new(64 * 1024);
if (scriptsSection is not null)
{
Result<Success> scriptResult = RenderNodes(scriptsSection.Children, new ThemeRenderScopeDto(model, Parent: null), scriptOutput);
if (scriptResult.IsFailure)
return scriptResult.Errors;
}
return new ThemePageRenderResultDto(contentOutput.ToString(), scriptOutput.ToString());
}
/// <summary>
@@ -22,6 +22,7 @@
<link rel="stylesheet" href="~/css/dialog.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/textbox.css" asp-append-version="true" />
<link rel="stylesheet" href="~/Lumina.Presentation.Web.styles.css" asp-append-version="true" />
@await RenderSectionAsync("Head", required: false) <!--needed for themes templates css files-->
</head>
<body>
<div id="page">
@@ -0,0 +1,14 @@
@model Lumina.Presentation.Web.Common.DTO.Themes.ThemeViewDto
@section Head {
@if (!string.IsNullOrEmpty(Model.AssetBase))
{
<link rel="stylesheet" href="@Model.AssetBase/theme.css" />
}
}
@Html.Raw(Model.Content)
@section Scripts {
@Html.Raw(Model.Script)
}