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

+36 -4
View File
@@ -14,6 +14,7 @@ The web client of Lumina is a themed shell: every page is rendered inside the te
- [Template Resolution](#template-resolution)
- [The Layout Template (shared/layout)](#the-layout-template-sharedlayout)
- [The Audio Player Bar](#the-audio-player-bar)
- [The audio player sub templates](#the-audio-player-sub-templates)
- [The Navigation Template (shared/nav-menu)](#the-navigation-template-sharednav-menu)
- [Page Templates](#page-templates)
- [The Scripts Section](#the-scripts-section)
@@ -162,6 +163,9 @@ Known page keys:
| `shared/layout` | The layout that wraps the shell of every page. |
| `shared/nav-menu` | The navigation menu of the theme. |
| `shared/not-found` | The 404 page. |
| `shared/audio-player` | The audio player bar shell. |
| `shared/audio-player/queue-item` | The queue item of the audio player bar. |
| `shared/audio-player/playlist-item` | The playlist item of the audio player bar. |
| `library/written-content-library/book-library/books/index` | The books browsing page. |
| `shared/file-system-browser` | The file system browser component shell. |
| `shared/file-system-browser/tree-node` | The tree view node of the file system browser. |
@@ -225,7 +229,7 @@ The rendered page content, navigation and scripts are inserted unescaped with `{
### The Audio Player Bar
Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar is hidden until the user starts playback of a track, album or artist, and the global audio player script shows it, expands it and hides it again. The theming work that turns the bar into a theme template (a `shared/audio-player` page key with sub templates) is not part of this contract yet; until it lands, the bar is the application fallback markup, passed in as the `audioPlayer` field.
Every authenticated page renders the audio player bar through the `audioPlayer` field of the layout model. The bar is hidden until the user starts playback of a track, album or artist, and the global audio player script shows it, expands it and hides it again. The markup comes from the `shared/audio-player` template of the active theme; when the theme does not provide that template, the application renders its own fallback markup, so the player always has a bar to bind to.
The bar is fixed to the bottom of the viewport, so the theme owns the room reserved for it on the main content element. A layout must keep these element hooks, which the audio player drives (the two id controls are bound by the global site script, which routes them to the audio player):
@@ -235,8 +239,18 @@ The bar is fixed to the bottom of the viewport, so the theme owns the room reser
| The bar container | `full-height` class | The bar is expanded to its full height form. |
| The main content element | `audio-player-not-shown` class | The bar is hidden, so the content area uses the full height. |
| The main content element | `audio-player-full-height` class | The bar is expanded, so the content area gives it the full height. |
| The full height control | `id="audio-player-full-height-toggle"` | Expands or collapses the bar. |
| The close control | `id="audio-player-close"` | Stops playback, and hides the bar while it is condensed. |
| The full height control | `id="audio-player-full-height-toggle"` | A focusable control, such as a `button`, that expands or collapses the bar. |
| The close control | `id="audio-player-close"` | A focusable control, such as a `button`, that stops playback and hides the bar while it is condensed. |
The `shared/audio-player` template receives the following model:
| Field | Content |
| --- | --- |
| `appBase` | The absolute base URL of the Web application, used to reference the application scripts. |
| `assetBase` | The base URL of the theme assets, used by the theme template to reference its own assets. |
| `queueItemTemplate` | The raw source of the `shared/audio-player/queue-item` sub template, inlined by the application into a plain text script element. |
| `playlistItemTemplate` | The raw source of the `shared/audio-player/playlist-item` sub template, inlined by the application into a plain text script element. |
| `strings` | The localized strings of the bar, keyed by their resource names. |
A theme must reserve the space for the bar itself, as the bundled themes do:
@@ -257,7 +271,25 @@ main.audio-player-full-height {
The application fallback layout, which renders when the active theme cannot be loaded, reserves the room itself, because the application stylesheet does not position the content area of a theme. A theme that omits the rules above leaves the fixed bar overlapping the bottom of the page.
The markup inside the bar exposes the hook attributes the audio player script binds, such as `data-audio-player-play-pause`, `data-audio-player-progress`, `data-audio-player-current-time` and `data-audio-player-track-name`. A theme that replaces the bar markup must keep those attributes, and the play affordances of the pages use the `data-audio-player-play` trigger attribute.
The markup inside the bar exposes the ten hook attributes the audio player script binds: `data-audio-player-play-pause`, `data-audio-player-progress`, `data-audio-player-progress-played`, `data-audio-player-progress-downloaded`, `data-audio-player-current-time`, `data-audio-player-total-time`, `data-audio-player-track-name`, `data-audio-player-cover-thumbnail`, `data-audio-player-cover-image` and `data-audio-player-queue`. A theme that replaces the bar markup must keep all of them; the part of the bar whose hook is missing stays inert. The play affordances of the pages use the `data-audio-player-play` trigger attribute.
#### The audio player sub templates
Like the file system browser, the audio player is split into a shell template and the sub templates of its dynamic content, all provided as mirrored files under `templates/shared/audio-player/`. The shell template inlines the raw source of each sub template into a plain text script element, so that the browser never parses the theme markup into live elements and requests their resources before the player renders them:
```html
<script type="text/plain" id="audio-player-template-queue-item">{{{queueItemTemplate}}}</script>
<script type="text/plain" id="audio-player-template-playlist-item">{{{playlistItemTemplate}}}</script>
```
The sub templates are rendered client side by the audio player script with the same Mustache syntax as the server side engine. They receive the following fields:
| Template | Fields |
| --- | --- |
| `queue-item` | `index` (the one based position in the queue), `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration` (the formatted `m:ss` duration), `durationSeconds`, `coverArtUrl`, `isCurrent`, `isPlayed` and `isLast`. The item root must keep the `audio-player-queue-item` class, the stylesheet hook of a queue item: the player appends the rendered element as-is, so the class is what lets the theme style it. |
| `playlist-item` | `index`, `trackId`, `albumId`, `artistId`, `libraryId`, `title`, `duration`, `durationSeconds`, `coverArtUrl` and `isCurrent`. The item root must keep the `audio-player-playlist-item` class, the stylesheet hook of a playlist item. Saved playlists do not exist yet, so the shell inlines this sub template for theme authors, but nothing renders it yet; the playlist feature renders the entries of a playlist from it. |
A theme can omit either sub template: the player then renders that part with its own built-in markup. When a theme replaces the shell, it must keep the two plain text script element ids above, the element hooks of the bar, and the `audio-player-container`, `not-shown` and `full-height` classes the player toggles.
### The Navigation Template (shared/nav-menu)
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Themes;
/// <summary>
/// Data transfer object for the model available to the themed audio player template.
/// </summary>
/// <param name="AppBase">The absolute base URL of the Web application, used to reference application scripts from the theme template.</param>
/// <param name="AssetBase">The base URL of the theme assets, used by the theme template to reference its own assets.</param>
/// <param name="QueueItemTemplate">The raw template source of a queue item, rendered client side for each track of the play context.</param>
/// <param name="PlaylistItemTemplate">The raw template source of a playlist item, rendered client side for each entry of a saved playlist.</param>
/// <param name="Strings">The localized strings of the audio player, keyed by resource name.</param>
[DebuggerDisplay("AssetBase: {AssetBase}")]
public sealed record ThemeAudioPlayerDto(
string AppBase,
string AssetBase,
string QueueItemTemplate,
string PlaylistItemTemplate,
IReadOnlyDictionary<string, object?> Strings
);
@@ -351,6 +351,8 @@ public static class PresentationWebLayerServices
services.AddScoped<ThemeLayoutRenderer>();
services.AddScoped<ThemeFileSystemBrowserBuilder>();
services.AddScoped<ThemeFileSystemBrowserRenderer>();
services.AddScoped<ThemeAudioPlayerBuilder>();
services.AddScoped<ThemeAudioPlayerRenderer>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddScoped<IAuthorizationHandler, RoleAuthorizationHandler>();
@@ -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>
@@ -1407,6 +1407,15 @@ html.audio-player-initializing .audio-player-container {
gap: 10px;
}
.audio-player-controls button {
background: none;
border: none;
padding: 0px;
color: inherit;
font: inherit;
cursor: pointer;
}
.audio-player-expanded {
display: none;
flex: 1 1 auto;
@@ -27,7 +27,7 @@
* - on(event, handler): subscribes to a player event, returns an unsubscribe function.
* - once(event, handler), off(event, handler): one shot subscribe, and unsubscribe.
* - getState(), getDescriptor(), getQueue(), getCurrentTime(), getDuration(),
* getVolume(), isMuted(), getPreferences(), getCapabilities(), getLastError().
* getVolume(), isMuted(), getPreferences(), getCapabilities(), getLastError(), getSubTemplates().
* - destroyAsync(): releases every resource of the player. It is only used for an explicit teardown, never
* by a navigation, because the navigation manager never recreates the player.
* - registerEngine(name, factory): registers an engine factory on this player, by name.
@@ -264,6 +264,26 @@
return text === '' ? '' : text;
}
/**
* Reads the raw source of a theme sub template element of the player bar, or null when the theme does not provide one.
*
* The theme inlines the sub template sources into plain text script elements of the bar, so that the browser never
* parses the theme markup into live elements and requests their resources before the player renders them. The raw
* source is recovered by reading the element text, exactly like the file system browser does it.
* @param {string} elementId - The id of the plain text template element.
* @returns {string|null} The raw template source, or null when the element or the template engine is missing.
*/
function readSubTemplate(elementId) {
const templateElement = document.getElementById(elementId);
if (!templateElement)
return null;
// The theme template engine may be absent on a partially loaded page, in which case the built-in markup is used.
if (typeof window.renderThemeTemplate !== 'function')
return null;
// An empty template element means the theme does not provide the template, in which case the built-in markup is used.
return templateElement.textContent || null;
}
/**
* Reads a play descriptor from the data attributes of a play trigger element, per
* {@link LuminaAudioPlayer.PLAY_DESCRIPTOR_DATA_KEYS}.
@@ -335,6 +355,8 @@
this.container = null;
this.main = null;
this.dom = {};
// The raw theme sub templates of the dynamic content, read once with the bar elements and null when the theme does not provide them.
this.subTemplates = { queueItem: null, playlistItem: null };
this.descriptorClickHandler = null;
this.controlHandlers = [];
this.isProgressRenderScheduled = false;
@@ -392,6 +414,12 @@
this.dom.progressDownloaded = query('[data-audio-player-progress-downloaded]');
this.dom.playPause = query('[data-audio-player-play-pause]');
this.dom.queue = query('[data-audio-player-queue]');
// The sub template sources are read once, with the bar elements, because the theme markup is part of the bar
// the player was bound to, and the player is never recreated by a navigation.
this.subTemplates = {
queueItem: readSubTemplate('audio-player-template-queue-item'),
playlistItem: readSubTemplate('audio-player-template-playlist-item')
};
}
/**
@@ -715,6 +743,14 @@
return [...this.queue];
}
/**
* Gets the raw theme sub templates the player renders its dynamic content from.
* @returns {Object} The sub templates, with a queueItem and a playlistItem source, each null when the theme provides none.
*/
getSubTemplates() {
return { ...this.subTemplates };
}
/**
* Gets the playhead of the current track.
* @returns {number} The playhead, in seconds.
@@ -1272,27 +1308,82 @@
/**
* Renders the ordered queue in the expanded bar. The list is only shown when the play context
* holds more than one track, so that a single track never renders a one item list.
*
* Each item is rendered from the 'shared/audio-player/queue-item' sub template of the active theme when it
* provides one, so that the theme owns the structure of a queue item, and the built-in markup is used otherwise.
*/
renderQueue() {
if (!this.dom.queue)
return;
this.dom.queue.innerHTML = '';
const items = this.queue.length > 1 ? this.queue : [];
for (const item of items) {
const entry = document.createElement('li');
entry.className = 'audio-player-queue-item';
entry.dataset.trackId = item.trackId;
const title = document.createElement('span');
title.className = 'audio-player-queue-item-title';
title.textContent = item.title || '';
const duration = document.createElement('span');
duration.className = 'audio-player-queue-item-duration';
duration.textContent = formatDuration(item.durationInSeconds);
entry.appendChild(title);
entry.appendChild(duration);
this.dom.queue.appendChild(entry);
for (let index = 0; index < items.length; index++) {
const entry = this.renderQueueItem(items[index], index, items.length);
if (entry)
this.dom.queue.appendChild(entry);
}
}
/**
* Renders one queue item, from the theme sub template when the theme provides one and from the built-in markup
* otherwise.
* @param {Object} item - The play descriptor of the item.
* @param {number} index - The zero based position of the item in the queue.
* @param {number} totalItems - The number of items in the queue.
* @returns {HTMLElement|null} The rendered queue item, or null when the markup produced no element.
*/
renderQueueItem(item, index, totalItems) {
// The model exposes only what a queue item can show, so a theme template never reaches into the player internals.
const viewModel = {
index: index + 1,
trackId: item.trackId,
albumId: item.albumId,
artistId: item.artistId,
libraryId: item.libraryId,
title: item.title || '',
duration: formatDuration(item.durationInSeconds),
durationSeconds: item.durationInSeconds,
coverArtUrl: item.coverArtUrl || '',
isCurrent: index === this.currentIndex,
isPlayed: index < this.currentIndex,
isLast: index === totalItems - 1
};
if (this.subTemplates.queueItem) {
try {
const container = document.createElement('div');
container.innerHTML = window.renderThemeTemplate(this.subTemplates.queueItem, viewModel);
const entry = container.firstElementChild;
if (entry)
return entry;
} catch (error) {
// A broken theme sub template falls through to the built-in markup, so the queue never disappears.
console.error('Audio player: the theme queue item template could not be rendered.', error);
}
}
return this.buildDefaultQueueItem(viewModel);
}
/**
* Builds one queue item with the built-in markup, used when the theme provides no queue item sub template.
* @param {Object} viewModel - The queue item model, per {@link LuminaAudioPlayer.AudioPlayer#renderQueueItem}.
* @returns {HTMLElement} The built-in queue item.
*/
buildDefaultQueueItem(viewModel) {
const entry = document.createElement('li');
entry.className = 'audio-player-queue-item';
entry.dataset.trackId = viewModel.trackId;
if (viewModel.isCurrent)
entry.classList.add('is-current');
const title = document.createElement('span');
title.className = 'audio-player-queue-item-title';
title.textContent = viewModel.title;
const duration = document.createElement('span');
duration.className = 'audio-player-queue-item-duration';
duration.textContent = viewModel.duration;
entry.appendChild(title);
entry.appendChild(duration);
return entry;
}
}
LuminaAudioPlayer.AudioPlayer = AudioPlayer;
@@ -1,6 +1,6 @@
// A small, non-executable Mustache-style renderer, mirroring the subset of the server side ThemeTemplateEngine that the
// file system browser uses. The theme sub templates rendered by this script can place values and test truthiness, but cannot execute JavaScript.
// It is loaded lazily together with the file system browser dialog script, and exposed globally so that components can share it.
// file system browser and the audio player use. The theme sub templates rendered by this script can place values and test truthiness, but cannot execute JavaScript.
// It is loaded globally by the layout scripts, and exposed globally so that every component shares a single instance.
(function () {
'use strict';
@@ -85,7 +85,9 @@ public class ThemeLayoutRendererTests
RazorViewToStringRenderer viewRenderer = new(_mockViewEngine, _mockTempDataProvider, _mockServiceProvider, _mockHttpContextAccessor);
ThemeNavBuilder navBuilder = new(_mockUrlService, _mockStringLocalizerFactory, _mockAuthorizationService, _mockHttpContextAccessor);
ThemeService themeService = new(_mockApiHttpClient);
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, _mockHttpContextAccessor);
ThemeAudioPlayerBuilder audioPlayerBuilder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor);
ThemeAudioPlayerRenderer audioPlayerRenderer = new(themeService, new ThemeTemplateEngine(), audioPlayerBuilder);
_sut = new ThemeLayoutRenderer(themeService, new ThemeTemplateEngine(), viewRenderer, navBuilder, audioPlayerRenderer, _mockHttpContextAccessor);
}
[Fact]