Adds the music library browsing and editing pages to the web client.

This commit is contained in:
BinaryAlley committed 2026-10-13 13:27:28 +03:00
1 parent c7aab63552
commit 5a2c6c2bd8
215 files changed
+60042 -3

No files matched your search

@@ -0,0 +1,486 @@
@*
FALLBACK MUSIC ARTISTS BROWSING VIEW - READ BEFORE EDITING
This view is the application fallback of the music artists browsing page, rendered only when the theme template
of the page cannot be loaded. On a healthy site the page comes from the theme's
library/audio-library/music-library/artists/index template. It keeps the DOM contract and the client script the
theme template mirrors, so that navigation, searching and the card actions menu keep working even without the theme.
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.
/library/audio-library/music-library/artists?libraryId=...
*@
@using Lumina.Presentation.Web.Common.DTO.Libraries
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Mvc.Localization
@{
// 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();
}
@inject IViewLocalizer _localizer
@inject IUrlService _urlService
@model LibraryDto
@Html.AntiForgeryToken()
<div class="cotton-candy">
<!-- Container with two rows, one fixed, one filling remaining space. -->
<div style="display: grid; grid-template-rows: auto 1fr;">
<!-- The first row is a dummy row for "margin", because setting a margin on the next row would offset the parent's position. -->
<div style="min-height: 1rem;"></div>
<div class="pl-10 pr-10 pb-10">
<!-- Library title. -->
<div class="text-center">
<h1 class="text-light-two engraved-title">@(Model.Title ?? string.Empty)</h1>
</div>
<div class="form-row">
<!-- Search box. -->
<input id="search-input" type="text" class="enlightenment-input w-200px" placeholder="@_localizer["Search"]" />
<button id="search-button" type="button" class="confirm-button">@_localizer["Search"]</button>
<!-- Sort toggle. -->
<button id="sort-toggle" type="button" class="confirm-button">@_localizer["SortAscending"]</button>
<!-- Item count. -->
<span id="count-label" class="text-light-two"></span>
</div>
<div style="display: flex; align-items: flex-start;">
<!-- Artists grid. -->
<div id="artists-container" class="cards-container justify-start h-100" style="flex: 1; min-width: 0;">
<!-- No items messages. -->
<p id="no-items" class="hidden text-light-two">@_localizer["NoItems"]</p>
<p id="no-items-matching" class="hidden text-light-two">@_localizer["NoItemsMatchFilters"]</p>
</div>
<!-- Alpha picker. -->
<div id="alpha-picker" class="alpha-picker"></div>
</div>
<!-- Pagination. -->
<div id="pagination" class="form-row mx-auto w-25 hidden" style="justify-content: center;">
<button id="prev-page" type="button" class="abort-button">@_localizer["Previous"]</button>
<span id="page-indicator" class="text-light-two"></span>
<button id="next-page" type="button" class="confirm-button">@_localizer["Next"]</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 cleanupFunctions = [];
let isInitialized = false;
let requestSequence = 0;
const libraryId = '@(Model.Id ?? Guid.Empty)';
const artistUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, new { artistId = default(Guid) })';
const deleteUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.DELETE_ARTIST, new { artistId = default(Guid) })';
const artistsContainer = document.getElementById('artists-container');
const noItemsMessage = document.getElementById('no-items');
const noItemsMatchingMessage = document.getElementById('no-items-matching');
const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
const sortToggle = document.getElementById('sort-toggle');
const countLabel = document.getElementById('count-label');
const alphaPicker = document.getElementById('alpha-picker');
const pagination = document.getElementById('pagination');
const prevPageButton = document.getElementById('prev-page');
const nextPageButton = document.getElementById('next-page');
const pageIndicator = document.getElementById('page-indicator');
// The special alpha keys for numbers and symbols, followed by the letters.
const alphaKeys = ['#', '*', ...Array.from({ length: 26 }, (_, index) => String.fromCharCode(65 + index))];
const state = {
currentPage: 1,
perPage: null,
searchTerm: '',
alphaKey: null,
ignoreThePrefix: false,
sortOrder: 'Ascending'
};
const jsLocalizedStrings = {
all: '@_localizer["All"]',
items: '@_localizer["Items"]',
of: '@_localizer["Of"]',
page: '@_localizer["Page"]',
sortAscending: '@_localizer["SortAscending"]',
sortDescending: '@_localizer["SortDescending"]',
viewDetails: '@_localizer["ViewDetails"]',
deleteItem: '@_localizer["Delete"]',
deleteConfirm: '@_localizer["DeleteConfirm"]',
deleteFailed: '@_localizer["DeleteFailed"]'
};
function buildItemsUrl() {
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.GET_ARTISTS)';
const params = new URLSearchParams();
params.set('libraryId', libraryId);
if (state.perPage !== null) {
params.set('currentPage', state.currentPage);
params.set('perPage', state.perPage);
}
if (state.searchTerm !== '')
params.set('searchTerm', state.searchTerm);
if (state.alphaKey !== null)
params.set('filterAlphaKey', state.alphaKey);
params.set('shouldIgnoreThePrefixForAlphaPicker', state.ignoreThePrefix);
params.set('sortOrder', state.sortOrder);
return `${url}?${params.toString()}`;
}
async function loadItemsAsync() {
const requestId = ++requestSequence;
const response = await callApiGetAsync(buildItemsUrl());
if (requestId !== requestSequence)
return;
if (response)
renderItems(response);
}
function renderItems(response) {
artistsContainer.querySelectorAll('.media-card').forEach(card => card.remove());
const hasActiveFilters = state.searchTerm !== '' || state.alphaKey !== null;
if (response.count === 0) {
artistsContainer.classList.add('justify-center');
noItemsMessage.classList.toggle('hidden', hasActiveFilters);
noItemsMatchingMessage.classList.toggle('hidden', !hasActiveFilters);
} else {
artistsContainer.classList.remove('justify-center');
noItemsMessage.classList.add('hidden');
noItemsMatchingMessage.classList.add('hidden');
response.data.forEach(artist => artistsContainer.appendChild(createArtistCard(artist)));
}
bindNavigationLinks();
updateCountLabel(response);
updatePagination(response);
}
function createArtistCard(artist) {
const card = document.createElement('div');
card.className = 'media-card';
card.dataset.artistId = artist.id;
const artistUrl = artistUrlTemplate.replace('/@(default(Guid))', `/${artist.id}`) + `?libraryId=${libraryId}`;
const cardLink = document.createElement('a');
cardLink.className = 'media-panel nav-link no-underline';
cardLink.style.width = '200px';
cardLink.style.height = 'auto';
cardLink.href = artistUrl;
// The cover is shown as a square, cropped from its center (never stretched), and the name is shown underneath it.
const image = document.createElement('img');
image.src = artist.coverPath
? `${globalConfiguration.serverBasePath}${artist.coverPath}`
: `/images/ui/music-placeholder.svg`;
image.alt = artist.name;
image.style.width = '200px';
image.style.height = '200px';
image.style.flexGrow = '0';
image.style.objectFit = 'cover';
image.style.objectPosition = 'center';
cardLink.appendChild(image);
// The name is kept on a single line, truncated with an ellipsis when it does not fit, so that all the cards share the same height.
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 = artist.name;
titleSpan.appendChild(title);
cardLink.appendChild(titleSpan);
const trigger = document.createElement('button');
trigger.type = 'button';
trigger.className = 'card-actions-trigger';
trigger.setAttribute('aria-haspopup', 'menu');
trigger.setAttribute('aria-label', jsLocalizedStrings.viewDetails);
trigger.addEventListener('click', event => {
event.preventDefault();
event.stopImmediatePropagation();
toggleCardMenu(card, resolveMenuAnchor(event));
});
const menu = document.createElement('nav');
menu.className = 'card-actions-menu';
menu.setAttribute('role', 'menu');
menu.innerHTML = `
<a role="menuitem" href="${artistUrl}">${jsLocalizedStrings.viewDetails}</a>
<a role="menuitem" href="#" class="card-action-delete">${jsLocalizedStrings.deleteItem}</a>`;
menu.addEventListener('click', async event => {
const deleteItem = event.target.closest('.card-action-delete');
const menuItem = event.target.closest('a[role="menuitem"]');
if (!menuItem)
return;
event.preventDefault();
event.stopImmediatePropagation();
closeCardMenus();
if (deleteItem) {
await deleteArtistAsync(card.dataset.artistId);
return;
}
await updateContentAsync(menuItem.href, true);
});
card.appendChild(cardLink);
card.appendChild(trigger);
card.appendChild(menu);
card.addEventListener('contextmenu', event => {
event.preventDefault();
event.stopImmediatePropagation();
toggleCardMenu(card, resolveMenuAnchor(event));
});
card.addEventListener('click', event => {
if (card.classList.contains('open') && !event.target.closest('.card-actions-menu'))
closeCardMenus();
});
return card;
}
function toggleCardMenu(card, anchor) {
const wasOpen = card.classList.contains('open');
closeCardMenus();
if (wasOpen)
return;
card.classList.add('open');
const menu = card.querySelector('.card-actions-menu');
if (menu) {
menu.classList.add('open');
positionActionsMenu(menu, anchor);
}
}
function resolveMenuAnchor(event) {
if (event.clientX !== 0 || event.clientY !== 0)
return { x: event.clientX, y: event.clientY };
const triggerRect = event.currentTarget.getBoundingClientRect();
return { x: triggerRect.left, y: triggerRect.bottom };
}
function positionActionsMenu(menu, anchor) {
const margin = 4;
const maxLeft = Math.max(margin, window.innerWidth - menu.offsetWidth - margin);
const maxTop = Math.max(margin, window.innerHeight - menu.offsetHeight - margin);
menu.style.position = 'fixed';
menu.style.left = `${Math.min(Math.max(margin, anchor.x), maxLeft)}px`;
menu.style.top = `${Math.min(Math.max(margin, anchor.y), maxTop)}px`;
}
function closeCardMenus() {
artistsContainer.querySelectorAll('.media-card.open').forEach(card => {
card.classList.remove('open');
const menu = card.querySelector('.card-actions-menu');
if (menu)
menu.classList.remove('open');
});
}
function handleCardMenuDismiss(event) {
if (event.type === 'keydown' && event.key !== 'Escape')
return;
if (event.type === 'click' && event.target.closest('.card-actions-menu, .card-actions-trigger'))
return;
closeCardMenus();
}
async function deleteArtistAsync(artistId) {
if (await dialogService.show(jsLocalizedStrings.deleteConfirm, jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) !== DialogButton.YES)
return;
const url = deleteUrlTemplate.replace('/@(default(Guid))', `/${artistId}`) + `?libraryId=${libraryId}`;
const success = await callApiDeleteAsync(url);
if (success)
await loadItemsAsync();
else
notificationService.show(jsLocalizedStrings.deleteFailed, NotificationType.ERROR);
}
function updateCountLabel(response) {
if (!countLabel)
return;
if (state.perPage === null)
countLabel.textContent = `${response.count} ${jsLocalizedStrings.items}`;
else if (response.count === 0)
countLabel.textContent = `0 ${jsLocalizedStrings.items}`;
else {
const start = (response.currentPage - 1) * response.perPage + 1;
const end = Math.min(response.currentPage * response.perPage, response.count);
countLabel.textContent = `${start}-${end} ${jsLocalizedStrings.of} ${response.count}`;
}
}
function updatePagination(response) {
if (!pagination)
return;
if (state.perPage === null) {
pagination.classList.add('hidden');
return;
}
const totalPages = Math.max(1, response.numberOfPages);
pagination.classList.remove('hidden');
pageIndicator.textContent = `${jsLocalizedStrings.page} ${response.currentPage} ${jsLocalizedStrings.of} ${totalPages}`;
prevPageButton.disabled = response.currentPage <= 1;
nextPageButton.disabled = response.currentPage >= totalPages;
}
// Builds the alpha picker column, with the "All" key followed by the numbers, symbols and letters keys.
function buildAlphaPicker() {
if (!alphaPicker)
return;
const allKey = document.createElement('span');
allKey.className = 'alpha-key';
allKey.dataset.alphaKey = '';
allKey.textContent = jsLocalizedStrings.all;
allKey.addEventListener('click', () => handleAlphaKeyClick(null));
alphaPicker.appendChild(allKey);
alphaKeys.forEach(key => {
const alphaKey = document.createElement('span');
alphaKey.className = 'alpha-key';
alphaKey.dataset.alphaKey = key;
alphaKey.textContent = key;
alphaKey.addEventListener('click', () => handleAlphaKeyClick(key));
alphaPicker.appendChild(alphaKey);
});
updateAlphaPickerActiveState();
}
// Highlights the currently active key of the alpha picker.
function updateAlphaPickerActiveState() {
if (!alphaPicker)
return;
alphaPicker.querySelectorAll('.alpha-key').forEach(key => {
const keyValue = key.dataset.alphaKey === '' ? null : key.dataset.alphaKey;
key.classList.toggle('alpha-key-active', keyValue === state.alphaKey);
});
}
// Applies the given alpha key (null clears the alpha filter) and reloads the artists.
function handleAlphaKeyClick(key) {
state.alphaKey = key;
state.currentPage = 1;
updateAlphaPickerActiveState();
loadItemsAsync();
}
// Toggles the sort direction and reloads the artists.
function handleSortToggle() {
state.sortOrder = state.sortOrder === 'Ascending' ? 'Descending' : 'Ascending';
sortToggle.textContent = state.sortOrder === 'Ascending' ? jsLocalizedStrings.sortAscending : jsLocalizedStrings.sortDescending;
state.currentPage = 1;
loadItemsAsync();
}
// Applies an alpha filter when a letter is pressed while the search input does not have focus; Escape clears the alpha filter.
function handleAlphaKeydown(event) {
if (document.activeElement === searchInput)
return;
if (event.key.length === 1 && /[a-zA-Z]/.test(event.key))
handleAlphaKeyClick(event.key.toUpperCase());
else if (event.key === 'Escape')
handleAlphaKeyClick(null);
}
function handleSearch() {
state.searchTerm = searchInput.value.trim();
state.currentPage = 1;
loadItemsAsync();
}
function handleSearchKeydown(event) {
if (event.key === 'Enter') {
event.preventDefault();
handleSearch();
}
}
function handlePrevPageClick() {
state.currentPage = Math.max(1, state.currentPage - 1);
loadItemsAsync();
}
function handleNextPageClick() {
state.currentPage = state.currentPage + 1;
loadItemsAsync();
}
async function loadSettingsAsync() {
const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)');
if (data) {
state.ignoreThePrefix = data.shouldIgnoreThePrefixForAlphaPicker === true;
state.perPage = data.isPaginationEnabled === true ? data.itemsPerPage : null;
}
}
function bindEventHandler(element, type, handler) {
if (element)
element.addEventListener(type, handler);
}
function unbindEventHandler(element, type, handler) {
if (element)
element.removeEventListener(type, handler);
}
bindEventHandler(searchButton, 'click', handleSearch);
bindEventHandler(searchInput, 'keydown', handleSearchKeydown);
bindEventHandler(sortToggle, 'click', handleSortToggle);
bindEventHandler(prevPageButton, 'click', handlePrevPageClick);
bindEventHandler(nextPageButton, 'click', handleNextPageClick);
document.addEventListener('keydown', handleAlphaKeydown);
document.addEventListener('click', handleCardMenuDismiss);
document.addEventListener('keydown', handleCardMenuDismiss);
document.addEventListener('DOMContentLoaded', InitializeAsync);
cleanupFunctions.push(() => {
unbindEventHandler(searchButton, 'click', handleSearch);
unbindEventHandler(searchInput, 'keydown', handleSearchKeydown);
unbindEventHandler(sortToggle, 'click', handleSortToggle);
unbindEventHandler(prevPageButton, 'click', handlePrevPageClick);
unbindEventHandler(nextPageButton, 'click', handleNextPageClick);
document.removeEventListener('keydown', handleAlphaKeydown);
document.removeEventListener('click', handleCardMenuDismiss);
document.removeEventListener('keydown', handleCardMenuDismiss);
document.removeEventListener('DOMContentLoaded', InitializeAsync);
});
async function InitializeAsync() {
if (isInitialized)
return;
if (!artistsContainer || !sortToggle || !countLabel) {
isInitialized = true;
return;
}
isInitialized = true;
sortToggle.textContent = jsLocalizedStrings.sortAscending;
buildAlphaPicker();
await loadSettingsAsync();
await loadItemsAsync();
}
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}