From 5f5803c9f8695cd9ec68471ee6e5276f5aae41c3 Mon Sep 17 00:00:00 2001 From: 1xDed Date: Tue, 1 Dec 2026 04:24:56 +0300 Subject: [PATCH] feat: add gamepad navigation and music library improvements - add TV/gamepad spatial navigation, focus ring and back/select controls - cache artwork persistently and add music cover placeholders - add compact songs list, shuffle-all queue and library error recovery - polish remote control layout and optimistic seek timeline --- src/components/albumMusicTrack/index.tsx | 11 + src/components/cachedImage/index.tsx | 50 +++ src/components/card/card.tsx | 24 +- src/components/carouselSlide/index.tsx | 5 +- src/components/itemHeader/index.tsx | 5 +- src/components/libraryHeader/index.tsx | 105 ++++- .../libraryHeader/libraryHeader.scss | 17 + src/components/libraryItemsGrid/index.tsx | 11 + src/components/musicTrack/index.tsx | 88 ++-- src/components/musicTrack/musicTrack.scss | 93 +++-- src/components/musicTracksList/index.tsx | 93 +++++ .../musicTracksList/musicTracksList.scss | 42 ++ src/components/spatialNavigation/index.tsx | 391 ++++++++++++++++++ src/components/utils/iconsCollection.tsx | 2 +- src/routes/__root.tsx | 2 + src/routes/_api/library/$id.tsx | 68 +-- src/routes/_api/library/library.scss | 46 ++- src/routes/_api/remote.scss | 186 ++++----- src/routes/_api/remote.tsx | 81 ++-- src/styles/global.scss | 16 +- src/utils/cache/imageCache.ts | 82 ++++ src/utils/constants/library.ts | 2 +- src/utils/queries/library.ts | 22 +- src/utils/queries/libraryItems.ts | 2 + 24 files changed, 1199 insertions(+), 245 deletions(-) create mode 100644 src/components/cachedImage/index.tsx create mode 100644 src/components/musicTracksList/index.tsx create mode 100644 src/components/musicTracksList/musicTracksList.scss create mode 100644 src/components/spatialNavigation/index.tsx create mode 100644 src/utils/cache/imageCache.ts diff --git a/src/components/albumMusicTrack/index.tsx b/src/components/albumMusicTrack/index.tsx index 77f2bc9..8a92031 100644 --- a/src/components/albumMusicTrack/index.tsx +++ b/src/components/albumMusicTrack/index.tsx @@ -72,6 +72,17 @@ export default function AlbumMusicTrack(props: AlbumMusicTrackProps) { handlePlayback(trackIndex, track, musicTracks.Items); } }} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + if (musicTracks?.Items) { + handlePlayback(trackIndex, track, musicTracks.Items); + } + } + }} + role="button" + tabIndex={0} + aria-label={track.Name ?? "Трек"} >
diff --git a/src/components/cachedImage/index.tsx b/src/components/cachedImage/index.tsx new file mode 100644 index 0000000..95133d1 --- /dev/null +++ b/src/components/cachedImage/index.tsx @@ -0,0 +1,50 @@ +import React, { useEffect, useState } from "react"; +import { getCachedImageUrl } from "@/utils/cache/imageCache"; + +type CachedImageProps = React.ImgHTMLAttributes & { + src?: string | null; + fallback?: React.ReactNode; +}; + +/** + * Drop-in `` that resolves Jellyfin artwork through the persistent + * Cache API. If the request cannot be read (CORS/offline), it falls back to + * the original URL so the browser can still render it. + */ +const CachedImage = ({ + src, + fallback = null, + onError, + ...props +}: CachedImageProps) => { + const [cachedSrc, setCachedSrc] = useState(null); + const [failed, setFailed] = useState(false); + + useEffect(() => { + let active = true; + setCachedSrc(null); + setFailed(false); + if (!src) return; + void getCachedImageUrl(src).then((url) => { + if (active && url) setCachedSrc(url); + }); + return () => { + active = false; + }; + }, [src]); + + if (!src || failed) return <>{fallback}; + + return ( + { + setFailed(true); + onError?.(event); + }} + /> + ); +}; + +export default CachedImage; diff --git a/src/components/card/card.tsx b/src/components/card/card.tsx index 874684b..f1bb90b 100644 --- a/src/components/card/card.tsx +++ b/src/components/card/card.tsx @@ -9,6 +9,7 @@ import { useNavigate } from "@tanstack/react-router"; import React, { memo, type Ref, useCallback } from "react"; import { ErrorBoundary } from "react-error-boundary"; import { useInView } from "react-intersection-observer"; +import CachedImage from "@/components/cachedImage"; import getImageUrlsApi from "@/utils/methods/getImageUrlsApi"; import { resolveItemImage } from "@/utils/methods/itemImages"; import { useApiInContext } from "@/utils/store/api"; @@ -60,6 +61,14 @@ const CardContent = ({ const image = resolveItemImage(item, imageType, { seriesId: seriesId ? (item.SeriesId ?? undefined) : undefined, }); + const isMusic = + item.Type === BaseItemKind.MusicAlbum || + item.Type === BaseItemKind.Audio || + item.Type === BaseItemKind.AudioBook || + item.Type === BaseItemKind.Playlist; + // Jellyfin generates a generic placeholder when a music item has no cover; + // prefer our own themed fallback in that case. + const hasCover = !isMusic || Boolean(image?.tag); const defaultOnClick = useCallback(() => { if (item?.Id) { @@ -72,6 +81,15 @@ const CardContent = ({ className="card" ref={forwardedRef} onClick={onClick || defaultOnClick} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + (onClick || defaultOnClick)(); + } + }} + role="button" + tabIndex={0} + aria-label={cardTitle ?? item.Name ?? "Элемент"} >
}> @@ -107,8 +125,8 @@ const CardContent = ({ ? getTypeIcon(overrideIcon) : getTypeIcon(item.Type ?? "universal")}
- {image && ( - {item.Name )} {inView && !disableOverlay && ( -
+
{ /> )} {heroArtwork ? ( - {item.Name {
)} {heroPoster && ( - {item.Name - {item.Name { const { api, user } = route.useRouteContext(); const navigate = useNavigate(); const queryClient = useQueryClient(); + const { enqueueSnackbar } = useSnackbar(); + const [shuffling, setShuffling] = useState(false); // Zustand library state (selected via shallow comparator) const { @@ -226,6 +239,70 @@ export const LibraryHeader = () => { [normalizedViewType, currentLibrary.data.CollectionType], ); + const isMusicSongs = + currentLibrary.data.CollectionType === "music" && + normalizedViewType === BaseItemKind.Audio; + + const shuffleAllTracks = useCallback(async () => { + if (!api || !user?.Id || !currentLibraryId || shuffling) return; + setShuffling(true); + try { + const result = await getLibraryApi(api).getItems({ + userId: user.Id, + parentId: currentLibraryId, + recursive: true, + includeItemTypes: [BaseItemKind.Audio], + sortBy: [ItemSortBy.SortName], + sortOrder: [SortOrder.Ascending], + enableUserData: true, + limit: 5000, + }); + const tracks = (result.data.Items ?? []).filter((item) => item.Id); + if (tracks.length === 0) { + enqueueSnackbar("В этой библиотеке нет композиций", { + variant: "info", + }); + return; + } + const queue = [...tracks]; + for (let i = queue.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [queue[i], queue[j]] = [queue[j], queue[i]]; + } + const first = queue[0]; + if (!first.Id) return; + playAudio( + generateAudioStreamUrl( + first.Id, + user.Id, + api.deviceInfo.id, + api.basePath, + api.accessToken, + ), + first, + ); + setQueue(queue, 0); + enqueueSnackbar(`Перемешано композиций: ${queue.length}`, { + variant: "success", + }); + navigate({ to: "/player/audio" }); + } catch (error) { + console.error("Could not shuffle music library", error); + enqueueSnackbar("Не удалось запустить перемешивание", { + variant: "error", + }); + } finally { + setShuffling(false); + } + }, [ + api, + user?.Id, + currentLibraryId, + shuffling, + enqueueSnackbar, + navigate, + ]); + const appBarStyling = useMemo( () => ({ backgroundColor: "transparent", paddingRight: "0 !important" }), [], @@ -334,6 +411,30 @@ export const LibraryHeader = () => { ))} + {isMusicSongs && ( + + + + )} { } }, [items.data?.TotalRecordCount, currentLibraryId, updateLibrary]); + if (effectiveViewType === BaseItemKind.Audio) { + return ( + + ); + } + return (
{ const api = useApiInContext((s) => s.api); const [currentTrackItem] = useAudioPlayback((state) => [state.item]); + const rowRef = useRef(null); + const activate = () => { + rowRef.current + ?.querySelector(".music-track-image-overlay button") + ?.click(); + }; + const image = resolveItemImage(item); + const imageUrl = + api && image?.tag + ? getImageUrlsApi(api).getItemImageUrlById( + image.itemId, + image.imageType, + { + quality: 70, + fillHeight: 128, + fillWidth: 128, + tag: image.tag, + }, + ) + : undefined; return ( -
+
{ + if ((event.target as HTMLElement).closest("a,button")) return; + activate(); + }} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + activate(); + } + }} + role="button" + tabIndex={0} + aria-label={item.Name ?? "Трек"} + >
- {item.Name -
+
-
+
))}
+ {item.Album && ( + + {item.Album} + + )}
{getRuntimeMusic(item.RunTimeTicks ?? 0)} - +
+ +
); }; diff --git a/src/components/musicTrack/musicTrack.scss b/src/components/musicTrack/musicTrack.scss index 8f4a3f1..3d8eb7c 100644 --- a/src/components/musicTrack/musicTrack.scss +++ b/src/components/musicTrack/musicTrack.scss @@ -1,52 +1,79 @@ - .music-track { display: grid; - grid-template-columns: 4.5em 80% 1fr 1fr; - gap: 0.5em; + grid-template-columns: 52px minmax(0, 1fr) auto auto; + gap: 14px; align-items: center; - justify-items: center; width: 100%; + padding: 6px 12px; + border-radius: 12px; cursor: pointer; - &-icon { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - display: flex; - align-items: center; - justify-content: center; - background: rgb(255 255 255 / 0.09); - z-index: -1; + transition: background-color 0.15s ease; + + &:hover { + background: rgb(255 255 255 / 0.06); } + &-image { - margin: 0.4em; - border-radius: $border-radius_04; - overflow: hidden; - aspect-ratio: 1; position: relative; - width: 4em; - box-shadow: 0 0 10px rgb(0 0 0 / 0.2); - transition: opacity $transition-time-default; + width: 52px; + height: 52px; + border-radius: 9px; + overflow: hidden; + box-shadow: 0 4px 12px rgb(0 0 0 / 0.22); + &-overlay { position: absolute; - top: 0; - left: 0; - backdrop-filter: blur(10px); - width: 100%; - height: 100%; + inset: 0; + z-index: 3; display: flex; - justify-content: center; align-items: center; + justify-content: center; + background: rgb(8 0 31 / 0.5); + backdrop-filter: blur(8px); opacity: 0; - transition: opacity $transition-time-fast; + transition: opacity 0.15s ease; + } + + > img { + position: relative; + z-index: 1; } } + + &-icon { + position: absolute; + inset: 0; + z-index: 0; + display: grid; + place-items: center; + background: linear-gradient( + 145deg, + rgb(255 255 255 / 0.12), + rgb(255 255 255 / 0.04) + ); + + .material-symbols-rounded { + color: rgb(255 255 255 / 0.55); + } + } + &-info { - justify-self: start; - &-lyrics { - margin-right: 0.4em; - } + display: flex; + flex-direction: column; + gap: 1px; + min-width: 0; + justify-self: stretch; + + .MuiTypography-root, + span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + } + + &-album { + opacity: 0.5; } &:hover { diff --git a/src/components/musicTracksList/index.tsx b/src/components/musicTracksList/index.tsx new file mode 100644 index 0000000..0e845b7 --- /dev/null +++ b/src/components/musicTracksList/index.tsx @@ -0,0 +1,93 @@ +import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client"; +import { useWindowVirtualizer } from "@tanstack/react-virtual"; +import React, { useEffect, useRef, useState } from "react"; +import MusicTrack from "@/components/musicTrack"; + +import "./musicTracksList.scss"; + +type MusicTracksListProps = { + items: BaseItemDto[]; + userId?: string; + queryKey: string[]; +}; + +/** Compact, virtualized row list used for the Songs view of a music library. */ +const MusicTracksList = ({ items, userId, queryKey }: MusicTracksListProps) => { + const parentRef = useRef(null); + const [scrollMargin, setScrollMargin] = useState(0); + + useEffect(() => { + const element = parentRef.current; + if (!element) return; + let frame = 0; + const measure = () => { + frame = requestAnimationFrame(() => setScrollMargin(element.offsetTop)); + }; + measure(); + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => { + if (frame) cancelAnimationFrame(frame); + observer.disconnect(); + }; + }, []); + + const virtualizer = useWindowVirtualizer({ + count: items.length, + estimateSize: () => 78, + overscan: 8, + scrollMargin, + }); + + if (items.length === 0) { + return ( +
+ music_off + В этой библиотеке пока нет треков +
+ ); + } + + return ( +
+
+ + Трек + Длительность + +
+
+ {virtualizer.getVirtualItems().map((row) => { + const item = items[row.index]; + return ( +
+ +
+ ); + })} +
+
+ ); +}; + +export default MusicTracksList; diff --git a/src/components/musicTracksList/musicTracksList.scss b/src/components/musicTracksList/musicTracksList.scss new file mode 100644 index 0000000..768242c --- /dev/null +++ b/src/components/musicTracksList/musicTracksList.scss @@ -0,0 +1,42 @@ +.music-tracks-list { + width: 100%; + max-width: 1180px; + margin: 0 auto; + padding-bottom: 7rem; +} + +.music-tracks-head { + display: grid; + grid-template-columns: 52px minmax(0, 1fr) auto auto; + gap: 14px; + align-items: center; + padding: 0 12px 8px; + font-size: 0.72rem; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; + color: rgb(255 255 255 / 0.4); + + span:nth-child(3) { + text-align: right; + } +} + +.music-tracks-row { + will-change: transform; +} + +.music-tracks-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 8px; + min-height: 280px; + color: rgb(255 255 255 / 0.55); + + .material-symbols-rounded { + font-size: 3rem; + opacity: 0.6; + } +} diff --git a/src/components/spatialNavigation/index.tsx b/src/components/spatialNavigation/index.tsx new file mode 100644 index 0000000..b0caded --- /dev/null +++ b/src/components/spatialNavigation/index.tsx @@ -0,0 +1,391 @@ +import { useSnackbar } from "notistack"; +import { useCallback, useEffect, useRef } from "react"; + +type Direction = "up" | "down" | "left" | "right"; + +const FOCUSABLE_SELECTOR = [ + "button:not([disabled])", + "a[href]", + "input:not([disabled])", + "select:not([disabled])", + "textarea:not([disabled])", + "[tabindex]:not([tabindex='-1'])", + "[role='button']", + "[role='menuitem']", + "[role='option']", + "[role='switch']", + "[role='slider']", + "[role='tab']", + "[contenteditable='true']", +].join(","); + +const isVisible = (element: HTMLElement) => { + const rect = element.getBoundingClientRect(); + if (rect.width < 2 || rect.height < 2) return false; + const style = window.getComputedStyle(element); + if (style.display === "none" || style.visibility === "hidden") return false; + if (Number.parseFloat(style.opacity || "1") === 0) return false; + if (element.closest("[aria-hidden='true'], [inert]")) return false; + return true; +}; + +const findOpenOverlay = (): HTMLElement | undefined => { + return Array.from( + document.querySelectorAll( + ".MuiDialog-root, .MuiMenu-root, .MuiPopover-root, .MuiDrawer-root", + ), + ) + .filter(isVisible) + .pop(); +}; + +const getScope = (): HTMLElement => { + const active = document.activeElement; + if (active instanceof HTMLElement) { + const activeScope = active.closest( + ".MuiDialog-root, .MuiMenu-root, .MuiPopover-root, .MuiDrawer-root", + ); + if (activeScope) return activeScope; + } + const dialogs = Array.from( + document.querySelectorAll(".MuiDialog-root"), + ).filter(isVisible); + if (dialogs.length > 0) return dialogs[dialogs.length - 1]; + const menus = Array.from( + document.querySelectorAll(".MuiMenu-root, .MuiPopover-root"), + ).filter(isVisible); + if (menus.length > 0) return menus[menus.length - 1]; + return document.body; +}; + +const getCandidates = (): HTMLElement[] => { + const scope = getScope(); + return Array.from(scope.querySelectorAll(FOCUSABLE_SELECTOR)) + .filter((element) => element !== scope) + .filter((element) => !element.closest("[data-tv-ignore]")) + .filter(isVisible) + .filter((element) => element.tabIndex >= 0 || element.hasAttribute("tabindex")); +}; + +const clearTvFocus = () => { + for (const element of document.querySelectorAll( + '[data-tv-focus="true"]', + )) { + element.removeAttribute("data-tv-focus"); + } +}; + +const focusElement = (element: HTMLElement) => { + clearTvFocus(); + element.setAttribute("data-tv-focus", "true"); + element.focus({ preventScroll: true }); + element.scrollIntoView({ + block: "center", + inline: "center", + behavior: "smooth", + }); +}; + +const isVideoPlayer = () => window.location.pathname === "/player"; + +const moveFocus = (direction: Direction) => { + const candidates = getCandidates(); + if (candidates.length === 0) return; + + const active = document.activeElement; + const current = + active instanceof HTMLElement && active !== document.body + ? active + : undefined; + + if (!current || !candidates.includes(current)) { + const contentCandidates = candidates.filter( + (element) => + !element.closest( + ".appBar, .library-header, .home-header, .remote-topbar, .audio-player, .video-player, .window-chrome, .window-controls, .follow-me, .alpha-selector", + ), + ); + const pool = contentCandidates.length > 0 ? contentCandidates : candidates; + const first = [...pool].sort((a, b) => { + const ar = a.getBoundingClientRect(); + const br = b.getBoundingClientRect(); + return ar.top - br.top || ar.left - br.left; + })[0]; + if (first) focusElement(first); + return; + } + + const currentRect = current.getBoundingClientRect(); + const currentX = currentRect.left + currentRect.width / 2; + const currentY = currentRect.top + currentRect.height / 2; + + let best: { element: HTMLElement; score: number } | undefined; + for (const candidate of candidates) { + if (candidate === current) continue; + const rect = candidate.getBoundingClientRect(); + const x = rect.left + rect.width / 2; + const y = rect.top + rect.height / 2; + const dx = x - currentX; + const dy = y - currentY; + + let primary = 0; + let secondary = 0; + if (direction === "left") { + if (dx >= -4) continue; + primary = -dx; + secondary = Math.abs(dy); + } else if (direction === "right") { + if (dx <= 4) continue; + primary = dx; + secondary = Math.abs(dy); + } else if (direction === "up") { + if (dy >= -4) continue; + primary = -dy; + secondary = Math.abs(dx); + } else { + if (dy <= 4) continue; + primary = dy; + secondary = Math.abs(dx); + } + + // Only move within the same visual row/column. This keeps D-pad + // navigation predictable in grids and prevents jumping to a toolbar + // when there is no neighbouring card in that direction. + const overlaps = + direction === "left" || direction === "right" + ? rect.top < currentRect.bottom && rect.bottom > currentRect.top + : rect.left < currentRect.right && rect.right > currentRect.left; + if (!overlaps) continue; + const score = primary + secondary * 2.2; + if (!best || score < best.score) best = { element: candidate, score }; + } + + if (best) focusElement(best.element); +}; + +const activateFocused = () => { + if (isVideoPlayer()) { + document.dispatchEvent( + new KeyboardEvent("keydown", { key: " ", bubbles: true }), + ); + return; + } + const active = document.activeElement; + if (active instanceof HTMLElement && active !== document.body) { + active.click(); + return; + } + const [first] = getCandidates(); + if (first) { + focusElement(first); + first.click(); + } +}; + +const goBack = () => { + if (isVideoPlayer()) { + document + .querySelector( + "[aria-label='Выйти из плеера'], [aria-label='Назад']", + ) + ?.click(); + return; + } + const modal = findOpenOverlay(); + if (modal) { + document.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), + ); + return; + } + const back = document.querySelector( + "[aria-label='Назад'], [aria-label='Выйти из плеера']", + ); + if (back) back.click(); + else window.history.back(); +}; + +const openMenu = () => { + if (isVideoPlayer()) return; + const menu = document.querySelector( + "button[aria-label='Открыть меню']", + ); + menu?.click(); +}; + +const SpatialNavigation = () => { + const { enqueueSnackbar } = useSnackbar(); + const heldDirection = useRef(null); + const nextRepeatAt = useRef(0); + const previousButtons = useRef([]); + + const onKeyDown = useCallback((event: KeyboardEvent) => { + if (event.defaultPrevented || event.altKey || event.metaKey || event.ctrlKey) + return; + const target = + event.target instanceof HTMLElement ? event.target : null; + if ( + target?.closest( + "input, textarea, select, [contenteditable='true'], [role='slider'], .MuiSlider-root", + ) + ) { + return; + } + + if ( + event.key === "Escape" || + event.key === "BrowserBack" || + event.key === "GoBack" + ) { + if (findOpenOverlay()) { + return; + } + const back = document.querySelector( + "[aria-label='Выйти из плеера'], [aria-label='Назад']", + ); + if (back) { + event.preventDefault(); + back.click(); + } else if (event.key !== "Escape") { + window.history.back(); + } + return; + } + if ( + target?.closest(".MuiMenu-root, .MuiPopover-root") && + (event.key === "ArrowUp" || event.key === "ArrowDown") + ) { + return; + } + if (isVideoPlayer()) return; + + const directions: Record = { + ArrowUp: "up", + ArrowDown: "down", + ArrowLeft: "left", + ArrowRight: "right", + }; + const direction = directions[event.key]; + if (!direction) return; + event.preventDefault(); + moveFocus(direction); + }, []); + + useEffect(() => { + document.addEventListener("keydown", onKeyDown); + const onPointerDown = () => clearTvFocus(); + document.addEventListener("pointerdown", onPointerDown, true); + return () => { + document.removeEventListener("keydown", onKeyDown); + document.removeEventListener("pointerdown", onPointerDown, true); + }; + }, [onKeyDown]); + + useEffect(() => { + let frame = 0; + let connected = false; + + const getPad = () => { + const pads = navigator.getGamepads?.() ?? []; + return Array.from(pads).find((pad) => pad?.connected) ?? null; + }; + + const pressed = (pad: Gamepad, index: number) => + Boolean(pad.buttons[index]?.pressed); + + const gamepadDirection = (pad: Gamepad): Direction | null => { + const up = pressed(pad, 12); + const down = pressed(pad, 13); + const left = pressed(pad, 14); + const right = pressed(pad, 15); + if (up) return "up"; + if (down) return "down"; + if (left) return "left"; + if (right) return "right"; + + const x = pad.axes[0] ?? 0; + const y = pad.axes[1] ?? 0; + if (Math.abs(x) < 0.55 && Math.abs(y) < 0.55) return null; + if (Math.abs(x) > Math.abs(y)) return x < 0 ? "left" : "right"; + return y < 0 ? "up" : "down"; + }; + + const tick = (time: number) => { + const pad = getPad(); + if (pad) { + if (!connected) { + connected = true; + previousButtons.current = []; + } + const direction = gamepadDirection(pad); + if (direction) { + if (heldDirection.current !== direction) { + heldDirection.current = direction; + nextRepeatAt.current = time + 320; + if (isVideoPlayer()) { + document.dispatchEvent( + new KeyboardEvent("keydown", { + key: + direction === "left" + ? "ArrowLeft" + : direction === "right" + ? "ArrowRight" + : direction === "up" + ? "ArrowUp" + : "ArrowDown", + bubbles: true, + }), + ); + } else { + moveFocus(direction); + } + } else if (time >= nextRepeatAt.current) { + nextRepeatAt.current = time + 140; + if (!isVideoPlayer()) moveFocus(direction); + } + } else { + heldDirection.current = null; + } + + const edge = (index: number) => { + const isPressed = pressed(pad, index); + const wasPressed = previousButtons.current[index] ?? false; + previousButtons.current[index] = isPressed; + return isPressed && !wasPressed; + }; + + if (edge(0)) activateFocused(); + if (edge(1)) goBack(); + if (edge(9)) openMenu(); + } else { + connected = false; + heldDirection.current = null; + } + frame = requestAnimationFrame(tick); + }; + + const onConnected = (event: GamepadEvent) => { + enqueueSnackbar(`Геймпад подключён: ${event.gamepad.id}`, { + variant: "info", + }); + }; + const onDisconnected = (event: GamepadEvent) => { + enqueueSnackbar(`Геймпад отключён: ${event.gamepad.id}`, { + variant: "warning", + }); + }; + + window.addEventListener("gamepadconnected", onConnected); + window.addEventListener("gamepaddisconnected", onDisconnected); + frame = requestAnimationFrame(tick); + return () => { + cancelAnimationFrame(frame); + window.removeEventListener("gamepadconnected", onConnected); + window.removeEventListener("gamepaddisconnected", onDisconnected); + }; + }, [enqueueSnackbar]); + + return null; +}; + +export default SpatialNavigation; diff --git a/src/components/utils/iconsCollection.tsx b/src/components/utils/iconsCollection.tsx index 5a26890..47e8118 100644 --- a/src/components/utils/iconsCollection.tsx +++ b/src/components/utils/iconsCollection.tsx @@ -11,7 +11,7 @@ export const getTypeIcon = ( case "Home": return
home
; case BaseItemKind.Audio: - return
mic
; + return
music_note
; case BaseItemKind.AudioBook: return
speech_to_text
; case BaseItemKind.Book: diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index c8fe4f8..6149a11 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -34,6 +34,7 @@ import RealtimeBridge from "@/components/realtime"; import SplashHider from "@/components/splash"; import RemoteControlDialog from "@/components/remoteControl"; import RouterLoading from "@/components/routerLoading"; +import SpatialNavigation from "@/components/spatialNavigation"; import SyncPlayController from "@/components/syncPlay/controller"; import SyncPlayDialog from "@/components/syncPlay"; import Search from "@/components/search"; @@ -79,6 +80,7 @@ export const Route = createRootRouteWithContext()({ + diff --git a/src/routes/_api/library/$id.tsx b/src/routes/_api/library/$id.tsx index b182141..755e8ec 100644 --- a/src/routes/_api/library/$id.tsx +++ b/src/routes/_api/library/$id.tsx @@ -1,6 +1,7 @@ import { BaseItemKind, ItemSortBy } from "@jellyfin/sdk/lib/generated-client"; import { useSuspenseQuery } from "@tanstack/react-query"; import React, { Suspense, useEffect } from "react"; +import { ErrorBoundary } from "react-error-boundary"; import "./library.scss"; import { createFileRoute } from "@tanstack/react-router"; import { useShallow } from "zustand/shallow"; @@ -65,14 +66,16 @@ function Library() { getLibraryQueryOptions(api, user?.Id, id), ); const updateLibrary = useLibraryStateStore((s) => s.updateLibrary); - const { libraryName: storeLibraryName } = useLibraryStateStore( - useShallow((s) => { - const sl = s.libraries[id || ""]; - return { - libraryName: sl?.libraryName, - } as const; - }), - ); + const { libraryName: storeLibraryName, currentViewType } = + useLibraryStateStore( + useShallow((s) => { + const sl = s.libraries[id || ""]; + return { + libraryName: sl?.libraryName, + currentViewType: sl?.currentViewType, + } as const; + }), + ); React.useEffect(() => { if (!id || !currentLib.data) return; @@ -107,23 +110,38 @@ function Library() { > - }> -
- -
-
- -
-
+ ( +
+ cloud_off +

Не удалось загрузить библиотеку

+

{error instanceof Error ? error.message : String(error)}

+ +
+ )} + > + }> +
+ +
+ {currentViewType !== BaseItemKind.Audio && ( +
+ +
+ )} +
+
); } \ No newline at end of file diff --git a/src/routes/_api/library/library.scss b/src/routes/_api/library/library.scss index 53984d3..f0ad1c1 100644 --- a/src/routes/_api/library/library.scss +++ b/src/routes/_api/library/library.scss @@ -169,4 +169,48 @@ flex-basis: 14%; } } -} \ No newline at end of file +} +.library-load-error { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.6em; + min-height: 50vh; + padding: 2em; + text-align: center; + + > .material-symbols-rounded { + font-size: 3.5rem; + opacity: 0.5; + } + + h2 { + margin: 0; + font-size: 1.4rem; + font-weight: 600; + } + + p { + max-width: 48ch; + margin: 0; + opacity: 0.65; + font-size: 0.9rem; + overflow-wrap: anywhere; + } + + button { + margin-top: 0.6em; + padding: 0.6em 1.2em; + border: 1px solid rgb(255 255 255 / 0.12); + border-radius: 999px; + background: rgb(255 255 255 / 0.08); + color: inherit; + font: inherit; + cursor: pointer; + + &:hover { + background: rgb(255 255 255 / 0.14); + } + } +} diff --git a/src/routes/_api/remote.scss b/src/routes/_api/remote.scss index 32f227b..f878d8b 100644 --- a/src/routes/_api/remote.scss +++ b/src/routes/_api/remote.scss @@ -1,14 +1,18 @@ /** * Remote control for another Jellyfin client. - * Layout follows the reference player: brand bar, poster + details + round - * transport, a full-width timeline, and a service bar with subtitles, volume, - * quality and fullscreen. + * Layout follows the reference player: title bar, poster + details + round + * transport, a full-width timeline, and a transparent service bar with + * subtitles, volume and fullscreen. */ .remote-page { --remote-accent: #{$clr-accent-default}; --remote-panel: #16191f; - --remote-chip: #1b1e25; - --remote-muted: #a9b0bb; + --remote-chip: rgb(255 255 255 / 0.08); + --remote-muted: rgb(255 255 255 / 0.64); + --remote-gutter: clamp(1.5rem, 2.5vw, 2rem); + --remote-surface: rgb(255 255 255 / 0.08); + --remote-surface-hover: rgb(255 255 255 / 0.14); + --remote-border: rgb(255 255 255 / 0.1); position: fixed; inset: 0; @@ -33,10 +37,35 @@ align-items: center; justify-content: space-between; gap: 24px; - height: 88px; - padding: 0 32px; + height: 58px; + padding: 0 var(--remote-gutter); box-sizing: border-box; + html.is-macos & { + padding-left: calc(var(--remote-gutter) + 64px); + } + + .MuiIconButton-root { + width: 38px; + height: 38px; + color: rgb(255 255 255 / 0.88); + background: rgb(255 255 255 / 0.08); + border: 1px solid rgb(255 255 255 / 0.1); + backdrop-filter: blur(10px); + transition: + background-color 0.18s ease, + color 0.18s ease; + + &:hover { + color: #fff; + background: rgb(255 255 255 / 0.16); + } + + .material-symbols-rounded { + font-size: 1.25rem; + } + } + &-left, &-right { display: flex; @@ -45,19 +74,6 @@ min-width: 0; } - .MuiIconButton-root { - color: #dfe3ea; - - &:hover { - color: #fff; - background: rgb(255 255 255 / 0.08); - } - - .material-symbols-rounded { - font-size: 1.5rem; - } - } - &-divider { width: 1px; height: 26px; @@ -65,57 +81,8 @@ } } -.remote-brand { - display: flex; - align-items: center; - gap: 10px; - - &-mark { - display: grid; - place-items: center; - width: 38px; - height: 38px; - border-radius: 50%; - background: linear-gradient( - 135deg, - $clr-accent-default, - $clr-secondary-default - ); - color: #fff; - - .material-symbols-rounded { - font-size: 1.3rem; - } - } - - &-name { - font-size: 1.35rem; - font-weight: 600; - letter-spacing: -0.01em; - } -} - -.remote-device-chip { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 8px 12px 8px 14px; - border: 0; - border-radius: 999px; - background: var(--remote-panel); - color: #e8ebf1; - font: inherit; - font-size: 0.88rem; - cursor: pointer; - transition: background-color 0.15s ease; - - &:hover { - background: #1d2028; - } - - > .material-symbols-rounded { - font-size: 1.2rem; - } +html.is-macos .remote-topbar-right .remote-topbar-divider { + display: none; } .remote-chevron { @@ -136,13 +103,13 @@ flex: 0 0 clamp(220px, 19vw, 280px); flex-direction: column; min-height: 0; - padding: clamp(0.5rem, 3vh, 2rem) 0 0 clamp(1.5rem, 4vw, 3.5rem); + padding: 14px 0 0 var(--remote-gutter); box-sizing: border-box; overflow: hidden; } .remote-devices-title { - margin: 0 0 0.5em 0.6em; + margin: 0 0 0.5em 0.45em; font-size: 0.72rem; font-weight: 500; letter-spacing: 0.2em; @@ -166,8 +133,8 @@ gap: 0.75em; width: 100%; padding: 0.6em 0.7em; - border: 0; - border-radius: 10px; + border: 1px solid transparent; + border-radius: 12px; background: transparent; color: rgb(255 255 255 / 0.75); font: inherit; @@ -180,7 +147,8 @@ } &.is-active { - background: rgb(255 255 255 / 0.1); + border-color: var(--remote-border); + background: var(--remote-surface); color: #fff; } @@ -232,7 +200,7 @@ min-width: 0; min-height: 0; margin: 0 auto; - padding: clamp(0.5rem, 3vh, 2.5rem) clamp(1.5rem, 4vw, 3.5rem) 0; + padding: 0 var(--remote-gutter); box-sizing: border-box; overflow: hidden; } @@ -276,7 +244,7 @@ flex: 1 1 auto; min-width: 0; max-width: 820px; - padding-top: clamp(0.5rem, 4vh, 3rem); + padding-top: 0; } .remote-title { @@ -306,10 +274,12 @@ .remote-chip { padding: 7px 15px; + border: 1px solid var(--remote-border); border-radius: 999px; background: var(--remote-chip); font-size: 0.95rem; color: #dfe3ea; + backdrop-filter: blur(12px); } .remote-overview { @@ -334,22 +304,27 @@ .remote-round { display: grid; place-items: center; - width: clamp(64px, 6vw, 86px); - height: clamp(64px, 6vw, 86px); + width: clamp(56px, 5vw, 72px); + height: clamp(56px, 5vw, 72px); padding: 0; - border: 0; + border: 1px solid var(--remote-border); border-radius: 50%; - background: var(--remote-panel); + background: var(--remote-surface); color: #fff; + backdrop-filter: blur(16px) saturate(150%); cursor: pointer; - transition: background-color 0.15s ease, transform 0.15s ease; + transition: + background-color 0.15s ease, + border-color 0.15s ease, + transform 0.15s ease; .material-symbols-rounded { font-size: clamp(1.5rem, 2vw, 2rem); } &:hover:not(:disabled) { - background: #1e222b; + border-color: rgb(255 255 255 / 0.18); + background: var(--remote-surface-hover); transform: scale(1.03); } @@ -359,17 +334,20 @@ } &.remote-round-primary { - width: clamp(74px, 7vw, 98px); - height: clamp(74px, 7vw, 98px); + width: clamp(68px, 6vw, 84px); + height: clamp(68px, 6vw, 84px); + border-color: transparent; background: var(--remote-accent); - box-shadow: 0 10px 24px rgb(0 0 0 / 0.3); + box-shadow: 0 10px 28px rgb(0 0 0 / 0.28); .material-symbols-rounded { - font-size: clamp(1.9rem, 2.6vw, 2.6rem); + font-size: clamp(1.8rem, 2.4vw, 2.4rem); } &:hover:not(:disabled) { - background: #8b70ff; + border-color: transparent; + background: var(--remote-accent); + filter: brightness(1.06); transform: scale(1.04); } } @@ -382,7 +360,7 @@ flex: 0 0 auto; align-items: center; gap: 22px; - padding: clamp(0.5rem, 1.5vh, 1rem) clamp(1.5rem, 4vw, 3.5rem) 0; + padding: 8px var(--remote-gutter) 0; box-sizing: border-box; .MuiSlider-root { @@ -432,11 +410,11 @@ align-items: center; justify-content: space-between; gap: 24px; - height: 72px; - padding: 0 clamp(1.5rem, 4vw, 3rem); + height: 68px; + padding: 0 var(--remote-gutter); box-sizing: border-box; - background: rgb(0 0 0 / 0.22); - border-top: 1px solid rgb(255 255 255 / 0.06); + background: transparent; + border-top: 0; } .remote-bottom-item { @@ -538,7 +516,7 @@ @media (max-height: 780px) { .remote-topbar { - height: 72px; + height: 52px; } .remote-title { @@ -562,17 +540,17 @@ } .remote-round { - width: 64px; - height: 64px; + width: 54px; + height: 54px; } .remote-round.remote-round-primary { - width: 78px; - height: 78px; + width: 66px; + height: 66px; } .remote-bottombar { - height: 64px; + height: 58px; } } @@ -586,7 +564,7 @@ } .remote-bottombar { - height: 90px; + height: 76px; gap: 16px; } @@ -597,10 +575,14 @@ @media (max-width: 820px) { .remote-topbar { - height: 72px; + height: 52px; padding: 0 16px; } + html.is-macos .remote-topbar { + padding-left: 76px; + } + .remote-hero { flex-direction: column; align-items: center; diff --git a/src/routes/_api/remote.tsx b/src/routes/_api/remote.tsx index 14597ae..bcd2209 100644 --- a/src/routes/_api/remote.tsx +++ b/src/routes/_api/remote.tsx @@ -12,6 +12,7 @@ import Tooltip from "@mui/material/Tooltip"; import { useQuery } from "@tanstack/react-query"; import { createFileRoute, useNavigate } from "@tanstack/react-router"; import React, { useEffect, useMemo, useRef, useState } from "react"; +import CachedImage from "@/components/cachedImage"; import { UserAvatarMenu } from "@/components/userAvatarMenu"; import WindowControls from "@/components/windowControls"; import { getRuntimeCompact } from "@/utils/date/time"; @@ -72,9 +73,10 @@ function RemotePage() { const [subtitleAnchor, setSubtitleAnchor] = useState( null, ); - const [qualityAnchor, setQualityAnchor] = useState(null); const [subtitleIndex, setSubtitleIndex] = useState(-1); const [volumeDraft, setVolumeDraft] = useState(null); + const [displayPosition, setDisplayPosition] = useState(0); + const [isSeeking, setIsSeeking] = useState(false); const volumeTimerRef = useRef | null>(null); const clearVolumeTimer = () => { @@ -176,10 +178,36 @@ function RemotePage() { const playState = selected?.PlayState; const isPaused = playState?.IsPaused ?? true; const duration = nowPlaying?.RunTimeTicks ?? 0; - const position = playState?.PositionTicks ?? 0; const volume = volumeDraft ?? (playState?.VolumeLevel ?? 100) / 100; const isMuted = playState?.IsMuted ?? false; + useEffect(() => { + setDisplayPosition(playState?.PositionTicks ?? 0); + setIsSeeking(false); + }, [selected?.Id]); + + // Session polling is slow, so keep the timeline moving locally between + // updates. Large jumps (another client seeking) still win. + useEffect(() => { + const serverPosition = playState?.PositionTicks; + if (serverPosition == null) return; + setDisplayPosition((current) => + Math.abs(serverPosition - current) > 2 * TICKS_PER_SECOND + ? serverPosition + : current, + ); + }, [playState?.PositionTicks]); + + useEffect(() => { + if (isPaused || isSeeking || duration <= 0) return; + const timer = window.setInterval(() => { + setDisplayPosition((current) => + Math.min(current + TICKS_PER_SECOND / 2, duration), + ); + }, 500); + return () => window.clearInterval(timer); + }, [isPaused, isSeeking, duration, selected?.Id]); + const coverUrl = useMemo(() => { if (!api || !nowPlaying) return undefined; const imageItemId = nowPlaying.AlbumId ?? nowPlaying.Id; @@ -228,9 +256,6 @@ function RemotePage() { channelLabel(audioStream?.Channels), ].filter(Boolean) as string[]; - const qualityLabel = videoStream?.Height - ? `${videoStream.Height}p` - : (nowPlaying?.MediaSources?.[0]?.Name ?? "Авто"); const subtitleLabel = subtitleIndex < 0 ? "Выкл." @@ -271,13 +296,6 @@ function RemotePage() { >
-
- - settings_remote - - Пульт -
-
{coverUrl ? ( - {title + ) : ( live_tv )} @@ -471,16 +489,23 @@ function RemotePage() {
- {formatTime(position)} + {formatTime(displayPosition)} { + const next = Array.isArray(value) ? value[0] : value; + setIsSeeking(true); + setDisplayPosition(next); + }} onChangeCommitted={(_, value) => { const next = Array.isArray(value) ? value[0] : value; + setIsSeeking(false); + setDisplayPosition(next); if (selected) { void command( selected, @@ -544,19 +569,6 @@ function RemotePage() { />
- -
diff --git a/src/styles/global.scss b/src/styles/global.scss index 7788e9f..c26b5c8 100644 --- a/src/styles/global.scss +++ b/src/styles/global.scss @@ -389,4 +389,18 @@ body.has-player-bar #root { a { color: $clr-accent-default; -} \ No newline at end of file +} + +/* TV / gamepad spatial navigation focus */ +[data-tv-focus="true"] { + outline: 2px solid var(--mui-palette-primary-main, #ff2d78) !important; + outline-offset: 3px; + border-radius: 8px; +} + +.card[data-tv-focus="true"] { + border-radius: 12px; + box-shadow: + 0 0 0 2px var(--mui-palette-primary-main, #ff2d78), + 0 12px 32px rgb(0 0 0 / 0.4); +} diff --git a/src/utils/cache/imageCache.ts b/src/utils/cache/imageCache.ts new file mode 100644 index 0000000..dda169e --- /dev/null +++ b/src/utils/cache/imageCache.ts @@ -0,0 +1,82 @@ +const CACHE_NAME = "blink-images-v1"; +const MAX_MEMORY_ENTRIES = 400; +const MAX_CACHE_ENTRIES = 800; + +const memory = new Map(); +const pending = new Map>(); +let cachePuts = 0; + +const remember = (src: string, objectUrl: string) => { + if (memory.size >= MAX_MEMORY_ENTRIES) { + const oldest = memory.keys().next().value; + if (oldest) { + const oldUrl = memory.get(oldest); + memory.delete(oldest); + if (oldUrl) URL.revokeObjectURL(oldUrl); + } + } + memory.set(src, objectUrl); +}; + +const trimCache = async (cache: Cache) => { + cachePuts += 1; + if (cachePuts % 50 !== 0) return; + const keys = await cache.keys(); + if (keys.length <= MAX_CACHE_ENTRIES) return; + for (const key of keys.slice(0, keys.length - MAX_CACHE_ENTRIES)) { + await cache.delete(key); + } +}; + +const cacheable = (src: string) => + src.startsWith("http://") || src.startsWith("https://"); + +/** + * Resolve an image through the WebView Cache API. The browser's HTTP cache + * only has `Cache-Control: public` for Jellyfin images (no max-age), so pages + * often refetch every poster. A named cache keeps decoded responses around. + */ +const loadImage = async (src: string): Promise => { + if (!cacheable(src)) return null; + try { + if ("caches" in window) { + const cache = await caches.open(CACHE_NAME); + let response = await cache.match(src); + if (!response) { + response = await fetch(src, { + mode: "cors", + credentials: "omit", + }); + if (!response.ok) return null; + await cache.put(src, response.clone()); + void trimCache(cache); + } + const blob = await response.blob(); + const objectUrl = URL.createObjectURL(blob); + remember(src, objectUrl); + return objectUrl; + } + + const response = await fetch(src, { + mode: "cors", + credentials: "omit", + }); + if (!response.ok) return null; + const blob = await response.blob(); + const objectUrl = URL.createObjectURL(blob); + remember(src, objectUrl); + return objectUrl; + } catch { + return null; + } +}; + +export const getCachedImageUrl = (src: string): Promise => { + const hit = memory.get(src); + if (hit) return Promise.resolve(hit); + const inFlight = pending.get(src); + if (inFlight) return inFlight; + const request = loadImage(src).finally(() => pending.delete(src)); + pending.set(src, request); + return request; +}; diff --git a/src/utils/constants/library.ts b/src/utils/constants/library.ts index a75593f..6d47433 100644 --- a/src/utils/constants/library.ts +++ b/src/utils/constants/library.ts @@ -92,7 +92,7 @@ export const SORT_BY_OPTIONS: Array<{ ], }, { - title: "Название трека", + title: "Название", value: ItemSortBy.Name, compatibleViewTypes: [ BaseItemKind.Audio, diff --git a/src/utils/queries/library.ts b/src/utils/queries/library.ts index 9a42e30..22b85cd 100644 --- a/src/utils/queries/library.ts +++ b/src/utils/queries/library.ts @@ -17,11 +17,23 @@ export const getLibraryQueryOptions = ( queryKey: ["library", "currentLib", id], queryFn: async () => { if (!api || !userId) throw Error("API or User ID is not defined"); - const result = await getLibraryApi(api).getItem({ - userId: userId, - itemId: id, - }); - return result.data; + try { + const result = await getLibraryApi(api).getItem({ + userId: userId, + itemId: id, + }); + return result.data; + } catch (error) { + // Jellyfin 12 no longer returns virtual library folders from + // /Items/{id}; resolve them from the media folder list instead. + if ((error as { response?: { status?: number } })?.response?.status !== 404) { + throw error; + } + const folders = await getLibraryApi(api).getMediaFolders(); + const folder = folders.data.Items?.find((item) => item.Id === id); + if (folder) return folder; + throw error; + } }, enabled: !!api && !!userId, }); diff --git a/src/utils/queries/libraryItems.ts b/src/utils/queries/libraryItems.ts index cb55544..f5135b3 100644 --- a/src/utils/queries/libraryItems.ts +++ b/src/utils/queries/libraryItems.ts @@ -174,5 +174,7 @@ export const getLibraryItemsQueryOptions = ( }, staleTime: 5_000, gcTime: 5 * 60_000, + retry: 1, + retryDelay: 500, }); };