diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs index 910d4112..9bdd21e5 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeDetectionSyncJob.cs @@ -99,9 +99,12 @@ internal sealed class ThemeDetectionSyncJob : BackgroundService Result 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 /// The unit of work for interacting with the theme repository. /// The installed themes read from the storage medium. /// Cancellation token that can be used to stop the execution. - private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, List themes, CancellationToken cancellationToken) + private async Task CleanUpMissingThemePacksAsync(IUnitOfWork unitOfWork, IReadOnlyList 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 brokenThemes = [.. themes.Where(theme => !theme.IsDeleted && !_themeService.HasThemePack(theme.ThemeId))]; + IReadOnlyList 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 + /// + /// Activates the configured default theme when no theme is currently active, so the application always has an active theme. + /// + /// The unit of work for interacting with the theme repository. + /// The installed themes read from the storage medium. + /// Cancellation token that can be used to stop the execution. + private async Task EnsureCurrentThemeExistsAsync(IUnitOfWork unitOfWork, IReadOnlyList 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); } } diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index d9e64869..b8948db1 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -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 fullPathResult = ResolveContainedPath(ResolveThemePath(themeId), templatePath); + Result fullPathResult = ResolveContainedPath(themePath, templatePath); if (fullPathResult.IsFailure) return fullPathResult.Errors; @@ -277,6 +280,33 @@ public sealed class ThemeService : IThemeService return template; } + /// + /// Resolves the mirrored template path of a page key, walking up the scopes of the path when the exact mirror does not exist. + /// + /// The absolute path of the theme pack directory. + /// The page key that selects the template. + /// The mirrored template path, or when no mirrored template exists. + 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 normalizedResult = NormalizeRelativePath($"templates/{candidate}.html"); + if (normalizedResult.IsSuccess) + { + Result 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; + } + /// /// Gets a theme asset file. /// diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 43b33ac7..6ccc0db4 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -14,7 +14,7 @@ "MaxExpandedBytes": 25165824, "MaxSingleFileBytes": 6291456, "MaxEntries": 250, - "AllowThemeScripts": false + "AllowThemeScripts": true }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;User Id=;Password=;" diff --git a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs index ed0b0169..f9e366ce 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Themes/ApiRoutes.Themes.cs @@ -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}"; diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs index b6b10f9e..439b27f4 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpoint.cs @@ -16,7 +16,7 @@ using System.Threading.Tasks; namespace Lumina.Presentation.Api.Core.Endpoints.Themes.Queries.GetThemeTemplate; /// -/// API endpoint for the /themes/{themeId}/templates/{pageKey} route. +/// API endpoint for the /themes/{themeId}/templates/{*pageKey} route. /// public class GetThemeTemplateEndpoint : BaseEndpoint { diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs index 6980380f..545cd57f 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Themes/Queries/GetThemeTemplate/GetThemeTemplateEndpointSummary.cs @@ -56,7 +56,7 @@ public class GetThemeTemplateEndpointSummary : Summary { { @@ -78,7 +78,7 @@ public class GetThemeTemplateEndpointSummary : Summary + + + PreserveNewest + PreserveNewest + themes\bundled\%(Filename)%(Extension) + + + diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs deleted file mode 100644 index 01bbaab2..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ContentItemDto.cs +++ /dev/null @@ -1,28 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for a content entry rendered by a theme. -/// -/// The ordering number of the content entry. -/// The title of the content entry. -/// The description of the content entry. -/// The metadata line of the content entry. -/// The badge text of the content entry. -/// The accent color of the content entry. -/// The glyph or icon of the content entry. -/// The URL the content entry links to. -[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 -); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs deleted file mode 100644 index fef38268..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/NavigationItemDto.cs +++ /dev/null @@ -1,20 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for a navigation entry rendered by a theme. -/// -/// The unique key of the navigation entry. -/// The display label of the navigation entry. -/// The URL the navigation entry links to. -/// Whether the navigation entry represents the currently displayed page. -[DebuggerDisplay("Key: {Key}, Label: {Label}")] -public sealed record NavigationItemDto( - string Key, - string Label, - string Url, - bool IsCurrent -); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs deleted file mode 100644 index 380039a6..00000000 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/StatItemDto.cs +++ /dev/null @@ -1,18 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Lumina.Presentation.Web.Common.DTO.Themes; - -/// -/// Data transfer object for a statistic rendered by a theme. -/// -/// The numeric or textual value of the statistic. -/// The label of the statistic. -/// The additional detail of the statistic. -[DebuggerDisplay("Value: {Value}, Label: {Label}")] -public sealed record StatItemDto( - string Value, - string Label, - string Detail -); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs index 6c3d3113..27968900 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageDto.cs @@ -6,7 +6,7 @@ using System.Diagnostics; namespace Lumina.Presentation.Web.Common.DTO.Themes; /// -/// 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. /// [DebuggerDisplay("Title: {Title}")] public sealed class ThemePageDto @@ -16,11 +16,6 @@ public sealed class ThemePageDto /// public required string PageKey { get; init; } - /// - /// Gets or sets the name of the site displayed by the theme. - /// - public required string SiteName { get; init; } - /// /// Gets or sets the title of the page. /// @@ -32,72 +27,23 @@ public sealed class ThemePageDto public required string Description { get; init; } /// - /// 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 strings key. /// - public required string Eyebrow { get; init; } + public required IReadOnlyDictionary PageData { get; init; } = new Dictionary(); /// - /// 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. /// - public required string PrimaryActionLabel { get; init; } - - /// - /// Gets or sets the URL of the primary call to action. - /// - public required string PrimaryActionUrl { get; init; } - - /// - /// Gets or sets the label of the secondary call to action. - /// - public required string SecondaryActionLabel { get; init; } - - /// - /// Gets or sets the URL of the secondary call to action. - /// - public required string SecondaryActionUrl { get; init; } - - /// - /// Gets or sets the navigation entries rendered by the theme. - /// - public required IReadOnlyList Navigation { get; init; } - - /// - /// Gets or sets the content entries rendered by the theme. - /// - public required IReadOnlyList Items { get; init; } - - /// - /// Gets or sets the statistics rendered by the theme. - /// - public required IReadOnlyList Stats { get; init; } - - /// - /// Gets or sets a value indicating whether the page is a theme preview. - /// - public bool IsPreview { get; init; } + public string ScriptId { get; set; } = string.Empty; /// /// Gets or sets the identifier of the theme rendering the page. Populated immediately before rendering. /// public string ThemeId { get; set; } = string.Empty; - /// - /// Gets or sets the name of the theme rendering the page. Populated immediately before rendering. - /// - public string ThemeName { get; set; } = string.Empty; - - /// - /// Gets or sets the version of the theme rendering the page. Populated immediately before rendering. - /// - public string ThemeVersion { get; set; } = string.Empty; - /// /// Gets or sets the base URL of the theme assets. Populated immediately before rendering. /// public string AssetBase { get; set; } = string.Empty; - - /// - /// Gets or sets the current year. Populated immediately before rendering. - /// - public int CurrentYear { get; set; } } diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageRenderResultDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageRenderResultDto.cs new file mode 100644 index 00000000..0e1bacf7 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemePageRenderResultDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the rendered content and script of a themed page section. +/// +/// The rendered HTML content of the page section. +/// The rendered script element of the page section, when the template defines one. +[DebuggerDisplay("Content length: {Content.Length}, Script length: {Script.Length}")] +public sealed record ThemePageRenderResultDto( + string Content, + string Script +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs new file mode 100644 index 00000000..2ec915c8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the rendered sections of a themed page, served through the shared themed view. +/// +/// The rendered HTML content of the page section. +/// The rendered script element of the page section, when the template defines one. +/// The base URL of the theme assets, used to load the theme stylesheet of the page. +[DebuggerDisplay("Content length: {Content.Length}, Script length: {Script.Length}")] +public sealed record ThemeViewDto( + string Content, + string Script, + string AssetBase +); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs index 8c8bc704..c7f14c91 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.Themes.cs @@ -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}"; diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs index 51c5a6b1..0d281a23 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpoint.cs @@ -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 /// public class BooksIndexViewEndpoint : BaseEndpoint { + // 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; /// /// Initializes a new instance of the class. /// /// Injected service for interactions with the API. /// Injected service for generating URLs from action and controller names, with localization. - public BooksIndexViewEndpoint(IApiHttpClient apiHttpClient, IUrlService urlService) + /// Injected service for rendering themed pages. + /// Injected factory used to create the localizer of the view resources. + 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); } /// @@ -46,7 +65,7 @@ public class BooksIndexViewEndpoint : BaseEndpoint } /// - /// Displays the books browsing view. + /// Displays the books browsing view, rendered by the active theme with a fallback to the Razor view. /// /// The request containing the Id of the media library whose books are browsed. /// Cancellation token that can be used to stop the execution. @@ -55,6 +74,25 @@ public class BooksIndexViewEndpoint : BaseEndpoint if (request.LibraryId is null) return Results.Redirect(_urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED)!); LibraryDto library = await _apiHttpClient.GetAsync(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 + { + ["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 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)); } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs index 2abfe226..77476bde 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpoint.cs @@ -52,7 +52,7 @@ public class ThemeAssetsEndpoint : BaseEndpoint 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); } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs new file mode 100644 index 00000000..85f1c29c --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageDataFactory.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.Extensions.Localization; +using System.Collections.Generic; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Builds the page data entries that the themed endpoints expose to their templates. +/// +public static class ThemePageDataFactory +{ + /// + /// Creates the localized strings of a page from the provided localizer, keyed by their resource names. + /// + /// The localizer of the page resources. + /// The localized strings keyed by their resource names. + public static Dictionary CreateLocalizedStrings(IStringLocalizer localizer) + { + Dictionary strings = []; + foreach (LocalizedString localizedString in localizer.GetAllStrings(includeParentCultures: true)) + strings[localizedString.Name] = localizedString.Value; + + return strings; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs index 660d0c91..1e7ceda8 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemePageRenderer.cs @@ -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; /// /// Renders a theme template against a page model, populating the theme metadata before rendering. /// -public sealed class ThemePageRenderer +public class ThemePageRenderer { private readonly ThemeService _themeService; private readonly ThemeTemplateEngine _templateEngine; @@ -28,22 +28,20 @@ public sealed class ThemePageRenderer } /// - /// 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. /// /// The page model to render. /// The optional unique identifier of the theme to render with, falling back to the current theme when . /// Cancellation token that can be used to stop the execution. - /// An containing either the rendered HTML, or an error. - public async Task> RenderAsync(ThemePageDto model, string? requestedThemeId = null, CancellationToken cancellationToken = default) + /// An containing either the rendered page, or an error. + public virtual async Task> 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); } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs index f9807e5d..ebb5b27a 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeService.cs @@ -110,7 +110,7 @@ public sealed class ThemeService themeId = requestedThemeId; ThemeTemplateResponseDto response = await _apiHttpClient.GetAsync( - 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); } diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs index e00d65f1..3a838b82 100644 --- a/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeTemplateEngine.cs @@ -26,28 +26,12 @@ public sealed class ThemeTemplateEngine RegexOptions.Compiled | RegexOptions.CultureInvariant); /// - /// Validates the structure and expressions of a theme template. - /// - /// The template source to validate. - /// An representing either a successful operation, or an error. - public Result Validate(string template) - { - ArgumentNullException.ThrowIfNull(template); - int cursor = 0; - Result> parseResult = ParseNodes(template, ref cursor, expectedClosingName: null, depth: 0); - if (parseResult.IsFailure) - return parseResult.Errors; - - return Result.Success; - } - - /// - /// Renders a theme template against the provided model. + /// Renders a theme template against the provided model, splitting the reserved top-level scripts section from the page content. /// /// The template source to render. /// The model the template expressions resolve against. - /// An containing either the rendered output, or an error. - public Result Render(string template, object model) + /// An containing either the rendered page, or an error. + public Result 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 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 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 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 scriptResult = RenderNodes(scriptsSection.Children, new ThemeRenderScopeDto(model, Parent: null), scriptOutput); + if (scriptResult.IsFailure) + return scriptResult.Errors; + } + + return new ThemePageRenderResultDto(contentOutput.ToString(), scriptOutput.ToString()); } /// diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index 2b8187f2..d7251b2c 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -22,6 +22,7 @@ + @await RenderSectionAsync("Head", required: false)
diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml new file mode 100644 index 00000000..770fbdad --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml @@ -0,0 +1,14 @@ +@model Lumina.Presentation.Web.Common.DTO.Themes.ThemeViewDto + +@section Head { + @if (!string.IsNullOrEmpty(Model.AssetBase)) + { + + } +} + +@Html.Raw(Model.Content) + +@section Scripts { + @Html.Raw(Model.Script) +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index bc80d5b6..a0d00dc3 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -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(); _mockUrlService = Substitute.For(); - _sut = Factory.Create(_mockApiHttpClient, _mockUrlService); + _mockThemePageRenderer = Substitute.For(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine()); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns(new LocalizedString[] { new("Search", "Search") }); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _sut = Factory.Create(_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(result); Assert.Equal("http://localhost/en-us", redirectResult.Url); await _mockApiHttpClient.DidNotReceive().GetAsync(Arg.Any(), Arg.Any()); + await _mockThemePageRenderer.DidNotReceive().RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] - public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldReturnRazorViewResultWithLibraryModel() + public async Task ExecuteAsync_WhenLibraryIdProvided_ShouldRenderThemedPageThroughTheSharedView() { // Arrange LibraryDto expectedLibrary = _libraryDtoFixture.Create(); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .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(), Arg.Any(), Arg.Any()) + .Returns(Result.From(new ThemePageRenderResultDto("
content
", ""))); // Act IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None); // Assert Assert.IsType(result); - string expectedEndpoint = ApiRoutes.Libraries.GET_LIBRARY_BY_ID.Replace("{id}", expectedLibrary.Id!.Value.ToString()); - await _mockApiHttpClient.Received(1).GetAsync(expectedEndpoint, Arg.Any()); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(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(requestedThemeId => requestedThemeId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToRazorView() + { + // Arrange + LibraryDto expectedLibrary = _libraryDtoFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedLibrary); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.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(result); + await _mockThemePageRenderer.Received(1).RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs new file mode 100644 index 00000000..182c9993 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly ThemeAssetsEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeAssetsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenAssetPathProvided_ShouldFetchAssetWithTheResolvedPath() + { + // Arrange + _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) + .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(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()); + } + + [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(result); + Assert.Equal(StatusCodes.Status400BadRequest, problemResult.StatusCode); + await _mockApiHttpClient.DidNotReceive().GetBlobAsync(Arg.Any(), Arg.Any()); + } +}