Files
Blink/src/components/playback/videoPlayer/controls.tsx
T
1xDed d9bce4de04
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
feat: localize UI and improve playback
- 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
2026-11-30 19:19:51 +03:00

493 lines
14 KiB
TypeScript

import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
import { IconButton, Slider, Tooltip, Typography } from "@mui/material";
import { WebviewWindow as appWindow } from "@tauri-apps/api/webviewWindow";
import { AnimatePresence, motion } from "motion/react";
import React, {
type MouseEvent,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { useShallow } from "zustand/shallow";
import CastButton from "@/components/buttons/castButton";
import PlayNextButton from "@/components/buttons/playNextButton";
import PlayPreviousButton from "@/components/buttons/playPreviousButtom";
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";
import "./controls.scss";
import { clearQueue } from "@/utils/store/queue";
import useQueue from "@/utils/store/queue";
import ProgressDisplay from "./ProgressDisplay";
/**
* Constant for the volume change interval when using the mouse wheel.
* This value determines how much the volume will change with each scroll step.
*/
const VOLUME_SCROLL_INTERVAL = 0.02;
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);
const api = useApiInContext((state) => state.api);
const syncEnabled = useSyncPlayback((state) => state.enabled);
const syncMaster = useSyncPlayback((state) => state.master);
const startSync = useSyncPlayback((state) => state.start);
const stopSync = useSyncPlayback((state) => state.stop);
const syncThisVideo = syncEnabled && syncMaster?.sessionId === null;
const toggleSync = () => {
if (syncThisVideo) {
stopSync();
return;
}
if (itemId) startSync({ itemId, sessionId: null });
};
const {
mediaSourceId,
itemId,
item,
itemName,
episodeTitle,
playsessionId,
isPlayerPlaying,
toggleIsPlaying,
toggleIsPlayerFullscreen,
isUserSeeking,
// seekValue,
isPlayerMuted,
volume,
setVolume,
toggleIsPlayerMuted,
increaseVolumeByStep,
decreaseVolumeByStep,
getCurrentTime,
isUserHovering,
currentTime,
} = usePlaybackStore(
useShallow((state) => ({
mediaSourceId: state.mediaSource.id,
itemChapters: state.metadata.item.Chapters,
itemId: state.metadata.item.Id,
item: state.metadata.item,
itemName: state.metadata.itemName,
episodeTitle: state.metadata.episodeTitle,
// mediaSegments: state.metadata.mediaSegments,
isPlayerPlaying: state.playerState.isPlayerPlaying,
playsessionId: state.playsessionId,
toggleIsPlaying: state.toggleIsPlaying,
toggleIsPlayerFullscreen: state.toggleIsPlayerFullscreen,
isUserSeeking: state.playerState.isUserSeeking,
seekValue: state.playerState.seekValue,
isPlayerMuted: state.playerState.isPlayerMuted,
volume: state.playerState.volume,
setVolume: state.setVolume,
toggleIsPlayerMuted: state.toggleIsPlayerMuted,
increaseVolumeByStep: state.increaseVolumeByStep,
decreaseVolumeByStep: state.decreaseVolumeByStep,
getCurrentTime: state.getCurrentTime,
isUserHovering: state.playerState.isUserHovering,
currentTime: state.playerState.currentTime,
})),
);
// Volume control with mouse wheel
useEffect(() => {
const handleMouseWheel = (event: WheelEvent) => {
if (event.deltaY < 0) {
increaseVolumeByStep(VOLUME_SCROLL_INTERVAL);
} else if (event.deltaY > 0) {
decreaseVolumeByStep(VOLUME_SCROLL_INTERVAL);
}
};
const currentRef = playerOSDRef.current;
// attach the event listener
currentRef?.addEventListener("wheel", handleMouseWheel);
// remove the event listener
return () => {
currentRef?.removeEventListener("wheel", handleMouseWheel);
};
}, [increaseVolumeByStep, decreaseVolumeByStep]);
const [clickTimeout, setClickTimeout] = useState<ReturnType<
typeof setTimeout
> | null>(null);
const [showVolumeControl, setShowVolumeControl] = useState(false);
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",
// );
// Credits and Next Episode Card
// const [forceShowCredits, setForceShowCredits] = useState(false);
// const showUpNextCard = useMemo(() => {
// if (queue?.[currentQueueItemIndex]?.Id === queue?.[queue.length - 1]?.Id) {
// return false; // Check if the current playing episode is last episode in queue
// }
// if (creditInfo) {
// if (
// currentTime >= (creditInfo.StartTicks ?? currentTime + 1) &&
// currentTime < (creditInfo.EndTicks ?? 0)
// )
// return true;
// }
// if (
// Math.ceil(ticksToSec(itemDuration) - ticksToSec(currentTime)) <= 30 &&
// Math.ceil(ticksToSec(itemDuration) - ticksToSec(currentTime)) > 0
// ) {
// return true;
// }
// return false;
// }, [currentTime, creditInfo, itemDuration, queue, currentQueueItemIndex]);
const handleExitPlayer = useCallback(async () => {
appWindow.getCurrent().setFullscreen(false);
history.back();
if (!api) {
throw Error("API is not available, cannot report playback stopped.");
}
// Report Jellyfin server: Playback has ended/stopped
getSessionApi(api).reportPlaybackStopped({
playbackStopInfo: {
Failed: false,
ItemId: itemId,
MediaSourceId: mediaSourceId,
PlaySessionId: playsessionId,
PositionTicks: secToTicks(getCurrentTime() ?? 0),
},
});
usePlaybackStore.setState(usePlaybackStore.getInitialState());
clearQueue();
}, [api, mediaSourceId, playsessionId, itemId]);
return (
<motion.div
className={
isUserHovering || isUserSeeking || !isPlayerPlaying
? "video-player-osd hovering"
: "video-player-osd"
}
onMouseEnter={onHover}
onMouseLeave={onLeave}
ref={playerOSDRef}
initial={{
opacity: 0,
}}
animate={{
opacity: isUserHovering || isUserSeeking || !isPlayerPlaying ? 1 : 0,
}}
style={{
zIndex: 2,
}}
onClick={(event) => {
if (event.currentTarget !== event.target) {
return;
}
if (event.detail === 1) {
setClickTimeout(
setTimeout(() => {
toggleIsPlaying();
}, 200),
);
} else if (event.detail === 2 && clickTimeout) {
clearTimeout(clickTimeout);
toggleIsPlayerFullscreen();
}
}}
>
<div
className="video-player-osd-back"
style={
videoFrame
? { top: videoFrame.top, left: videoFrame.left }
: undefined
}
>
<IconButton
onClick={handleExitPlayer}
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
.getState()
.openShareDialog(
buildPlayDeepLink(
itemId ?? "",
currentTime > 0 ? ticksToSec(currentTime) : getCurrentTime(),
),
"Поделиться этой сценой",
)
}
aria-label="Поделиться сценой"
title="Поделиться сценой"
>
<span className="material-symbols-rounded">share</span>
</IconButton>
<IconButton
onClick={openSyncPlayDialog}
aria-label="Смотреть вместе"
title="Смотреть вместе"
>
<span className="material-symbols-rounded">groups</span>
</IconButton>
<IconButton
onClick={(e) => setSettingsMenuRef(e.currentTarget)}
aria-label="Настройки плеера"
title="Настройки плеера"
>
<span className="material-symbols-rounded">settings</span>
</IconButton>
<VideoPlayerSettingsMenu
settingsMenuRef={settingsMenuRef}
handleClose={() => setSettingsMenuRef(null)}
/>
</div>
<div className="video-player-osd-info">
<div>
<Typography
variant="h4"
sx={{
fontWeight: 500,
mb: 2,
}}
>
{String(itemName)}
</Typography>
{episodeTitle && (
<Typography
variant="h6"
sx={{
fontWeight: 300,
mt: 1,
}}
>
{String(episodeTitle)}
</Typography>
)}
</div>
<div className="video-player-osd-controls">
<div className="video-player-osd-controls-timeline">
<BubbleSlider />
<ProgressDisplay />
</div>
<div className="flex flex-row flex-justify-spaced-between">
<div className="video-player-osd-controls-buttons">
<PlayPreviousButton />
<RewindButton />
<PrevChapterButton />
<PlayPauseButton />
<NextChapterButton />
<ForwardButton />
<PlayNextButton />
<EndsAtDisplay />
</div>
<div
className="video-player-osd-controls-buttons"
onMouseLeave={() => setShowVolumeControl(false)}
>
<AnimatePresence>
{showVolumeControl && (
<motion.div
initial={{ width: 0, opacity: 0, marginRight: 0 }}
animate={{ width: 100, opacity: 1, marginRight: 10 }}
exit={{ width: 0, opacity: 0, marginRight: 0 }}
style={{
overflow: "hidden",
display: "flex",
alignItems: "center",
}}
>
<Slider
size="small"
value={isPlayerMuted ? 0 : volume}
max={1}
step={0.01}
onChange={(_, newValue) => {
const val = Array.isArray(newValue)
? newValue[0]
: newValue;
setVolume(val);
}}
sx={{ width: 100, color: "white" }}
/>
</motion.div>
)}
</AnimatePresence>
<IconButton
onClick={toggleIsPlayerMuted}
onMouseEnter={() => setShowVolumeControl(true)}
>
<span className="material-symbols-rounded">
{isPlayerMuted
? "volume_off"
: volume < 0.4
? "volume_down"
: "volume_up"}
</span>
</IconButton>
<CastButton
item={item}
getTransfer={() => ({
kind: "video",
positionTicks: secToTicks(
usePlaybackStore.getState().getCurrentTime(),
),
queue: useQueue.getState().tracks ?? [],
startIndex: useQueue.getState().currentItemIndex,
})}
/>
<Tooltip
title={syncThisVideo ? "Остановить синхронизацию" : "Синхронизация воспроизведения"}
>
<IconButton
aria-label="Синхронизация воспроизведения"
onClick={toggleSync}
sx={
syncThisVideo
? { color: "var(--mui-palette-primary-main)" }
: undefined
}
>
<span className="material-symbols-rounded">sync</span>
</IconButton>
</Tooltip>
<QueueButton />
<ChaptersListButton />
<VideoFitButton mode={fitMode} onChange={onFitModeChange} />
<CaptionsButton />
<PictureInPictureButton />
<FullscreenButton />
</div>
</div>
</div>
</div>
</motion.div>
);
};
export default VideoPlayerControls;