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

@@ -99,9 +99,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
Result<Created> insertResult = await unitOfWork.ThemeRepository.InsertAsync(themeEntity, stoppingToken);
if (insertResult.IsFailure)
_logger.LogWarning("Failed to persist the detection of theme '{ThemeId}': {Error}", manifestResult.Value.Id, insertResult.FirstError.Description);
else
themes.Add(themeEntity);
}
await CleanUpMissingThemePacksAsync(unitOfWork, themes, stoppingToken);
await EnsureCurrentThemeExistsAsync(unitOfWork, themes, stoppingToken);
await unitOfWork.SaveChangesAsync(stoppingToken);
}
@@ -112,12 +115,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, List<ThemeEntity> themes, CancellationToken cancellationToken)
private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
{
// a soft deleted theme was deleted intentionally from the admin interface, so it must never be restored
// automatically; only a theme that was not deleted, but whose files went missing, was corrupted or removed
// externally, and is the only case where the files are restored
List<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))];
IReadOnlyList<ThemeEntity> brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))];
if (brokenThemes.Count is 0)
return;
@@ -151,22 +154,30 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService
_logger.LogWarning("Failed to delete theme '{ThemeId}': {Error}", brokenTheme.ThemeId, deleteResult.FirstError.Description);
}
}
}
// if the deleted theme was the active one, switch to another available theme, preferring the configured default
/// <summary>
/// Activates the configured default theme when no theme is currently active, so the application always has an active theme.
/// </summary>
/// <param name="unitOfWork">The unit of work for interacting with the theme repository.</param>
/// <param name="themes">The installed themes read from the storage medium.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList<ThemeEntity> themes, CancellationToken cancellationToken)
{
if (themes.Any(theme => !theme.IsDeleted && theme.IsCurrent == true))
return;
ThemeEntity? replacementTheme = themes
ThemeEntity? defaultTheme = themes
.Where(theme => !theme.IsDeleted && _themeService.HasThemePack(theme.ThemeId))
.OrderBy(theme => string.Equals(theme.ThemeId, _themeService.DefaultThemeId, StringComparison.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(theme => theme.ThemeId, StringComparer.OrdinalIgnoreCase)
.FirstOrDefault();
if (replacementTheme is null)
if (defaultTheme is null)
return;
replacementTheme.IsCurrent = true;
replacementTheme.UpdatedOnUtc = DateTime.UtcNow;
replacementTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(replacementTheme, cancellationToken);
defaultTheme.IsCurrent = true;
defaultTheme.UpdatedOnUtc = DateTime.UtcNow;
defaultTheme.UpdatedBy = default;
await unitOfWork.ThemeRepository.UpdateAsync(defaultTheme, cancellationToken);
}
}
@@ -260,10 +260,13 @@ public sealed class ThemeService : IThemeService
return manifestResult.Errors;
ThemeManifestDto manifest = manifestResult.Value;
if (!manifest.Templates.TryGetValue(pageKey, out string? templatePath))
templatePath = manifest.Templates["default"]; // the manifest validation guarantees a default template
string themePath = ResolveThemePath(themeId);
string? templatePath = manifest.Templates.TryGetValue(pageKey, out string? explicitPath)
? explicitPath
: ResolveMirroredTemplatePath(themePath, pageKey);
templatePath ??= manifest.Templates["default"]; // the manifest validation guarantees a default template
Result<string> fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), templatePath);
Result<string> fullPathResult = ResolveContainedPath(themePath, templatePath);
if (fullPathResult.IsFailure)
return fullPathResult.Errors;
@@ -277,6 +280,33 @@ public sealed class ThemeService : IThemeService
return template;
}
/// <summary>
/// Resolves the mirrored template path of a page key, walking up the scopes of the path when the exact mirror does not exist.
/// </summary>
/// <param name="themePath">The absolute path of the theme pack directory.</param>
/// <param name="pageKey">The page key that selects the template.</param>
/// <returns>The mirrored template path, or <see langword="null"/> when no mirrored template exists.</returns>
private static string? ResolveMirroredTemplatePath(string themePath, string pageKey)
{
string? candidate = pageKey;
while (candidate is not null)
{
// normalize the mirrored candidate so that malicious page keys cannot escape the theme pack
Result<string> normalizedResult = NormalizeRelativePath($"templates/{candidate}.html");
if (normalizedResult.IsSuccess)
{
Result<string> fullPathResult = ResolveContainedPath(themePath, normalizedResult.Value);
if (fullPathResult.IsSuccess && File.Exists(fullPathResult.Value))
return normalizedResult.Value;
}
int lastSlash = candidate.LastIndexOf('/');
candidate = lastSlash < 0 ? null : candidate[..lastSlash];
}
return null;
}
/// <summary>
/// Gets a theme asset file.
/// </summary>
@@ -14,7 +14,7 @@
"MaxExpandedBytes": 25165824,
"MaxSingleFileBytes": 6291456,
"MaxEntries": 250,
"AllowThemeScripts": false
"AllowThemeScripts": true
},
"ConnectionStrings": {
"DefaultConnection": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;"
@@ -12,7 +12,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}";
@@ -16,7 +16,7 @@ using System.Threading.Tasks;
namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate;
/// <summary>
/// API endpoint for the <c>/themes/{themeId}/templates/{pageKey}</c> route.
/// API endpoint for the <c>/themes/{themeId}/templates/{*pageKey}</c> route.
/// </summary>
public class GetThemeTemplateEndpoint : BaseEndpoint<GetThemeTemplateRequest, IResult>
{
@@ -56,7 +56,7 @@ public class GetThemeTemplateEndpointSummary : Summary<GetThemeTemplateEndpoint,
title = "General.Validation",
status = 422,
detail = "OneOrMoreValidationErrorsOccurred",
instance = "/api/v1/themes/{themeId}/templates/{pageKey}",
instance = "/api/v1/themes/{themeId}/templates/{*pageKey}",
errors = new Dictionary<string, string[]>
{
{
@@ -78,7 +78,7 @@ public class GetThemeTemplateEndpointSummary : Summary<GetThemeTemplateEndpoint,
title = "General.Failure",
status = 403,
detail = "ThemeNotAvailable",
instance = "/api/v1/themes/{themeId}/templates/{pageKey}",
instance = "/api/v1/themes/{themeId}/templates/{*pageKey}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
);
@@ -90,7 +90,7 @@ public class GetThemeTemplateEndpointSummary : Summary<GetThemeTemplateEndpoint,
title = "General.NotFound",
status = 404,
detail = "ThemeNotFound",
instance = "/api/v1/themes/{themeId}/templates/{pageKey}",
instance = "/api/v1/themes/{themeId}/templates/{*pageKey}",
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
}
);
@@ -50,6 +50,14 @@
</None>
</ItemGroup>
<ItemGroup>
<Content Include="Themes\Bundled\*.zip">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Link>themes\bundled\%(Filename)%(Extension)</Link>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Lumina.Contracts\Lumina.Contracts.csproj" />
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
@@ -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)
}
@@ -2,17 +2,22 @@
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.Http;
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.Library.WrittenContentLibrary.BookLibrary.Books.Index;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
@@ -28,6 +33,9 @@ public class BooksIndexViewEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IUrlService _mockUrlService;
private readonly ThemePageRenderer _mockThemePageRenderer;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly BooksIndexViewEndpoint _sut;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
@@ -38,7 +46,12 @@ public class BooksIndexViewEndpointTests
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockUrlService = Substitute.For<IUrlService>();
_sut = Factory.Create<BooksIndexViewEndpoint>(_mockApiHttpClient, _mockUrlService);
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(new LocalizedString[] { new("Search", "Search") });
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_sut = Factory.Create<BooksIndexViewEndpoint>(_mockApiHttpClient, _mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
_sut.HttpContext.Request.Path = "/en-us/library/written-content-library/books-library/books";
}
@@ -56,22 +69,56 @@ public class BooksIndexViewEndpointTests
RedirectHttpResult redirectResult = Assert.IsType<RedirectHttpResult>(result);
Assert.Equal("http://localhost/en-us", redirectResult.Url);
await _mockApiHttpClient.DidNotReceive().GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldReturnRazorViewResultWithLibraryModel()
public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldRenderThemedPageThroughTheSharedView()
{
// Arrange
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(expectedLibrary);
_mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items");
_mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings");
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new ThemePageRenderResultDto("<section>content</section>", "<script>script</script>")));
// Act
IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None);
// Assert
Assert.IsType<RazorViewResult>(result);
string expectedEndpoint = ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id!.Value.ToString());
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto>(expectedEndpoint, Arg.Any<CancellationToken>());
await _mockThemePageRenderer.Received(1).RenderAsync(
Arg.Is<ThemePageDto>(page =>
page.PageKey == "library/written-content-library/book-library/books/index" &&
page.Title == expectedLibrary.Title &&
page.PageData.ContainsKey("libraryId") &&
page.PageData.ContainsKey("settingsUrl") &&
page.PageData.ContainsKey("strings") &&
string.Equals(
page.PageData["itemsUrl"] as string,
"http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items",
StringComparison.Ordinal)),
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView()
{
// Arrange
LibraryDto expectedLibrary = _libraryDtoFixture.Create();
_mockApiHttpClient.GetAsync<LibraryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(expectedLibrary);
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
// Act
IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None);
// Assert
Assert.IsType<RazorViewResult>(result);
await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.FileSystemManagement;
using Lumina.Presentation.Web.Common.Requests.Themes;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Themes.ThemeAssets;
/// <summary>
/// Contains unit tests for the <see cref="ThemeAssetsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeAssetsEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly ThemeAssetsEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeAssetsEndpointTests"/> class.
/// </summary>
public ThemeAssetsEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<ThemeAssetsEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenAssetPathProvided_ShouldFetchAssetWithTheResolvedPath()
{
// Arrange
_mockApiHttpClient.GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(new BlobDataDto { Data = [1, 2, 3], ContentType = "text/css" });
// Act
IResult result = await _sut.ExecuteAsync(new GetThemeAssetRequest(ThemeId: "editorial-paper", Path: "assets/style.css"), CancellationToken.None);
// Assert
FileContentHttpResult fileResult = Assert.IsType<FileContentHttpResult>(result);
Assert.Equal("text/css", fileResult.ContentType);
string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ASSET
.Replace("{themeId}", "editorial-paper")
.Replace("{*assetPath}", "assets/style.css");
await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAssetPathMissing_ShouldReturnProblem()
{
// Act
IResult result = await _sut.ExecuteAsync(new GetThemeAssetRequest(ThemeId: "editorial-paper", Path: null), CancellationToken.None);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode);
await _mockApiHttpClient.DidNotReceive().GetBlobAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
}