feat: add gamepad navigation and music library improvements
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped

- 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
This commit is contained in:
1xDed committed 2026-12-01 04:24:56 +03:00
1 parent 04ab9f767b
commit 5f5803c9f8
24 files changed
+1199 -245

No files matched your search

+11
View File
@@ -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 ?? "Трек"}
>
<div className="album-track-index">
<span className="material-symbols-rounded album-track-play">
+50
View File
@@ -0,0 +1,50 @@
import React, { useEffect, useState } from "react";
import { getCachedImageUrl } from "@/utils/cache/imageCache";
type CachedImageProps = React.ImgHTMLAttributes<HTMLImageElement> & {
src?: string | null;
fallback?: React.ReactNode;
};
/**
* Drop-in `<img>` 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<string | null>(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 (
<img
{...props}
src={cachedSrc ?? src}
onError={(event) => {
setFailed(true);
onError?.(event);
}}
/>
);
};
export default CachedImage;
+21 -3
View File
@@ -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 ?? "Элемент"}
>
<div className={`card-image-container ${cardType}`}>
<ErrorBoundary fallback={<></>}>
@@ -107,8 +125,8 @@ const CardContent = ({
? getTypeIcon(overrideIcon)
: getTypeIcon(item.Type ?? "universal")}
</div>
{image && (
<img
{image && hasCover && (
<CachedImage
alt={item.Name ?? "blink"}
decoding="async"
src={
@@ -136,7 +154,7 @@ const CardContent = ({
/>
)}
{inView && !disableOverlay && (
<div className="card-overlay">
<div className="card-overlay" data-tv-ignore>
<PlayButton
item={item}
userId={userId}
+3 -2
View File
@@ -17,6 +17,7 @@ import {
getItemImagesQueryOptions,
resolveHeroArtwork,
} from "@/utils/methods/heroArtwork";
import CachedImage from "@/components/cachedImage";
import BlurhashCanvas from "../blurhash-canvas";
import { useApiInContext } from "@/utils/store/api";
@@ -97,7 +98,7 @@ const CarouselSlide = ({ item }: { item: BaseItemDto }) => {
/>
)}
{heroArtwork ? (
<img
<CachedImage
alt={item.Name ?? "item"}
className={`hero-carousel-background-image${heroArtwork.isPortrait ? " is-poster" : ""}`}
src={heroArtwork.url}
@@ -110,7 +111,7 @@ const CarouselSlide = ({ item }: { item: BaseItemDto }) => {
</div>
)}
{heroPoster && (
<img
<CachedImage
alt={item.Name ?? "poster"}
className="hero-carousel-poster"
src={heroPoster}
+3 -2
View File
@@ -22,6 +22,7 @@ import hdr10Icon from "@/assets/icons/hdr10.svg";
import hdr10PlusIcon from "@/assets/icons/hdr10-plus.svg";
import sdIcon from "@/assets/icons/sd.svg";
import sdrIcon from "@/assets/icons/sdr.svg";
import CachedImage from "@/components/cachedImage";
import ItemBackdrop from "@/components/itemBackdrop";
import { getTypeIcon } from "@/components/utils/iconsCollection";
import { endsAt, getRuntime } from "@/utils/date/time";
@@ -66,7 +67,7 @@ const ItemHeader = ({
isEpisode && parentLogoImageTag ? (item.SeriesId ?? item.Id) : item.Id;
const logo = logoTag ? (
<img
<CachedImage
alt={item.Name ?? ""}
src={
api &&
@@ -127,7 +128,7 @@ const ItemHeader = ({
}
className="item-hero-image-blurhash"
/>
<img
<CachedImage
alt={item.Name ?? ""}
src={
api &&
+103 -2
View File
@@ -1,22 +1,33 @@
import type { BaseItemKind } from "@jellyfin/sdk/lib/generated-client";
import { ItemSortBy, SortOrder } from "@jellyfin/sdk/lib/generated-client";
import {
BaseItemKind,
ItemSortBy,
SortOrder,
} from "@jellyfin/sdk/lib/generated-client";
import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api";
import {
AppBar,
Button,
Chip,
IconButton,
MenuItem,
TextField,
Tooltip,
Typography,
useScrollTrigger,
} from "@mui/material";
import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { useSnackbar } from "notistack";
import { getRouteApi, useNavigate } from "@tanstack/react-router";
import type { ChangeEvent } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useShallow } from "zustand/shallow";
import { AVAILABLE_VIEWS, SORT_BY_OPTIONS } from "@/utils/constants/library";
import { getLibraryQueryOptions } from "@/utils/queries/library";
import {
generateAudioStreamUrl,
playAudio,
} from "@/utils/store/audioPlayback";
import { setQueue } from "@/utils/store/queue";
// import removed: header reads name/count from Zustand slice
import { useLibraryStateStore } from "@/utils/store/libraryState";
import useSearchStore from "@/utils/store/search";
@@ -37,6 +48,8 @@ export const LibraryHeader = () => {
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 = () => {
</MenuItem>
))}
</TextField>
{isMusicSongs && (
<Tooltip title="Перемешать все композиции">
<Button
className="music-shuffle-button"
variant="contained"
size="small"
onClick={shuffleAllTracks}
disabled={shuffling}
startIcon={
<span className="material-symbols-rounded">shuffle</span>
}
sx={{
borderRadius: "999px",
textTransform: "none",
whiteSpace: "nowrap",
px: 2,
}}
>
<span className="music-shuffle-label">
{shuffling ? "Перемешиваем…" : "Перемешать"}
</span>
</Button>
</Tooltip>
)}
<IconButton
onClick={handleSortAscendingToggle}
aria-label="Изменить порядок сортировки"
@@ -51,3 +51,20 @@
}
}
.music-shuffle-button {
.material-symbols-rounded {
font-size: 1.15rem;
}
}
@media (max-width: 1200px) {
.music-shuffle-button .music-shuffle-label {
display: none;
}
.music-shuffle-button {
min-width: 0;
padding: 6px 10px;
}
}
+11
View File
@@ -23,6 +23,7 @@ import { useCentralStore } from "@/utils/store/central";
import { useLibraryStateStore } from "@/utils/store/libraryState";
import BackdropWorker from "@/utils/workers/backdrop.worker?worker";
import { Card } from "../card/card";
import MusicTracksList from "../musicTracksList";
const libraryRoute = getRouteApi("/_api/library/$id");
@@ -264,6 +265,16 @@ const LibraryItemsGrid = () => {
}
}, [items.data?.TotalRecordCount, currentLibraryId, updateLibrary]);
if (effectiveViewType === BaseItemKind.Audio) {
return (
<MusicTracksList
items={items.data?.Items ?? []}
userId={user?.Id}
queryKey={["library", "items", currentLibraryId]}
/>
);
}
return (
<div
ref={parentRef}
+62 -26
View File
@@ -1,11 +1,13 @@
import Typography from "@mui/material/Typography";
import React from "react";
import React, { useRef } from "react";
import { getRuntimeMusic } from "../../utils/date/time";
import { useAudioPlayback } from "../../utils/store/audioPlayback";
import LikeButton from "../buttons/likeButton";
import PlayButton from "../buttons/playButton";
import "./musicTrack.scss";
import CachedImage from "@/components/cachedImage";
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
import { resolveItemImage } from "@/utils/methods/itemImages";
import { useApiInContext } from "@/utils/store/api";
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client";
import { Link } from "@tanstack/react-router";
@@ -33,9 +35,45 @@ const MusicTrack = ({
}) => {
const api = useApiInContext((s) => s.api);
const [currentTrackItem] = useAudioPlayback((state) => [state.item]);
const rowRef = useRef<HTMLDivElement | null>(null);
const activate = () => {
rowRef.current
?.querySelector<HTMLElement>(".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 (
<div className={`music-track ${className}`}>
<div
ref={rowRef}
className={`music-track ${className}`}
onClick={(event) => {
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 ?? "Трек"}
>
<div className="music-track-image">
<div className="music-track-icon">
<span
@@ -45,22 +83,9 @@ const MusicTrack = ({
music_note
</span>
</div>
<img
<CachedImage
alt={item.Name ?? "Трек"}
src={
api &&
getImageUrlsApi(api).getItemImageUrlById(
(Object.keys(item.ImageTags ?? {}).length === 0
? item.AlbumId
: item.Id) ?? "",
"Primary",
{
quality: 70,
fillHeight: 128,
fillWidth: 128,
},
)
}
src={imageUrl}
style={{
width: "100%",
height: "100%",
@@ -71,7 +96,7 @@ const MusicTrack = ({
e.currentTarget.style.opacity = "1";
}}
/>
<div className="music-track-image-overlay">
<div className="music-track-image-overlay" data-tv-ignore>
<PlayButton
item={item}
itemType="Audio"
@@ -85,7 +110,7 @@ const MusicTrack = ({
/>
</div>
</div>
<div className="music-track-info">
<div className="music-track-info" data-tv-ignore>
<Typography
variant="subtitle1"
style={{
@@ -143,17 +168,28 @@ const MusicTrack = ({
</span>
))}
</div>
{item.Album && (
<Typography
variant="caption"
className="music-track-album"
noWrap
>
{item.Album}
</Typography>
)}
</div>
<Typography variant="subtitle1">
{getRuntimeMusic(item.RunTimeTicks ?? 0)}
</Typography>
<LikeButton
itemId={item.Id}
isFavorite={item.UserData?.IsFavorite}
queryKey={queryKey}
userId={userId}
itemName={item.Name}
/>
<div data-tv-ignore>
<LikeButton
itemId={item.Id}
isFavorite={item.UserData?.IsFavorite}
queryKey={queryKey}
userId={userId}
itemName={item.Name}
/>
</div>
</div>
);
};
+60 -33
View File
@@ -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 {
+93
View File
@@ -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<HTMLDivElement | null>(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 (
<div className="music-tracks-empty">
<span className="material-symbols-rounded">music_off</span>
<span>В этой библиотеке пока нет треков</span>
</div>
);
}
return (
<div className="music-tracks-list" ref={parentRef}>
<div className="music-tracks-head">
<span />
<span>Трек</span>
<span>Длительность</span>
<span />
</div>
<div
style={{
position: "relative",
height: virtualizer.getTotalSize(),
width: "100%",
}}
>
{virtualizer.getVirtualItems().map((row) => {
const item = items[row.index];
return (
<div
key={item.Id ?? row.key}
className="music-tracks-row"
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
transform: `translateY(${row.start - virtualizer.options.scrollMargin}px)`,
}}
>
<MusicTrack
item={item}
queryKey={queryKey}
userId={userId}
/>
</div>
);
})}
</div>
</div>
);
};
export default MusicTracksList;
@@ -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;
}
}
+391
View File
@@ -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<HTMLElement>(
".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<HTMLElement>(
".MuiDialog-root, .MuiMenu-root, .MuiPopover-root, .MuiDrawer-root",
);
if (activeScope) return activeScope;
}
const dialogs = Array.from(
document.querySelectorAll<HTMLElement>(".MuiDialog-root"),
).filter(isVisible);
if (dialogs.length > 0) return dialogs[dialogs.length - 1];
const menus = Array.from(
document.querySelectorAll<HTMLElement>(".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<HTMLElement>(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<HTMLElement>(
'[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<HTMLElement>(
"[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<HTMLElement>(
"[aria-label='Назад'], [aria-label='Выйти из плеера']",
);
if (back) back.click();
else window.history.back();
};
const openMenu = () => {
if (isVideoPlayer()) return;
const menu = document.querySelector<HTMLElement>(
"button[aria-label='Открыть меню']",
);
menu?.click();
};
const SpatialNavigation = () => {
const { enqueueSnackbar } = useSnackbar();
const heldDirection = useRef<Direction | null>(null);
const nextRepeatAt = useRef(0);
const previousButtons = useRef<boolean[]>([]);
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<HTMLElement>(
"[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<string, Direction> = {
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;
+1 -1
View File
@@ -11,7 +11,7 @@ export const getTypeIcon = (
case "Home":
return <div className="material-symbols-rounded">home</div>;
case BaseItemKind.Audio:
return <div className="material-symbols-rounded">mic</div>;
return <div className="material-symbols-rounded">music_note</div>;
case BaseItemKind.AudioBook:
return <div className="material-symbols-rounded">speech_to_text</div>;
case BaseItemKind.Book: