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

@@ -1,28 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for a content entry rendered by a theme.
/// </summary>
/// <param name="Number">The ordering number of the content entry.</param>
/// <param name="Title">The title of the content entry.</param>
/// <param name="Description">The description of the content entry.</param>
/// <param name="Meta">The metadata line of the content entry.</param>
/// <param name="Badge">The badge text of the content entry.</param>
/// <param name="Accent">The accent color of the content entry.</param>
/// <param name="Glyph">The glyph or icon of the content entry.</param>
/// <param name="Url">The URL the content entry links to.</param>
[DebuggerDisplay("Number: {Number}, Title: {Title}")]
public sealed record ContentItemDto(
string Number,
string Title,
string Description,
string Meta,
string Badge,
string Accent,
string Glyph,
string Url
);
@@ -1,20 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for a navigation entry rendered by a theme.
/// </summary>
/// <param name="Key">The unique key of the navigation entry.</param>
/// <param name="Label">The display label of the navigation entry.</param>
/// <param name="Url">The URL the navigation entry links to.</param>
/// <param name="IsCurrent">Whether the navigation entry represents the currently displayed page.</param>
[DebuggerDisplay("Key: {Key}, Label: {Label}")]
public sealed record NavigationItemDto(
string Key,
string Label,
string Url,
bool IsCurrent
);
@@ -1,18 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for a statistic rendered by a theme.
/// </summary>
/// <param name="Value">The numeric or textual value of the statistic.</param>
/// <param name="Label">The label of the statistic.</param>
/// <param name="Detail">The additional detail of the statistic.</param>
[DebuggerDisplay("Value: {Value}, Label: {Label}")]
public sealed record StatItemDto(
string Value,
string Label,
string Detail
);
@@ -6,7 +6,7 @@ using System.Diagnostics;
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the full model available to a theme template while rendering a page.
/// Data transfer object for the model available to a theme template while rendering a page.
/// </summary>
[DebuggerDisplay("Title: {Title}")]
public sealed class ThemePageDto
@@ -16,11 +16,6 @@ public sealed class ThemePageDto
/// </summary>
public required string PageKey { get; init; }
/// <summary>
/// Gets or sets the name of the site displayed by the theme.
/// </summary>
public required string SiteName { get; init; }
/// <summary>
/// Gets or sets the title of the page.
/// </summary>
@@ -32,72 +27,23 @@ public sealed class ThemePageDto
public required string Description { get; init; }
/// <summary>
/// Gets or sets the eyebrow text shown above the page title.
/// Gets or sets the resolved values exposed to the theme template and its scripts. Each page populates the entries its
/// template needs, such as resolved URLs, identifiers and server paths, and the localized strings of the page under the <c>strings</c> key.
/// </summary>
public required string Eyebrow { get; init; }
public required IReadOnlyDictionary<string, object?> PageData { get; init; } = new Dictionary<string, object?>();
/// <summary>
/// Gets or sets the label of the primary call to action.
/// Gets or sets the identifier of the script section of the page. Populated immediately before rendering.
/// </summary>
public required string PrimaryActionLabel { get; init; }
/// <summary>
/// Gets or sets the URL of the primary call to action.
/// </summary>
public required string PrimaryActionUrl { get; init; }
/// <summary>
/// Gets or sets the label of the secondary call to action.
/// </summary>
public required string SecondaryActionLabel { get; init; }
/// <summary>
/// Gets or sets the URL of the secondary call to action.
/// </summary>
public required string SecondaryActionUrl { get; init; }
/// <summary>
/// Gets or sets the navigation entries rendered by the theme.
/// </summary>
public required IReadOnlyList<NavigationItemDto> Navigation { get; init; }
/// <summary>
/// Gets or sets the content entries rendered by the theme.
/// </summary>
public required IReadOnlyList<ContentItemDto> Items { get; init; }
/// <summary>
/// Gets or sets the statistics rendered by the theme.
/// </summary>
public required IReadOnlyList<StatItemDto> Stats { get; init; }
/// <summary>
/// Gets or sets a value indicating whether the page is a theme preview.
/// </summary>
public bool IsPreview { get; init; }
public string ScriptId { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the identifier of the theme rendering the page. Populated immediately before rendering.
/// </summary>
public string ThemeId { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the name of the theme rendering the page. Populated immediately before rendering.
/// </summary>
public string ThemeName { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the version of the theme rendering the page. Populated immediately before rendering.
/// </summary>
public string ThemeVersion { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the base URL of the theme assets. Populated immediately before rendering.
/// </summary>
public string AssetBase { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the current year. Populated immediately before rendering.
/// </summary>
public int CurrentYear { get; set; }
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the rendered content and script of a themed page section.
/// </summary>
/// <param name="Content">The rendered HTML content of the page section.</param>
/// <param name="Script">The rendered script element of the page section, when the template defines one.</param>
[DebuggerDisplay("Content length: {Content.Length}, Script length: {Script.Length}")]
public sealed record ThemePageRenderResultDto(
string Content,
string Script
);
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the rendered sections of a themed page, served through the shared themed view.
/// </summary>
/// <param name="Content">The rendered HTML content of the page section.</param>
/// <param name="Script">The rendered script element of the page section, when the template defines one.</param>
/// <param name="AssetBase">The base URL of the theme assets, used to load the theme stylesheet of the page.</param>
[DebuggerDisplay("Content length: {Content.Length}, Script length: {Script.Length}")]
public sealed record ThemeViewDto(
string Content,
string Script,
string AssetBase
);
@@ -15,7 +15,7 @@ public static partial class ApiRoutes
public const string GET_THEME_SETTINGS = "themes/settings";
public const string GET_CURRENT_THEME = "themes/current";
public const string SET_CURRENT_THEME = "themes/current";
public const string GET_THEME_TEMPLATE = "themes/{themeId}/templates/{pageKey}";
public const string GET_THEME_TEMPLATE = "themes/{themeId}/templates/{*pageKey}";
public const string GET_THEME_ASSET = "themes/{themeId}/assets/{*assetPath}";
public const string GET_THEME_ARCHIVE = "themes/{themeId}/archive";
public const string DELETE_THEME = "themes/{themeId}";
@@ -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)
}