Adds favorites and aligns playlist and favorite pagination

This commit is contained in:
BinaryAlley committed 2026-10-22 20:27:07 +03:00
1 parent 2e9f7d8496
commit 525ac1348d
193 files changed
+10944 -643

No files matched your search

@@ -0,0 +1,534 @@
@*
FALLBACK FAVORITES PAGE - READ BEFORE EDITING
This view is the application fallback of the favorites page, rendered only when the theme template of the page cannot be
loaded. The bundled themes ship no template for it, so this view is what the user sees on a healthy site as well. It keeps
the DOM contract and the client script a theme template would mirror, so that listing, filtering and removing favorites
keep working with any theme.
The page lists the favorites of the current user across every media kind, from the most recently favorited, in pages of
50 items, and the kind filter restricts the list to one kind. Every card links to the page of its item, and carries a
favorite heart (a card-favorite-toggle button, always visible, in the place the actions trigger has on the library cards)
that the global favorites script drives, so a favorite is removed from the card itself. The page listens to
the lumina:favorite-changed event the script dispatches and removes the card of an item that is no longer a favorite, so
the counter and the empty state follow without another request. A favorite whose item was deleted, or whose library the
user can no longer access, is kept as an unavailable card without a link, so the owner can still remove it.
The element hooks the script needs are favorites-container, no-favorites, favorite-count, favorites-kind-filter,
load-more-favorites-button and retry-favorites-button, and the classes of the cards are media-card, media-panel and
card-favorite-toggle. A failed reload clears the rendered window and shows the retry button, so the page never keeps the cards
of a filter the combo no longer shows.
To restyle the page, edit the theme files. This fallback is intentionally plain, so that a broken theme is obvious to the user while the page still functions.
/favorites
*@
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Mvc.Localization
@using System
@using System.Collections.Generic
@using System.Text.Json
@using System.Text.Json.Serialization
@inject IViewLocalizer _localizer
@inject IUrlService _urlService
@{
// Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler.
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
var strings = new Dictionary<string, string>
{
["title"] = _localizer["Title"].Value,
["noFavorites"] = _localizer["NoFavorites"].Value,
["noFavoritesInKind"] = _localizer["NoFavoritesInKind"].Value,
["unavailable"] = _localizer["Unavailable"].Value,
["itemsCount"] = _localizer["ItemsCount"].Value,
["loadFailed"] = _localizer["LoadFailed"].Value,
["kindMusicArtist"] = _localizer["KindArtist"].Value,
["kindMusicAlbum"] = _localizer["KindAlbum"].Value,
["kindMusicTrack"] = _localizer["KindTrack"].Value,
["kindBook"] = _localizer["KindBook"].Value
};
var jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
};
}
@Html.AntiForgeryToken()
<div class="cotton-candy">
<div style="display: grid; grid-template-rows: auto 1fr;">
<div style="min-height: 1rem;"></div>
<div class="pl-10 pr-10 pb-10">
<div class="text-center">
<h1 class="text-light-two engraved-title">@_localizer["Title"]</h1>
</div>
<!-- Kind filter. -->
<div class="form-row">
<div class="enlightenment-combobox inline-block w-200px" id="favorites-kind-filter">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" class="enlightenment-toggle-checkbox" id="favorites-kind-filter-toggle" />
<label class="enlightenment-toggle" for="favorites-kind-filter-toggle">
<span class="enlightenment-selected-text" data-value="">@_localizer["FilterAll"]</span>
</label>
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option" data-value="">@_localizer["FilterAll"]</div>
<div class="enlightenment-option" data-value="MusicArtist">@_localizer["FilterArtists"]</div>
<div class="enlightenment-option" data-value="MusicAlbum">@_localizer["FilterAlbums"]</div>
<div class="enlightenment-option" data-value="MusicTrack">@_localizer["FilterTracks"]</div>
<div class="enlightenment-option last-option" data-value="Book">@_localizer["FilterBooks"]</div>
</div>
</div>
</div>
<div class="form-row">
<span id="favorite-count" class="text-light-two" aria-live="polite"></span>
</div>
<div id="favorites-container" class="cards-container justify-start h-100"></div>
<p id="no-favorites" class="hidden text-light-two text-center" aria-live="polite" aria-atomic="true" tabindex="-1">@_localizer["NoFavorites"]</p>
<div class="form-row">
<button id="load-more-favorites-button" type="button" class="confirm-button hidden">@_localizer["LoadMore"]</button>
<button id="retry-favorites-button" type="button" class="confirm-button hidden">@_localizer["Retry"]</button>
</div>
</div>
</div>
</div>
@section Scripts {
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls. site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
const strings = @Html.Raw(JsonSerializer.Serialize(strings, jsonOptions));
const getFavoritesUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITES)';
const artistUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, new { artistId = default(Guid) })';
const albumUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.ALBUM, new { artistId = default(Guid), albumId = default(Guid) })';
const trackUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) })';
const bookUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) })';
const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
const PAGE_SIZE = 50;
const favoritesContainer = document.getElementById('favorites-container');
const noFavoritesMessage = document.getElementById('no-favorites');
const favoriteCount = document.getElementById('favorite-count');
const kindFilter = document.getElementById('favorites-kind-filter');
const loadMoreButton = document.getElementById('load-more-favorites-button');
const retryButton = document.getElementById('retry-favorites-button');
let isInitialized = false;
let isLoading = false;
let requestSequence = 0;
let currentKind = '';
let hasLoadedWindow = false;
let hasLoadFailed = false;
let isRetrying = false;
// The page of the last loaded window, the page size, the total number of pages, the number of cards that are rendered and
// the total the server reported for the current filter.
let currentPage = 1;
let perPage = PAGE_SIZE;
let numberOfPages = 0;
let loadedCount = 0;
let totalCount = 0;
// A removal shifts one item of the next page into the last loaded page, so the next load more reads that page again.
let isWindowStale = false;
function isKnownId(id) {
return typeof id === 'string' && id !== '' && id !== EMPTY_GUID;
}
// Builds the page route of the item of a favorite. Returns an empty string when the page of the item cannot be addressed,
// for example a track whose album is not known, so the card is rendered without a link instead of with a broken one.
function buildItemUrl(item) {
if (!isKnownId(item.libraryId))
return '';
const libraryQuery = `?libraryId=${encodeURIComponent(item.libraryId)}`;
switch (item.mediaKind) {
case 'MusicArtist':
return artistUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
case 'MusicAlbum':
if (!isKnownId(item.creatorId))
return '';
return albumUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.creatorId}`).replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
case 'MusicTrack':
if (!isKnownId(item.creatorId) || !isKnownId(item.collectionId))
return '';
return trackUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.creatorId}`).replace(`/${EMPTY_GUID}`, `/${item.collectionId}`).replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
case 'Book':
return bookUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
default:
return '';
}
}
// The creator and the collection of the item, for example the artist and the album of a track, on one line.
function buildSubtitle(item) {
return [item.creatorName, item.collectionTitle].filter(value => value).join(' - ');
}
function createTextLine(text, isKindLine) {
const line = document.createElement('span');
line.className = 'text-light-two';
line.textContent = text;
line.style.display = 'block';
line.style.width = '200px';
line.style.height = 'auto';
line.style.boxSizing = 'border-box';
line.style.textAlign = 'center';
if (isKindLine) {
line.style.padding = '0 4px 4px';
line.style.fontSize = '12px';
line.style.opacity = '0.6';
} else {
line.style.padding = '0 4px';
line.style.whiteSpace = 'nowrap';
line.style.overflow = 'hidden';
line.style.textOverflow = 'ellipsis';
line.style.opacity = '0.8';
}
return line;
}
function findCard(mediaKind, mediaItemId) {
const itemId = String(mediaItemId).toLowerCase();
return Array.from(favoritesContainer.querySelectorAll('.media-card'))
.find(card => card.dataset.mediaKind === mediaKind && card.dataset.mediaItemId.toLowerCase() === itemId) || null;
}
// The heart of a card, drawn by the application style sheet like the actions trigger of the library cards, which the cards
// of this page do not have. It is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
function createFavoriteToggle(item) {
const toggle = document.createElement('button');
toggle.type = 'button';
toggle.className = 'card-favorite-toggle';
toggle.setAttribute('data-favorite-toggle', '');
toggle.setAttribute('data-favorite-media-kind', item.mediaKind);
toggle.setAttribute('data-favorite-media-item-id', item.mediaItemId);
// Every card of this page is a favorite, so the toggle starts in that state and does not flash while the global favorites
// script checks it. The script confirms the state and keeps the accessible name and the hover text in its language.
toggle.setAttribute('aria-pressed', 'true');
toggle.setAttribute('data-favorite-state', 'favorited');
return toggle;
}
function createFavoriteCard(item) {
const isAvailable = item.isAvailable === true;
const itemUrl = isAvailable ? buildItemUrl(item) : '';
const card = document.createElement('div');
card.className = 'media-card';
card.dataset.mediaKind = item.mediaKind;
card.dataset.mediaItemId = item.mediaItemId;
// A card without a page to open is not a link: the unavailable items have nothing to open, and a link to nowhere
// would only mislead the keyboard and the screen reader users.
const panel = document.createElement(itemUrl ? 'a' : 'div');
panel.className = itemUrl ? 'media-panel nav-link no-underline' : 'media-panel no-underline';
panel.style.width = '200px';
panel.style.height = 'auto';
if (itemUrl)
panel.href = itemUrl;
else
panel.style.cursor = 'default';
// The cover is shown as a square, cropped from its center (never stretched), like the cards of the library pages.
const image = document.createElement('img');
image.src = isAvailable && item.coverPath
? `${globalConfiguration.serverBasePath}${item.coverPath}`
: (item.mediaKind === 'Book' ? '/images/ui/book-placeholder.svg' : '/images/ui/music-placeholder.svg');
image.alt = '';
image.style.width = '200px';
image.style.height = '200px';
image.style.flexGrow = '0';
image.style.objectFit = 'cover';
image.style.objectPosition = 'center';
panel.appendChild(image);
// The title of an available item is kept on a single line, truncated with an ellipsis when it does not fit, so that all the cards share
// the same height. The unavailable message is a whole sentence and wraps on its own lines instead.
const titleSpan = document.createElement('span');
titleSpan.className = 'text-light-two';
titleSpan.style.display = 'block';
titleSpan.style.width = '200px';
titleSpan.style.boxSizing = 'border-box';
titleSpan.style.height = 'auto';
titleSpan.style.padding = '4px';
titleSpan.style.textAlign = 'center';
titleSpan.style.whiteSpace = 'nowrap';
titleSpan.style.overflow = 'hidden';
titleSpan.style.textOverflow = 'ellipsis';
const title = document.createElement('strong');
title.textContent = isAvailable ? item.title : strings.unavailable;
titleSpan.appendChild(title);
titleSpan.title = title.textContent;
// The unavailable message is a whole sentence, so it wraps instead of being cut to fit the single title line of an item.
if (!isAvailable) {
titleSpan.style.whiteSpace = 'normal';
titleSpan.style.overflow = 'visible';
titleSpan.style.textOverflow = 'clip';
}
panel.appendChild(titleSpan);
// The subtitle line is always rendered, with a non-breaking space when there is nothing to show, so that every card has the same
// number of lines and therefore the same height, whatever the kind of the favorite.
const subtitle = isAvailable ? buildSubtitle(item) : '';
const subtitleLine = createTextLine(subtitle || '\u00A0', false);
if (subtitle)
subtitleLine.title = subtitle;
panel.appendChild(subtitleLine);
panel.appendChild(createTextLine(strings[`kind${item.mediaKind}`] || item.mediaKind, true));
card.appendChild(panel);
card.appendChild(createFavoriteToggle(item));
return card;
}
function updateState() {
const hasCards = loadedCount > 0;
// A removal shifts one item of the next page into the last loaded page even when it was the last page, so the rendered
// count, not the page number alone, decides whether that shifted item still has to be fetched.
const hasMore = hasLoadedWindow && (currentPage < numberOfPages || (isWindowStale && loadedCount < totalCount));
// The empty state appears only after a window of the current filter was received, so it never flashes while the first
// window is loading, and the failure message replaces it when that window or a later reload failed.
const showEmptyState = hasLoadedWindow && !hasCards && !hasMore;
// Clearing the message while a retry is in flight lets the live region announce the failure again when the message returns.
noFavoritesMessage.textContent = isRetrying
? ''
: (hasLoadFailed ? strings.loadFailed : (currentKind === '' ? strings.noFavorites : strings.noFavoritesInKind));
noFavoritesMessage.classList.toggle('hidden', !hasLoadFailed && !showEmptyState);
favoriteCount.textContent = totalCount > 0 ? `${totalCount} ${strings.itemsCount}` : '';
loadMoreButton.classList.toggle('hidden', hasLoadFailed || isRetrying || !hasMore);
loadMoreButton.disabled = isLoading;
if (retryButton) {
retryButton.classList.toggle('hidden', !hasLoadFailed && !isRetrying);
retryButton.disabled = isLoading;
retryButton.setAttribute('aria-busy', isRetrying ? 'true' : 'false');
}
}
function buildFavoritesUrl(page) {
const parameters = new URLSearchParams();
if (currentKind !== '')
parameters.set('mediaKind', currentKind);
parameters.set('currentPage', page);
parameters.set('perPage', perPage);
return `${getFavoritesUrl}?${parameters.toString()}`;
}
// Loads a page of the favorites and renders it. A reload replaces the cards, which is what changing the filter does, and a
// load more appends the next page. An answer that was overtaken by a newer request is dropped.
async function loadFavoritesAsync(isAppend, isRetry = false, shouldRestartFromFirstPage = true) {
const requestId = ++requestSequence;
// A reload starts again from the first page of the filter. A load more asks for the page after the last one, or asks for
// the last one again when a removal shifted an item of the next page into it.
const requestedPage = isAppend ? (isWindowStale ? currentPage : currentPage + 1) : 1;
// A reload starts a new page chain for the filter, so the empty state stays hidden until its first answer arrives. A retry keeps
// the failure message and the retry button visible, with the button disabled and marked busy, until the answer arrives.
isRetrying = isRetry;
if (!isAppend) {
hasLoadedWindow = false;
if (!isRetry)
hasLoadFailed = false;
}
isLoading = true;
updateState();
const page = await callApiGetAsync(buildFavoritesUrl(requestedPage));
if (requestId !== requestSequence)
return;
isLoading = false;
isRetrying = false;
if (!page || !Array.isArray(page.data)) {
// The API helper already reported the failure. A reload has nothing left to show, so it clears the cards of the
// previous page and leaves a retry instead of hiding the only way to continue. A failed load more keeps its
// button, because the rendered page is still valid.
if (!isAppend) {
favoritesContainer.querySelectorAll('.media-card').forEach(card => card.remove());
loadedCount = 0;
currentPage = 1;
perPage = PAGE_SIZE;
numberOfPages = 0;
totalCount = 0;
hasLoadedWindow = false;
hasLoadFailed = true;
isWindowStale = false;
}
updateState();
if (isRetry)
focusAfterReload('', '');
return;
}
const wasWindowStale = isWindowStale;
if (!isAppend) {
favoritesContainer.querySelectorAll('.media-card').forEach(card => card.remove());
loadedCount = 0;
}
let pageHasRenderedItems = false;
page.data.forEach(item => {
// An item favorited since an earlier page shifts the list, so the same favorite could come twice. The card that is
// already rendered is kept, but the duplicate means the page chain no longer matches the rendered rows.
if (findCard(item.mediaKind, item.mediaItemId)) {
pageHasRenderedItems = true;
return;
}
favoritesContainer.appendChild(createFavoriteCard(item));
loadedCount++;
});
isWindowStale = false;
currentPage = Number.isInteger(page.currentPage) && page.currentPage > 0 ? page.currentPage : requestedPage;
perPage = Number.isInteger(page.perPage) && page.perPage > 0 ? page.perPage : PAGE_SIZE;
totalCount = Number.isInteger(page.count) ? page.count : loadedCount;
numberOfPages = Number.isInteger(page.numberOfPages) ? page.numberOfPages : (perPage > 0 ? Math.ceil(totalCount / perPage) : 0);
// An empty page means there is nothing more to read, even when a stale total still claims otherwise.
if (page.data.length === 0) {
totalCount = Math.min(totalCount, loadedCount);
numberOfPages = Math.min(numberOfPages, currentPage);
}
// An item favorited in another tab or on another device shifts every server page after it. The page then contains cards that
// are already rendered, and the last page can be reached while cards are still missing. Both mean the page chain no longer
// covers the rendered rows, so the only consistent window is a fresh read from the first page. The stale re-read after a
// removal is excluded, because that overlap is expected there and it keeps the card of the shifted item.
if (shouldRestartFromFirstPage && ((!wasWindowStale && pageHasRenderedItems) || (currentPage >= numberOfPages && loadedCount < totalCount))) {
await loadFavoritesAsync(false, false, false);
// The restart is a fresh read, so it does not carry the retry flag. The outer retry still owns the focus, and the inner
// call replaced the cards and hid the retry button, so the focus has to move after it completes.
if (isRetry)
focusAfterReload('', '');
return;
}
hasLoadedWindow = true;
hasLoadFailed = false;
bindNavigationLinks();
updateState();
if (isRetry)
focusAfterReload('', '');
}
async function loadMoreAsync() {
if (isLoading)
return;
await loadFavoritesAsync(true);
}
async function retryLoadAsync() {
if (isLoading)
return;
await loadFavoritesAsync(false, true);
}
// Moves focus into the window a removal or a retry loaded: the neighboring card when it is still there, the first card otherwise,
// the load more button or the retry button, and finally the visible message when the window is empty.
function focusAfterReload(neighborKind, neighborId) {
const refreshedNeighbor = neighborKind ? findCard(neighborKind, neighborId) : null;
const firstCard = favoritesContainer.querySelector('.media-card');
const focusTarget = refreshedNeighbor || firstCard;
const focusToggle = focusTarget ? focusTarget.querySelector('[data-favorite-toggle]') : null;
if (focusToggle)
focusToggle.focus();
else if (!loadMoreButton.classList.contains('hidden'))
loadMoreButton.focus();
else if (retryButton && !retryButton.classList.contains('hidden'))
retryButton.focus();
else if (!noFavoritesMessage.classList.contains('hidden'))
noFavoritesMessage.focus();
}
// Removes the card of an item that is no longer a favorite, and moves the keyboard focus to the neighboring card, so a keyboard user is not dropped to the top of the page.
async function handleFavoriteChanged(event) {
const detail = event.detail;
if (!detail || detail.isFavorite)
return;
const card = findCard(detail.mediaKind, detail.mediaItemId);
if (!card)
return;
const neighbor = card.nextElementSibling || card.previousElementSibling;
const neighborKind = neighbor ? neighbor.dataset.mediaKind : '';
const neighborId = neighbor ? neighbor.dataset.mediaItemId : '';
const hadFocus = card.contains(document.activeElement);
card.remove();
loadedCount--;
totalCount = Math.max(0, totalCount - 1);
numberOfPages = perPage > 0 ? Math.ceil(totalCount / perPage) : 0;
// A page that was requested before this removal describes the list that still contained the item, so neither its
// cards nor its total can be applied. Drop it and load the first page again.
const mustReload = isLoading;
if (mustReload) {
requestSequence++;
isLoading = false;
hasLoadedWindow = false;
isWindowStale = false;
updateState();
await loadFavoritesAsync(false);
if (hadFocus)
focusAfterReload(neighborKind, neighborId);
return;
}
// The list lost one item, so one item of the next page shifted into the last loaded page. The next load more reads
// that page again, so the shifted item is not skipped.
isWindowStale = true;
updateState();
// Every rendered card was removed but the user has more favorites, so the first page is loaded again instead of
// starting from a page that no longer matches the empty screen. Focus moves after that reload, because it
// replaces the cards and hides the load more button the old focus fallback would have chosen.
if (loadedCount === 0 && totalCount > 0) {
await loadFavoritesAsync(false);
if (hadFocus)
focusAfterReload(neighborKind, neighborId);
return;
}
if (hadFocus) {
const neighborToggle = neighbor ? neighbor.querySelector('[data-favorite-toggle]') : null;
if (neighborToggle)
neighborToggle.focus();
else if (!loadMoreButton.classList.contains('hidden'))
loadMoreButton.focus();
}
}
function handleKindFilterClick(event) {
const option = event.target.closest('.enlightenment-option');
if (!option || option.classList.contains('disabled'))
return;
const selected = kindFilter.querySelector('.enlightenment-selected-text');
if (selected) {
selected.textContent = option.textContent;
selected.setAttribute('data-value', option.getAttribute('data-value') || '');
}
const toggle = kindFilter.querySelector('.enlightenment-toggle-checkbox');
if (toggle)
toggle.checked = false;
const kind = option.getAttribute('data-value') || '';
if (kind === currentKind)
return;
currentKind = kind;
loadFavoritesAsync(false);
}
document.addEventListener('lumina:favorite-changed', handleFavoriteChanged);
if (kindFilter)
kindFilter.addEventListener('click', handleKindFilterClick);
if (loadMoreButton)
loadMoreButton.addEventListener('click', loadMoreAsync);
if (retryButton)
retryButton.addEventListener('click', retryLoadAsync);
async function InitializeAsync() {
if (isInitialized)
return;
if (!favoritesContainer)
return;
isInitialized = true;
await loadFavoritesAsync(false);
}
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
document.removeEventListener('lumina:favorite-changed', handleFavoriteChanged);
if (kindFilter)
kindFilter.removeEventListener('click', handleKindFilterClick);
if (loadMoreButton)
loadMoreButton.removeEventListener('click', loadMoreAsync);
if (retryButton)
retryButton.removeEventListener('click', retryLoadAsync);
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -137,6 +137,7 @@
<col class="track-number-column" />
<col />
<col class="track-duration-column" />
<col class="track-favorite-column" />
<col class="track-actions-column" />
</colgroup>
<tbody id="tracks-body"></tbody>
@@ -995,7 +996,7 @@
}
// Creates a row of the tracks table, with the play trigger, the number, the name of the track linking to its own page,
// the duration and the actions menu of the track.
// the duration, the favorite heart and the actions menu of the track.
function createTrackRow(track) {
const row = document.createElement('tr');
row.className = 'track-row';
@@ -1021,10 +1022,26 @@
row.appendChild(numberCell);
row.appendChild(nameCell);
row.appendChild(durationCell);
row.appendChild(createTrackFavoriteCell(track));
row.appendChild(createTrackActionsCell(track));
return row;
}
// Creates the favorite cell of a track row, right after the duration. The heart is a plain button: the global favorites
// script finds it by its data attributes, hydrates its state and handles its click.
function createTrackFavoriteCell(track) {
const cell = document.createElement('td');
cell.className = 'track-favorite-cell';
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle track-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicTrack');
favoriteToggle.setAttribute('data-favorite-media-item-id', track.id);
cell.appendChild(favoriteToggle);
return cell;
}
// Gets the singleton audio player, or null when the layout did not render it.
function getAudioPlayer() {
return window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance
@@ -298,7 +298,16 @@
await updateContentAsync(menuItem.href, true);
});
// The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicArtist');
favoriteToggle.setAttribute('data-favorite-media-item-id', artist.id);
card.appendChild(cardLink);
card.appendChild(favoriteToggle);
card.appendChild(trigger);
card.appendChild(menu);
@@ -1159,7 +1159,16 @@
await deleteAlbumAsync(card.dataset.albumId);
});
// The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicAlbum');
favoriteToggle.setAttribute('data-favorite-media-item-id', album.id);
card.appendChild(cardLink);
card.appendChild(favoriteToggle);
card.appendChild(trigger);
card.appendChild(menu);
@@ -226,7 +226,16 @@
await updateContentAsync(menuItem.href, true);
});
// The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'Book');
favoriteToggle.setAttribute('data-favorite-media-item-id', book.id);
card.appendChild(cardLink);
card.appendChild(favoriteToggle);
card.appendChild(trigger);
card.appendChild(menu);
@@ -54,6 +54,7 @@
["track"] = _localizer["Track"].Value,
["add"] = _localizer["Add"].Value,
["addFailed"] = _localizer["AddFailed"].Value,
["refreshFailed"] = _localizer["RefreshFailed"].Value,
["selectLibrary"] = _localizer["SelectLibrary"].Value,
["selectArtist"] = _localizer["SelectArtist"].Value,
["selectAlbum"] = _localizer["SelectAlbum"].Value,
@@ -276,10 +277,23 @@
const addTrackButton = document.getElementById('add-track-button');
const noMusicLibrariesMessage = document.getElementById('no-music-libraries');
const loadMoreEntriesButton = document.getElementById('load-more-entries-button');
const entriesWindowSize = 200;
// The global position of the first row currently on screen. Local row indexes are only meaningful after adding this offset, which
// is why the move and Load more logic use it for every comparison against the whole playlist.
const DEFAULT_PAGE_SIZE = 200;
// The page the first rendered row belongs to, the size of each page and the total number of pages. The global position of the
// first row currently on screen is derived from the page, and local row indexes are only meaningful after adding this offset,
// which is why the move and Load more logic use it for every comparison against the whole playlist.
let currentPage = 1;
let perPage = DEFAULT_PAGE_SIZE;
let numberOfPages = 0;
let entriesOffset = 0;
if (playlist && playlist.entries) {
if (Number.isInteger(playlist.entries.currentPage) && playlist.entries.currentPage > 0)
currentPage = playlist.entries.currentPage;
if (Number.isInteger(playlist.entries.perPage) && playlist.entries.perPage > 0)
perPage = playlist.entries.perPage;
if (Number.isInteger(playlist.entries.numberOfPages))
numberOfPages = playlist.entries.numberOfPages;
entriesOffset = (currentPage - 1) * perPage;
}
let isInitialized = false;
let draggedEntryId = null;
let dragWasDropped = false;
@@ -289,6 +303,32 @@
return itemUrlTemplate.replace(`/${EMPTY_GUID}`, `/${playlistId}`);
}
// The entries of the page currently rendered, and the total the server reported for the whole playlist.
function getPlaylistEntries() {
return playlist && playlist.entries && Array.isArray(playlist.entries.data) ? playlist.entries.data : [];
}
function getPlaylistEntryCount() {
return playlist && playlist.entries && Number.isFinite(playlist.entries.count) ? playlist.entries.count : getPlaylistEntries().length;
}
function findEntryRow(entryId) {
if (!entriesContainer)
return null;
return Array.from(entriesContainer.querySelectorAll('.playlist-entry'))
.find(row => row.dataset.entryId === entryId) || null;
}
// Applies a playlist read back from the server and derives the global position of its first row.
function applyPlaylistPage(page) {
playlist = page;
const entries = page && page.entries ? page.entries : null;
currentPage = entries && Number.isInteger(entries.currentPage) && entries.currentPage > 0 ? entries.currentPage : 1;
perPage = entries && Number.isInteger(entries.perPage) && entries.perPage > 0 ? entries.perPage : DEFAULT_PAGE_SIZE;
numberOfPages = entries && Number.isInteger(entries.numberOfPages) ? entries.numberOfPages : 0;
entriesOffset = (currentPage - 1) * perPage;
}
function formatDuration(totalSeconds) {
const seconds = Number.isFinite(Number(totalSeconds)) ? Math.max(0, Math.floor(Number(totalSeconds))) : 0;
const minutes = Math.floor(seconds / 60);
@@ -387,12 +427,12 @@
}
}
// Shows the load more control only while the page has entry windows left to fetch.
// Shows the load more control only while the page has entry pages left to fetch.
function updateLoadMoreButton() {
if (!loadMoreEntriesButton)
return;
const loaded = Array.isArray(playlist.entries) ? playlist.entries.length : 0;
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : loaded;
const loaded = getPlaylistEntries().length;
const total = getPlaylistEntryCount();
// The rows on screen start at entriesOffset, not at the beginning of the playlist, so the loaded count alone cannot tell
// whether the whole playlist is on screen.
const hasMore = entriesOffset + loaded < total;
@@ -413,37 +453,89 @@
if (!entriesContainer)
return;
entriesContainer.querySelectorAll('.playlist-entry').forEach(row => row.remove());
const entries = Array.isArray(playlist.entries) ? playlist.entries : [];
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : entries.length;
const entries = getPlaylistEntries();
const total = getPlaylistEntryCount();
if (total === 0) {
noTracksMessage.classList.remove('hidden');
return;
}
noTracksMessage.classList.add('hidden');
entries.forEach((entry, index) => entriesContainer.appendChild(createEntryRow(entry, index, entries.length)));
entries.forEach((entry, index) => entriesContainer.appendChild(createEntryRow(entry, index)));
updateLoadMoreButton();
}
// Fetches the next window of entries and appends it to the rows already on screen.
// Whether the fetched page proves that the rendered window no longer matches the server. A page behind the requested one means
// the server clamped it because the playlist shrank, and a total smaller than the rendered rows means the rows themselves are
// stale. Neither can be fixed by appending, so the caller reloads the first page instead.
function pageShrankBeforeWindow(page, requestedPage) {
if (!page || !page.entries)
return false;
const resolvedPage = Number.isInteger(page.entries.currentPage) && page.entries.currentPage > 0
? page.entries.currentPage
: requestedPage;
return resolvedPage < requestedPage
|| (Number.isInteger(page.entries.count) && page.entries.count < entriesOffset + getPlaylistEntries().length);
}
// Replaces the rendered rows with the first page, which is the only window that is valid after the playlist shrank.
async function reloadFirstPageAsync() {
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=1&perPage=${perPage}`);
if (!page || !page.entries || !Array.isArray(page.entries.data))
return false;
applyPlaylistPage(page);
renderPlaylist();
return true;
}
// Merges the entries of one fetched page into the rows already on screen, without replacing them. A page that starts after the
// first entry that is not on screen would leave a hole in the rendered rows, so it is not merged and the Load more state stays
// responsible for reaching it. The rows are numbered from entriesOffset, which is only valid while the rendered entries are
// contiguous, so a page that overlaps the rendered rows is merged by Id and a page after a gap is left for Load more.
function mergeEntriesPage(page, pageNumber) {
if (!entriesContainer || !page || !page.entries || !Array.isArray(page.entries.data))
return false;
// The server can clamp the requested page to the last one, so its answer is the page that actually arrived.
const resolvedPage = Number.isInteger(page.entries.currentPage) && page.entries.currentPage > 0 ? page.entries.currentPage : pageNumber;
const pageStart = (resolvedPage - 1) * perPage;
const entries = getPlaylistEntries();
if (pageStart < entriesOffset || pageStart > entriesOffset + entries.length)
return false;
page.entries.data.forEach(entry => {
if (findEntryRow(entry.id))
return;
entries.push(entry);
entriesContainer.appendChild(createEntryRow(entry, entries.length - 1));
});
playlist.entries.count = page.entries.count;
playlist.entries.numberOfPages = page.entries.numberOfPages;
numberOfPages = Number.isInteger(page.entries.numberOfPages) ? page.entries.numberOfPages : numberOfPages;
refreshEntryRows();
return true;
}
// Fetches the next page of entries and appends it to the rows already on screen.
async function loadMoreEntriesAsync() {
if (!entriesContainer || !loadMoreEntriesButton || isEntryMutationInFlight)
return;
const loaded = Array.isArray(playlist.entries) ? playlist.entries.length : 0;
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : loaded;
const loaded = getPlaylistEntries().length;
const total = getPlaylistEntryCount();
// The loaded rows begin at entriesOffset, so they cover the playlist only when offset plus loaded reaches the total.
if (entriesOffset + loaded >= total)
return;
// The next page is the one that contains the first entry that is not on screen yet. A removal shifts the entries by one,
// so this page can overlap the rows already rendered; rows are appended by Id, so the overlap is skipped and the shifted entry is not lost.
const nextPage = Math.floor((entriesOffset + loaded) / perPage) + 1;
if (numberOfPages > 0 && nextPage > numberOfPages)
return;
setEntryMutationInFlight(true);
try {
const page = await callApiGetAsync(`${getPlaylistUrl}?offset=${entriesOffset + loaded}&limit=${entriesWindowSize}`);
if (!page || !Array.isArray(page.entries))
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${nextPage}&perPage=${perPage}`);
if (pageShrankBeforeWindow(page, nextPage)) {
if (!await reloadFirstPageAsync())
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
return;
playlist.entryCount = page.entryCount;
page.entries.forEach(entry => {
playlist.entries.push(entry);
entriesContainer.appendChild(createEntryRow(entry, playlist.entries.length - 1, playlist.entries.length));
});
refreshEntryRows();
}
mergeEntriesPage(page, nextPage);
} finally {
setEntryMutationInFlight(false);
}
@@ -454,7 +546,7 @@
if (!entriesContainer)
return;
const rows = Array.from(entriesContainer.querySelectorAll('.playlist-entry'));
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : rows.length;
const total = getPlaylistEntryCount();
rows.forEach((row, index) => {
// The move controls are guarded by the global position of the row, not by its index inside the loaded window.
const globalIndex = entriesOffset + index;
@@ -483,7 +575,7 @@
return;
// Use the rows already on screen, not the post-push entries length, so the new row is numbered correctly before refreshEntryRows.
const index = entriesContainer.querySelectorAll('.playlist-entry').length;
entriesContainer.appendChild(createEntryRow(entry, index, index + 1));
entriesContainer.appendChild(createEntryRow(entry, index));
refreshEntryRows();
}
@@ -514,11 +606,11 @@
// Keeps the in-memory entries in the same order as the rows, so playback and later moves use the order on screen.
function syncPlaylistEntriesFromOrder(orderedEntryIds) {
const entriesById = new Map((playlist.entries || []).map(entry => [entry.id, entry]));
playlist.entries = orderedEntryIds
const entriesById = new Map(getPlaylistEntries().map(entry => [entry.id, entry]));
playlist.entries.data = orderedEntryIds
.map(entryId => entriesById.get(entryId))
.filter(entry => !!entry);
playlist.entries.forEach((entry, index) => entry.position = entriesOffset + index);
playlist.entries.data.forEach((entry, index) => entry.position = entriesOffset + index);
}
// Applies a details update without touching the rows of the playlist.
@@ -534,7 +626,7 @@
playlistDescriptionInput.value = playlist.description;
}
function createEntryRow(entry, index, count) {
function createEntryRow(entry, index) {
const row = document.createElement('div');
row.className = 'playlist-entry form-row';
row.dataset.entryId = entry.id;
@@ -576,7 +668,7 @@
else
// Escape, or a drop outside the list, cancels the drag. The DOM was already reordered while dragging, so it is
// restored to the last order the server accepted instead of persisting the cancelled order.
applyEntryOrderByIds((playlist.entries || []).map(entry => entry.id));
applyEntryOrderByIds(getPlaylistEntries().map(entry => entry.id));
});
row.appendChild(dragHandle);
@@ -663,7 +755,7 @@
// The index passed to this function is local to the rendered rows. Disabling the move controls requires the global position,
// otherwise the first row of a window that does not start at zero looks like the first row of the whole playlist.
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : entriesOffset + count;
const total = getPlaylistEntryCount();
const globalIndex = entriesOffset + index;
const moveUpButton = document.createElement('button');
@@ -701,7 +793,7 @@
return;
const orderedEntryIds = Array.from(entriesContainer.querySelectorAll('.playlist-entry'))
.map(row => row.dataset.entryId);
const currentEntryIds = (playlist.entries || []).map(entry => entry.id);
const currentEntryIds = getPlaylistEntries().map(entry => entry.id);
if (orderedEntryIds.length !== currentEntryIds.length) {
applyEntryOrderByIds(currentEntryIds);
return;
@@ -748,26 +840,40 @@
return;
if (detail.playlist && detail.playlist.id && detail.playlist.id !== playlist.id)
return;
// An append made elsewhere only announces the playlist Id. Re-read the window the user is currently looking at, instead of
// resetting the view to the first window and throwing a user who is deep in a large playlist back to the top.
const currentOffset = entriesOffset;
const updatedPlaylist = await callApiGetAsync(`${getPlaylistUrl}?offset=${currentOffset}&limit=${entriesWindowSize}`);
if (!updatedPlaylist)
// A local mutation already refreshes the view, so an external event that arrives while one is running must not read a
// playlist that the mutation is still changing. Dropping it avoids replacing the rows with an answer taken mid-write.
if (isEntryMutationInFlight)
return;
if (currentOffset > 0 && updatedPlaylist.entries.length === 0 && updatedPlaylist.entryCount > 0) {
// The playlist shrank past this window. Show the last window instead of an empty page.
const lastWindowOffset = Math.max(0, updatedPlaylist.entryCount - entriesWindowSize);
const lastWindow = await callApiGetAsync(`${getPlaylistUrl}?offset=${lastWindowOffset}&limit=${entriesWindowSize}`);
if (!lastWindow)
setEntryMutationInFlight(true);
try {
// An append made elsewhere announces either a batch result with addedCount, or a single entry result with entry.
// The rows on screen start at currentPage, which is the first rendered page and never advances when more pages are
// loaded. The page to read is therefore the first page that is not fully rendered, not currentPage. Reading it merges
// the appended entries into the rows already on screen instead of replacing pages 2 and later with page 1.
const addedCount = Number.isInteger(detail.addedCount) ? detail.addedCount : (detail.entry ? 1 : 0);
if (addedCount > 0) {
playlist.entries.count = getPlaylistEntryCount() + addedCount;
playlist.entries.numberOfPages = perPage > 0 ? Math.ceil(playlist.entries.count / perPage) : 0;
numberOfPages = playlist.entries.numberOfPages;
}
if (detail.updatedOnUtc)
playlist.updatedOnUtc = detail.updatedOnUtc;
const loaded = getPlaylistEntries().length;
const nextPage = Math.floor((entriesOffset + loaded) / perPage) + 1;
if (nextPage > numberOfPages)
return;
entriesOffset = lastWindowOffset;
playlist = lastWindow;
renderPlaylist();
return;
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${nextPage}&perPage=${perPage}`);
if (!page || !page.entries || !Array.isArray(page.entries.data))
return;
if (pageShrankBeforeWindow(page, nextPage)) {
if (!await reloadFirstPageAsync())
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
return;
}
mergeEntriesPage(page, nextPage);
} finally {
setEntryMutationInFlight(false);
}
entriesOffset = currentOffset;
playlist = updatedPlaylist;
renderPlaylist();
}
async function saveDetailsAsync(event) {
@@ -823,7 +929,7 @@
// The server accepts a target position anywhere in the whole playlist. The target is therefore compared with the global
// position of the row, so the first row of a shifted window can still move up and the last loaded row can still move down into
// the entries that are not loaded yet.
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : orderedEntryIds.length;
const total = getPlaylistEntryCount();
const targetGlobalIndex = entriesOffset + index + offset;
if (targetGlobalIndex < 0 || targetGlobalIndex >= total)
return;
@@ -834,11 +940,11 @@
playlist.updatedOnUtc = result.data.updatedOnUtc;
const isOutsideLoadedWindow = targetGlobalIndex < entriesOffset || targetGlobalIndex >= entriesOffset + orderedEntryIds.length;
if (isOutsideLoadedWindow) {
// The row moved into a window that is not loaded, so another entry moved into its place. Re-read the current window
// The row moved into a page that is not loaded, so another entry moved into its place. Re-read the current page
// instead of leaving an order on screen that the next Load more would duplicate.
const refreshedWindow = await callApiGetAsync(`${getPlaylistUrl}?offset=${entriesOffset}&limit=${entriesWindowSize}`);
if (refreshedWindow && Array.isArray(refreshedWindow.entries)) {
playlist = refreshedWindow;
const refreshedWindow = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${currentPage}&perPage=${perPage}`);
if (refreshedWindow && refreshedWindow.entries && Array.isArray(refreshedWindow.entries.data)) {
applyPlaylistPage(refreshedWindow);
renderPlaylist();
} else
notificationService.show(strings.reorderFailed, NotificationType.ERROR);
@@ -867,11 +973,13 @@
try {
const removed = await callApiDeleteAsync(buildRemoveEntryUrl(entryId));
if (removed) {
// The row is removed from the existing DOM and the remaining rows are renumbered, so the page does not read the whole
// playlist back for a single removed entry.
playlist.entries = (playlist.entries || []).filter(entry => entry.id !== entryId);
playlist.entries.forEach((entry, index) => entry.position = entriesOffset + index);
playlist.entryCount = Math.max(0, (Number.isFinite(playlist.entryCount) ? playlist.entryCount : playlist.entries.length) - 1);
// The row is removed from the existing DOM and the remaining rows are renumbered, so the page does not read the whole playlist back for a single removed entry.
const totalBefore = getPlaylistEntryCount();
playlist.entries.data = getPlaylistEntries().filter(entry => entry.id !== entryId);
playlist.entries.data.forEach((entry, index) => entry.position = entriesOffset + index);
playlist.entries.count = Math.max(0, totalBefore - 1);
playlist.entries.numberOfPages = perPage > 0 ? Math.ceil(playlist.entries.count / perPage) : 0;
numberOfPages = playlist.entries.numberOfPages;
removeEntryRow(entryId);
} else
notificationService.show(strings.removeFailed, NotificationType.ERROR);
@@ -880,18 +988,21 @@
}
}
// Fetches every entry of the playlist in windows, for the explicit play action. A large playlist is never loaded for the page itself.
// Fetches every entry of the playlist page by page, for the explicit play action. A large playlist is never loaded for the page itself.
async function fetchAllPlaylistEntriesAsync() {
const allEntries = [];
let offset = 0;
let pageNumber = 1;
while (true) {
const page = await callApiGetAsync(`${getPlaylistUrl}?offset=${offset}&limit=1000`);
if (!page || !Array.isArray(page.entries) || page.entries.length === 0)
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${pageNumber}&perPage=1000`);
if (!page || !page.entries || !Array.isArray(page.entries.data) || page.entries.data.length === 0)
break;
allEntries.push(...page.entries);
offset += page.entries.length;
if (offset >= page.entryCount)
allEntries.push(...page.entries.data);
const totalPages = Number.isInteger(page.entries.numberOfPages) && page.entries.numberOfPages > 0
? page.entries.numberOfPages
: Math.max(1, Math.ceil(page.entries.count / 1000));
if (allEntries.length >= page.entries.count || pageNumber >= totalPages)
break;
pageNumber++;
}
return allEntries;
}
@@ -984,22 +1095,45 @@
try {
const added = await callApiPostAsync(addEntryUrl, { trackId });
if (added && added.entry) {
playlist.entries = Array.isArray(playlist.entries) ? playlist.entries : [];
const totalBefore = Number.isFinite(playlist.entryCount) ? playlist.entryCount : playlist.entries.length;
if (playlist.entries.length >= totalBefore) {
playlist.entries.push(added.entry);
playlist.entryCount = totalBefore + 1;
const entries = getPlaylistEntries();
const totalBefore = getPlaylistEntryCount();
if (entries.length >= totalBefore) {
entries.push(added.entry);
playlist.entries.count = totalBefore + 1;
playlist.entries.numberOfPages = perPage > 0 ? Math.ceil(playlist.entries.count / perPage) : 0;
numberOfPages = playlist.entries.numberOfPages;
playlist.updatedOnUtc = added.updatedOnUtc;
appendEntryRow(added.entry);
} else {
// The new entry is at the global end, beyond the loaded window, so the last window is loaded to show it.
// The new entry is at the global end, beyond the rendered rows. The count and the number of pages change even
// when the page that contains the new entry cannot be merged, because that page may start after the first entry
// that is not on screen. Keeping the optimistic values means Load more still leads to it.
const newCount = totalBefore + 1;
const newOffset = Math.max(0, newCount - entriesWindowSize);
const page = await callApiGetAsync(`${getPlaylistUrl}?offset=${newOffset}&limit=${entriesWindowSize}`);
if (page) {
entriesOffset = newOffset;
playlist = page;
renderPlaylist();
const newNumberOfPages = perPage > 0 ? Math.ceil(newCount / perPage) : 0;
playlist.entries.count = newCount;
playlist.entries.numberOfPages = newNumberOfPages;
numberOfPages = newNumberOfPages;
playlist.updatedOnUtc = added.updatedOnUtc;
// The last page is fetched to show the new entry, and merged only when it is the page that directly follows the
// rendered rows. When several pages are not on screen, replacing the rows with only the last page would hide the
// entries that were already rendered, so the page is left to Load more instead.
const lastPage = Math.max(1, Math.ceil(newCount / perPage));
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${lastPage}&perPage=${perPage}`);
if (!page || !page.entries || !Array.isArray(page.entries.data)) {
// The add is committed and the counts above already include it, but the rows could not be read back. Saying so
// is what keeps the user from adding the same track again because the list still looks unchanged.
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
} else if (pageShrankBeforeWindow(page, lastPage)) {
// Another client shrank the playlist while the rows were on screen, and the server clamped the requested page
// behind them. Appending would keep rows that no longer exist, so the whole window is read again.
if (!await reloadFirstPageAsync())
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
} else {
// The fetched page is authoritative for the totals, which can differ from the optimistic values when another request changed the playlist in the meantime.
playlist.entries.count = page.entries.count;
playlist.entries.numberOfPages = page.entries.numberOfPages;
numberOfPages = Number.isInteger(page.entries.numberOfPages) ? page.entries.numberOfPages : numberOfPages;
mergeEntriesPage(page, lastPage);
}
}
resetCombobox(trackCombobox, strings.selectTrack);
@@ -104,6 +104,20 @@
add: '@localizer["AudioPlayerAdd"]'
}
};
// The endpoints and labels of the favorite toggles that every media page and theme template can render. The script reads which
// items of a kind are favorites of the current user, adds a favorite, and removes one through the culture aware web routes, so
// the pages never hardcode a path. The remove route is rendered with its named mediaKind and mediaItemId placeholders intact, which
// the script fills in, so the two values keep their meaning even if the route segment order changes. The labels are serialized as
// script literals, because a localized text can contain characters that would end a quoted literal.
var favoritesConfiguration = {
getFavoriteStatusUrl: '@_urlService.GetRelativeUrl(WebRoutes.Favorites.GET_FAVORITE_STATUS)',
addFavoriteUrl: '@_urlService.GetRelativeUrl(WebRoutes.Favorites.ADD_FAVORITE)',
removeFavoriteUrlTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Favorites.REMOVE_FAVORITE)',
strings: {
add: @Json.Serialize(localizer["FavoritesAdd"].Value),
remove: @Json.Serialize(localizer["FavoritesRemove"].Value)
}
};
</script>
@if (User?.Identity?.IsAuthenticated == true)
{
@@ -118,6 +132,7 @@
<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/playlists.js" asp-append-version="true"></script>
<script defer src="~/js/favorites.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>