Moves the file explorer styling and layout into the bundled themes

This commit is contained in:
BinaryAlley committed 2026-08-29 16:28:58 +03:00
1 parent 3f69693332
commit a32f80337b
72 files changed
+1577 -1682

No files matched your search

@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeFileSystemBrowserBuilder"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeFileSystemBrowserBuilderTests
{
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly ThemeFileSystemBrowserBuilder _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeFileSystemBrowserBuilderTests"/> class.
/// </summary>
public ThemeFileSystemBrowserBuilderTests()
{
_mockStringLocalizer = CreateLocalizer();
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_sut = new ThemeFileSystemBrowserBuilder(_mockStringLocalizerFactory, _mockHttpContextAccessor);
}
[Fact]
public void Build_WhenCalled_ShouldResolveThemeAssetUrlsFromAssetBase()
{
// Arrange
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", "<div>{{name}}</div>", "<div>{{name}}</div>", "<li>{{path}}</li>");
// Assert
Assert.Equal("/theme-assets/editorial/assets", model.AssetBase);
Assert.Equal("/theme-assets/editorial/assets/images/icons", model.IconBaseUrl);
Assert.Equal("/theme-assets/editorial/assets/file-icons.json", model.FileIconsUrl);
}
[Fact]
public void Build_WhenCalled_ShouldKeepTheSubTemplatesOfTheDynamicContent()
{
// Arrange
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", "<div class=\"tree-node\">{{name}}</div>", "<div class=\"e\">{{name}}</div>", "<li>{{path}}</li>");
// Assert
Assert.Equal("<div class=\"tree-node\">{{name}}</div>", model.TreeNodeTemplate);
Assert.Equal("<div class=\"e\">{{name}}</div>", model.ExplorerItemTemplate);
Assert.Equal("<li>{{path}}</li>", model.PathSegmentTemplate);
}
[Fact]
public void Build_WhenCalled_ShouldLocalizeAllFileSystemBrowserStrings()
{
// Arrange
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty);
// Assert
string[] expectedKeys =
[
"listView", "detailsView", "smallIconsView", "mediumIconsView", "largeIconsView", "extraLargeIconsView",
"back", "forward", "upOneLevel", "toggleTreeView", "toggleThumbnails", "toggleHiddenItems",
"toggleSelectionMode", "editPath", "navigate", "newDirectory", "favoriteDirectory",
"name", "directory", "cancel", "open"
];
foreach (string key in expectedKeys)
{
Assert.True(model.Strings.TryGetValue(key, out object? value), $"The '{key}' string is missing.");
Assert.StartsWith("Localized-", Assert.IsType<string>(value));
}
}
[Fact]
public void Build_WhenRequestIsAvailable_ShouldResolveAppBaseFromCurrentRequest()
{
// Arrange
DefaultHttpContext httpContext = TestHttpContextFactory.Create();
httpContext.Request.Scheme = "https";
httpContext.Request.Host = new HostString("localhost", 5001);
_mockHttpContextAccessor.HttpContext.Returns(httpContext);
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty);
// Assert
Assert.Equal("https://localhost:5001/", model.AppBase);
}
[Fact]
public void Build_WhenRequestIsUnavailable_ShouldReturnEmptyAppBase()
{
// Arrange
_mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null);
// Act
ThemeFileSystemBrowserDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty, string.Empty);
// Assert
Assert.Equal(string.Empty, model.AppBase);
}
/// <summary>
/// Creates a substitute string localizer that returns a string prefixed with "Localized-".
/// </summary>
/// <returns>The created substitute string localizer.</returns>
private static IStringLocalizer CreateLocalizer()
{
IStringLocalizer localizer = Substitute.For<IStringLocalizer>();
localizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"Localized-{callInfo.Arg<string>()}"));
return localizer;
}
}
@@ -0,0 +1,232 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeFileSystemBrowserRenderer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeFileSystemBrowserRendererTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly IHttpContextAccessor _mockHttpContextAccessor;
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
private readonly IStringLocalizer _mockStringLocalizer;
private readonly ThemeFileSystemBrowserRenderer _sut;
private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new();
private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new();
private readonly ThemeFileSystemBrowserConfigurationDtoFixture _themeFileSystemBrowserConfigurationDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeFileSystemBrowserRendererTests"/> class.
/// </summary>
public ThemeFileSystemBrowserRendererTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
_mockStringLocalizer = CreateLocalizer();
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
ThemeService themeService = new(_mockApiHttpClient);
ThemeFileSystemBrowserBuilder builder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor);
_sut = new ThemeFileSystemBrowserRenderer(themeService, new ThemeTemplateEngine(), builder);
}
[Fact]
public async Task RenderAsync_WhenShellTemplateRendered_ShouldReturnThemedContentWithSubTemplatesAndInitScript()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme,
shellTemplate: "<div id=\"file-system-browser-dialog\">{{assetBase}}|{{iconBaseUrl}}|{{fileIconsUrl}}|{{strings.cancel}}</div><template id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</template>",
treeNodeTemplate: "<div class=\"tree-node\" data-path=\"{{path}}\">{{name}}</div>",
explorerItemTemplate: "<div class=\"e\">{{name}}</div>",
pathSegmentTemplate: "<li>{{path}}</li>");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(path: "C:\\Users\\", viewMode: "list", iconSize: "large");
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Contains("/theme-assets/editorial/assets", result.Value);
Assert.Contains("/theme-assets/editorial/assets/images/icons", result.Value);
Assert.Contains("data-path=\"{{path}}\"", result.Value);
Assert.Contains("initFileSystemBrowser(", result.Value);
Assert.Contains("serverBasePath", result.Value);
}
[Fact]
public async Task RenderAsync_WhenSubTemplateIsMissing_ShouldRenderEmptySubTemplate()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme,
shellTemplate: "<template id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</template>",
treeNodeTemplate: "not-returned",
explorerItemTemplate: "not-returned",
pathSegmentTemplate: "not-returned");
StubSubTemplateFailure(theme.ThemeId, "shared/file-system-browser/tree-node");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Contains("<template id=\"fsb-template-tree-node\"></template>", result.Value);
}
[Fact]
public async Task RenderAsync_WhenShellDocumentCannotBeLoaded_ShouldReturnTemplateUnavailableError()
{
// Arrange
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(Task.FromException<ThemeResponseDto>(new HttpRequestException("The theme API is unavailable.")));
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Unavailable", result.FirstError.Code);
}
[Fact]
public async Task RenderAsync_WhenShellTemplateIsInvalid_ShouldReturnTemplateUnavailableError()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme,
shellTemplate: "{{#unclosed}}",
treeNodeTemplate: string.Empty,
explorerItemTemplate: string.Empty,
pathSegmentTemplate: string.Empty);
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Template.Invalid", result.FirstError.Code);
}
[Fact]
public async Task RenderAsync_WhenCalled_ShouldFetchShellAndAllSubTemplatesFromActiveTheme()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme, "shell", "tree", "item", "segment");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create();
// Act
await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
string[] pageKeys =
[
"shared/file-system-browser",
"shared/file-system-browser/tree-node",
"shared/file-system-browser/explorer-item",
"shared/file-system-browser/path-segment"
];
foreach (string pageKey in pageKeys)
{
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", "editorial")
.Replace("{*pageKey}", pageKey);
await _mockApiHttpClient.Received(1).GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Any<CancellationToken>());
}
}
[Fact]
public async Task RenderAsync_WhenCalled_ShouldEscapeInitialPathInInitializationScript()
{
// Arrange
ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial");
SetupRenderDocuments(theme, "shell", "tree", "item", "segment");
ThemeFileSystemBrowserConfigurationDto configuration = _themeFileSystemBrowserConfigurationDtoFixture.Create(path: "C:\\Users\\", viewMode: "list", iconSize: "large");
// Act
Result<string> result = await _sut.RenderAsync(configuration, CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
Assert.Contains(@"C:\\Users\\", result.Value);
}
/// <summary>
/// Creates a substitute string localizer that returns a string prefixed with "Localized-".
/// </summary>
/// <returns>The created substitute string localizer.</returns>
private static IStringLocalizer CreateLocalizer()
{
IStringLocalizer localizer = Substitute.For<IStringLocalizer>();
localizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"Localized-{callInfo.Arg<string>()}"));
return localizer;
}
/// <summary>
/// Stubs the API responses that return the component shell and sub templates of the given theme, together with the current theme.
/// </summary>
/// <param name="theme">The theme whose templates are stubbed.</param>
/// <param name="shellTemplate">The template returned for the component shell document.</param>
/// <param name="treeNodeTemplate">The template returned for the tree node document.</param>
/// <param name="explorerItemTemplate">The template returned for the explorer item document.</param>
/// <param name="pathSegmentTemplate">The template returned for the path segment document.</param>
private void SetupRenderDocuments(ThemeResponseDto theme, string shellTemplate, string treeNodeTemplate, string explorerItemTemplate, string pathSegmentTemplate)
{
_mockApiHttpClient.GetAsync<ThemeResponseDto>(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any<CancellationToken>())
.Returns(theme);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser", shellTemplate);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/tree-node", treeNodeTemplate);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/explorer-item", explorerItemTemplate);
StubTemplateResponse(theme.ThemeId, "shared/file-system-browser/path-segment", pathSegmentTemplate);
}
/// <summary>
/// Stubs the API response that returns a single theme template document.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key of the template.</param>
/// <param name="template">The template returned for the document.</param>
private void StubTemplateResponse(string themeId, string pageKey, string template)
{
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", themeId)
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Any<CancellationToken>())
.Returns(_themeTemplateResponseDtoFixture.Create(theme: _themeResponseDtoFixture.Create(themeId: themeId), template: template));
}
/// <summary>
/// Stubs the API response of a theme template document to fail, as when the theme does not provide the template.
/// </summary>
/// <param name="themeId">The manifest id of the theme.</param>
/// <param name="pageKey">The page key of the template.</param>
private void StubSubTemplateFailure(string themeId, string pageKey)
{
string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE
.Replace("{themeId}", themeId)
.Replace("{*pageKey}", pageKey);
_mockApiHttpClient.GetAsync<ThemeTemplateResponseDto>(endpoint, Arg.Any<CancellationToken>())
.Returns(Task.FromException<ThemeTemplateResponseDto>(new HttpRequestException("The sub template is unavailable.")));
}
}
@@ -23,6 +23,7 @@ public class ThemeTemplateEngineTests
private readonly ThemeNavMenuDtoFixture _themeNavMenuDtoFixture = new();
private readonly ThemeNavSectionDtoFixture _themeNavSectionDtoFixture = new();
private readonly ThemeNavEntryDtoFixture _themeNavEntryDtoFixture = new();
private readonly ThemeFileSystemBrowserDtoFixture _themeFileSystemBrowserDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeTemplateEngineTests"/> class.
@@ -158,6 +159,24 @@ public class ThemeTemplateEngineTests
Assert.Equal("Tools:[Language]English,Francais,Settings", result.Value.Content);
}
[Fact]
public void RenderPage_WhenFileSystemBrowserModelUsed_ShouldResolveStringsAndInlineRawSubTemplates()
{
// Arrange
ThemeFileSystemBrowserDto model = _themeFileSystemBrowserDtoFixture.Create(
assetBase: "/theme-assets/editorial/assets",
treeNodeTemplate: "<div class=\"tree-node\" data-path=\"{{path}}\">{{name}}</div>",
strings: new Dictionary<string, object?> { ["cancel"] = "Annuler" });
string template = "{{assetBase}}|{{strings.cancel}}|<template id=\"fsb-template-tree-node\">{{{treeNodeTemplate}}}</template>";
// Act
Result<ThemePageRenderResultDto> result = _sut.RenderPage(template, model);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal("/theme-assets/editorial/assets|Annuler|<template id=\"fsb-template-tree-node\"><div class=\"tree-node\" data-path=\"{{path}}\">{{name}}</div></template>", result.Value.Content);
}
[Fact]
public void RenderPage_WhenSectionIsTruthy_ShouldRenderChildren()
{
@@ -0,0 +1,104 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Core.Themes;
using Lumina.Presentation.Web.Core.ViewComponents;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.ViewComponents;
/// <summary>
/// Contains unit tests for the <see cref="FileSystemBrowserViewComponent"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class FileSystemBrowserViewComponentTests
{
private readonly IOptions<ServerConfigurationDto> _serverConfigurationOptions;
private readonly ThemeFileSystemBrowserRenderer _mockRenderer;
private readonly FileSystemBrowserViewComponent _sut;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemBrowserViewComponentTests"/> class.
/// </summary>
public FileSystemBrowserViewComponentTests()
{
_serverConfigurationOptions = Options.Create(new ServerConfigurationDto
{
ApiVersion = '1',
BaseAddress = "http://localhost",
Port = 5214
});
ThemeService themeService = new(Substitute.For<IApiHttpClient>());
ThemeFileSystemBrowserBuilder builder = new(Substitute.For<IStringLocalizerFactory>(), Substitute.For<IHttpContextAccessor>());
_mockRenderer = Substitute.For<ThemeFileSystemBrowserRenderer>(themeService, new ThemeTemplateEngine(), builder);
_sut = new FileSystemBrowserViewComponent(_serverConfigurationOptions, _mockRenderer);
}
[Fact]
public async Task InvokeAsync_WhenThemedRenderSucceeds_ShouldReturnContentWithRenderedHtml()
{
// Arrange
_mockRenderer.RenderAsync(Arg.Any<ThemeFileSystemBrowserConfigurationDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("themed-html"));
// Act
IViewComponentResult result = await _sut.InvokeAsync();
// Assert
ViewViewComponentResult viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.Equal("Themed", viewResult.ViewName);
Assert.Equal("themed-html", viewResult.ViewData.Model);
}
[Fact]
public async Task InvokeAsync_WhenThemedRenderFails_ShouldReturnFallbackView()
{
// Arrange
_mockRenderer.RenderAsync(Arg.Any<ThemeFileSystemBrowserConfigurationDto>(), Arg.Any<CancellationToken>())
.Returns(Error.NotFound("Theme.Template.Unavailable", "The file system browser theme template could not be loaded."));
// Act
IViewComponentResult result = await _sut.InvokeAsync();
// Assert
ViewViewComponentResult viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.NotNull(viewResult.ViewData);
Assert.NotNull(viewResult.ViewData!.Model);
dynamic model = viewResult.ViewData!.Model!;
Assert.Equal("/", (string)model.Path);
Assert.Equal("list", (string)model.ViewMode);
Assert.Equal("large", (string)model.IconSize);
}
[Fact]
public async Task InvokeAsync_WhenCalled_ShouldPassConfigurationToRenderer()
{
// Arrange
_mockRenderer.RenderAsync(Arg.Any<ThemeFileSystemBrowserConfigurationDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("themed-html"));
// Act
await _sut.InvokeAsync();
// Assert
await _mockRenderer.Received(1).RenderAsync(
Arg.Is<ThemeFileSystemBrowserConfigurationDto>(configuration =>
configuration.ServerBasePath == "http://localhost:5214/api/v1/" &&
configuration.ClientBasePath == "http://localhost:5012/" &&
configuration.ViewMode == "list" &&
configuration.IconSize == "large"),
Arg.Any<CancellationToken>());
}
}