From 4ef8570854c8cd59d8b0a83f81104450dc035a18 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 20 Aug 2026 10:21:05 -0700 Subject: [PATCH] Renders every page through the themed shell with a themed navigation menu --- .../Common/DTO/Themes/ThemeLayoutModelDto.cs | 30 +++ .../Common/DTO/Themes/ThemeLayoutPageDto.cs | 18 ++ .../Common/DTO/Themes/ThemeNavEntryDto.cs | 21 ++ .../Common/DTO/Themes/ThemeNavMenuDto.cs | 19 ++ .../Common/DTO/Themes/ThemeNavSectionDto.cs | 17 ++ .../Common/DTO/Themes/ThemeViewDto.cs | 4 +- .../PresentationWebLayerServices.cs | 3 + .../Home/HomeNotFoundViewEndpoint.cs | 49 +++- .../Books/Index/BooksIndexViewEndpoint.cs | 9 +- .../Core/Themes/RazorViewToStringRenderer.cs | 64 +++++ .../Core/Themes/ThemeLayoutRenderer.cs | 95 +++++++ .../Core/Themes/ThemeNavBuilder.cs | 251 ++++++++++++++++++ .../Views/Library/Management/Index.cshtml | 3 +- .../Core/Views/Shared/_AudioPlayer.cshtml | 17 ++ .../Core/Views/Shared/_Layout.cshtml | 152 +++++------ .../Core/Views/Shared/_NavMenu.cshtml | 4 +- .../Core/Views/Shared/_ThemeLayoutHead.cshtml | 11 + .../Views/Shared/_ThemeLayoutScripts.cshtml | 37 +++ .../Core/Views/Shared/_ThemedView.cshtml | 7 - 19 files changed, 707 insertions(+), 104 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs create mode 100644 src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs create mode 100644 src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs create mode 100644 src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml create mode 100644 src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml create mode 100644 src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs new file mode 100644 index 00000000..b361e203 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutModelDto.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model available to the themed layout template while rendering the shell of a page. +/// +/// The title of the page, rendered by the theme. +/// The base URL of the theme assets. +/// The application head links, such as its global stylesheets. +/// The rendered navigation menu of the page. +/// The rendered content section of the page. +/// The rendered audio player, when the current user is authenticated. +/// The application global scripts, such as its client libraries and configuration. +/// The rendered script section of the page. +/// The inline style of the main content area, used to fill the viewport when the user is not authenticated. +[DebuggerDisplay("Title: {Title}")] +public sealed record ThemeLayoutModelDto( + string Title, + string AssetBase, + string AppHead, + string Nav, + string Content, + string AudioPlayer, + string AppScripts, + string Scripts, + string MainStyle +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs new file mode 100644 index 00000000..5c674c47 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeLayoutPageDto.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the page content handed to the layout renderer, which wraps it in the themed shell. +/// +/// The title of the page, displayed by the themed shell. +/// The rendered HTML content of the page section. +/// The rendered script element of the page section, when the template defines one. +[DebuggerDisplay("Title: {Title}")] +public sealed record ThemeLayoutPageDto( + string Title, + string Content, + string Script +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs new file mode 100644 index 00000000..3cab20a2 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavEntryDto.cs @@ -0,0 +1,21 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a menu entry of the themed navigation menu, either a link or a submenu. +/// +/// The localized label of the menu entry. +/// The URL of the link, or for a submenu. +/// The CSS classes of the link, such as nav-link for AJAX navigation. +/// The child links of a submenu, empty for a plain link. +[DebuggerDisplay("Label: {Label}")] +public sealed record ThemeNavEntryDto( + string Label, + string? Url, + string? CssClass, + IReadOnlyList Children +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs new file mode 100644 index 00000000..978f3337 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavMenuDto.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for the model available to the themed navigation menu template. +/// +/// The name of the site displayed by the navigation menu. +/// The menu sections of the mobile navigation menu. +/// The menu sections of the desktop navigation menu bar. +[DebuggerDisplay("SiteName: {SiteName}")] +public sealed record ThemeNavMenuDto( + string SiteName, + IReadOnlyList MobileSections, + IReadOnlyList MenubarSections +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs new file mode 100644 index 00000000..cd016274 --- /dev/null +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeNavSectionDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Presentation.Web.Common.DTO.Themes; + +/// +/// Data transfer object for a menu section of the themed navigation menu. +/// +/// The localized label of the menu section. +/// The menu entries of the section, visible to the current user. +[DebuggerDisplay("Label: {Label}")] +public sealed record ThemeNavSectionDto( + string Label, + IReadOnlyList Items +); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs index 2ec915c8..d3fd5350 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Themes/ThemeViewDto.cs @@ -9,10 +9,8 @@ namespace Lumina.Presentation.Web.Common.DTO.Themes; /// /// 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 + string Script ); diff --git a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs index 176cedab..757dc241 100644 --- a/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs +++ b/src/Lumina.Presentation.Web/Common/DependencyInjection/PresentationWebLayerServices.cs @@ -304,6 +304,9 @@ public static class PresentationWebLayerServices services.AddScoped(); services.AddSingleton(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs index 25e9853a..6e5c239e 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Home/HomeNotFoundViewEndpoint.cs @@ -1,9 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Routes; 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 @@ -15,6 +20,26 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Home; /// public class HomeNotFoundViewEndpoint : BaseEndpoint { + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared.NotFound"; + 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 = "shared/not-found"; + + private readonly ThemePageRenderer _themePageRenderer; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for rendering themed pages. + /// Injected factory used to create the localizer of the view resources. + public HomeNotFoundViewEndpoint(ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory) + { + _themePageRenderer = themePageRenderer; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + /// /// Configures the endpoint. /// @@ -28,12 +53,30 @@ public class HomeNotFoundViewEndpoint : BaseEndpoint } /// - /// Displays the not-found page. + /// Displays the not-found page, rendered by the active theme with a fallback to the Razor view. /// /// The request object. /// Cancellation token that can be used to stop the execution. - public override Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) { - return Task.FromResult(View("/Core/Views/Shared/NotFound.cshtml")); + ThemePageDto pageModel = new() + { + PageKey = VIEW_PAGE_KEY, + Title = _localizer["PageNotFound"].Value, + Description = _localizer["ThereIsNoPage"].Value, + PageData = new Dictionary + { + ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) + } + }; + + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.IsFailure) + return View("/Core/Views/Shared/NotFound.cshtml"); + + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = pageModel.Title }); } } 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 0d281a23..d384431e 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 @@ -89,10 +89,13 @@ public class BooksIndexViewEndpoint : BaseEndpoint } }; - Result renderResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); - if (renderResult.IsFailure) + Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); + if (sectionResult.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)); + return View( + "/Core/Views/Shared/_ThemedView.cshtml", + new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), + new Dictionary { ["Title"] = pageModel.Title }); } } diff --git a/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs new file mode 100644 index 00000000..834fd809 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/RazorViewToStringRenderer.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewEngines; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders a Razor partial to a string, so that the application chrome can be reused by the themed layout renderer. +/// +public sealed class RazorViewToStringRenderer +{ + private readonly ICompositeViewEngine _viewEngine; + private readonly ITempDataProvider _tempDataProvider; + private readonly IServiceProvider _serviceProvider; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// Injected engine used to resolve the partial to render. + /// Injected provider used to create the temp data dictionary of the view context. + /// Injected service provider used to resolve the model metadata provider. + /// Injected accessor for the current HTTP context. + public RazorViewToStringRenderer(ICompositeViewEngine viewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider, IHttpContextAccessor httpContextAccessor) + { + _viewEngine = viewEngine; + _tempDataProvider = tempDataProvider; + _serviceProvider = serviceProvider; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Renders the partial with the specified name to a string. + /// + /// The name of the partial to render. + /// Cancellation token that can be used to stop the execution. + /// The rendered HTML of the partial. + public async Task RenderPartialAsync(string partialName, CancellationToken cancellationToken = default) + { + HttpContext httpContext = _httpContextAccessor.HttpContext ?? throw new InvalidOperationException("The current HTTP context is unavailable."); + ActionContext actionContext = new(httpContext, httpContext.GetRouteData() ?? new RouteData(), new ActionDescriptor()); + IView view = _viewEngine.FindView(actionContext, partialName, isMainPage: false).View + ?? throw new InvalidOperationException($"The partial '{partialName}' could not be found."); + + IModelMetadataProvider metadataProvider = _serviceProvider.GetRequiredService(); + ViewDataDictionary viewData = new(metadataProvider, new ModelStateDictionary()); + using StringWriter writer = new(); + ViewContext viewContext = new(actionContext, view, viewData, new TempDataDictionary(httpContext, _tempDataProvider), writer, new HtmlHelperOptions()); + await view.RenderAsync(viewContext).ConfigureAwait(false); + return writer.ToString(); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs new file mode 100644 index 00000000..65a7ca79 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeLayoutRenderer.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Primitives; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Renders the themed shell of a page, wrapping the page section in the layout and navigation templates of the active theme. +/// +public class ThemeLayoutRenderer +{ + // the page keys mirror the paths of the corresponding Razor views under Core/Views, so that theme templates can override them at the page, section or default scope + private const string LAYOUT_PAGE_KEY = "shared/layout"; + private const string NAV_PAGE_KEY = "shared/nav-menu"; + + private readonly ThemeService _themeService; + private readonly ThemeTemplateEngine _templateEngine; + private readonly RazorViewToStringRenderer _viewRenderer; + private readonly ThemeNavBuilder _navBuilder; + private readonly IHttpContextAccessor _httpContextAccessor; + + /// + /// Initializes a new instance of the class. + /// + /// The service that resolves the render documents. + /// The template engine used to render the documents. + /// The renderer used to produce the application chrome fragments. + /// The builder used to produce the navigation menu model. + /// Injected accessor for the current HTTP context. + public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, IHttpContextAccessor httpContextAccessor) + { + _themeService = themeService; + _templateEngine = templateEngine; + _viewRenderer = viewRenderer; + _navBuilder = navBuilder; + _httpContextAccessor = httpContextAccessor; + } + + /// + /// Renders the themed shell of the page, wrapping the page section in the layout template of the active theme. + /// + /// The rendered page section to wrap. + /// 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 full page HTML, or an error. + public virtual async Task> RenderAsync(ThemeLayoutPageDto page, string? requestedThemeId = null, CancellationToken cancellationToken = default) + { + ThemeRenderDocumentDto layoutDocument = await _themeService.GetRenderDocumentAsync(LAYOUT_PAGE_KEY, requestedThemeId, cancellationToken); + string themeId = layoutDocument.Theme.Id; + bool isAuthenticated = _httpContextAccessor.HttpContext?.User.Identity?.IsAuthenticated == true; + + string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken); + string nav = await RenderNavAsync(themeId, cancellationToken); + string audioPlayer = isAuthenticated ? await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken) : string.Empty; + string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken); + + ThemeLayoutModelDto layoutModel = new( + page.Title, + $"/theme-assets/{themeId}/assets", + appHead, + nav, + page.Content, + audioPlayer, + appScripts, + page.Script, + isAuthenticated ? string.Empty : "bottom: 0px;"); + + Result renderResult = _templateEngine.RenderPage(layoutDocument.Template, layoutModel); + if (renderResult.IsFailure) + return renderResult.Errors; + + return renderResult.Value.Content; + } + + /// + /// Renders the navigation menu of the active theme, falling back to the application Razor menu when the theme template cannot be rendered. + /// + /// The manifest id of the active theme. + /// Cancellation token that can be used to stop the execution. + /// The rendered navigation menu HTML. + private async Task RenderNavAsync(string themeId, CancellationToken cancellationToken) + { + ThemeNavMenuDto navModel = await _navBuilder.BuildAsync(cancellationToken); + ThemeRenderDocumentDto navDocument = await _themeService.GetRenderDocumentAsync(NAV_PAGE_KEY, themeId, cancellationToken); + Result navRenderResult = _templateEngine.RenderPage(navDocument.Template, navModel); + if (navRenderResult.IsSuccess) + return navRenderResult.Value.Content; + + return await _viewRenderer.RenderPartialAsync("_NavMenu", cancellationToken); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs new file mode 100644 index 00000000..7dd6b983 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs @@ -0,0 +1,251 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using System; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Themes; + +/// +/// Builds the navigation menu model for the themed navigation template, resolving the authorization conditions and localized labels server side. +/// +public sealed class ThemeNavBuilder +{ + // the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath + private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Shared._NavMenu"; + private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web"; + + private readonly IUrlService _urlService; + private readonly IStringLocalizerFactory _stringLocalizerFactory; + private readonly IAuthorizationService _authorizationService; + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly IStringLocalizer _localizer; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for generating URLs from action and controller names, with localization. + /// Injected factory used to create the localizer of the navigation resources. + /// Injected service used to resolve the roles and permissions of the current user. + /// Injected accessor for the current HTTP context. + public ThemeNavBuilder(IUrlService urlService, IStringLocalizerFactory stringLocalizerFactory, IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor) + { + _urlService = urlService; + _stringLocalizerFactory = stringLocalizerFactory; + _authorizationService = authorizationService; + _httpContextAccessor = httpContextAccessor; + _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + } + + /// + /// Builds the navigation menu model for the current user and request. + /// + /// Cancellation token that can be used to stop the execution. + /// The navigation menu model, with the sections visible to the current user. + public async Task BuildAsync(CancellationToken cancellationToken) + { + ClaimsPrincipal user = _httpContextAccessor.HttpContext?.User ?? new ClaimsPrincipal(); + bool isAuthenticated = user.Identity?.IsAuthenticated == true; + bool isAdmin = isAuthenticated && await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false); + bool canCreateLibraries = isAuthenticated && (isAdmin || await _authorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false)); + string returnUrl = Uri.EscapeDataString(GetCurrentRequestUrl()); + ThemeNavEntryDto[] languages = CreateLanguageEntries(returnUrl); + + List mobileSections = []; + mobileSections.Add(CreateSiteSection()); + mobileSections.Add(CreateAccountSection(isAuthenticated)); + if (isAdmin) + mobileSections.Add(CreateAdministratorSection()); + if (isAuthenticated) + mobileSections.Add(CreateLibrarySection(canCreateLibraries)); + mobileSections.Add(new ThemeNavSectionDto(Localize("Language"), languages)); + if (isAuthenticated) + mobileSections.Add(CreateToolsSection(isAuthenticated, languages: [])); + mobileSections.Add(CreateHelpSection()); + + List menubarSections = []; + menubarSections.Add(CreateSiteSection()); + menubarSections.Add(CreateAccountSection(isAuthenticated)); + if (isAdmin) + menubarSections.Add(CreateAdministratorSection()); + if (isAuthenticated) + menubarSections.Add(CreateLibrarySection(canCreateLibraries)); + menubarSections.Add(CreateToolsSection(isAuthenticated, languages)); + menubarSections.Add(CreateHelpSection()); + + return new ThemeNavMenuDto("Lumina", mobileSections, menubarSections); + } + + /// + /// Creates the site section, which links to the home page. + /// + /// The site section of the navigation menu. + private ThemeNavSectionDto CreateSiteSection() + { + return new ThemeNavSectionDto( + "Lumina", + [new ThemeNavEntryDto(Localize("Home"), _urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED), "nav-link", [])]); + } + + /// + /// Creates the account section, whose entries depend on the authentication state of the user. + /// + /// Whether the current user is authenticated. + /// The account section of the navigation menu. + private ThemeNavSectionDto CreateAccountSection(bool isAuthenticated) + { + List items = []; + if (isAuthenticated) + { + items.Add(new ThemeNavEntryDto(Localize("Logout"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGOUT), CssClass: null, Children: [])); + items.Add(new ThemeNavEntryDto(Localize("Register"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("ChangePassword"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.CHANGE_PASSWORD_VIEW), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("Profile"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.PROFILE_VIEW), "nav-link", [])); + } + else + { + items.Add(new ThemeNavEntryDto(Localize("Login"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.LOGIN_VIEW), CssClass: null, Children: [])); + items.Add(new ThemeNavEntryDto(Localize("RecoverPassword"), _urlService.GetAbsoluteUrl(WebRoutes.Authentication.RECOVER_PASSWORD_VIEW), CssClass: null, Children: [])); + } + + return new ThemeNavSectionDto(Localize("Account"), items); + } + + /// + /// Creates the administrator section, shown only to administrators. + /// + /// The administrator section of the navigation menu. + private ThemeNavSectionDto CreateAdministratorSection() + { + return new ThemeNavSectionDto( + Localize("Administrator"), + [ + new ThemeNavEntryDto(Localize("ManageRoles"), _urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_ROLES), "nav-link", []), + new ThemeNavEntryDto(Localize("ManagePermissions"), _urlService.GetAbsoluteUrl(WebRoutes.Admin.MANAGE_PERMISSIONS), "nav-link", []), + new ThemeNavEntryDto(Localize("Plugins"), _urlService.GetAbsoluteUrl(WebRoutes.Plugins.INDEX), "nav-link", []) + ]); + } + + /// + /// Creates the library section, shown only to authenticated users. + /// + /// Whether the current user can create media libraries. + /// The library section of the navigation menu. + private ThemeNavSectionDto CreateLibrarySection(bool canCreateLibraries) + { + List items = + [ + new ThemeNavEntryDto(Localize("ManageLibraries"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.INDEX), "nav-link", []) + ]; + if (canCreateLibraries) + items.Add(new ThemeNavEntryDto(Localize("AddNewLibrary"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY), "nav-link", [])); + items.Add(new ThemeNavEntryDto(Localize("WrittenContent"), Url: null, CssClass: null, + [ + new ThemeNavEntryDto(Localize("Books"), "library/written-content-library/books-library/books", "nav-link", []), + new ThemeNavEntryDto(Localize("Magazines"), "library/written-content/magazines", "nav-link", []) + ])); + items.Add(new ThemeNavEntryDto(Localize("Audio"), Url: null, CssClass: null, + [ + new ThemeNavEntryDto(Localize("Music"), "library/audio/music", "nav-link", []), + new ThemeNavEntryDto(Localize("Interviews"), "library/audio/interviews", "nav-link", []) + ])); + items.Add(new ThemeNavEntryDto(Localize("Video"), Url: null, CssClass: null, + [ + new ThemeNavEntryDto(Localize("Movies"), "library/video/movies", "nav-link", []), + new ThemeNavEntryDto(Localize("TvShows"), "library/video/tvshows", "nav-link", []) + ])); + + return new ThemeNavSectionDto(Localize("Library"), items); + } + + /// + /// Creates the tools section, with the language submenu and the settings entry. + /// + /// Whether the current user is authenticated. + /// The language entries of the submenu. + /// The tools section of the navigation menu. + private ThemeNavSectionDto CreateToolsSection(bool isAuthenticated, IReadOnlyList languages) + { + List items = []; + if (languages.Count > 0) + items.Add(new ThemeNavEntryDto(Localize("Language"), Url: null, CssClass: null, Children: languages)); + if (isAuthenticated) + items.Add(new ThemeNavEntryDto(Localize("Settings"), _urlService.GetAbsoluteUrl(WebRoutes.Settings.INDEX), "nav-link", [])); + + return new ThemeNavSectionDto(Localize("Tools"), items); + } + + /// + /// Creates the help section. + /// + /// The help section of the navigation menu. + private ThemeNavSectionDto CreateHelpSection() + { + return new ThemeNavSectionDto( + Localize("Help"), + [ + new ThemeNavEntryDto(Localize("Documentation"), "help/documentation", "nav-link", []), + new ThemeNavEntryDto(Localize("About"), "help/about", "nav-link", []) + ]); + } + + /// + /// Creates the language entries of the navigation menu, each keeping the current request URL as the return URL. + /// + /// The encoded current request URL used as the return URL. + /// The language entries of the navigation menu. + private ThemeNavEntryDto[] CreateLanguageEntries(string returnUrl) + { + string baseUrl = _urlService.GetAbsoluteUrl(WebRoutes.Language.SET_LANGUAGE) ?? string.Empty; + (string Culture, string DisplayName)[] cultures = + [ + ("zh-cn", "简体中文"), + ("de-de", "Deutsch"), + ("en-us", "English"), + ("es-es", "Español"), + ("fr-fr", "Français"), + ("it-it", "Italiano"), + ("ja-jp", "日本語"), + ("ro-ro", "Română"), + ("ru-ru", "Русский") + ]; + + ThemeNavEntryDto[] entries = new ThemeNavEntryDto[cultures.Length]; + for (int index = 0; index < cultures.Length; index++) + { + (string culture, string displayName) = cultures[index]; + entries[index] = new ThemeNavEntryDto(displayName, $"{baseUrl}?newCulture={culture}&returnUrl={returnUrl}", "lang-set", []); + } + + return entries; + } + + /// + /// Gets the path and query string of the current request. + /// + /// The path and query string of the current request. + private string GetCurrentRequestUrl() + { + HttpRequest request = _httpContextAccessor.HttpContext?.Request ?? throw new InvalidOperationException("The current HTTP context is unavailable."); + return $"{request.Path}{request.QueryString}"; + } + + /// + /// Resolves a localized navigation label. + /// + /// The resource key of the label. + /// The localized label. + private string Localize(string key) + { + return _localizer[key].Value; + } +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml index 8cca8518..1d7bcd51 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Management/Index.cshtml @@ -259,7 +259,7 @@
@_localizer[ - + @_localizer[ @_localizer[ @@ -269,6 +269,7 @@ `; }).join(''); + bindNavigationLinks(); // bind the dynamically created edit links, so that editing keeps the persistent chrome running } else { btnScanAllLibraries.style.display = 'none'; table.style.display = 'none'; diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml new file mode 100644 index 00000000..65f7ceaa --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_AudioPlayer.cshtml @@ -0,0 +1,17 @@ +@using Microsoft.Extensions.Localization + +@inject IStringLocalizerFactory _stringLocalizerFactory + +@{ + IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); +} + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml index d7251b2c..8bb2c584 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_Layout.cshtml @@ -1,89 +1,71 @@ -@using Lumina.Presentation.Web.Common.DTO.Configuration -@using Microsoft.AspNetCore.Mvc.Localization -@using Microsoft.Extensions.Options +@using Lumina.Presentation.Web.Common.DTO.Themes +@using Lumina.Presentation.Web.Common.Primitives +@using Lumina.Presentation.Web.Core.Themes +@using Microsoft.AspNetCore.Html +@using System.IO +@using System.Text.Encodings.Web -@inject IViewLocalizer _localizer -@inject IOptions _serverConfigurationModel +@inject ThemeLayoutRenderer _themeLayoutRenderer - - - - - - @ViewData["Title"] - Lumina - - - - - - - - - - - - @await RenderSectionAsync("Head", required: false) - - -
-
- @await Html.PartialAsync("_NavMenu") -
-
-
- @RenderBody() -
-
-
-
- @if (User?.Identity?.IsAuthenticated == true) - { - - - } -
- - +@{ + string bodyHtml; + using (StringWriter bodyWriter = new()) + { + IHtmlContent bodyContent = RenderBody(); + bodyContent.WriteTo(bodyWriter, HtmlEncoder.Default); + bodyHtml = bodyWriter.ToString(); + } - - - - - -
- @await RenderSectionAsync("Scripts", required: false) -
- - + string title = ViewData["Title"]?.ToString() ?? string.Empty; + Result themedResult = await _themeLayoutRenderer.RenderAsync(new ThemeLayoutPageDto(title, bodyHtml, scriptsHtml), cancellationToken: ViewContext.HttpContext.RequestAborted); +} + +@if (themedResult.IsSuccess) +{ + @Html.Raw(themedResult.Value) +} +else +{ + + + + + + @ViewData["Title"] - Lumina + @await Html.PartialAsync("_ThemeLayoutHead") + + +
+
+ @await Html.PartialAsync("_NavMenu") +
+
+
+ @Html.Raw(bodyHtml) +
+
+
+
+ @if (User?.Identity?.IsAuthenticated == true) + { + @await Html.PartialAsync("_AudioPlayer") + } +
+ + @await Html.PartialAsync("_ThemeLayoutScripts") +
+ @Html.Raw(scriptsHtml) +
+ + +} diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml index a1f51376..cd8b1705 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_NavMenu.cshtml @@ -19,7 +19,7 @@ Lumina
@_localizer["Account"] @@ -124,7 +124,7 @@
  • diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml new file mode 100644 index 00000000..abe3dcc8 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutHead.cshtml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml new file mode 100644 index 00000000..68f3d5a5 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemeLayoutScripts.cshtml @@ -0,0 +1,37 @@ +@using Lumina.Presentation.Web.Common.DTO.Configuration +@using Microsoft.Extensions.Localization +@using Microsoft.Extensions.Options + +@inject IStringLocalizerFactory _stringLocalizerFactory +@inject IOptions _serverConfigurationModel + +@{ + IStringLocalizer localizer = _stringLocalizerFactory.Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); +} + + + + + + diff --git a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml index 770fbdad..ed431a82 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Shared/_ThemedView.cshtml @@ -1,12 +1,5 @@ @model Lumina.Presentation.Web.Common.DTO.Themes.ThemeViewDto -@section Head { - @if (!string.IsNullOrEmpty(Model.AssetBase)) - { - - } -} - @Html.Raw(Model.Content) @section Scripts {