feat: localize UI and improve playback
Continuous Integration / build_web (push) Failing after 1s
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

- translate the interface into Russian
- add picture-in-picture and video fit modes
- derive skip segments from Jellyfin chapter markers
- align player navigation and add a window drag region
- keep audio playback alive across routes
This commit is contained in:
1xDed committed 2026-11-30 19:19:51 +03:00
1 parent 5784036eb1
commit d9bce4de04
100 files changed
+1364 -706

No files matched your search

@@ -43,9 +43,9 @@ const DeviceMenu = ({
return (
<>
<Tooltip title="Devices">
<Tooltip title="Устройства">
<IconButton
aria-label="Devices"
aria-label="Устройства"
onClick={(event) => setAnchor(event.currentTarget)}
>
<span className="material-symbols-rounded">devices</span>
@@ -68,16 +68,16 @@ const DeviceMenu = ({
<span className="material-symbols-rounded">computer</span>
</ListItemIcon>
<ListItemText
primary="This device"
primary="Это устройство"
secondary={
localActive ? (localItem?.Name ?? "Playing") : "Idle"
localActive ? (localItem?.Name ?? "Играет") : "Свободно"
}
/>
</MenuItem>
<Divider />
{sessions.length === 0 ? (
<MenuItem disabled>
<ListItemText primary="No other devices are online" />
<ListItemText primary="Другие устройства не в сети" />
</MenuItem>
) : (
sessions.map((session) => (
@@ -95,11 +95,11 @@ const DeviceMenu = ({
</span>
</ListItemIcon>
<ListItemText
primary={session.DeviceName || session.Client || "Device"}
primary={session.DeviceName || session.Client || "Устройство"}
secondary={
session.NowPlayingItem?.Name ??
session.Client ??
"Not playing"
"Ничего не играет"
}
/>
</MenuItem>
@@ -115,7 +115,7 @@ const DeviceMenu = ({
<ListItemIcon>
<span className="material-symbols-rounded">settings_remote</span>
</ListItemIcon>
<ListItemText primary="Remote control…" />
<ListItemText primary="Удалённое управление…" />
</MenuItem>
<Divider />
<MenuItem
@@ -129,11 +129,11 @@ const DeviceMenu = ({
<span className="material-symbols-rounded">sync</span>
</ListItemIcon>
<ListItemText
primary="Sync playback"
primary="Синхронизация воспроизведения"
secondary={
syncEnabled
? "Devices follow this session"
: "Keep devices in step"
? "Устройства следуют за этим сеансом"
: "Синхронизировать устройства"
}
/>
<Switch
@@ -60,7 +60,7 @@ const LyricsPanel = ({ item, api, currentTime, onSeek }: LyricsPanelProps) => {
if (lyrics.isLoading) {
return (
<div className="audio-lyrics-status">
<Typography>Loading lyrics...</Typography>
<Typography>Загрузка текста...</Typography>
</div>
);
}
@@ -68,7 +68,7 @@ const LyricsPanel = ({ item, api, currentTime, onSeek }: LyricsPanelProps) => {
if (lyrics.isError || !lyrics.data || !lyrics.data.Lyrics?.length) {
return (
<div className="audio-lyrics-status">
<Typography>No lyrics available</Typography>
<Typography>Текст недоступен</Typography>
</div>
);
}
@@ -119,7 +119,7 @@ const LyricsPanel = ({ item, api, currentTime, onSeek }: LyricsPanelProps) => {
{!hasSyncedLyrics && (
<div className="audio-lyrics-unsynced-notice">
<span className="material-symbols-rounded">info</span>
<Typography variant="caption">Synced lyrics not available</Typography>
<Typography variant="caption">Синхронизированный текст недоступен</Typography>
</div>
)}
</div>
@@ -42,13 +42,13 @@ const PlayerActions = ({
/>}
<QueueButton />
<div className="audio-player-volume">{children}</div>
<Tooltip title="Open player">
<IconButton onClick={onExpand} aria-label="Open player">
<Tooltip title="Открыть плеер">
<IconButton onClick={onExpand} aria-label="Открыть плеер">
<span className="material-symbols-rounded">open_in_full</span>
</IconButton>
</Tooltip>
<Tooltip title="Stop and close">
<IconButton onClick={onClose} aria-label="Stop and close">
<Tooltip title="Остановить и закрыть">
<IconButton onClick={onClose} aria-label="Остановить и закрыть">
<span className="material-symbols-rounded">close</span>
</IconButton>
</Tooltip>
@@ -36,7 +36,7 @@ const PlayerInfo = ({ item, api, onOpen }: PlayerInfoProps) => {
type="button"
className="audio-player-image-container"
onClick={onOpen}
aria-label="Open player"
aria-label="Открыть плеер"
>
<span className="material-symbols-rounded audio-player-image-icon">
music_note
@@ -56,7 +56,7 @@ const PlayerProgress = ({
max={duration}
onChange={handleChange}
onChangeCommitted={handleChangeCommitted}
aria-label="Seek"
aria-label="Перемотка"
/>
);
}
@@ -71,7 +71,7 @@ const PlayerProgress = ({
max={duration}
onChange={handleChange}
onChangeCommitted={handleChangeCommitted}
aria-label="Seek"
aria-label="Перемотка"
/>
<div className="player-progress-stacked-times">
<span>{getRuntimeMusic(sliderValue)}</span>
@@ -64,7 +64,7 @@ const StatsPanel: React.FC<StatsPanelProps> = ({ item, audioRef }) => {
return (
<Box sx={{ p: 2 }}>
<Typography variant="h6" sx={{ mb: 2 }}>
Stats for Nerds
Статистика
</Typography>
<Paper
@@ -78,11 +78,11 @@ const StatsPanel: React.FC<StatsPanelProps> = ({ item, audioRef }) => {
variant="subtitle2"
sx={{ mb: 1, opacity: 0.5, textTransform: "uppercase" }}
>
Media Source
Источник медиа
</Typography>
<StatRow label="Container" value={mediaSource?.Container} />
<StatRow label="Контейнер" value={mediaSource?.Container} />
<StatRow
label="Bitrate"
label="Битрейт"
value={
mediaSource?.Bitrate
? `${Math.round(mediaSource.Bitrate / 1000)} kbps`
@@ -90,34 +90,34 @@ const StatsPanel: React.FC<StatsPanelProps> = ({ item, audioRef }) => {
}
/>
<StatRow
label="Size"
label="Размер"
value={
mediaSource?.Size
? `${(mediaSource.Size / 1024 / 1024).toFixed(2)} MB`
: undefined
}
/>
<StatRow label="Path" value={mediaSource?.Path} />
<StatRow label="Путь" value={mediaSource?.Path} />
<Box sx={{ mt: 3 }}>
<Typography
variant="subtitle2"
sx={{ mb: 1, opacity: 0.5, textTransform: "uppercase" }}
>
Audio Stream
Аудиопоток
</Typography>
<StatRow label="Codec" value={mediaStream?.Codec} />
<StatRow label="Channels" value={mediaStream?.Channels} />
<StatRow label="Кодек" value={mediaStream?.Codec} />
<StatRow label="Каналы" value={mediaStream?.Channels} />
<StatRow
label="Sample Rate"
label="Частота дискретизации"
value={
mediaStream?.SampleRate
? `${mediaStream.SampleRate} Hz`
: undefined
}
/>
<StatRow label="Bit Depth" value={mediaStream?.BitDepth} />
<StatRow label="Language" value={mediaStream?.Language} />
<StatRow label="Глубина" value={mediaStream?.BitDepth} />
<StatRow label="Язык" value={mediaStream?.Language} />
</Box>
<Box sx={{ mt: 3 }}>
@@ -125,11 +125,11 @@ const StatsPanel: React.FC<StatsPanelProps> = ({ item, audioRef }) => {
variant="subtitle2"
sx={{ mb: 1, opacity: 0.5, textTransform: "uppercase" }}
>
Player
Плеер
</Typography>
<StatRow label="Buffered" value={buffered} />
<StatRow label="Буфер" value={buffered} />
<StatRow
label="Volume"
label="Громкость"
value={
audioRef?.current
? `${Math.round(audioRef.current.volume * 100)}%`
@@ -137,7 +137,7 @@ const StatsPanel: React.FC<StatsPanelProps> = ({ item, audioRef }) => {
}
/>
<StatRow
label="Playback Rate"
label="Скорость воспроизведения"
value={audioRef?.current?.playbackRate}
/>
</Box>
+71 -63
View File
@@ -139,12 +139,12 @@ const AudioPlayer = () => {
: (activeItem?.AlbumArtists ?? []);
const artistNames = artists.map((artist) => artist.Name).filter(Boolean);
const remoteDevice = remote
? remote.DeviceName || remote.Client || "another device"
? remote.DeviceName || remote.Client || "другое устройство"
: undefined;
const subtitle = remote
? artistNames.length > 0
? `${artistNames.join(", ")} · ${remoteDevice}`
: `Playing on ${remoteDevice}`
: `Идёт на ${remoteDevice}`
: artistNames.join(", ") || activeItem?.Album || "";
const coverUrl =
api && activeItem?.Id
@@ -231,9 +231,9 @@ const AudioPlayer = () => {
})
: undefined;
navigator.mediaSession.metadata = new MediaMetadata({
title: item.Name ?? "Unknown Title",
artist: item.Artists?.join(", ") ?? "Unknown Artist",
album: item.Album ?? "Unknown Album",
title: item.Name ?? "Неизвестное название",
artist: item.Artists?.join(", ") ?? "Неизвестный исполнитель",
album: item.Album ?? "Неизвестный альбом",
artwork: imageUrl
? [{ src: imageUrl, sizes: "512x512", type: "image/jpeg" }]
: [],
@@ -368,8 +368,8 @@ const AudioPlayer = () => {
});
await sessions.refetch();
} catch (error) {
console.error("Remote command failed", error);
enqueueSnackbar("Remote command failed", { variant: "error" });
console.error("Команда не выполнена", error);
enqueueSnackbar("Команда не выполнена", { variant: "error" });
}
};
@@ -385,7 +385,7 @@ const AudioPlayer = () => {
if (kind === "video") navigate({ to: "/player" });
} catch (error) {
console.error("Transfer failed", error);
enqueueSnackbar("Could not transfer playback", { variant: "error" });
enqueueSnackbar("Не удалось перенести воспроизведение", { variant: "error" });
}
};
@@ -432,8 +432,8 @@ const AudioPlayer = () => {
setSelectedRemoteId(session.Id);
await sessions.refetch();
} catch (error) {
console.error("Could not switch device", error);
enqueueSnackbar("Could not switch device", { variant: "error" });
console.error("Не удалось переключить устройство", error);
enqueueSnackbar("Не удалось переключить устройство", { variant: "error" });
}
};
@@ -462,7 +462,7 @@ const AudioPlayer = () => {
await sessions.refetch();
} catch (error) {
console.error("Remote general command failed", error);
enqueueSnackbar("Remote command failed", { variant: "error" });
enqueueSnackbar("Команда не выполнена", { variant: "error" });
}
};
@@ -512,13 +512,13 @@ const AudioPlayer = () => {
try {
const { count } = await startInstantMix(api, user.Id, activeItem);
if (count === 0) {
enqueueSnackbar("No tracks found for Instant Mix", {
enqueueSnackbar("Нет треков для микса", {
variant: "warning",
});
}
} catch (error) {
console.error(error);
enqueueSnackbar("Could not start Instant Mix", { variant: "error" });
enqueueSnackbar("Не удалось запустить микс", { variant: "error" });
}
};
@@ -534,11 +534,34 @@ const AudioPlayer = () => {
});
};
if (!barVisible || isFullPlayer) {
const audioElement = display ? (
<audio
autoPlay
src={url}
ref={audioRef}
key={item?.Id ?? "noItem"}
onTimeUpdate={handleTimeUpdate}
onEnded={handleEnded}
onPlay={onPlay}
onPause={onPause}
onSeeked={updatePositionState}
onLoadedMetadata={(event) => {
const player = event.currentTarget;
if (!seekAppliedRef.current && startTimeTicks > 0) {
seekAppliedRef.current = true;
player.currentTime = ticksToSec(startTimeTicks);
}
updatePositionState();
}}
id="audio-player"
/>
) : null;
if (!barVisible && !display) {
return null;
}
return (
const bar = (
<AnimatePresence mode="sync">
<motion.div
initial={{ transform: "translate(-50%, 150%)" }}
@@ -552,7 +575,7 @@ const AudioPlayer = () => {
type="button"
className="media-bar-cover"
onClick={handleNavigate}
aria-label="Open player"
aria-label="Открыть плеер"
>
{coverUrl ? (
<img src={coverUrl} alt="" />
@@ -567,7 +590,7 @@ const AudioPlayer = () => {
title={activeItem?.Name ?? undefined}
onClick={handleNavigate}
>
{activeItem?.Name ?? "Unknown"}
{activeItem?.Name ?? "Неизвестно"}
</Typography>
<Typography variant="caption" noWrap className="media-bar-subtitle">
{subtitle || "Blink"}
@@ -575,7 +598,7 @@ const AudioPlayer = () => {
</div>
<IconButton
size="small"
aria-label="More"
aria-label="Ещё"
className="media-bar-more"
onClick={handleMoreOpen}
>
@@ -585,7 +608,7 @@ const AudioPlayer = () => {
<div className="media-bar-center">
<div className="media-bar-controls">
<Tooltip title="Shuffle">
<Tooltip title="Перемешать">
<IconButton
size="small"
onClick={handleShuffle}
@@ -594,21 +617,21 @@ const AudioPlayer = () => {
<span className="material-symbols-rounded">shuffle</span>
</IconButton>
</Tooltip>
<Tooltip title="Previous">
<Tooltip title="Предыдущий">
<IconButton
size="small"
onClick={handlePrevious}
aria-label="Previous"
aria-label="Предыдущий"
>
<span className="material-symbols-rounded">
skip_previous
</span>
</IconButton>
</Tooltip>
<Tooltip title={isPlaying ? "Pause" : "Play"}>
<Tooltip title={isPlaying ? "Пауза" : "Слушать"}>
<IconButton
className="media-bar-play"
aria-label={isPlaying ? "Pause" : "Play"}
aria-label={isPlaying ? "Пауза" : "Слушать"}
onClick={() =>
remote
? remoteCommand(PlaystateCommand.PlayPause)
@@ -620,8 +643,8 @@ const AudioPlayer = () => {
</span>
</IconButton>
</Tooltip>
<Tooltip title="Next">
<IconButton size="small" onClick={handleNext} aria-label="Next">
<Tooltip title="Следующий">
<IconButton size="small" onClick={handleNext} aria-label="Следующий">
<span className="material-symbols-rounded">skip_next</span>
</IconButton>
</Tooltip>
@@ -629,15 +652,15 @@ const AudioPlayer = () => {
title={
remote
? remoteRepeat === "RepeatNone"
? "Repeat off"
? "Повтор выкл."
: remoteRepeat === "RepeatAll"
? "Repeat all"
: "Repeat one"
? "Повтор всех"
: "Повтор одного"
: repeatMode === "off"
? "Repeat off"
? "Повтор выкл."
: repeatMode === "all"
? "Repeat all"
: "Repeat one"
? "Повтор всех"
: "Повтор одного"
}
>
<IconButton
@@ -667,10 +690,10 @@ const AudioPlayer = () => {
<div className="media-bar-right">
{remote && (
<Tooltip title="Transfer to this device">
<Tooltip title="Перенести на это устройство">
<IconButton
size="small"
aria-label="Transfer to this device"
aria-label="Перенести на это устройство"
onClick={transferToLocal}
>
<span className="material-symbols-rounded">
@@ -680,7 +703,7 @@ const AudioPlayer = () => {
</Tooltip>
)}
{!remote && <QueueButton />}
<Tooltip title={remote ? (remoteMuted ? "Unmute" : "Mute") : (isMuted ? "Unmute" : "Mute")}>
<Tooltip title={remote ? (remoteMuted ? "Включить звук" : "Выключить звук") : (isMuted ? "Включить звук" : "Выключить звук")}>
<IconButton size="small" onClick={handleMute}>
<span className="material-symbols-rounded">
{remote
@@ -700,7 +723,7 @@ const AudioPlayer = () => {
min={0}
max={1}
step={0.01}
aria-label="Volume"
aria-label="Громкость"
onChange={(_, value) => {
const next = Array.isArray(value) ? value[0] : value;
if (remote) {
@@ -730,7 +753,7 @@ const AudioPlayer = () => {
canSync={canSync}
onToggleSync={toggleSync}
/>
<Tooltip title="Open player">
<Tooltip title="Открыть плеер">
<IconButton size="small" onClick={handleNavigate}>
<span className="material-symbols-rounded">open_in_full</span>
</IconButton>
@@ -747,7 +770,7 @@ const AudioPlayer = () => {
<ListItemIcon>
<span className="material-symbols-rounded">radio</span>
</ListItemIcon>
<ListItemText primary="Instant Mix" />
<ListItemText primary="Микс" />
</MenuItem>
{remote ? (
<MenuItem
@@ -761,14 +784,14 @@ const AudioPlayer = () => {
system_update_alt
</span>
</ListItemIcon>
<ListItemText primary="Transfer to this device" />
<ListItemText primary="Перенести на это устройство" />
</MenuItem>
) : (
<MenuItem onClick={openCastForLocal}>
<ListItemIcon>
<span className="material-symbols-rounded">cast</span>
</ListItemIcon>
<ListItemText primary="Play on another device…" />
<ListItemText primary="Воспроизвести на другом устройстве…" />
</MenuItem>
)}
<MenuItem
@@ -780,7 +803,7 @@ const AudioPlayer = () => {
<ListItemIcon>
<span className="material-symbols-rounded">settings_remote</span>
</ListItemIcon>
<ListItemText primary="Remote control…" />
<ListItemText primary="Удалённое управление…" />
</MenuItem>
<Divider />
<MenuItem
@@ -797,35 +820,20 @@ const AudioPlayer = () => {
<ListItemIcon>
<span className="material-symbols-rounded">stop</span>
</ListItemIcon>
<ListItemText primary="Stop" />
<ListItemText primary="Остановить" />
</MenuItem>
</Menu>
{display && (
<audio
autoPlay
src={url}
ref={audioRef}
key={item?.Id ?? "noItem"}
onTimeUpdate={handleTimeUpdate}
onEnded={handleEnded}
onPlay={onPlay}
onPause={onPause}
onSeeked={updatePositionState}
onLoadedMetadata={(event) => {
const player = event.currentTarget;
if (!seekAppliedRef.current && startTimeTicks > 0) {
seekAppliedRef.current = true;
player.currentTime = ticksToSec(startTimeTicks);
}
updatePositionState();
}}
id="audio-player"
/>
)}
</motion.div>
</AnimatePresence>
);
return (
<>
{audioElement}
{barVisible && !isFullPlayer && bar}
</>
);
};
export default AudioPlayer;
@@ -29,20 +29,20 @@ const ErrorDisplay = ({ error, onRetry, onExit }: ErrorDisplayProps) => {
}}
>
<Typography variant="h5" color="error">
Playback Error
Ошибка воспроизведения
</Typography>
<Typography variant="body1">
{error.message || "An unknown error occurred during playback."}
{error.message || "Во время воспроизведения произошла неизвестная ошибка."}
</Typography>
<div style={{ display: "flex", gap: "1rem" }}>
{onRetry && (
<Button variant="contained" color="primary" onClick={onRetry}>
Retry
Повторить
</Button>
)}
{onExit && (
<Button variant="outlined" color="secondary" onClick={onExit}>
Exit
Выйти
</Button>
)}
</div>
@@ -115,7 +115,7 @@ const StatsForNerds = ({ playerRef }: StatsForNerdsProps) => {
fontWeight: "bold",
}}
>
Stats for Nerds
Статистика
</Typography>
<IconButton
size="small"
@@ -138,29 +138,29 @@ const StatsForNerds = ({ playerRef }: StatsForNerdsProps) => {
gap: "0.5em 1em",
}}
>
<span>Video ID:</span> <span>{itemId}</span>
<span>Media Source ID:</span> <span>{mediaSourceId}</span>
<span>Play Session ID:</span> <span>{playsessionId}</span>
<span>Playback Method:</span> <span>{mediaSource.playMethod}</span>
<span>Container:</span> <span>{mediaSource.container}</span>
<span>Video Codec:</span> <span>{mediaSource.videoCodec}</span>
<span>Audio Codec:</span> <span>{mediaSource.audioCodec}</span>
<span>Bitrate:</span>{" "}
<span>ID видео:</span> <span>{itemId}</span>
<span>ID источника:</span> <span>{mediaSourceId}</span>
<span>ID сеанса:</span> <span>{playsessionId}</span>
<span>Метод воспроизведения:</span> <span>{mediaSource.playMethod}</span>
<span>Контейнер:</span> <span>{mediaSource.container}</span>
<span>Видеокодек:</span> <span>{mediaSource.videoCodec}</span>
<span>Аудиокодек:</span> <span>{mediaSource.audioCodec}</span>
<span>Битрейт:</span>{" "}
<span>
{mediaSource.bitrate
? `${(mediaSource.bitrate / 1000000).toFixed(2)} Mbps`
: "-"}
</span>
<span>Stream URL:</span>{" "}
<span>URL потока:</span>{" "}
<span style={{ wordBreak: "break-all" }}>{playbackStream}</span>
<span>Resolution:</span> <span>{videoStats.resolution}</span>
<span>Volume:</span> <span>{Math.round(volume * 100)}%</span>
<span>Buffer Health:</span> <span>{videoStats.buffered}</span>
<span>Dropped Frames:</span>{" "}
<span>Разрешение:</span> <span>{videoStats.resolution}</span>
<span>Громкость:</span> <span>{Math.round(volume * 100)}%</span>
<span>Буфер:</span> <span>{videoStats.buffered}</span>
<span>Пропущенные кадры:</span>{" "}
<span>
{videoStats.droppedFrames} / {videoStats.totalFrames}
</span>
<span>Is Buffering:</span> <span>{isBuffering ? "Yes" : "No"}</span>
<span>Буферизация:</span> <span>{isBuffering ? "Да" : "Нет"}</span>
</div>
</Paper>
);
@@ -0,0 +1,94 @@
import { IconButton, Tooltip } from "@mui/material";
import { useSnackbar } from "notistack";
import React, { useEffect, useState } from "react";
import {
getPlayerVideoElement,
isPictureInPictureActive,
supportsPictureInPicture,
togglePictureInPicture,
} from "@/utils/methods/pictureInPicture";
import { usePlaybackStore } from "@/utils/store/playback";
const PictureInPictureButton = () => {
const playsessionId = usePlaybackStore((state) => state.playsessionId);
const { enqueueSnackbar } = useSnackbar();
const [supported, setSupported] = useState(() => supportsPictureInPicture());
const [active, setActive] = useState(false);
const [busy, setBusy] = useState(false);
useEffect(() => {
const update = () => {
const currentVideo = getPlayerVideoElement();
if (currentVideo) {
setSupported(supportsPictureInPicture(currentVideo));
}
setActive(currentVideo ? isPictureInPictureActive(currentVideo) : false);
};
const video = getPlayerVideoElement();
if (video) {
setSupported(supportsPictureInPicture(video));
setActive(isPictureInPictureActive(video));
}
document.addEventListener("enterpictureinpicture", update, true);
document.addEventListener("leavepictureinpicture", update, true);
document.addEventListener("webkitpresentationmodechanged", update, true);
const interval = window.setInterval(update, 1000);
return () => {
window.clearInterval(interval);
document.removeEventListener("enterpictureinpicture", update, true);
document.removeEventListener("leavepictureinpicture", update, true);
document.removeEventListener(
"webkitpresentationmodechanged",
update,
true,
);
};
}, [playsessionId]);
if (!supported) return null;
const label = active ? "Выйти из картинки в картинке" : "Картинка в картинке";
const handleClick = async () => {
const video = getPlayerVideoElement();
if (!video) {
enqueueSnackbar("Видео ещё не готово", { variant: "info" });
return;
}
try {
setBusy(true);
await togglePictureInPicture(video);
setActive(isPictureInPictureActive(video));
} catch (error) {
console.error("Picture-in-picture failed", error);
enqueueSnackbar("Не удалось включить картинку в картинке", {
variant: "error",
});
} finally {
setBusy(false);
}
};
return (
<Tooltip title={label}>
<span>
<IconButton
onClick={handleClick}
disabled={busy}
aria-label={label}
title={label}
>
<span className="material-symbols-rounded fill">
{active ? "picture_in_picture" : "picture_in_picture_alt"}
</span>
</IconButton>
</span>
</Tooltip>
);
};
export default PictureInPictureButton;
@@ -35,7 +35,7 @@ const SkipSegmentButton = () => {
currentSegmentIndex >= 0 &&
activeSegmentId &&
(segmentType !== "Outro" || !hasNextItem);
const label = segmentType === "Outro" ? "Skip credits" : `Skip ${segmentType}`;
const label = segmentType === "Outro" ? "Пропустить титры" : segmentType === "Intro" ? "Пропустить интро" : segmentType === "Recap" ? "Пропустить рекап" : segmentType === "Commercial" ? "Пропустить рекламу" : segmentType === "Preview" ? "Пропустить превью" : "Пропустить";
return (
<AnimatePresence>
@@ -0,0 +1,93 @@
import {
IconButton,
ListItemIcon,
ListItemText,
Menu,
MenuItem,
Tooltip,
} from "@mui/material";
import React, { useState } from "react";
import type { VideoFitMode } from "@/utils/types/videoFitMode";
const OPTIONS: Array<{
value: VideoFitMode;
label: string;
icon: string;
hint: string;
}> = [
{
value: "fit",
label: "По размеру",
icon: "fit_screen",
hint: "Вписать видео целиком",
},
{
value: "fill",
label: "Заполнить экран",
icon: "zoom_out_map",
hint: "Убрать полосы, обрезав края",
},
{
value: "stretch",
label: "Растянуть",
icon: "aspect_ratio",
hint: "Растянуть на весь экран",
},
];
type VideoFitButtonProps = {
mode: VideoFitMode;
onChange: (mode: VideoFitMode) => void;
};
const VideoFitButton = ({ mode, onChange }: VideoFitButtonProps) => {
const [anchor, setAnchor] = useState<HTMLButtonElement | null>(null);
const current = OPTIONS.find((option) => option.value === mode) ?? OPTIONS[0];
return (
<>
<Tooltip title={`Режим изображения: ${current.label}`}>
<IconButton
onClick={(event) => setAnchor(event.currentTarget)}
aria-label="Режим изображения"
>
<span className="material-symbols-rounded">aspect_ratio</span>
</IconButton>
</Tooltip>
<Menu
anchorEl={anchor}
open={Boolean(anchor)}
onClose={() => setAnchor(null)}
anchorOrigin={{ vertical: "top", horizontal: "center" }}
transformOrigin={{ vertical: "bottom", horizontal: "center" }}
slotProps={{ paper: { className: "glass-menu-paper" } }}
>
{OPTIONS.map((option) => (
<MenuItem
key={option.value}
selected={option.value === mode}
onClick={() => {
onChange(option.value);
setAnchor(null);
}}
>
<ListItemIcon>
<span className="material-symbols-rounded">{option.icon}</span>
</ListItemIcon>
<ListItemText primary={option.label} secondary={option.hint} />
{option.value === mode && (
<span
className="material-symbols-rounded"
style={{ marginLeft: "1em" }}
>
check
</span>
)}
</MenuItem>
))}
</Menu>
</>
);
};
export default VideoFitButton;
@@ -1,10 +1,34 @@
.video-player {
--media-object-fit: contain;
background: black;
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
video {
object-fit: var(--media-object-fit);
}
&.video-fit-fill {
--media-object-fit: cover;
}
&.video-fit-stretch {
--media-object-fit: fill;
}
&-drag-region {
position: absolute;
inset: 0 0 auto;
height: 38px;
z-index: 4;
cursor: default;
user-select: none;
}
&-osd {
position: absolute;
width: 100vw;
@@ -27,6 +51,29 @@
&.hovering {
cursor: default;
}
&-back,
&-actions {
position: absolute;
top: 2em;
z-index: 3;
display: flex;
align-items: center;
padding: 0.3em;
border-radius: 999px;
border: 1px solid rgb(255 255 255 / 0.08);
background: rgb(0 0 0 / 0.28);
backdrop-filter: blur(12px);
}
&-back {
left: 3em;
}
&-actions {
right: 3em;
gap: 0.35em;
}
&-info {
margin-top: auto;
}
&-controls {
display: flex;
flex-direction: column;
+101 -12
View File
@@ -17,19 +17,23 @@ import QueueButton from "@/components/buttons/queueButton";
import BubbleSlider from "@/components/playback/videoPlayer/bubbleSlider";
import { secToTicks, ticksToSec } from "@/utils/date/time";
import { buildPlayDeepLink } from "@/utils/deepLinks";
import { getPlayerVideoElement } from "@/utils/methods/pictureInPicture";
import { openSyncPlayDialog } from "@/utils/methods/syncPlay";
import { useApiInContext } from "@/utils/store/api";
import { useShareStore } from "@/utils/store/share";
import { usePlaybackStore } from "@/utils/store/playback";
import useSyncPlayback from "@/utils/store/syncPlayback";
import type { VideoFitMode } from "@/utils/types/videoFitMode";
import CaptionsButton from "./buttons/CaptionsButton";
import ChaptersListButton from "./buttons/ChaptersListButton";
import ForwardButton from "./buttons/ForwardButton";
import FullscreenButton from "./buttons/FullscreenButton";
import NextChapterButton from "./buttons/NextChapterButton";
import PictureInPictureButton from "./buttons/PictureInPictureButton";
import PlayPauseButton from "./buttons/PlayPauseButton";
import PrevChapterButton from "./buttons/PrevChapterButton";
import RewindButton from "./buttons/RewindButton";
import VideoFitButton from "./buttons/VideoFitButton";
import EndsAtDisplay from "./EndsAtDisplay";
import VideoPlayerSettingsMenu from "./settingsMenu";
@@ -48,12 +52,16 @@ type VideoPlayerControlsProps = {
// isVisible: boolean;
onHover?: (event: MouseEvent<HTMLDivElement>) => void;
onLeave?: (event: MouseEvent<HTMLDivElement>) => void;
fitMode: VideoFitMode;
onFitModeChange: (mode: VideoFitMode) => void;
};
const VideoPlayerControls = ({
// isVisible,
onHover,
onLeave,
fitMode,
onFitModeChange,
}: VideoPlayerControlsProps) => {
const playerOSDRef = useRef<HTMLDivElement>(null);
@@ -145,6 +153,69 @@ const VideoPlayerControls = ({
const [settingsMenuRef, setSettingsMenuRef] =
useState<HTMLButtonElement | null>(null);
const [videoFrame, setVideoFrame] = useState<{
top: number;
left: number;
right: number;
} | null>(null);
// Keep the back button and the top action buttons on one line inside the
// visible video area, below any letterbox bars.
useEffect(() => {
let frame = 0;
const update = () => {
const video = getPlayerVideoElement();
if (!video) return;
const rect = video.getBoundingClientRect();
const ratio =
video.videoWidth > 0 && video.videoHeight > 0
? video.videoWidth / video.videoHeight
: null;
const contentWidth = ratio
? Math.min(rect.width, rect.height * ratio)
: rect.width;
const contentHeight = ratio ? contentWidth / ratio : rect.height;
const contentLeft = rect.left + (rect.width - contentWidth) / 2;
const contentTop = rect.top + (rect.height - contentHeight) / 2;
setVideoFrame((current) => {
const next = {
// 14% keeps the controls inside the picture even when the
// file has letterbox bars baked into a 16:9 frame.
top: Math.round(
contentTop + Math.max(28, contentHeight * 0.14),
),
left: Math.round(contentLeft + 24),
right: Math.round(
window.innerWidth - contentLeft - contentWidth + 24,
),
};
return current?.top === next.top &&
current?.left === next.left &&
current?.right === next.right
? current
: next;
});
};
const schedule = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(update);
};
schedule();
const video = getPlayerVideoElement();
video?.addEventListener("loadedmetadata", schedule);
window.addEventListener("resize", schedule);
const interval = window.setInterval(schedule, 1000);
return () => {
cancelAnimationFrame(frame);
window.clearInterval(interval);
video?.removeEventListener("loadedmetadata", schedule);
window.removeEventListener("resize", schedule);
};
}, [playsessionId]);
// const creditInfo = mediaSegments?.Items?.find(
// (segment) => segment.Type === "Outro",
@@ -229,14 +300,30 @@ const VideoPlayerControls = ({
}
}}
>
<div className="video-player-osd-header flex flex-justify-spaced-between flex-align-center">
<div
className="video-player-osd-back"
style={
videoFrame
? { top: videoFrame.top, left: videoFrame.left }
: undefined
}
>
<IconButton
onClick={handleExitPlayer}
aria-label="Exit player"
title="Exit player"
aria-label="Выйти из плеера"
title="Выйти из плеера"
>
<span className="material-symbols-rounded">arrow_back</span>
</IconButton>
</div>
<div
className="video-player-osd-actions"
style={
videoFrame
? { top: videoFrame.top, right: videoFrame.right }
: undefined
}
>
<IconButton
onClick={() =>
useShareStore
@@ -246,25 +333,25 @@ const VideoPlayerControls = ({
itemId ?? "",
currentTime > 0 ? ticksToSec(currentTime) : getCurrentTime(),
),
"Share this scene",
"Поделиться этой сценой",
)
}
aria-label="Share scene"
title="Share scene"
aria-label="Поделиться сценой"
title="Поделиться сценой"
>
<span className="material-symbols-rounded">share</span>
</IconButton>
<IconButton
onClick={openSyncPlayDialog}
aria-label="Watch together"
title="Watch together"
aria-label="Смотреть вместе"
title="Смотреть вместе"
>
<span className="material-symbols-rounded">groups</span>
</IconButton>
<IconButton
onClick={(e) => setSettingsMenuRef(e.currentTarget)}
aria-label="Player settings"
title="Player settings"
aria-label="Настройки плеера"
title="Настройки плеера"
>
<span className="material-symbols-rounded">settings</span>
</IconButton>
@@ -372,10 +459,10 @@ const VideoPlayerControls = ({
})}
/>
<Tooltip
title={syncThisVideo ? "Stop device sync" : "Sync playback"}
title={syncThisVideo ? "Остановить синхронизацию" : "Синхронизация воспроизведения"}
>
<IconButton
aria-label="Sync playback"
aria-label="Синхронизация воспроизведения"
onClick={toggleSync}
sx={
syncThisVideo
@@ -390,7 +477,9 @@ const VideoPlayerControls = ({
<ChaptersListButton />
<VideoFitButton mode={fitMode} onChange={onFitModeChange} />
<CaptionsButton />
<PictureInPictureButton />
<FullscreenButton />
</div>
</div>
@@ -156,7 +156,7 @@ const VideoPlayerSettingsMenu = ({
>
<TextField
select
label="Audio"
label="Аудио"
variant="outlined"
value={mediaSource.audio?.track}
onChange={handleAudioTrackChange}
@@ -171,7 +171,7 @@ const VideoPlayerSettingsMenu = ({
</TextField>
<TextField
select
label="Subtitles"
label="Субтитры"
variant="outlined"
value={mediaSource.subtitle?.track}
onChange={handleSubtitleChange}
@@ -179,7 +179,7 @@ const VideoPlayerSettingsMenu = ({
disabled={mediaSource.subtitle?.track === -2 || subtitleIsChanging}
>
<MenuItem key={-1} value={-1}>
No Subtitle
Без субтитров
</MenuItem>
{mediaSource.subtitle?.allTracks?.map((sub) => (
<MenuItem key={sub.Index} value={sub.Index}>
@@ -194,7 +194,7 @@ const VideoPlayerSettingsMenu = ({
flexGrow: 1,
}}
>
Stats for Nerds
Статистика
</Typography>
<Switch checked={showStatsForNerds} />
</MenuItem>
@@ -204,7 +204,7 @@ const VideoPlayerSettingsMenu = ({
flexGrow: 1,
}}
>
Sync playback
Синхронизация воспроизведения
</Typography>
<Switch
checked={syncForThisVideo}
@@ -219,7 +219,7 @@ const VideoPlayerSettingsMenu = ({
flexGrow: 1,
}}
>
Auto-skip intro &amp; recap
Автопропуск заставок, рекапов, рекламы и превью
</Typography>
<Switch
checked={autoSkip}
@@ -106,7 +106,7 @@ const UpNextFlyout = () => {
quality: 90,
fillWidth: 320,
})}
alt="next item thumbnail"
alt="Миниатюра следующего элемента"
style={{
width: "100%",
height: "100%",
@@ -142,7 +142,7 @@ const UpNextFlyout = () => {
letterSpacing: 1.2,
}}
>
UP NEXT
ДАЛЕЕ
</Typography>
<Typography
variant="h6"
@@ -192,7 +192,7 @@ const UpNextFlyout = () => {
flex: 1,
}}
>
Play Now
Смотреть
</Button>
<IconButton
onClick={() => setIsHidden(true)}