Adds the themeable audio player bar and its theming contract.

This commit is contained in:
BinaryAlley committed 2026-10-16 10:02:55 +03:00
1 parent 687371bfd2
commit a8e85d0673
14 files changed
+392 -28

No files matched your search

@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Themes;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Core.Themes;
/// <summary>
/// Builds the audio player model for the themed component template, resolving the localized strings and theme asset URLs server side.
/// </summary>
public sealed class ThemeAudioPlayerBuilder
{
// 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._Layout";
private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web";
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IStringLocalizer _localizer;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeAudioPlayerBuilder"/> class.
/// </summary>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the audio player resources.</param>
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
public ThemeAudioPlayerBuilder(IStringLocalizerFactory stringLocalizerFactory, IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION);
}
/// <summary>
/// Builds the model of the audio player for the given theme.
/// </summary>
/// <param name="assetBase">The base URL of the assets of the active theme.</param>
/// <param name="queueItemTemplate">The raw template source of a queue item, or an empty string when the theme does not provide one.</param>
/// <param name="playlistItemTemplate">The raw template source of a playlist item, or an empty string when the theme does not provide one.</param>
/// <returns>The model available to the themed audio player template.</returns>
public ThemeAudioPlayerDto Build(string assetBase, string queueItemTemplate, string playlistItemTemplate)
{
Dictionary<string, object?> strings = new()
{
["toggleFullHeight"] = Localize("ToggleFullHeight"),
["toggleVisibility"] = Localize("ToggleVisibility")
};
return new ThemeAudioPlayerDto(
AppBase: GetAppBaseUrl(),
AssetBase: assetBase,
QueueItemTemplate: queueItemTemplate,
PlaylistItemTemplate: playlistItemTemplate,
Strings: strings);
}
/// <summary>
/// Gets the absolute base URL of the current Web application request, used to reference the application scripts from a static theme template.
/// </summary>
/// <returns>The absolute base URL with a trailing slash, or an empty string when the current HTTP context is unavailable.</returns>
private string GetAppBaseUrl()
{
HttpRequest? request = _httpContextAccessor.HttpContext?.Request;
if (request is null)
return string.Empty;
return $"{request.Scheme}://{request.Host}{request.PathBase}/";
}
/// <summary>
/// Resolves a localized audio player string.
/// </summary>
/// <param name="key">The resource key of the string.</param>
/// <returns>The localized string.</returns>
private string Localize(string key)
{
return _localizer[key].Value;
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Themes;
/// <summary>
/// Renders the audio player bar with a theme, inlining the sub templates of its dynamic content so that the client script can render queue items and playlist items from theme markup.
/// </summary>
public class ThemeAudioPlayerRenderer
{
// The page keys mirror the template files of the theme packs, pinned in each theme manifest so that a missing sub template does not resolve to the component shell template.
private const string SHELL_PAGE_KEY = "shared/audio-player";
private const string QUEUE_ITEM_PAGE_KEY = "shared/audio-player/queue-item";
private const string PLAYLIST_ITEM_PAGE_KEY = "shared/audio-player/playlist-item";
private readonly ThemeService _themeService;
private readonly ThemeTemplateEngine _templateEngine;
private readonly ThemeAudioPlayerBuilder _builder;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeAudioPlayerRenderer"/> class.
/// </summary>
/// <param name="themeService">The service that resolves the render documents.</param>
/// <param name="templateEngine">The template engine used to render the component shell template.</param>
/// <param name="builder">The builder used to produce the component model.</param>
public ThemeAudioPlayerRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, ThemeAudioPlayerBuilder builder)
{
_themeService = themeService;
_templateEngine = templateEngine;
_builder = builder;
}
/// <summary>
/// Renders the themed audio player bar with the specified theme.
/// </summary>
/// <param name="themeId">The manifest id of the theme to render the bar with, normally the theme the layout was resolved with.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the component HTML, or an error.</returns>
public virtual async Task<Result<string>> RenderAsync(string themeId, CancellationToken cancellationToken)
{
try
{
ThemeRenderDocumentDto shellDocument = await _themeService.GetRenderDocumentAsync(SHELL_PAGE_KEY, themeId, cancellationToken).ConfigureAwait(false);
string assetBase = $"/theme-assets/{themeId}/assets";
string queueItemTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, QUEUE_ITEM_PAGE_KEY, cancellationToken).ConfigureAwait(false);
string playlistItemTemplate = await GetSubTemplateAsync(themeId, shellDocument.Template, PLAYLIST_ITEM_PAGE_KEY, cancellationToken).ConfigureAwait(false);
ThemeAudioPlayerDto model = _builder.Build(assetBase, queueItemTemplate, playlistItemTemplate);
Result<ThemePageRenderResultDto> renderResult = _templateEngine.RenderPage(shellDocument.Template, model);
if (renderResult.IsFailure)
return renderResult.Errors;
return renderResult.Value.Content + renderResult.Value.Script;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception)
{
// The audio player bar is best effort: when the component template of the active theme cannot be loaded or rendered, the application Razor fallback is rendered instead.
return Error.NotFound(code: "Theme.Template.Unavailable", description: "The audio player theme template could not be loaded.");
}
}
/// <summary>
/// Gets the raw template source of an audio player sub template, degrading to an empty string when the theme does not provide one.
/// </summary>
/// <param name="themeId">The manifest id of the active theme.</param>
/// <param name="shellTemplate">The raw template source of the component shell, used to detect the mirrored resolution falling back to the shell when a sub template is missing.</param>
/// <param name="pageKey">The page key of the sub template.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The raw template source, or an empty string when the theme does not provide the template.</returns>
private async Task<string> GetSubTemplateAsync(string themeId, string shellTemplate, string pageKey, CancellationToken cancellationToken)
{
try
{
ThemeRenderDocumentDto document = await _themeService.GetRenderDocumentAsync(pageKey, themeId, cancellationToken).ConfigureAwait(false);
// When the theme does not ship the sub template, the mirrored template resolution walks up the path scopes
// and returns the component shell template instead, which the client script must not render as dynamic content.
if (string.Equals(document.Template, shellTemplate, StringComparison.Ordinal))
return string.Empty;
return document.Template;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception)
{
// Each sub template is best effort: when the theme omits one, the client script renders that part with its built-in markup instead.
return string.Empty;
}
}
}
@@ -22,6 +22,7 @@ public class ThemeLayoutRenderer
private readonly ThemeTemplateEngine _templateEngine;
private readonly RazorViewToStringRenderer _viewRenderer;
private readonly ThemeNavBuilder _navBuilder;
private readonly ThemeAudioPlayerRenderer _audioPlayerRenderer;
private readonly IHttpContextAccessor _httpContextAccessor;
/// <summary>
@@ -31,13 +32,15 @@ public class ThemeLayoutRenderer
/// <param name="templateEngine">The template engine used to render the documents.</param>
/// <param name="viewRenderer">The renderer used to produce the application chrome fragments.</param>
/// <param name="navBuilder">The builder used to produce the navigation menu model.</param>
/// <param name="audioPlayerRenderer">The renderer used to produce the themed audio player bar.</param>
/// <param name="httpContextAccessor">Injected accessor for the current HTTP context.</param>
public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, IHttpContextAccessor httpContextAccessor)
public ThemeLayoutRenderer(ThemeService themeService, ThemeTemplateEngine templateEngine, RazorViewToStringRenderer viewRenderer, ThemeNavBuilder navBuilder, ThemeAudioPlayerRenderer audioPlayerRenderer, IHttpContextAccessor httpContextAccessor)
{
_themeService = themeService;
_templateEngine = templateEngine;
_viewRenderer = viewRenderer;
_navBuilder = navBuilder;
_audioPlayerRenderer = audioPlayerRenderer;
_httpContextAccessor = httpContextAccessor;
}
@@ -58,7 +61,7 @@ public class ThemeLayoutRenderer
string appHead = await _viewRenderer.RenderPartialAsync("_ThemeLayoutHead", cancellationToken);
string nav = await RenderNavAsync(themeId, cancellationToken);
string audioPlayer = isAuthenticated ? await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken) : string.Empty;
string audioPlayer = isAuthenticated ? await RenderAudioPlayerAsync(themeId, cancellationToken) : string.Empty;
string appScripts = await _viewRenderer.RenderPartialAsync("_ThemeLayoutScripts", cancellationToken);
ThemeLayoutModelDto layoutModel = new(
@@ -119,4 +122,21 @@ public class ThemeLayoutRenderer
return await _viewRenderer.RenderPartialAsync("_NavMenu", cancellationToken);
}
/// <summary>
/// Renders the audio player bar with the theme the layout was resolved with, falling back to the application Razor markup when the theme does not provide a bar template.
/// </summary>
/// <param name="themeId">The manifest id of the theme the layout was rendered with, so that the bar always matches the shell, including a preview of another theme.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The rendered audio player bar HTML.</returns>
private async Task<string> RenderAudioPlayerAsync(string themeId, CancellationToken cancellationToken)
{
// The audio player renderer already degrades to an error when the theme template is missing or cannot be
// rendered, so a failure here only means the application fallback markup is rendered instead.
Result<string> audioPlayerResult = await _audioPlayerRenderer.RenderAsync(themeId, cancellationToken);
if (audioPlayerResult.IsSuccess)
return audioPlayerResult.Value;
return await _viewRenderer.RenderPartialAsync("_AudioPlayer", cancellationToken);
}
}
@@ -9,9 +9,10 @@
@*
APPLICATION FALLBACK AUDIO PLAYER BAR - READ BEFORE EDITING
This partial renders the audio player bar into the layout of the application and of every theme, for an
authenticated visitor. It is only the markup: the behavior lives in the global audio player script
(wwwroot/js/audio-player/), which binds to the hooks documented below.
This partial renders the audio player bar into the fallback layout of the application, for an authenticated visitor.
The themed layout renders the same bar from the 'shared/audio-player' template of the active theme instead, and only
calls this partial when the theme does not provide one. Either way, the markup is only the structure: the behavior
lives in the global audio player script (wwwroot/js/audio-player/), which binds to the hooks documented below.
The bar is hidden by default. The 'hidden' attribute keeps it unrendered until the audio player script takes over,
so a page load never shows the bar, not even for a frame while the stylesheets settle. The script then hands the bar
@@ -26,6 +27,9 @@
binds and routes to the audio player.
- The hook attributes the audio player binds: 'data-audio-player-play-pause', '-progress', '-progress-played',
'-progress-downloaded', '-current-time', '-total-time', '-track-name', '-cover-thumbnail', '-cover-image' and '-queue'.
- The plain text script elements that carry the raw source of the 'shared/audio-player/queue-item' and
'shared/audio-player/playlist-item' sub templates, with the ids 'audio-player-template-queue-item' and
'audio-player-template-playlist-item'.
The play affordances the pages hand to the player use the 'data-audio-player-play' trigger attribute. The
'The Audio Player Bar' section of docs/technical/theming/Theming.md documents this contract for theme authors.
@@ -53,8 +57,8 @@
</button>
</div>
<div class="audio-player-controls">
<a id="audio-player-full-height-toggle">@localizer["ToggleFullHeight"]</a>
<a id="audio-player-close">@localizer["ToggleVisibility"]</a>
<button type="button" id="audio-player-full-height-toggle">@localizer["ToggleFullHeight"]</button>
<button type="button" id="audio-player-close">@localizer["ToggleVisibility"]</button>
</div>
</div>
</div>
@@ -45,6 +45,7 @@
<script defer src="~/js/dialogs.js" asp-append-version="true"></script>
<script defer src="~/js/image-viewer.js" asp-append-version="true"></script>
<script defer src="~/js/site.js" asp-append-version="true"></script>
<script defer src="~/js/theme-client-template-engine.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-utils.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-errors.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-events.js" asp-append-version="true"></script>