1"use client";
2
3import {
4 AlertTriangleIcon,
5 CaptionsOffIcon,
6 CheckIcon,
7 DownloadIcon,
8 FastForwardIcon,
9 Loader2Icon,
10 Maximize2Icon,
11 Minimize2Icon,
12 PauseIcon,
13 PictureInPicture2Icon,
14 PictureInPictureIcon,
15 PlayIcon,
16 RefreshCcwIcon,
17 RepeatIcon,
18 RewindIcon,
19 RotateCcwIcon,
20 SettingsIcon,
21 SubtitlesIcon,
22 Volume1Icon,
23 Volume2Icon,
24 VolumeXIcon,
25} from "lucide-react";
26import {
27 MediaActionTypes,
28 MediaProvider,
29 timeUtils,
30 useMediaDispatch,
31 useMediaFullscreenRef,
32 useMediaRef,
33 useMediaSelector,
34} from "media-chrome/react/media-store";
35import {
36 Direction as DirectionPrimitive,
37 Slider as SliderPrimitive,
38 Slot as SlotPrimitive,
39} from "radix-ui";
40import * as React from "react";
41import * as ReactDOM from "react-dom";
42import { useComposedRefs } from "@/lib/compose-refs";
43import { cn } from "@/lib/utils";
44import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
45import { Badge } from "@/registry/bases/radix/ui/badge";
46import { Button } from "@/registry/bases/radix/ui/button";
47import {
48 DropdownMenu,
49 DropdownMenuContent,
50 DropdownMenuItem,
51 DropdownMenuLabel,
52 DropdownMenuSub,
53 DropdownMenuSubContent,
54 DropdownMenuSubTrigger,
55 DropdownMenuTrigger,
56} from "@/registry/bases/radix/ui/dropdown-menu";
57import {
58 Tooltip,
59 TooltipContent,
60 TooltipTrigger,
61} from "@/registry/bases/radix/ui/tooltip";
62
63const ROOT_NAME = "MediaPlayer";
64const SEEK_NAME = "MediaPlayerSeek";
65const SETTINGS_NAME = "MediaPlayerSettings";
66const VOLUME_NAME = "MediaPlayerVolume";
67const PLAYBACK_SPEED_NAME = "MediaPlayerPlaybackSpeed";
68
69const FLOATING_MENU_SIDE_OFFSET = 10;
70const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
71
72const SEEK_STEP_SHORT = 5;
73const SEEK_STEP_LONG = 10;
74const SEEK_COLLISION_PADDING = 10;
75const SEEK_TOOLTIP_WIDTH_FALLBACK = 240;
76
77const SEEK_HOVER_PERCENT = "--seek-hover-percent";
78const SEEK_TOOLTIP_X = "--seek-tooltip-x";
79const SEEK_TOOLTIP_Y = "--seek-tooltip-y";
80
81const SPRITE_CONTAINER_WIDTH = 224;
82const SPRITE_CONTAINER_HEIGHT = 128;
83
84interface DivProps extends React.ComponentProps<"div"> {
85 asChild?: boolean;
86}
87
88type RootElement = React.ComponentRef<typeof MediaPlayer>;
89
90type Direction = "ltr" | "rtl";
91
92interface StoreState {
93 controlsVisible: boolean;
94 dragging: boolean;
95 menuOpen: boolean;
96 volumeIndicatorVisible: boolean;
97}
98
99interface Store {
100 subscribe: (cb: () => void) => () => void;
101 getState: () => StoreState;
102 setState: (
103 key: keyof StoreState,
104 value: StoreState[keyof StoreState],
105 ) => void;
106 notify: () => void;
107}
108
109const StoreContext = React.createContext<Store | null>(null);
110
111function useStoreContext(consumerName: string) {
112 const context = React.useContext(StoreContext);
113 if (!context) {
114 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
115 }
116 return context;
117}
118
119function useStore<T>(selector: (state: StoreState) => T): T {
120 const store = useStoreContext("useStore");
121
122 const getSnapshot = React.useCallback(
123 () => selector(store.getState()),
124 [store, selector],
125 );
126
127 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
128}
129
130interface MediaPlayerContextValue {
131 mediaId: string;
132 labelId: string;
133 descriptionId: string;
134 dir: Direction;
135 rootRef: React.RefObject<RootElement | null>;
136 mediaRef: React.RefObject<HTMLVideoElement | HTMLAudioElement | null>;
137 portalContainer: Element | DocumentFragment | null;
138 tooltipDelayDuration: number;
139 tooltipSideOffset: number;
140 disabled: boolean;
141 isVideo: boolean;
142 withoutTooltip: boolean;
143}
144
145const MediaPlayerContext = React.createContext<MediaPlayerContextValue | null>(
146 null,
147);
148
149function useMediaPlayerContext(consumerName: string) {
150 const context = React.useContext(MediaPlayerContext);
151 if (!context) {
152 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
153 }
154 return context;
155}
156
157interface MediaPlayerProps
158 extends Omit<DivProps, "onTimeUpdate" | "onVolumeChange"> {
159 onPlay?: () => void;
160 onPause?: () => void;
161 onEnded?: () => void;
162 onTimeUpdate?: (time: number) => void;
163 onVolumeChange?: (volume: number) => void;
164 onMuted?: (muted: boolean) => void;
165 onMediaError?: (error: MediaError | null) => void;
166 onPipError?: (error: unknown, state: "enter" | "exit") => void;
167 onFullscreenChange?: (fullscreen: boolean) => void;
168 dir?: Direction;
169 label?: string;
170 tooltipDelayDuration?: number;
171 tooltipSideOffset?: number;
172 autoHide?: boolean;
173 disabled?: boolean;
174 withoutTooltip?: boolean;
175}
176
177function MediaPlayer(props: MediaPlayerProps) {
178 const listenersRef = useLazyRef(() => new Set<() => void>());
179 const stateRef = useLazyRef<StoreState>(() => ({
180 controlsVisible: true,
181 dragging: false,
182 menuOpen: false,
183 volumeIndicatorVisible: false,
184 }));
185
186 const store: Store = React.useMemo(() => {
187 return {
188 subscribe: (cb) => {
189 listenersRef.current.add(cb);
190 return () => listenersRef.current.delete(cb);
191 },
192 getState: () => stateRef.current,
193 setState: (key, value) => {
194 if (Object.is(stateRef.current[key], value)) return;
195 stateRef.current[key] = value;
196 store.notify();
197 },
198 notify: () => {
199 for (const cb of listenersRef.current) {
200 cb();
201 }
202 },
203 };
204 }, [listenersRef, stateRef]);
205
206 return (
207 <MediaProvider>
208 <StoreContext.Provider value={store}>
209 <MediaPlayerImpl {...props} />
210 </StoreContext.Provider>
211 </MediaProvider>
212 );
213}
214
215function MediaPlayerImpl(props: MediaPlayerProps) {
216 const {
217 onPlay,
218 onPause,
219 onEnded,
220 onTimeUpdate,
221 onFullscreenChange,
222 onVolumeChange,
223 onMuted,
224 onMediaError,
225 onPipError,
226 dir: dirProp,
227 label,
228 tooltipDelayDuration = 600,
229 tooltipSideOffset = FLOATING_MENU_SIDE_OFFSET,
230 asChild,
231 autoHide = false,
232 disabled = false,
233 withoutTooltip = false,
234 children,
235 className,
236 ref,
237 ...rootImplProps
238 } = props;
239
240 const mediaId = React.useId();
241 const labelId = React.useId();
242 const descriptionId = React.useId();
243
244 const rootRef = React.useRef<RootElement | null>(null);
245 const fullscreenRef = useMediaFullscreenRef();
246 const composedRef = useComposedRefs(ref, rootRef, fullscreenRef);
247
248 const dir = DirectionPrimitive.useDirection(dirProp);
249 const dispatch = useMediaDispatch();
250 const mediaRef = React.useRef<HTMLVideoElement | HTMLAudioElement | null>(
251 null,
252 );
253
254 const store = useStoreContext(ROOT_NAME);
255
256 const controlsVisible = useStore((state) => state.controlsVisible);
257 const dragging = useStore((state) => state.dragging);
258 const menuOpen = useStore((state) => state.menuOpen);
259
260 const hideControlsTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
261 const lastMouseMoveRef = React.useRef<number>(Date.now());
262 const volumeIndicatorTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
263
264 const mediaPaused = useMediaSelector((state) => state.mediaPaused ?? true);
265 const isFullscreen = useMediaSelector(
266 (state) => state.mediaIsFullscreen ?? false,
267 );
268
269 const [mounted, setMounted] = React.useState(false);
270 React.useLayoutEffect(() => {
271 setMounted(true);
272 }, []);
273
274 const portalContainer = mounted
275 ? isFullscreen
276 ? rootRef.current
277 : globalThis.document.body
278 : null;
279
280 const isVideo =
281 (typeof HTMLVideoElement !== "undefined" &&
282 mediaRef.current instanceof HTMLVideoElement) ||
283 mediaRef.current?.tagName?.toLowerCase() === "mux-player";
284
285 const onControlsShow = React.useCallback(() => {
286 store.setState("controlsVisible", true);
287 lastMouseMoveRef.current = Date.now();
288
289 if (hideControlsTimeoutRef.current) {
290 clearTimeout(hideControlsTimeoutRef.current);
291 }
292
293 if (autoHide && !mediaPaused && !menuOpen && !dragging) {
294 hideControlsTimeoutRef.current = setTimeout(() => {
295 store.setState("controlsVisible", false);
296 }, 3000);
297 }
298 }, [store.setState, autoHide, mediaPaused, menuOpen, dragging]);
299
300 const onVolumeIndicatorTrigger = React.useCallback(() => {
301 if (menuOpen) return;
302
303 store.setState("volumeIndicatorVisible", true);
304
305 if (volumeIndicatorTimeoutRef.current) {
306 clearTimeout(volumeIndicatorTimeoutRef.current);
307 }
308
309 volumeIndicatorTimeoutRef.current = setTimeout(() => {
310 store.setState("volumeIndicatorVisible", false);
311 }, 2000);
312
313 if (autoHide) {
314 onControlsShow();
315 }
316 }, [store.setState, menuOpen, autoHide, onControlsShow]);
317
318 const onMouseLeave = React.useCallback(
319 (event: React.MouseEvent<RootElement>) => {
320 rootImplProps.onMouseLeave?.(event);
321
322 if (event.defaultPrevented) return;
323
324 if (autoHide && !mediaPaused && !menuOpen && !dragging) {
325 store.setState("controlsVisible", false);
326 }
327 },
328 [
329 store.setState,
330 rootImplProps.onMouseLeave,
331 autoHide,
332 mediaPaused,
333 menuOpen,
334 dragging,
335 ],
336 );
337
338 const onMouseMove = React.useCallback(
339 (event: React.MouseEvent<RootElement>) => {
340 rootImplProps.onMouseMove?.(event);
341
342 if (event.defaultPrevented) return;
343
344 if (autoHide) {
345 onControlsShow();
346 }
347 },
348 [autoHide, rootImplProps.onMouseMove, onControlsShow],
349 );
350
351 React.useEffect(() => {
352 if (mediaPaused || menuOpen || dragging) {
353 store.setState("controlsVisible", true);
354 if (hideControlsTimeoutRef.current) {
355 clearTimeout(hideControlsTimeoutRef.current);
356 }
357 return;
358 }
359
360 if (autoHide) {
361 onControlsShow();
362 }
363 }, [
364 store.setState,
365 onControlsShow,
366 autoHide,
367 menuOpen,
368 mediaPaused,
369 dragging,
370 ]);
371
372 const onKeyDown = React.useCallback(
373 (event: React.KeyboardEvent<RootElement>) => {
374 if (disabled) return;
375
376 rootImplProps.onKeyDown?.(event);
377
378 if (event.defaultPrevented) return;
379
380 const mediaElement = mediaRef.current;
381 if (!mediaElement) return;
382
383 const isMediaFocused = document.activeElement === mediaElement;
384 const isPlayerFocused =
385 document.activeElement?.closest('[data-slot="media-player"]') !== null;
386
387 if (!isMediaFocused && !isPlayerFocused) return;
388
389 if (autoHide) onControlsShow();
390
391 switch (event.key.toLowerCase()) {
392 case " ":
393 case "k":
394 event.preventDefault();
395 dispatch({
396 type: mediaElement.paused
397 ? MediaActionTypes.MEDIA_PLAY_REQUEST
398 : MediaActionTypes.MEDIA_PAUSE_REQUEST,
399 });
400 break;
401
402 case "f":
403 event.preventDefault();
404 dispatch({
405 type: document.fullscreenElement
406 ? MediaActionTypes.MEDIA_EXIT_FULLSCREEN_REQUEST
407 : MediaActionTypes.MEDIA_ENTER_FULLSCREEN_REQUEST,
408 });
409 break;
410
411 case "m": {
412 event.preventDefault();
413 if (isVideo) {
414 onVolumeIndicatorTrigger();
415 }
416 dispatch({
417 type: mediaElement.muted
418 ? MediaActionTypes.MEDIA_UNMUTE_REQUEST
419 : MediaActionTypes.MEDIA_MUTE_REQUEST,
420 });
421 break;
422 }
423
424 case "arrowright":
425 event.preventDefault();
426 if (
427 isVideo ||
428 (mediaElement instanceof HTMLAudioElement && event.shiftKey)
429 ) {
430 dispatch({
431 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
432 detail: Math.min(
433 mediaElement.duration,
434 mediaElement.currentTime + SEEK_STEP_SHORT,
435 ),
436 });
437 }
438 break;
439
440 case "arrowleft":
441 event.preventDefault();
442 if (
443 isVideo ||
444 (mediaElement instanceof HTMLAudioElement && event.shiftKey)
445 ) {
446 dispatch({
447 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
448 detail: Math.max(0, mediaElement.currentTime - SEEK_STEP_SHORT),
449 });
450 }
451 break;
452
453 case "arrowup":
454 event.preventDefault();
455 if (isVideo) {
456 onVolumeIndicatorTrigger();
457 dispatch({
458 type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
459 detail: Math.min(1, mediaElement.volume + 0.1),
460 });
461 }
462 break;
463
464 case "arrowdown":
465 event.preventDefault();
466 if (isVideo) {
467 onVolumeIndicatorTrigger();
468 dispatch({
469 type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
470 detail: Math.max(0, mediaElement.volume - 0.1),
471 });
472 }
473 break;
474
475 case "<": {
476 event.preventDefault();
477 const currentRate = mediaElement.playbackRate;
478 const currentIndex = SPEEDS.indexOf(currentRate);
479 const newIndex = Math.max(0, currentIndex - 1);
480 const newRate = SPEEDS[newIndex] ?? 1;
481 dispatch({
482 type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
483 detail: newRate,
484 });
485 break;
486 }
487
488 case ">": {
489 event.preventDefault();
490 const currentRate = mediaElement.playbackRate;
491 const currentIndex = SPEEDS.indexOf(currentRate);
492 const newIndex = Math.min(SPEEDS.length - 1, currentIndex + 1);
493 const newRate = SPEEDS[newIndex] ?? 1;
494 dispatch({
495 type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
496 detail: newRate,
497 });
498 break;
499 }
500
501 case "c":
502 event.preventDefault();
503 if (isVideo && mediaElement.textTracks.length > 0) {
504 dispatch({
505 type: MediaActionTypes.MEDIA_TOGGLE_SUBTITLES_REQUEST,
506 });
507 }
508 break;
509
510 case "d": {
511 const hasDownload = mediaElement.querySelector(
512 '[data-slot="media-player-download"]',
513 );
514
515 if (!hasDownload) break;
516
517 event.preventDefault();
518 if (mediaElement.currentSrc) {
519 const link = document.createElement("a");
520 link.href = mediaElement.currentSrc;
521 link.download = "";
522 document.body.appendChild(link);
523 link.click();
524 document.body.removeChild(link);
525 }
526 break;
527 }
528
529 case "p": {
530 event.preventDefault();
531 if (isVideo && "requestPictureInPicture" in mediaElement) {
532 const isPip = document.pictureInPictureElement === mediaElement;
533 dispatch({
534 type: isPip
535 ? MediaActionTypes.MEDIA_EXIT_PIP_REQUEST
536 : MediaActionTypes.MEDIA_ENTER_PIP_REQUEST,
537 });
538 if (isPip) {
539 document.exitPictureInPicture().catch((error) => {
540 onPipError?.(error, "exit");
541 });
542 } else {
543 mediaElement.requestPictureInPicture().catch((error) => {
544 onPipError?.(error, "enter");
545 });
546 }
547 }
548 break;
549 }
550
551 case "r": {
552 event.preventDefault();
553 mediaElement.loop = !mediaElement.loop;
554 break;
555 }
556
557 case "j": {
558 event.preventDefault();
559 dispatch({
560 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
561 detail: Math.max(0, mediaElement.currentTime - SEEK_STEP_LONG),
562 });
563 break;
564 }
565
566 case "l": {
567 event.preventDefault();
568 dispatch({
569 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
570 detail: Math.min(
571 mediaElement.duration,
572 mediaElement.currentTime + SEEK_STEP_LONG,
573 ),
574 });
575 break;
576 }
577
578 case "0":
579 case "1":
580 case "2":
581 case "3":
582 case "4":
583 case "5":
584 case "6":
585 case "7":
586 case "8":
587 case "9": {
588 event.preventDefault();
589 const percent = Number.parseInt(event.key, 10) / 10;
590 const seekTime = mediaElement.duration * percent;
591 dispatch({
592 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
593 detail: seekTime,
594 });
595 break;
596 }
597
598 case "home": {
599 event.preventDefault();
600 dispatch({
601 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
602 detail: 0,
603 });
604 break;
605 }
606
607 case "end": {
608 event.preventDefault();
609 dispatch({
610 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
611 detail: mediaElement.duration,
612 });
613 break;
614 }
615 }
616 },
617 [
618 dispatch,
619 rootImplProps.onKeyDown,
620 onVolumeIndicatorTrigger,
621 onPipError,
622 disabled,
623 isVideo,
624 onControlsShow,
625 autoHide,
626 ],
627 );
628
629 const onKeyUp = React.useCallback(
630 (event: React.KeyboardEvent<RootElement>) => {
631 rootImplProps.onKeyUp?.(event);
632
633 const key = event.key.toLowerCase();
634 if (key === "arrowup" || key === "arrowdown" || key === "m") {
635 onVolumeIndicatorTrigger();
636 }
637 },
638 [rootImplProps.onKeyUp, onVolumeIndicatorTrigger],
639 );
640
641 React.useEffect(() => {
642 const mediaElement = mediaRef.current;
643 if (!mediaElement) return;
644
645 if (onPlay) mediaElement.addEventListener("play", onPlay);
646 if (onPause) mediaElement.addEventListener("pause", onPause);
647 if (onEnded) mediaElement.addEventListener("ended", onEnded);
648 if (onTimeUpdate)
649 mediaElement.addEventListener("timeupdate", () =>
650 onTimeUpdate?.(mediaElement.currentTime),
651 );
652 if (onVolumeChange)
653 mediaElement.addEventListener("volumechange", () => {
654 onVolumeChange?.(mediaElement.volume);
655 onMuted?.(mediaElement.muted);
656 });
657 if (onMediaError)
658 mediaElement.addEventListener("error", () =>
659 onMediaError?.(mediaElement.error),
660 );
661 if (onFullscreenChange) {
662 document.addEventListener("fullscreenchange", () =>
663 onFullscreenChange?.(!!document.fullscreenElement),
664 );
665 }
666
667 return () => {
668 if (onPlay) mediaElement.removeEventListener("play", onPlay);
669 if (onPause) mediaElement.removeEventListener("pause", onPause);
670 if (onEnded) mediaElement.removeEventListener("ended", onEnded);
671 if (onTimeUpdate)
672 mediaElement.removeEventListener("timeupdate", () =>
673 onTimeUpdate?.(mediaElement.currentTime),
674 );
675 if (onVolumeChange)
676 mediaElement.removeEventListener("volumechange", () => {
677 onVolumeChange?.(mediaElement.volume);
678 onMuted?.(mediaElement.muted);
679 });
680 if (onMediaError)
681 mediaElement.removeEventListener("error", () =>
682 onMediaError?.(mediaElement.error),
683 );
684 if (onFullscreenChange) {
685 document.removeEventListener("fullscreenchange", () =>
686 onFullscreenChange?.(!!document.fullscreenElement),
687 );
688 }
689 if (volumeIndicatorTimeoutRef.current) {
690 clearTimeout(volumeIndicatorTimeoutRef.current);
691 }
692 if (hideControlsTimeoutRef.current) {
693 clearTimeout(hideControlsTimeoutRef.current);
694 }
695 };
696 }, [
697 onPlay,
698 onPause,
699 onEnded,
700 onTimeUpdate,
701 onVolumeChange,
702 onMuted,
703 onMediaError,
704 onFullscreenChange,
705 ]);
706
707 const contextValue = React.useMemo<MediaPlayerContextValue>(
708 () => ({
709 mediaId,
710 labelId,
711 descriptionId,
712 dir,
713 rootRef,
714 mediaRef,
715 portalContainer,
716 tooltipDelayDuration,
717 tooltipSideOffset,
718 disabled,
719 isVideo,
720 withoutTooltip,
721 }),
722 [
723 mediaId,
724 labelId,
725 descriptionId,
726 dir,
727 portalContainer,
728 tooltipDelayDuration,
729 tooltipSideOffset,
730 disabled,
731 isVideo,
732 withoutTooltip,
733 ],
734 );
735
736 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
737
738 return (
739 <MediaPlayerContext.Provider value={contextValue}>
740 <RootPrimitive
741 aria-labelledby={labelId}
742 aria-describedby={descriptionId}
743 aria-disabled={disabled}
744 data-disabled={disabled ? "" : undefined}
745 data-controls-visible={controlsVisible ? "" : undefined}
746 data-slot="media-player"
747 data-state={isFullscreen ? "fullscreen" : "windowed"}
748 dir={dir}
749 tabIndex={disabled ? undefined : 0}
750 {...rootImplProps}
751 ref={composedRef}
752 onMouseLeave={onMouseLeave}
753 onMouseMove={onMouseMove}
754 onKeyDown={onKeyDown}
755 onKeyUp={onKeyUp}
756 className={cn(
757 "dark relative isolate flex flex-col overflow-hidden rounded-lg bg-background outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-disabled:pointer-events-none data-disabled:opacity-50 [&_video]:relative [&_video]:object-contain",
758 "in-[:fullscreen]:flex in-[:fullscreen]:h-full in-[:fullscreen]:max-h-screen in-[:fullscreen]:flex-col in-[:fullscreen]:justify-between data-[state=fullscreen]:[&_video]:size-full",
759 "**:data-slider:relative [&_[data-slider]::before]:absolute [&_[data-slider]::before]:inset-x-0 [&_[data-slider]::before]:-top-4 [&_[data-slider]::before]:-bottom-2 [&_[data-slider]::before]:z-10 [&_[data-slider]::before]:h-8 [&_[data-slider]::before]:cursor-pointer [&_[data-slider]::before]:content-[''] [&_[data-slot='media-player-seek']:not([data-hovering])::before]:cursor-default",
760 "[&_video::-webkit-media-text-track-display]:top-auto! [&_video::-webkit-media-text-track-display]:bottom-[4%]! [&_video::-webkit-media-text-track-display]:mb-0! data-[state=fullscreen]:data-controls-visible:[&_video::-webkit-media-text-track-display]:bottom-[9%]! data-[state=fullscreen]:[&_video::-webkit-media-text-track-display]:bottom-[7%]! data-controls-visible:[&_video::-webkit-media-text-track-display]:bottom-[13%]!",
761 className,
762 )}
763 >
764 <span id={labelId} className="sr-only">
765 {label ?? "Media player"}
766 </span>
767 <span id={descriptionId} className="sr-only">
768 {isVideo
769 ? "Video player with custom controls for playback, volume, seeking, and more. Use space bar to play/pause, arrow keys (←/→) to seek, and arrow keys (↑/↓) to adjust volume."
770 : "Audio player with custom controls for playback, volume, seeking, and more. Use space bar to play/pause, Shift + arrow keys (←/→) to seek, and arrow keys (↑/↓) to adjust volume."}
771 </span>
772 {children}
773 <MediaPlayerVolumeIndicator />
774 </RootPrimitive>
775 </MediaPlayerContext.Provider>
776 );
777}
778
779interface MediaPlayerVideoProps extends React.ComponentProps<"video"> {
780 asChild?: boolean;
781}
782
783function MediaPlayerVideo(props: MediaPlayerVideoProps) {
784 const { asChild, ref, ...videoProps } = props;
785
786 const context = useMediaPlayerContext("MediaPlayerVideo");
787 const dispatch = useMediaDispatch();
788 const mediaRefCallback = useMediaRef();
789 const composedRef = useComposedRefs(ref, context.mediaRef, mediaRefCallback);
790
791 const onPlayToggle = React.useCallback(
792 (event: React.MouseEvent<HTMLVideoElement>) => {
793 props.onClick?.(event);
794
795 if (event.defaultPrevented) return;
796
797 const mediaElement = event.currentTarget;
798 if (!mediaElement) return;
799
800 dispatch({
801 type: mediaElement.paused
802 ? MediaActionTypes.MEDIA_PLAY_REQUEST
803 : MediaActionTypes.MEDIA_PAUSE_REQUEST,
804 });
805 },
806 [dispatch, props.onClick],
807 );
808
809 const VideoPrimitive = asChild ? SlotPrimitive.Slot : "video";
810
811 return (
812 <VideoPrimitive
813 aria-describedby={context.descriptionId}
814 aria-labelledby={context.labelId}
815 data-slot="media-player-video"
816 {...videoProps}
817 id={context.mediaId}
818 ref={composedRef}
819 onClick={onPlayToggle}
820 />
821 );
822}
823
824interface MediaPlayerAudioProps extends React.ComponentProps<"audio"> {
825 asChild?: boolean;
826}
827
828function MediaPlayerAudio(props: MediaPlayerAudioProps) {
829 const { asChild, ref, ...audioProps } = props;
830
831 const context = useMediaPlayerContext("MediaPlayerAudio");
832 const mediaRefCallback = useMediaRef();
833 const composedRef = useComposedRefs(ref, context.mediaRef, mediaRefCallback);
834
835 const AudioPrimitive = asChild ? SlotPrimitive.Slot : "audio";
836
837 return (
838 <AudioPrimitive
839 aria-describedby={context.descriptionId}
840 aria-labelledby={context.labelId}
841 data-slot="media-player-audio"
842 {...audioProps}
843 id={context.mediaId}
844 ref={composedRef}
845 />
846 );
847}
848
849function MediaPlayerControls(props: DivProps) {
850 const { asChild, className, ...controlsProps } = props;
851
852 const context = useMediaPlayerContext("MediaPlayerControls");
853 const isFullscreen = useMediaSelector(
854 (state) => state.mediaIsFullscreen ?? false,
855 );
856 const controlsVisible = useStore((state) => state.controlsVisible);
857
858 const ControlsPrimitive = asChild ? SlotPrimitive.Slot : "div";
859
860 return (
861 <ControlsPrimitive
862 data-disabled={context.disabled ? "" : undefined}
863 data-slot="media-player-controls"
864 data-state={isFullscreen ? "fullscreen" : "windowed"}
865 data-visible={controlsVisible ? "" : undefined}
866 dir={context.dir}
867 className={cn(
868 "dark pointer-events-none absolute right-0 bottom-0 left-0 z-50 flex items-center gap-2 in-[:fullscreen]:px-6 px-4 in-[:fullscreen]:py-4 py-3 opacity-0 transition-opacity duration-200 data-visible:pointer-events-auto data-visible:opacity-100",
869 className,
870 )}
871 {...controlsProps}
872 />
873 );
874}
875
876interface MediaPlayerLoadingProps extends DivProps {
877 delayMs?: number;
878}
879
880function MediaPlayerLoading(props: MediaPlayerLoadingProps) {
881 const {
882 delayMs = 500,
883 asChild,
884 className,
885 children,
886 ...loadingProps
887 } = props;
888
889 const isLoading = useMediaSelector((state) => state.mediaLoading ?? false);
890 const isPaused = useMediaSelector((state) => state.mediaPaused ?? true);
891 const hasPlayed = useMediaSelector((state) => state.mediaHasPlayed ?? false);
892
893 const shouldShowLoading = isLoading && !isPaused;
894 const shouldUseDelay = hasPlayed && shouldShowLoading;
895 const loadingDelayMs = shouldUseDelay ? delayMs : 0;
896
897 const [shouldRender, setShouldRender] = React.useState(false);
898 const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);
899
900 React.useEffect(() => {
901 if (timeoutRef.current) {
902 clearTimeout(timeoutRef.current);
903 timeoutRef.current = null;
904 }
905
906 if (shouldShowLoading) {
907 if (loadingDelayMs > 0) {
908 timeoutRef.current = setTimeout(() => {
909 setShouldRender(true);
910 timeoutRef.current = null;
911 }, loadingDelayMs);
912 } else {
913 setShouldRender(true);
914 }
915 } else {
916 setShouldRender(false);
917 }
918
919 return () => {
920 if (timeoutRef.current) {
921 clearTimeout(timeoutRef.current);
922 timeoutRef.current = null;
923 }
924 };
925 }, [shouldShowLoading, loadingDelayMs]);
926
927 if (!shouldRender) return null;
928
929 const LoadingPrimitive = asChild ? SlotPrimitive.Slot : "div";
930
931 return (
932 <LoadingPrimitive
933 role="status"
934 aria-live="polite"
935 data-slot="media-player-loading"
936 {...loadingProps}
937 className={cn(
938 "fade-in-0 zoom-in-95 pointer-events-none absolute inset-0 z-50 flex animate-in items-center justify-center duration-200",
939 className,
940 )}
941 >
942 {children ?? (
943 <Loader2Icon className="size-20 animate-spin stroke-[.0938rem] text-primary" />
944 )}
945 </LoadingPrimitive>
946 );
947}
948
949interface MediaPlayerErrorProps extends DivProps {
950 error?: MediaError | null;
951 label?: string;
952 description?: string;
953 onRetry?: () => void;
954 onReload?: () => void;
955 asChild?: boolean;
956}
957
958function MediaPlayerError(props: MediaPlayerErrorProps) {
959 const {
960 error: errorProp,
961 label,
962 description,
963 onRetry: onRetryProp,
964 onReload: onReloadProp,
965 asChild,
966 className,
967 children,
968 ...errorProps
969 } = props;
970
971 const context = useMediaPlayerContext("MediaPlayerError");
972 const isFullscreen = useMediaSelector(
973 (state) => state.mediaIsFullscreen ?? false,
974 );
975 const mediaError = useMediaSelector((state) => state.mediaError);
976
977 const error = errorProp ?? mediaError;
978
979 const labelId = React.useId();
980 const descriptionId = React.useId();
981
982 const [actionState, setActionState] = React.useState<{
983 retryPending: boolean;
984 reloadPending: boolean;
985 }>({
986 retryPending: false,
987 reloadPending: false,
988 });
989
990 const onRetry = React.useCallback(() => {
991 setActionState((prev) => ({ ...prev, retryPending: true }));
992
993 requestAnimationFrame(() => {
994 const mediaElement = context.mediaRef.current;
995 if (!mediaElement) {
996 setActionState((prev) => ({ ...prev, retryPending: false }));
997 return;
998 }
999
1000 if (onRetryProp) {
1001 onRetryProp();
1002 } else {
1003 const currentSrc = mediaElement.currentSrc ?? mediaElement.src;
1004 if (currentSrc) {
1005 mediaElement.load();
1006 }
1007 }
1008
1009 setActionState((prev) => ({ ...prev, retryPending: false }));
1010 });
1011 }, [context.mediaRef, onRetryProp]);
1012
1013 const onReload = React.useCallback(() => {
1014 setActionState((prev) => ({ ...prev, reloadPending: true }));
1015
1016 requestAnimationFrame(() => {
1017 if (onReloadProp) {
1018 onReloadProp();
1019 } else {
1020 window.location.reload();
1021 }
1022 });
1023 }, [onReloadProp]);
1024
1025 const errorLabel = React.useMemo(() => {
1026 if (label) return label;
1027
1028 if (!error) return "Playback Error";
1029
1030 const labelMap: Record<number, string> = {
1031 [MediaError.MEDIA_ERR_ABORTED]: "Playback Interrupted",
1032 [MediaError.MEDIA_ERR_NETWORK]: "Connection Problem",
1033 [MediaError.MEDIA_ERR_DECODE]: "Media Error",
1034 [MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED]: "Unsupported Format",
1035 };
1036
1037 return labelMap[error.code] ?? "Playback Error";
1038 }, [label, error]);
1039
1040 const errorDescription = React.useMemo(() => {
1041 if (description) return description;
1042
1043 if (!error) return "An unknown error occurred";
1044
1045 const descriptionMap: Record<number, string> = {
1046 [MediaError.MEDIA_ERR_ABORTED]: "Media playback was aborted",
1047 [MediaError.MEDIA_ERR_NETWORK]:
1048 "A network error occurred while loading the media",
1049 [MediaError.MEDIA_ERR_DECODE]:
1050 "An error occurred while decoding the media",
1051 [MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED]:
1052 "The media format is not supported",
1053 };
1054
1055 return descriptionMap[error.code] ?? "An unknown error occurred";
1056 }, [description, error]);
1057
1058 if (!error) return null;
1059
1060 const ErrorPrimitive = asChild ? SlotPrimitive.Slot : "div";
1061
1062 return (
1063 <ErrorPrimitive
1064 role="alert"
1065 aria-describedby={descriptionId}
1066 aria-labelledby={labelId}
1067 aria-live="assertive"
1068 data-slot="media-player-error"
1069 data-state={isFullscreen ? "fullscreen" : "windowed"}
1070 {...errorProps}
1071 className={cn(
1072 "pointer-events-auto absolute inset-0 z-50 flex flex-col items-center justify-center bg-black/80 text-white backdrop-blur-sm",
1073 className,
1074 )}
1075 >
1076 {children ?? (
1077 <div className="flex max-w-md flex-col items-center gap-4 px-6 py-8 text-center">
1078 <AlertTriangleIcon className="size-12 text-destructive" />
1079 <div className="flex flex-col gap-px text-center">
1080 <h3 className="font-semibold text-xl tracking-tight">
1081 {errorLabel}
1082 </h3>
1083 <p className="text-balance text-muted-foreground text-sm leading-relaxed">
1084 {errorDescription}
1085 </p>
1086 </div>
1087 <div className="flex items-center gap-2">
1088 <Button
1089 variant="secondary"
1090 size="sm"
1091 onClick={onRetry}
1092 disabled={actionState.retryPending}
1093 >
1094 {actionState.retryPending ? (
1095 <Loader2Icon className="animate-spin" />
1096 ) : (
1097 <RefreshCcwIcon />
1098 )}
1099 Try again
1100 </Button>
1101 <Button
1102 variant="outline"
1103 size="sm"
1104 onClick={onReload}
1105 disabled={actionState.reloadPending}
1106 >
1107 {actionState.reloadPending ? (
1108 <Loader2Icon className="animate-spin" />
1109 ) : (
1110 <RotateCcwIcon />
1111 )}
1112 Reload page
1113 </Button>
1114 </div>
1115 </div>
1116 )}
1117 </ErrorPrimitive>
1118 );
1119}
1120
1121function MediaPlayerVolumeIndicator(props: DivProps) {
1122 const { asChild, className, ...indicatorProps } = props;
1123
1124 const mediaVolume = useMediaSelector((state) => state.mediaVolume ?? 1);
1125 const mediaMuted = useMediaSelector((state) => state.mediaMuted ?? false);
1126 const mediaVolumeLevel = useMediaSelector(
1127 (state) => state.mediaVolumeLevel ?? "high",
1128 );
1129 const volumeIndicatorVisible = useStore(
1130 (state) => state.volumeIndicatorVisible,
1131 );
1132
1133 if (!volumeIndicatorVisible) return null;
1134
1135 const effectiveVolume = mediaMuted ? 0 : mediaVolume;
1136 const volumePercentage = Math.round(effectiveVolume * 100);
1137 const barCount = 10;
1138 const activeBarCount = Math.ceil(effectiveVolume * barCount);
1139
1140 const VolumeIndicatorPrimitive = asChild ? SlotPrimitive.Slot : "div";
1141
1142 return (
1143 <VolumeIndicatorPrimitive
1144 role="status"
1145 aria-live="polite"
1146 aria-label={`Volume ${mediaMuted ? "muted" : `${volumePercentage}%`}`}
1147 data-slot="media-player-volume-indicator"
1148 {...indicatorProps}
1149 className={cn(
1150 "pointer-events-none absolute inset-0 z-50 flex items-center justify-center",
1151 className,
1152 )}
1153 >
1154 <div className="fade-in-0 zoom-in-95 flex animate-in flex-col items-center gap-3 rounded-lg bg-black/30 px-6 py-4 text-white backdrop-blur-xs duration-200">
1155 <div className="flex items-center gap-2">
1156 {mediaVolumeLevel === "off" || mediaMuted ? (
1157 <VolumeXIcon className="size-6" />
1158 ) : mediaVolumeLevel === "high" ? (
1159 <Volume2Icon className="size-6" />
1160 ) : (
1161 <Volume1Icon className="size-6" />
1162 )}
1163 <span className="font-medium text-sm tabular-nums">
1164 {mediaMuted ? "Muted" : `${volumePercentage}%`}
1165 </span>
1166 </div>
1167 <div className="flex items-center gap-1">
1168 {Array.from({ length: barCount }, (_, index) => (
1169 <div
1170 key={index}
1171 className={cn(
1172 "w-1.5 rounded-full transition-all duration-150",
1173 index < activeBarCount && !mediaMuted
1174 ? "scale-100 bg-white"
1175 : "scale-90 bg-white/30",
1176 )}
1177 style={{
1178 height: `${12 + index * 2}px`,
1179 animationDelay: `${index * 50}ms`,
1180 }}
1181 />
1182 ))}
1183 </div>
1184 </div>
1185 </VolumeIndicatorPrimitive>
1186 );
1187}
1188
1189function MediaPlayerControlsOverlay(props: DivProps) {
1190 const { asChild, className, ...overlayProps } = props;
1191
1192 const isFullscreen = useMediaSelector(
1193 (state) => state.mediaIsFullscreen ?? false,
1194 );
1195 const controlsVisible = useStore((state) => state.controlsVisible);
1196
1197 const OverlayPrimitive = asChild ? SlotPrimitive.Slot : "div";
1198
1199 return (
1200 <OverlayPrimitive
1201 data-slot="media-player-controls-overlay"
1202 data-state={isFullscreen ? "fullscreen" : "windowed"}
1203 data-visible={controlsVisible ? "" : undefined}
1204 {...overlayProps}
1205 className={cn(
1206 "pointer-events-none absolute inset-0 -z-10 bg-linear-to-t from-black/80 to-transparent opacity-0 transition-opacity duration-200 data-visible:opacity-100",
1207 className,
1208 )}
1209 />
1210 );
1211}
1212
1213function MediaPlayerPlay(props: React.ComponentProps<typeof Button>) {
1214 const { children, className, disabled, ...playButtonProps } = props;
1215
1216 const context = useMediaPlayerContext("MediaPlayerPlay");
1217 const dispatch = useMediaDispatch();
1218 const mediaPaused = useMediaSelector((state) => state.mediaPaused ?? true);
1219
1220 const isDisabled = disabled || context.disabled;
1221
1222 const onPlayToggle = React.useCallback(
1223 (event: React.MouseEvent<HTMLButtonElement>) => {
1224 props.onClick?.(event);
1225
1226 if (event.defaultPrevented) return;
1227
1228 dispatch({
1229 type: mediaPaused
1230 ? MediaActionTypes.MEDIA_PLAY_REQUEST
1231 : MediaActionTypes.MEDIA_PAUSE_REQUEST,
1232 });
1233 },
1234 [dispatch, props.onClick, mediaPaused],
1235 );
1236
1237 return (
1238 <MediaPlayerTooltip
1239 tooltip={mediaPaused ? "Play" : "Pause"}
1240 shortcut="Space"
1241 >
1242 <Button
1243 type="button"
1244 aria-controls={context.mediaId}
1245 aria-label={mediaPaused ? "Play" : "Pause"}
1246 aria-pressed={!mediaPaused}
1247 data-disabled={isDisabled ? "" : undefined}
1248 data-slot="media-player-play-button"
1249 data-state={mediaPaused ? "off" : "on"}
1250 disabled={isDisabled}
1251 {...playButtonProps}
1252 variant="ghost"
1253 size="icon"
1254 className={cn(
1255 "size-8 [&_svg:not([class*='fill-'])]:fill-current",
1256 className,
1257 )}
1258 onClick={onPlayToggle}
1259 >
1260 {children ?? (mediaPaused ? <PlayIcon /> : <PauseIcon />)}
1261 </Button>
1262 </MediaPlayerTooltip>
1263 );
1264}
1265
1266interface MediaPlayerSeekBackwardProps
1267 extends React.ComponentProps<typeof Button> {
1268 seconds?: number;
1269}
1270
1271function MediaPlayerSeekBackward(props: MediaPlayerSeekBackwardProps) {
1272 const {
1273 seconds = SEEK_STEP_SHORT,
1274 children,
1275 className,
1276 disabled,
1277 ...seekBackwardProps
1278 } = props;
1279
1280 const context = useMediaPlayerContext("MediaPlayerSeekBackward");
1281 const dispatch = useMediaDispatch();
1282 const mediaCurrentTime = useMediaSelector(
1283 (state) => state.mediaCurrentTime ?? 0,
1284 );
1285
1286 const isDisabled = disabled || context.disabled;
1287
1288 const onSeekBackward = React.useCallback(
1289 (event: React.MouseEvent<HTMLButtonElement>) => {
1290 props.onClick?.(event);
1291
1292 if (event.defaultPrevented) return;
1293
1294 dispatch({
1295 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
1296 detail: Math.max(0, mediaCurrentTime - seconds),
1297 });
1298 },
1299 [dispatch, props.onClick, mediaCurrentTime, seconds],
1300 );
1301
1302 return (
1303 <MediaPlayerTooltip
1304 tooltip={`Back ${seconds}s`}
1305 shortcut={context.isVideo ? ["←"] : ["Shift ←"]}
1306 >
1307 <Button
1308 type="button"
1309 aria-controls={context.mediaId}
1310 aria-label={`Back ${seconds} seconds`}
1311 data-disabled={isDisabled ? "" : undefined}
1312 data-slot="media-player-seek-backward"
1313 disabled={isDisabled}
1314 {...seekBackwardProps}
1315 variant="ghost"
1316 size="icon"
1317 className={cn("size-8", className)}
1318 onClick={onSeekBackward}
1319 >
1320 {children ?? <RewindIcon />}
1321 </Button>
1322 </MediaPlayerTooltip>
1323 );
1324}
1325
1326interface MediaPlayerSeekForwardProps
1327 extends React.ComponentProps<typeof Button> {
1328 seconds?: number;
1329}
1330
1331function MediaPlayerSeekForward(props: MediaPlayerSeekForwardProps) {
1332 const {
1333 seconds = SEEK_STEP_LONG,
1334 children,
1335 className,
1336 disabled,
1337 ...seekForwardProps
1338 } = props;
1339
1340 const context = useMediaPlayerContext("MediaPlayerSeekForward");
1341 const dispatch = useMediaDispatch();
1342 const mediaCurrentTime = useMediaSelector(
1343 (state) => state.mediaCurrentTime ?? 0,
1344 );
1345 const [, seekableEnd] = useMediaSelector(
1346 (state) => state.mediaSeekable ?? [0, 0],
1347 );
1348 const isDisabled = disabled || context.disabled;
1349
1350 const onSeekForward = React.useCallback(
1351 (event: React.MouseEvent<HTMLButtonElement>) => {
1352 props.onClick?.(event);
1353
1354 if (event.defaultPrevented) return;
1355
1356 dispatch({
1357 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
1358 detail: Math.min(
1359 seekableEnd ?? Number.POSITIVE_INFINITY,
1360 mediaCurrentTime + seconds,
1361 ),
1362 });
1363 },
1364 [dispatch, props.onClick, mediaCurrentTime, seekableEnd, seconds],
1365 );
1366
1367 return (
1368 <MediaPlayerTooltip
1369 tooltip={`Forward ${seconds}s`}
1370 shortcut={context.isVideo ? ["→"] : ["Shift →"]}
1371 >
1372 <Button
1373 type="button"
1374 aria-controls={context.mediaId}
1375 aria-label={`Forward ${seconds} seconds`}
1376 data-disabled={isDisabled ? "" : undefined}
1377 data-slot="media-player-seek-forward"
1378 disabled={isDisabled}
1379 {...seekForwardProps}
1380 variant="ghost"
1381 size="icon"
1382 className={cn("size-8", className)}
1383 onClick={onSeekForward}
1384 >
1385 {children ?? <FastForwardIcon />}
1386 </Button>
1387 </MediaPlayerTooltip>
1388 );
1389}
1390
1391interface SeekState {
1392 isHovering: boolean;
1393 pendingSeekTime: number | null;
1394 hasInitialPosition: boolean;
1395}
1396
1397interface MediaPlayerSeekProps
1398 extends React.ComponentProps<typeof SliderPrimitive.Root> {
1399 withTime?: boolean;
1400 withoutChapter?: boolean;
1401 withoutTooltip?: boolean;
1402 tooltipThumbnailSrc?: string | ((time: number) => string);
1403 tooltipTimeVariant?: "current" | "progress";
1404 tooltipSideOffset?: number;
1405 tooltipCollisionBoundary?: Element | Element[];
1406 tooltipCollisionPadding?:
1407 | number
1408 | Partial<Record<"top" | "right" | "bottom" | "left", number>>;
1409}
1410
1411function MediaPlayerSeek(props: MediaPlayerSeekProps) {
1412 const {
1413 withTime = false,
1414 withoutChapter = false,
1415 withoutTooltip = false,
1416 tooltipTimeVariant = "current",
1417 tooltipThumbnailSrc,
1418 tooltipSideOffset,
1419 tooltipCollisionPadding = SEEK_COLLISION_PADDING,
1420 tooltipCollisionBoundary,
1421 className,
1422 disabled,
1423 ...seekProps
1424 } = props;
1425
1426 const context = useMediaPlayerContext(SEEK_NAME);
1427 const store = useStoreContext(SEEK_NAME);
1428 const dispatch = useMediaDispatch();
1429 const mediaCurrentTime = useMediaSelector(
1430 (state) => state.mediaCurrentTime ?? 0,
1431 );
1432 const [seekableStart = 0, seekableEnd = 0] = useMediaSelector(
1433 (state) => state.mediaSeekable ?? [0, 0],
1434 );
1435 const mediaBuffered = useMediaSelector((state) => state.mediaBuffered ?? []);
1436 const mediaEnded = useMediaSelector((state) => state.mediaEnded ?? false);
1437
1438 const chapterCues = useMediaSelector(
1439 (state) => state.mediaChaptersCues ?? [],
1440 );
1441 const mediaPreviewTime = useMediaSelector((state) => state.mediaPreviewTime);
1442 const mediaPreviewImage = useMediaSelector(
1443 (state) => state.mediaPreviewImage,
1444 );
1445 const mediaPreviewCoords = useMediaSelector(
1446 (state) => state.mediaPreviewCoords,
1447 );
1448
1449 const seekRef = React.useRef<HTMLDivElement>(null);
1450 const tooltipRef = React.useRef<HTMLDivElement>(null);
1451 const justCommittedRef = React.useRef<boolean>(false);
1452
1453 const hoverTimeRef = React.useRef(0);
1454 const tooltipXRef = React.useRef(0);
1455 const tooltipYRef = React.useRef(0);
1456 const seekRectRef = React.useRef<DOMRect | null>(null);
1457 const collisionDataRef = React.useRef<{
1458 padding: { top: number; right: number; bottom: number; left: number };
1459 boundaries: Element[];
1460 } | null>(null);
1461
1462 const [seekState, setSeekState] = React.useState<SeekState>({
1463 isHovering: false,
1464 pendingSeekTime: null,
1465 hasInitialPosition: false,
1466 });
1467
1468 const rafIdRef = React.useRef<number | null>(null);
1469 const seekThrottleRef = React.useRef<number | null>(null);
1470 const hoverTimeoutRef = React.useRef<number | null>(null);
1471 const lastPointerXRef = React.useRef<number>(0);
1472 const lastPointerYRef = React.useRef<number>(0);
1473 const previewDebounceRef = React.useRef<number | null>(null);
1474 const pointerEnterTimeRef = React.useRef<number>(0);
1475 const horizontalMovementRef = React.useRef<number>(0);
1476 const verticalMovementRef = React.useRef<number>(0);
1477 const lastSeekCommitTimeRef = React.useRef<number>(0);
1478
1479 const timeCache = React.useRef<Map<number, string>>(new Map());
1480
1481 const displayValue = seekState.pendingSeekTime ?? mediaCurrentTime;
1482
1483 const isDisabled = disabled || context.disabled;
1484 const tooltipDisabled =
1485 withoutTooltip || context.withoutTooltip || store.getState().menuOpen;
1486
1487 const currentTooltipSideOffset =
1488 tooltipSideOffset ?? context.tooltipSideOffset;
1489
1490 const getCachedTime = React.useCallback((time: number, duration: number) => {
1491 const roundedTime = Math.floor(time);
1492 const key = roundedTime + duration * 10000;
1493
1494 if (timeCache.current.has(key)) {
1495 return timeCache.current.get(key) as string;
1496 }
1497
1498 const formatted = timeUtils.formatTime(time, duration);
1499 timeCache.current.set(key, formatted);
1500
1501 if (timeCache.current.size > 100) {
1502 timeCache.current.clear();
1503 }
1504
1505 return formatted;
1506 }, []);
1507
1508 const currentTime = getCachedTime(displayValue, seekableEnd);
1509 const duration = getCachedTime(seekableEnd, seekableEnd);
1510 const remainingTime = getCachedTime(seekableEnd - displayValue, seekableEnd);
1511
1512 const onCollisionDataUpdate = React.useCallback(() => {
1513 if (collisionDataRef.current) return collisionDataRef.current;
1514
1515 const padding =
1516 typeof tooltipCollisionPadding === "number"
1517 ? {
1518 top: tooltipCollisionPadding,
1519 right: tooltipCollisionPadding,
1520 bottom: tooltipCollisionPadding,
1521 left: tooltipCollisionPadding,
1522 }
1523 : { top: 0, right: 0, bottom: 0, left: 0, ...tooltipCollisionPadding };
1524
1525 const boundaries = tooltipCollisionBoundary
1526 ? Array.isArray(tooltipCollisionBoundary)
1527 ? tooltipCollisionBoundary
1528 : [tooltipCollisionBoundary]
1529 : ([context.rootRef.current].filter(Boolean) as Element[]);
1530
1531 collisionDataRef.current = { padding, boundaries };
1532 return collisionDataRef.current;
1533 }, [tooltipCollisionPadding, tooltipCollisionBoundary, context.rootRef]);
1534
1535 const getCurrentChapterCue = React.useCallback(
1536 (time: number) => {
1537 if (withoutChapter || chapterCues.length === 0) return null;
1538 return chapterCues.find((c) => time >= c.startTime && time < c.endTime);
1539 },
1540 [chapterCues, withoutChapter],
1541 );
1542
1543 const getThumbnail = React.useCallback(
1544 (time: number) => {
1545 if (tooltipDisabled) return null;
1546
1547 if (tooltipThumbnailSrc) {
1548 const src =
1549 typeof tooltipThumbnailSrc === "function"
1550 ? tooltipThumbnailSrc(time)
1551 : tooltipThumbnailSrc;
1552 return { src, coords: null };
1553 }
1554
1555 if (
1556 mediaPreviewTime !== undefined &&
1557 Math.abs(time - mediaPreviewTime) < 0.1 &&
1558 mediaPreviewImage
1559 ) {
1560 return {
1561 src: mediaPreviewImage,
1562 coords: mediaPreviewCoords ?? null,
1563 };
1564 }
1565
1566 return null;
1567 },
1568 [
1569 tooltipThumbnailSrc,
1570 mediaPreviewTime,
1571 mediaPreviewImage,
1572 mediaPreviewCoords,
1573 tooltipDisabled,
1574 ],
1575 );
1576
1577 const onPreviewUpdate = React.useCallback(
1578 (time: number) => {
1579 if (tooltipDisabled) return;
1580
1581 if (previewDebounceRef.current) {
1582 cancelAnimationFrame(previewDebounceRef.current);
1583 }
1584
1585 previewDebounceRef.current = requestAnimationFrame(() => {
1586 dispatch({
1587 type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
1588 detail: time,
1589 });
1590 previewDebounceRef.current = null;
1591 });
1592 },
1593 [dispatch, tooltipDisabled],
1594 );
1595
1596 const onTooltipPositionUpdate = React.useCallback(
1597 (clientX: number) => {
1598 if (!seekRef.current) return;
1599
1600 const tooltipWidth =
1601 tooltipRef.current?.offsetWidth ?? SEEK_TOOLTIP_WIDTH_FALLBACK;
1602
1603 let x = clientX;
1604 const y = seekRectRef.current?.top ?? 0;
1605
1606 const collisionData = onCollisionDataUpdate();
1607 const halfTooltipWidth = tooltipWidth / 2;
1608
1609 let minLeft = 0;
1610 let maxRight = window.innerWidth;
1611
1612 for (const boundary of collisionData.boundaries) {
1613 const boundaryRect = boundary.getBoundingClientRect();
1614 minLeft = Math.max(
1615 minLeft,
1616 boundaryRect.left + collisionData.padding.left,
1617 );
1618 maxRight = Math.min(
1619 maxRight,
1620 boundaryRect.right - collisionData.padding.right,
1621 );
1622 }
1623
1624 if (x - halfTooltipWidth < minLeft) {
1625 x = minLeft + halfTooltipWidth;
1626 } else if (x + halfTooltipWidth > maxRight) {
1627 x = maxRight - halfTooltipWidth;
1628 }
1629
1630 const viewportPadding = SEEK_COLLISION_PADDING;
1631 if (x - halfTooltipWidth < viewportPadding) {
1632 x = viewportPadding + halfTooltipWidth;
1633 } else if (x + halfTooltipWidth > window.innerWidth - viewportPadding) {
1634 x = window.innerWidth - viewportPadding - halfTooltipWidth;
1635 }
1636
1637 tooltipXRef.current = x;
1638 tooltipYRef.current = y;
1639
1640 if (tooltipRef.current) {
1641 tooltipRef.current.style.setProperty(SEEK_TOOLTIP_X, `${x}px`);
1642 tooltipRef.current.style.setProperty(SEEK_TOOLTIP_Y, `${y}px`);
1643 }
1644
1645 if (!seekState.hasInitialPosition) {
1646 setSeekState((prev) => ({ ...prev, hasInitialPosition: true }));
1647 }
1648 },
1649 [onCollisionDataUpdate, seekState.hasInitialPosition],
1650 );
1651
1652 const onHoverProgressUpdate = React.useCallback(() => {
1653 if (!seekRef.current || seekableEnd <= 0) return;
1654
1655 const hoverPercent = Math.min(
1656 100,
1657 (hoverTimeRef.current / seekableEnd) * 100,
1658 );
1659 seekRef.current.style.setProperty(
1660 SEEK_HOVER_PERCENT,
1661 `${hoverPercent.toFixed(4)}%`,
1662 );
1663 }, [seekableEnd]);
1664
1665 React.useEffect(() => {
1666 if (seekState.pendingSeekTime !== null) {
1667 const diff = Math.abs(mediaCurrentTime - seekState.pendingSeekTime);
1668 if (diff < 0.5) {
1669 setSeekState((prev) => ({ ...prev, pendingSeekTime: null }));
1670 }
1671 }
1672 }, [mediaCurrentTime, seekState.pendingSeekTime]);
1673
1674 React.useEffect(() => {
1675 if (!seekState.isHovering || tooltipDisabled) return;
1676
1677 function onScroll() {
1678 setSeekState((prev) => ({
1679 ...prev,
1680 isHovering: false,
1681 hasInitialPosition: false,
1682 }));
1683 dispatch({
1684 type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
1685 detail: undefined,
1686 });
1687 }
1688
1689 document.addEventListener("scroll", onScroll, { passive: true });
1690 return () => {
1691 document.removeEventListener("scroll", onScroll);
1692 };
1693 }, [dispatch, seekState.isHovering, tooltipDisabled]);
1694
1695 const bufferedProgress = React.useMemo(() => {
1696 if (mediaBuffered.length === 0 || seekableEnd <= 0) return 0;
1697
1698 if (mediaEnded) return 1;
1699
1700 const containingRange = mediaBuffered.find(
1701 ([start, end]) => start <= mediaCurrentTime && mediaCurrentTime <= end,
1702 );
1703
1704 if (containingRange) {
1705 return Math.min(1, containingRange[1] / seekableEnd);
1706 }
1707
1708 return Math.min(1, seekableStart / seekableEnd);
1709 }, [mediaBuffered, mediaCurrentTime, seekableEnd, mediaEnded, seekableStart]);
1710
1711 const onPointerEnter = React.useCallback(() => {
1712 if (seekRef.current) {
1713 seekRectRef.current = seekRef.current.getBoundingClientRect();
1714 }
1715
1716 collisionDataRef.current = null;
1717 pointerEnterTimeRef.current = Date.now();
1718 horizontalMovementRef.current = 0;
1719 verticalMovementRef.current = 0;
1720
1721 if (seekableEnd > 0) {
1722 if (hoverTimeoutRef.current) {
1723 clearTimeout(hoverTimeoutRef.current);
1724 }
1725
1726 if (!tooltipDisabled) {
1727 if (lastPointerXRef.current && seekRectRef.current) {
1728 const clientX = Math.max(
1729 seekRectRef.current.left,
1730 Math.min(lastPointerXRef.current, seekRectRef.current.right),
1731 );
1732 onTooltipPositionUpdate(clientX);
1733 }
1734 }
1735 }
1736 }, [seekableEnd, onTooltipPositionUpdate, tooltipDisabled]);
1737
1738 const onPointerLeave = React.useCallback(() => {
1739 if (hoverTimeoutRef.current) {
1740 clearTimeout(hoverTimeoutRef.current);
1741 hoverTimeoutRef.current = null;
1742 }
1743 if (rafIdRef.current) {
1744 cancelAnimationFrame(rafIdRef.current);
1745 rafIdRef.current = null;
1746 }
1747 if (previewDebounceRef.current) {
1748 cancelAnimationFrame(previewDebounceRef.current);
1749 previewDebounceRef.current = null;
1750 }
1751
1752 setSeekState((prev) => ({
1753 ...prev,
1754 isHovering: false,
1755 hasInitialPosition: false,
1756 }));
1757
1758 justCommittedRef.current = false;
1759 seekRectRef.current = null;
1760 collisionDataRef.current = null;
1761
1762 pointerEnterTimeRef.current = 0;
1763 horizontalMovementRef.current = 0;
1764 verticalMovementRef.current = 0;
1765 lastPointerXRef.current = 0;
1766 lastPointerYRef.current = 0;
1767 lastSeekCommitTimeRef.current = 0;
1768
1769 if (!tooltipDisabled) {
1770 dispatch({
1771 type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
1772 detail: undefined,
1773 });
1774 }
1775 }, [dispatch, tooltipDisabled]);
1776
1777 const onPointerMove = React.useCallback(
1778 (event: React.PointerEvent<HTMLDivElement>) => {
1779 if (seekableEnd <= 0) return;
1780
1781 if (!seekRectRef.current && seekRef.current) {
1782 seekRectRef.current = seekRef.current.getBoundingClientRect();
1783 }
1784
1785 if (!seekRectRef.current) return;
1786
1787 const currentX = event.clientX;
1788 const currentY = event.clientY;
1789
1790 if (lastPointerXRef.current !== 0 && lastPointerYRef.current !== 0) {
1791 const deltaX = Math.abs(currentX - lastPointerXRef.current);
1792 const deltaY = Math.abs(currentY - lastPointerYRef.current);
1793
1794 horizontalMovementRef.current += deltaX;
1795 verticalMovementRef.current += deltaY;
1796 }
1797
1798 lastPointerXRef.current = currentX;
1799 lastPointerYRef.current = currentY;
1800
1801 if (rafIdRef.current) {
1802 cancelAnimationFrame(rafIdRef.current);
1803 }
1804
1805 rafIdRef.current = requestAnimationFrame(() => {
1806 const wasJustCommitted = justCommittedRef.current;
1807 if (wasJustCommitted) {
1808 justCommittedRef.current = false;
1809 }
1810
1811 const seekRect = seekRectRef.current;
1812 if (!seekRect) {
1813 rafIdRef.current = null;
1814 return;
1815 }
1816
1817 const clientX = lastPointerXRef.current;
1818 const offsetXOnSeekBar = Math.max(
1819 0,
1820 Math.min(clientX - seekRect.left, seekRect.width),
1821 );
1822 const relativeX = offsetXOnSeekBar / seekRect.width;
1823 const calculatedHoverTime = relativeX * seekableEnd;
1824
1825 hoverTimeRef.current = calculatedHoverTime;
1826
1827 onHoverProgressUpdate();
1828
1829 const wasHovering = seekState.isHovering;
1830 const isCurrentlyHovering =
1831 clientX >= seekRect.left && clientX <= seekRect.right;
1832
1833 const timeHovering = Date.now() - pointerEnterTimeRef.current;
1834 const totalMovement =
1835 horizontalMovementRef.current + verticalMovementRef.current;
1836 const horizontalRatio =
1837 totalMovement > 0 ? horizontalMovementRef.current / totalMovement : 0;
1838
1839 const timeSinceSeekCommit = Date.now() - lastSeekCommitTimeRef.current;
1840 const isInSeekCooldown = timeSinceSeekCommit < 300;
1841
1842 const shouldShowTooltip =
1843 !wasJustCommitted &&
1844 !isInSeekCooldown &&
1845 (timeHovering > 150 ||
1846 horizontalRatio > 0.6 ||
1847 (totalMovement < 10 && timeHovering > 50));
1848
1849 if (
1850 !wasHovering &&
1851 isCurrentlyHovering &&
1852 shouldShowTooltip &&
1853 !tooltipDisabled
1854 ) {
1855 setSeekState((prev) => ({ ...prev, isHovering: true }));
1856 }
1857
1858 if (!tooltipDisabled) {
1859 onPreviewUpdate(calculatedHoverTime);
1860
1861 if (isCurrentlyHovering && (wasHovering || shouldShowTooltip)) {
1862 onTooltipPositionUpdate(clientX);
1863 }
1864 }
1865
1866 rafIdRef.current = null;
1867 });
1868 },
1869 [
1870 onPreviewUpdate,
1871 onTooltipPositionUpdate,
1872 onHoverProgressUpdate,
1873 seekableEnd,
1874 seekState.isHovering,
1875 tooltipDisabled,
1876 ],
1877 );
1878
1879 const onSeek = React.useCallback(
1880 (value: number[]) => {
1881 const time = value[0] ?? 0;
1882
1883 setSeekState((prev) => ({ ...prev, pendingSeekTime: time }));
1884
1885 if (!store.getState().dragging) {
1886 store.setState("dragging", true);
1887 }
1888
1889 if (seekThrottleRef.current) {
1890 cancelAnimationFrame(seekThrottleRef.current);
1891 }
1892
1893 seekThrottleRef.current = requestAnimationFrame(() => {
1894 dispatch({
1895 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
1896 detail: time,
1897 });
1898 seekThrottleRef.current = null;
1899 });
1900 },
1901 [dispatch, store.getState, store.setState],
1902 );
1903
1904 const onSeekCommit = React.useCallback(
1905 (value: number[]) => {
1906 const time = value[0] ?? 0;
1907
1908 if (seekThrottleRef.current) {
1909 cancelAnimationFrame(seekThrottleRef.current);
1910 seekThrottleRef.current = null;
1911 }
1912
1913 if (hoverTimeoutRef.current) {
1914 clearTimeout(hoverTimeoutRef.current);
1915 hoverTimeoutRef.current = null;
1916 }
1917 if (rafIdRef.current) {
1918 cancelAnimationFrame(rafIdRef.current);
1919 rafIdRef.current = null;
1920 }
1921 if (previewDebounceRef.current) {
1922 cancelAnimationFrame(previewDebounceRef.current);
1923 previewDebounceRef.current = null;
1924 }
1925
1926 setSeekState((prev) => ({
1927 ...prev,
1928 pendingSeekTime: time,
1929 isHovering: false,
1930 hasInitialPosition: false,
1931 }));
1932
1933 justCommittedRef.current = true;
1934 collisionDataRef.current = null;
1935 lastSeekCommitTimeRef.current = Date.now();
1936
1937 // Reset movement tracking after seek commit
1938 pointerEnterTimeRef.current = Date.now();
1939 horizontalMovementRef.current = 0;
1940 verticalMovementRef.current = 0;
1941
1942 if (store.getState().dragging) {
1943 store.setState("dragging", false);
1944 }
1945
1946 dispatch({
1947 type: MediaActionTypes.MEDIA_SEEK_REQUEST,
1948 detail: time,
1949 });
1950
1951 dispatch({
1952 type: MediaActionTypes.MEDIA_PREVIEW_REQUEST,
1953 detail: undefined,
1954 });
1955 },
1956 [dispatch, store.getState, store.setState],
1957 );
1958
1959 React.useEffect(() => {
1960 return () => {
1961 if (seekThrottleRef.current) {
1962 cancelAnimationFrame(seekThrottleRef.current);
1963 }
1964 if (hoverTimeoutRef.current) {
1965 clearTimeout(hoverTimeoutRef.current);
1966 }
1967 if (rafIdRef.current) {
1968 cancelAnimationFrame(rafIdRef.current);
1969 }
1970 if (previewDebounceRef.current) {
1971 cancelAnimationFrame(previewDebounceRef.current);
1972 }
1973 };
1974 }, []);
1975
1976 const currentChapterCue = getCurrentChapterCue(hoverTimeRef.current);
1977 const thumbnail = getThumbnail(hoverTimeRef.current);
1978 const hoverTime = getCachedTime(hoverTimeRef.current, seekableEnd);
1979
1980 const chapterSeparators = React.useMemo(() => {
1981 if (withoutChapter || chapterCues.length <= 1 || seekableEnd <= 0) {
1982 return null;
1983 }
1984
1985 return chapterCues.slice(1).map((chapterCue, index) => {
1986 const position = (chapterCue.startTime / seekableEnd) * 100;
1987
1988 return (
1989 <div
1990 key={`chapter-${index}-${chapterCue.startTime}`}
1991 role="presentation"
1992 aria-hidden="true"
1993 data-slot="media-player-seek-chapter-separator"
1994 className="absolute top-0 h-full bg-zinc-50 dark:bg-zinc-950"
1995 style={{
1996 width: ".1563rem",
1997 left: `${position}%`,
1998 transform: "translateX(-50%)",
1999 }}
2000 />
2001 );
2002 });
2003 }, [chapterCues, seekableEnd, withoutChapter]);
2004
2005 const spriteStyle = React.useMemo<React.CSSProperties>(() => {
2006 if (!thumbnail?.coords || !thumbnail?.src) {
2007 return {};
2008 }
2009
2010 const coordX = thumbnail.coords[0];
2011 const coordY = thumbnail.coords[1];
2012
2013 const spriteWidth = Number.parseFloat(thumbnail.coords[2] ?? "0");
2014 const spriteHeight = Number.parseFloat(thumbnail.coords[3] ?? "0");
2015
2016 const scaleX = spriteWidth > 0 ? SPRITE_CONTAINER_WIDTH / spriteWidth : 1;
2017 const scaleY =
2018 spriteHeight > 0 ? SPRITE_CONTAINER_HEIGHT / spriteHeight : 1;
2019 const scale = Math.min(scaleX, scaleY);
2020
2021 return {
2022 width: `${spriteWidth}px`,
2023 height: `${spriteHeight}px`,
2024 backgroundImage: `url(${thumbnail.src})`,
2025 backgroundPosition: `-${coordX}px -${coordY}px`,
2026 backgroundRepeat: "no-repeat",
2027 transform: `scale(${scale})`,
2028 transformOrigin: "top left",
2029 };
2030 }, [thumbnail?.coords, thumbnail?.src]);
2031
2032 const SeekSlider = (
2033 <div data-slot="media-player-seek-container" className="relative w-full">
2034 <SliderPrimitive.Root
2035 aria-controls={context.mediaId}
2036 aria-valuetext={`${currentTime} of ${duration}`}
2037 data-hovering={seekState.isHovering ? "" : undefined}
2038 data-slider=""
2039 data-slot="media-player-seek"
2040 disabled={isDisabled}
2041 {...seekProps}
2042 ref={seekRef}
2043 min={seekableStart}
2044 max={seekableEnd}
2045 step={0.01}
2046 className={cn(
2047 "relative flex w-full touch-none select-none items-center data-disabled:pointer-events-none data-disabled:opacity-50",
2048 className,
2049 )}
2050 value={[displayValue]}
2051 onValueChange={onSeek}
2052 onValueCommit={onSeekCommit}
2053 onPointerEnter={onPointerEnter}
2054 onPointerLeave={onPointerLeave}
2055 onPointerMove={onPointerMove}
2056 >
2057 <SliderPrimitive.Track className="relative h-1 w-full grow overflow-hidden rounded-full bg-primary/40">
2058 <div
2059 data-slot="media-player-seek-buffered"
2060 className="absolute h-full bg-primary/70 will-change-[width]"
2061 style={{
2062 width: `${bufferedProgress * 100}%`,
2063 }}
2064 />
2065 <SliderPrimitive.Range className="absolute h-full bg-primary will-change-[width]" />
2066 {seekState.isHovering && seekableEnd > 0 && (
2067 <div
2068 data-slot="media-player-seek-hover-range"
2069 className="absolute h-full bg-primary/70 will-change-[width,opacity]"
2070 style={{
2071 width: `var(${SEEK_HOVER_PERCENT}, 0%)`,
2072 transition: "opacity 150ms ease-out",
2073 }}
2074 />
2075 )}
2076 {chapterSeparators}
2077 </SliderPrimitive.Track>
2078 <SliderPrimitive.Thumb className="relative z-10 block size-2.5 shrink-0 rounded-full bg-primary shadow-sm ring-ring/50 transition-[color,box-shadow] will-change-transform hover:ring-4 focus-visible:outline-hidden focus-visible:ring-4 disabled:pointer-events-none disabled:opacity-50" />
2079 </SliderPrimitive.Root>
2080 {!withoutTooltip &&
2081 !context.withoutTooltip &&
2082 seekState.isHovering &&
2083 seekableEnd > 0 && (
2084 <MediaPlayerPortal>
2085 <div
2086 ref={tooltipRef}
2087 className="backface-hidden contain-[layout_style] pointer-events-none z-50 [transition:opacity_150ms_ease-in-out]"
2088 style={{
2089 position: "fixed" as const,
2090 left: `var(${SEEK_TOOLTIP_X}, 0rem)`,
2091 top: `var(${SEEK_TOOLTIP_Y}, 0rem)`,
2092 transform: `translateX(-50%) translateY(calc(-100% - ${currentTooltipSideOffset}px))`,
2093 visibility: seekState.hasInitialPosition ? "visible" : "hidden",
2094 opacity: seekState.hasInitialPosition ? 1 : 0,
2095 }}
2096 >
2097 <div
2098 className={cn(
2099 "flex flex-col items-center gap-1.5 rounded-md border bg-background text-foreground shadow-sm dark:bg-zinc-900",
2100 thumbnail && "min-h-10",
2101 !thumbnail && currentChapterCue && "px-3 py-1.5",
2102 )}
2103 >
2104 {thumbnail?.src && (
2105 <div
2106 data-slot="media-player-seek-thumbnail"
2107 className="overflow-hidden rounded-md rounded-b-none"
2108 style={{
2109 width: `${SPRITE_CONTAINER_WIDTH}px`,
2110 height: `${SPRITE_CONTAINER_HEIGHT}px`,
2111 }}
2112 >
2113 {thumbnail.coords ? (
2114 <div style={spriteStyle} />
2115 ) : (
2116 // biome-ignore lint/performance/noImgElement: dynamic thumbnail URLs from media don't work well with Next.js Image optimization
2117 <img
2118 src={thumbnail.src}
2119 alt={`Preview at ${hoverTime}`}
2120 className="size-full object-cover"
2121 />
2122 )}
2123 </div>
2124 )}
2125 {currentChapterCue && (
2126 <div
2127 data-slot="media-player-seek-chapter-title"
2128 className="line-clamp-2 max-w-48 text-balance text-center text-xs"
2129 >
2130 {currentChapterCue.text}
2131 </div>
2132 )}
2133 <div
2134 data-slot="media-player-seek-time"
2135 className={cn(
2136 "whitespace-nowrap text-center text-xs tabular-nums",
2137 thumbnail && "pb-1.5",
2138 !(thumbnail || currentChapterCue) && "px-2.5 py-1",
2139 )}
2140 >
2141 {tooltipTimeVariant === "progress"
2142 ? `${hoverTime} / ${duration}`
2143 : hoverTime}
2144 </div>
2145 </div>
2146 </div>
2147 </MediaPlayerPortal>
2148 )}
2149 </div>
2150 );
2151
2152 if (withTime) {
2153 return (
2154 <div className="flex w-full items-center gap-2">
2155 <span className="text-sm tabular-nums">{currentTime}</span>
2156 {SeekSlider}
2157 <span className="text-sm tabular-nums">{remainingTime}</span>
2158 </div>
2159 );
2160 }
2161
2162 return SeekSlider;
2163}
2164
2165interface MediaPlayerVolumeProps
2166 extends React.ComponentProps<typeof SliderPrimitive.Root> {
2167 asChild?: boolean;
2168 expandable?: boolean;
2169}
2170
2171function MediaPlayerVolume(props: MediaPlayerVolumeProps) {
2172 const { expandable = false, className, disabled, ...volumeProps } = props;
2173
2174 const context = useMediaPlayerContext(VOLUME_NAME);
2175 const store = useStoreContext(VOLUME_NAME);
2176 const dispatch = useMediaDispatch();
2177 const mediaVolume = useMediaSelector((state) => state.mediaVolume ?? 1);
2178 const mediaMuted = useMediaSelector((state) => state.mediaMuted ?? false);
2179 const mediaVolumeLevel = useMediaSelector(
2180 (state) => state.mediaVolumeLevel ?? "high",
2181 );
2182
2183 const sliderId = React.useId();
2184 const volumeTriggerId = React.useId();
2185
2186 const isDisabled = disabled || context.disabled;
2187
2188 const onMute = React.useCallback(() => {
2189 dispatch({
2190 type: mediaMuted
2191 ? MediaActionTypes.MEDIA_UNMUTE_REQUEST
2192 : MediaActionTypes.MEDIA_MUTE_REQUEST,
2193 });
2194 }, [dispatch, mediaMuted]);
2195
2196 const onVolumeChange = React.useCallback(
2197 (value: number[]) => {
2198 const volume = value[0] ?? 0;
2199
2200 if (!store.getState().dragging) {
2201 store.setState("dragging", true);
2202 }
2203
2204 dispatch({
2205 type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
2206 detail: volume,
2207 });
2208 },
2209 [dispatch, store.getState, store.setState],
2210 );
2211
2212 const onVolumeCommit = React.useCallback(
2213 (value: number[]) => {
2214 const volume = value[0] ?? 0;
2215
2216 if (store.getState().dragging) {
2217 store.setState("dragging", false);
2218 }
2219
2220 dispatch({
2221 type: MediaActionTypes.MEDIA_VOLUME_REQUEST,
2222 detail: volume,
2223 });
2224 },
2225 [dispatch, store],
2226 );
2227
2228 const effectiveVolume = mediaMuted ? 0 : mediaVolume;
2229
2230 return (
2231 <div
2232 data-disabled={isDisabled ? "" : undefined}
2233 data-slot="media-player-volume-container"
2234 className={cn(
2235 "group flex items-center",
2236 expandable
2237 ? "gap-0 group-focus-within:gap-2 group-hover:gap-1.5"
2238 : "gap-1.5",
2239 className,
2240 )}
2241 >
2242 <MediaPlayerTooltip tooltip="Volume" shortcut="M">
2243 <Button
2244 id={volumeTriggerId}
2245 type="button"
2246 aria-controls={`${context.mediaId} ${sliderId}`}
2247 aria-label={mediaMuted ? "Unmute" : "Mute"}
2248 aria-pressed={mediaMuted}
2249 data-slot="media-player-volume-trigger"
2250 data-state={mediaMuted ? "on" : "off"}
2251 variant="ghost"
2252 size="icon"
2253 className="size-8"
2254 disabled={isDisabled}
2255 onClick={onMute}
2256 >
2257 {mediaVolumeLevel === "off" || mediaMuted ? (
2258 <VolumeXIcon />
2259 ) : mediaVolumeLevel === "high" ? (
2260 <Volume2Icon />
2261 ) : (
2262 <Volume1Icon />
2263 )}
2264 </Button>
2265 </MediaPlayerTooltip>
2266 <SliderPrimitive.Root
2267 id={sliderId}
2268 aria-controls={context.mediaId}
2269 aria-valuetext={`${Math.round(effectiveVolume * 100)}% volume`}
2270 data-slider=""
2271 data-slot="media-player-volume"
2272 {...volumeProps}
2273 min={0}
2274 max={1}
2275 step={0.1}
2276 className={cn(
2277 "relative flex touch-none select-none items-center",
2278 expandable
2279 ? "w-0 opacity-0 transition-[width,opacity] duration-200 ease-in-out group-focus-within:w-16 group-focus-within:opacity-100 group-hover:w-16 group-hover:opacity-100"
2280 : "w-16",
2281 className,
2282 )}
2283 disabled={isDisabled}
2284 value={[effectiveVolume]}
2285 onValueChange={onVolumeChange}
2286 onValueCommit={onVolumeCommit}
2287 >
2288 <SliderPrimitive.Track className="relative h-1 w-full grow overflow-hidden rounded-full bg-zinc-500">
2289 <SliderPrimitive.Range className="absolute h-full bg-primary will-change-[width]" />
2290 </SliderPrimitive.Track>
2291 <SliderPrimitive.Thumb className="block size-2.5 shrink-0 rounded-full bg-primary shadow-sm ring-ring/50 transition-[color,box-shadow] will-change-transform hover:ring-4 focus-visible:outline-hidden focus-visible:ring-4 disabled:pointer-events-none disabled:opacity-50" />
2292 </SliderPrimitive.Root>
2293 </div>
2294 );
2295}
2296
2297interface MediaPlayerTimeProps extends React.ComponentProps<"div"> {
2298 variant?: "progress" | "remaining" | "duration";
2299 asChild?: boolean;
2300}
2301
2302function MediaPlayerTime(props: MediaPlayerTimeProps) {
2303 const { variant = "progress", asChild, className, ...timeProps } = props;
2304
2305 const context = useMediaPlayerContext("MediaPlayerTime");
2306 const mediaCurrentTime = useMediaSelector(
2307 (state) => state.mediaCurrentTime ?? 0,
2308 );
2309 const [, seekableEnd = 0] = useMediaSelector(
2310 (state) => state.mediaSeekable ?? [0, 0],
2311 );
2312
2313 const times = React.useMemo(() => {
2314 if (variant === "remaining") {
2315 return {
2316 remaining: timeUtils.formatTime(
2317 seekableEnd - mediaCurrentTime,
2318 seekableEnd,
2319 ),
2320 };
2321 }
2322
2323 if (variant === "duration") {
2324 return {
2325 duration: timeUtils.formatTime(seekableEnd, seekableEnd),
2326 };
2327 }
2328
2329 return {
2330 current: timeUtils.formatTime(mediaCurrentTime, seekableEnd),
2331 duration: timeUtils.formatTime(seekableEnd, seekableEnd),
2332 };
2333 }, [variant, mediaCurrentTime, seekableEnd]);
2334
2335 const TimePrimitive = asChild ? SlotPrimitive.Slot : "div";
2336
2337 if (variant === "remaining" || variant === "duration") {
2338 return (
2339 <TimePrimitive
2340 data-slot="media-player-time"
2341 data-variant={variant}
2342 dir={context.dir}
2343 {...timeProps}
2344 className={cn("text-foreground/80 text-sm tabular-nums", className)}
2345 >
2346 {times[variant]}
2347 </TimePrimitive>
2348 );
2349 }
2350
2351 return (
2352 <TimePrimitive
2353 data-slot="media-player-time"
2354 data-variant={variant}
2355 dir={context.dir}
2356 {...timeProps}
2357 className={cn(
2358 "flex items-center gap-1 text-foreground/80 text-sm",
2359 className,
2360 )}
2361 >
2362 <span className="tabular-nums">{times.current}</span>
2363 <span role="separator" aria-hidden="true" aria-valuenow={0} tabIndex={-1}>
2364 /
2365 </span>
2366 <span className="tabular-nums">{times.duration}</span>
2367 </TimePrimitive>
2368 );
2369}
2370
2371interface MediaPlayerPlaybackSpeedProps
2372 extends React.ComponentProps<typeof DropdownMenuTrigger>,
2373 React.ComponentProps<typeof Button>,
2374 Omit<React.ComponentProps<typeof DropdownMenu>, "dir">,
2375 Pick<React.ComponentProps<typeof DropdownMenuContent>, "sideOffset"> {
2376 speeds?: number[];
2377}
2378
2379function MediaPlayerPlaybackSpeed(props: MediaPlayerPlaybackSpeedProps) {
2380 const {
2381 open,
2382 defaultOpen,
2383 onOpenChange: onOpenChangeProp,
2384 sideOffset = FLOATING_MENU_SIDE_OFFSET,
2385 speeds = SPEEDS,
2386 modal = false,
2387 className,
2388 disabled,
2389 ...playbackSpeedProps
2390 } = props;
2391
2392 const context = useMediaPlayerContext(PLAYBACK_SPEED_NAME);
2393 const store = useStoreContext(PLAYBACK_SPEED_NAME);
2394 const dispatch = useMediaDispatch();
2395 const mediaPlaybackRate = useMediaSelector(
2396 (state) => state.mediaPlaybackRate ?? 1,
2397 );
2398
2399 const isDisabled = disabled || context.disabled;
2400
2401 const onPlaybackRateChange = React.useCallback(
2402 (rate: number) => {
2403 dispatch({
2404 type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
2405 detail: rate,
2406 });
2407 },
2408 [dispatch],
2409 );
2410
2411 const onOpenChange = React.useCallback(
2412 (open: boolean) => {
2413 store.setState("menuOpen", open);
2414 onOpenChangeProp?.(open);
2415 },
2416 [store.setState, onOpenChangeProp],
2417 );
2418
2419 return (
2420 <DropdownMenu
2421 modal={modal}
2422 open={open}
2423 defaultOpen={defaultOpen}
2424 onOpenChange={onOpenChange}
2425 >
2426 <MediaPlayerTooltip tooltip="Playback speed" shortcut={["<", ">"]}>
2427 <DropdownMenuTrigger asChild>
2428 <Button
2429 type="button"
2430 aria-controls={context.mediaId}
2431 disabled={isDisabled}
2432 {...playbackSpeedProps}
2433 variant="ghost"
2434 size="icon"
2435 className={cn("h-8 w-16 aria-expanded:bg-accent/50", className)}
2436 >
2437 {mediaPlaybackRate}x
2438 </Button>
2439 </DropdownMenuTrigger>
2440 </MediaPlayerTooltip>
2441 <DropdownMenuContent
2442 container={context.portalContainer}
2443 sideOffset={sideOffset}
2444 align="center"
2445 className="min-w-(--radix-dropdown-menu-trigger-width) data-[side=top]:mb-3.5"
2446 >
2447 {speeds.map((speed) => (
2448 <DropdownMenuItem
2449 key={speed}
2450 className="justify-between"
2451 onSelect={() => onPlaybackRateChange(speed)}
2452 >
2453 {speed}x{mediaPlaybackRate === speed && <CheckIcon />}
2454 </DropdownMenuItem>
2455 ))}
2456 </DropdownMenuContent>
2457 </DropdownMenu>
2458 );
2459}
2460
2461interface MediaPlayerLoopProps extends React.ComponentProps<typeof Button> {}
2462
2463function MediaPlayerLoop(props: MediaPlayerLoopProps) {
2464 const { children, className, disabled, ...loopProps } = props;
2465
2466 const context = useMediaPlayerContext("MediaPlayerLoop");
2467 const isDisabled = disabled || context.disabled;
2468
2469 const [isLooping, setIsLooping] = React.useState(() => {
2470 const mediaElement = context.mediaRef.current;
2471 return mediaElement?.loop ?? false;
2472 });
2473
2474 React.useEffect(() => {
2475 const mediaElement = context.mediaRef.current;
2476 if (!mediaElement) return;
2477
2478 setIsLooping(mediaElement.loop);
2479
2480 const checkLoop = () => setIsLooping(mediaElement.loop);
2481 const observer = new MutationObserver(checkLoop);
2482 observer.observe(mediaElement, {
2483 attributes: true,
2484 attributeFilter: ["loop"],
2485 });
2486
2487 return () => observer.disconnect();
2488 }, [context.mediaRef]);
2489
2490 const onLoopToggle = React.useCallback(
2491 (event: React.MouseEvent<HTMLButtonElement>) => {
2492 props.onClick?.(event);
2493 if (event.defaultPrevented) return;
2494
2495 const mediaElement = context.mediaRef.current;
2496 if (mediaElement) {
2497 const newLoopState = !mediaElement.loop;
2498 mediaElement.loop = newLoopState;
2499 setIsLooping(newLoopState);
2500 }
2501 },
2502 [context.mediaRef, props.onClick],
2503 );
2504
2505 return (
2506 <MediaPlayerTooltip
2507 tooltip={isLooping ? "Disable loop" : "Enable loop"}
2508 shortcut="R"
2509 >
2510 <Button
2511 type="button"
2512 aria-controls={context.mediaId}
2513 aria-label={isLooping ? "Disable loop" : "Enable loop"}
2514 aria-pressed={isLooping}
2515 data-disabled={isDisabled ? "" : undefined}
2516 data-slot="media-player-loop"
2517 data-state={isLooping ? "on" : "off"}
2518 disabled={isDisabled}
2519 {...loopProps}
2520 variant="ghost"
2521 size="icon"
2522 className={cn("size-8", className)}
2523 onClick={onLoopToggle}
2524 >
2525 {children ??
2526 (isLooping ? (
2527 <RepeatIcon className="text-muted-foreground" />
2528 ) : (
2529 <RepeatIcon />
2530 ))}
2531 </Button>
2532 </MediaPlayerTooltip>
2533 );
2534}
2535
2536interface MediaPlayerFullscreenProps
2537 extends React.ComponentProps<typeof Button> {}
2538
2539function MediaPlayerFullscreen(props: MediaPlayerFullscreenProps) {
2540 const { children, className, disabled, ...fullscreenProps } = props;
2541
2542 const context = useMediaPlayerContext("MediaPlayerFullscreen");
2543 const dispatch = useMediaDispatch();
2544 const isFullscreen = useMediaSelector(
2545 (state) => state.mediaIsFullscreen ?? false,
2546 );
2547
2548 const isDisabled = disabled || context.disabled;
2549
2550 const onFullscreen = React.useCallback(
2551 (event: React.MouseEvent<HTMLButtonElement>) => {
2552 props.onClick?.(event);
2553
2554 if (event.defaultPrevented) return;
2555
2556 dispatch({
2557 type: isFullscreen
2558 ? MediaActionTypes.MEDIA_EXIT_FULLSCREEN_REQUEST
2559 : MediaActionTypes.MEDIA_ENTER_FULLSCREEN_REQUEST,
2560 });
2561 },
2562 [dispatch, props.onClick, isFullscreen],
2563 );
2564
2565 return (
2566 <MediaPlayerTooltip tooltip="Fullscreen" shortcut="F">
2567 <Button
2568 type="button"
2569 aria-label={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
2570 data-disabled={isDisabled ? "" : undefined}
2571 data-slot="media-player-fullscreen"
2572 data-state={isFullscreen ? "on" : "off"}
2573 disabled={isDisabled}
2574 {...fullscreenProps}
2575 variant="ghost"
2576 size="icon"
2577 className={cn("size-8", className)}
2578 onClick={onFullscreen}
2579 >
2580 {children ?? (isFullscreen ? <Minimize2Icon /> : <Maximize2Icon />)}
2581 </Button>
2582 </MediaPlayerTooltip>
2583 );
2584}
2585
2586interface MediaPlayerPiPProps
2587 extends Omit<React.ComponentProps<typeof Button>, "children"> {
2588 children?:
2589 | React.ReactNode
2590 | ((isPictureInPicture: boolean) => React.ReactNode);
2591 onPipError?: (error: unknown, state: "enter" | "exit") => void;
2592}
2593
2594function MediaPlayerPiP(props: MediaPlayerPiPProps) {
2595 const { children, className, onPipError, disabled, ...pipButtonProps } =
2596 props;
2597
2598 const context = useMediaPlayerContext("MediaPlayerPiP");
2599 const dispatch = useMediaDispatch();
2600 const isPictureInPicture = useMediaSelector(
2601 (state) => state.mediaIsPip ?? false,
2602 );
2603
2604 const isDisabled = disabled || context.disabled;
2605
2606 const onPictureInPicture = React.useCallback(
2607 (event: React.MouseEvent<HTMLButtonElement>) => {
2608 props.onClick?.(event);
2609
2610 if (event.defaultPrevented) return;
2611
2612 dispatch({
2613 type: isPictureInPicture
2614 ? MediaActionTypes.MEDIA_EXIT_PIP_REQUEST
2615 : MediaActionTypes.MEDIA_ENTER_PIP_REQUEST,
2616 });
2617
2618 const mediaElement = context.mediaRef.current;
2619
2620 if (mediaElement instanceof HTMLVideoElement) {
2621 if (isPictureInPicture) {
2622 document.exitPictureInPicture().catch((error) => {
2623 onPipError?.(error, "exit");
2624 });
2625 } else {
2626 mediaElement.requestPictureInPicture().catch((error) => {
2627 onPipError?.(error, "enter");
2628 });
2629 }
2630 }
2631 },
2632 [dispatch, props.onClick, isPictureInPicture, onPipError, context.mediaRef],
2633 );
2634
2635 return (
2636 <MediaPlayerTooltip tooltip="Picture in picture" shortcut="P">
2637 <Button
2638 type="button"
2639 aria-controls={context.mediaId}
2640 aria-label={isPictureInPicture ? "Exit pip" : "Enter pip"}
2641 data-disabled={isDisabled ? "" : undefined}
2642 data-slot="media-player-pip"
2643 data-state={isPictureInPicture ? "on" : "off"}
2644 disabled={isDisabled}
2645 {...pipButtonProps}
2646 variant="ghost"
2647 size="icon"
2648 className={cn("size-8", className)}
2649 onClick={onPictureInPicture}
2650 >
2651 {typeof children === "function"
2652 ? children(isPictureInPicture)
2653 : (children ??
2654 (isPictureInPicture ? (
2655 <PictureInPicture2Icon />
2656 ) : (
2657 <PictureInPictureIcon />
2658 )))}
2659 </Button>
2660 </MediaPlayerTooltip>
2661 );
2662}
2663
2664function MediaPlayerCaptions(props: React.ComponentProps<typeof Button>) {
2665 const { children, className, disabled, ...captionsProps } = props;
2666
2667 const context = useMediaPlayerContext("MediaPlayerCaptions");
2668 const dispatch = useMediaDispatch();
2669 const isSubtitlesActive = useMediaSelector(
2670 (state) => (state.mediaSubtitlesShowing ?? []).length > 0,
2671 );
2672
2673 const isDisabled = disabled || context.disabled;
2674 const onCaptionsToggle = React.useCallback(
2675 (event: React.MouseEvent<HTMLButtonElement>) => {
2676 props.onClick?.(event);
2677
2678 if (event.defaultPrevented) return;
2679
2680 dispatch({
2681 type: MediaActionTypes.MEDIA_TOGGLE_SUBTITLES_REQUEST,
2682 });
2683 },
2684 [dispatch, props.onClick],
2685 );
2686
2687 return (
2688 <MediaPlayerTooltip tooltip="Captions" shortcut="C">
2689 <Button
2690 type="button"
2691 aria-controls={context.mediaId}
2692 aria-label={isSubtitlesActive ? "Disable captions" : "Enable captions"}
2693 aria-pressed={isSubtitlesActive}
2694 data-disabled={isDisabled ? "" : undefined}
2695 data-slot="media-player-captions"
2696 data-state={isSubtitlesActive ? "on" : "off"}
2697 disabled={isDisabled}
2698 {...captionsProps}
2699 variant="ghost"
2700 size="icon"
2701 className={cn("size-8", className)}
2702 onClick={onCaptionsToggle}
2703 >
2704 {children ??
2705 (isSubtitlesActive ? <SubtitlesIcon /> : <CaptionsOffIcon />)}
2706 </Button>
2707 </MediaPlayerTooltip>
2708 );
2709}
2710
2711function MediaPlayerDownload(props: React.ComponentProps<typeof Button>) {
2712 const { children, className, disabled, ...downloadProps } = props;
2713
2714 const context = useMediaPlayerContext("MediaPlayerDownload");
2715
2716 const isDisabled = disabled || context.disabled;
2717
2718 const onDownload = React.useCallback(
2719 (event: React.MouseEvent<HTMLButtonElement>) => {
2720 props.onClick?.(event);
2721
2722 if (event.defaultPrevented) return;
2723
2724 const mediaElement = context.mediaRef.current;
2725
2726 if (!mediaElement?.currentSrc) return;
2727
2728 const link = document.createElement("a");
2729 link.href = mediaElement.currentSrc;
2730 link.download = "";
2731 document.body.appendChild(link);
2732 link.click();
2733 document.body.removeChild(link);
2734 },
2735 [context.mediaRef, props.onClick],
2736 );
2737
2738 return (
2739 <MediaPlayerTooltip tooltip="Download" shortcut="D">
2740 <Button
2741 type="button"
2742 aria-controls={context.mediaId}
2743 aria-label="Download"
2744 data-disabled={isDisabled ? "" : undefined}
2745 data-slot="media-player-download"
2746 disabled={isDisabled}
2747 {...downloadProps}
2748 variant="ghost"
2749 size="icon"
2750 className={cn("size-8", className)}
2751 onClick={onDownload}
2752 >
2753 {children ?? <DownloadIcon />}
2754 </Button>
2755 </MediaPlayerTooltip>
2756 );
2757}
2758
2759interface MediaPlayerSettingsProps extends MediaPlayerPlaybackSpeedProps {}
2760
2761function MediaPlayerSettings(props: MediaPlayerSettingsProps) {
2762 const {
2763 open,
2764 defaultOpen,
2765 onOpenChange: onOpenChangeProp,
2766 sideOffset = FLOATING_MENU_SIDE_OFFSET,
2767 speeds = SPEEDS,
2768 modal = false,
2769 className,
2770 disabled,
2771 ...settingsProps
2772 } = props;
2773
2774 const context = useMediaPlayerContext(SETTINGS_NAME);
2775 const store = useStoreContext(SETTINGS_NAME);
2776 const dispatch = useMediaDispatch();
2777
2778 const mediaPlaybackRate = useMediaSelector(
2779 (state) => state.mediaPlaybackRate ?? 1,
2780 );
2781 const mediaSubtitlesList = useMediaSelector(
2782 (state) => state.mediaSubtitlesList ?? [],
2783 );
2784 const mediaSubtitlesShowing = useMediaSelector(
2785 (state) => state.mediaSubtitlesShowing ?? [],
2786 );
2787 const mediaRenditionList = useMediaSelector(
2788 (state) => state.mediaRenditionList ?? [],
2789 );
2790 const selectedRenditionId = useMediaSelector(
2791 (state) => state.mediaRenditionSelected,
2792 );
2793
2794 const isDisabled = disabled || context.disabled;
2795 const isSubtitlesActive = mediaSubtitlesShowing.length > 0;
2796
2797 const onPlaybackRateChange = React.useCallback(
2798 (rate: number) => {
2799 dispatch({
2800 type: MediaActionTypes.MEDIA_PLAYBACK_RATE_REQUEST,
2801 detail: rate,
2802 });
2803 },
2804 [dispatch],
2805 );
2806
2807 const onRenditionChange = React.useCallback(
2808 (renditionId: string) => {
2809 dispatch({
2810 type: MediaActionTypes.MEDIA_RENDITION_REQUEST,
2811 detail: renditionId === "auto" ? undefined : renditionId,
2812 });
2813 },
2814 [dispatch],
2815 );
2816
2817 const onSubtitlesToggle = React.useCallback(() => {
2818 dispatch({
2819 type: MediaActionTypes.MEDIA_TOGGLE_SUBTITLES_REQUEST,
2820 detail: false,
2821 });
2822 }, [dispatch]);
2823
2824 const onShowSubtitleTrack = React.useCallback(
2825 (subtitleTrack: (typeof mediaSubtitlesList)[number]) => {
2826 dispatch({
2827 type: MediaActionTypes.MEDIA_TOGGLE_SUBTITLES_REQUEST,
2828 detail: false,
2829 });
2830 dispatch({
2831 type: MediaActionTypes.MEDIA_SHOW_SUBTITLES_REQUEST,
2832 detail: subtitleTrack,
2833 });
2834 },
2835 [dispatch],
2836 );
2837
2838 const selectedSubtitleLabel = React.useMemo(() => {
2839 if (!isSubtitlesActive) return "Off";
2840 if (mediaSubtitlesShowing.length > 0) {
2841 return mediaSubtitlesShowing[0]?.label ?? "On";
2842 }
2843 return "Off";
2844 }, [isSubtitlesActive, mediaSubtitlesShowing]);
2845
2846 const selectedRenditionLabel = React.useMemo(() => {
2847 if (!selectedRenditionId) return "Auto";
2848
2849 const currentRendition = mediaRenditionList?.find(
2850 (rendition) => rendition.id === selectedRenditionId,
2851 );
2852 if (!currentRendition) return "Auto";
2853
2854 if (currentRendition.height) return `${currentRendition.height}p`;
2855 if (currentRendition.width) return `${currentRendition.width}p`;
2856 return currentRendition.id ?? "Auto";
2857 }, [selectedRenditionId, mediaRenditionList]);
2858
2859 const onOpenChange = React.useCallback(
2860 (open: boolean) => {
2861 store.setState("menuOpen", open);
2862 onOpenChangeProp?.(open);
2863 },
2864 [store.setState, onOpenChangeProp],
2865 );
2866
2867 return (
2868 <DropdownMenu
2869 modal={modal}
2870 open={open}
2871 defaultOpen={defaultOpen}
2872 onOpenChange={onOpenChange}
2873 >
2874 <MediaPlayerTooltip tooltip="Settings">
2875 <DropdownMenuTrigger asChild>
2876 <Button
2877 type="button"
2878 aria-controls={context.mediaId}
2879 aria-label="Settings"
2880 data-disabled={isDisabled ? "" : undefined}
2881 data-slot="media-player-settings"
2882 disabled={isDisabled}
2883 {...settingsProps}
2884 variant="ghost"
2885 size="icon"
2886 className={cn("size-8 aria-expanded:bg-accent/50", className)}
2887 >
2888 <SettingsIcon />
2889 </Button>
2890 </DropdownMenuTrigger>
2891 </MediaPlayerTooltip>
2892 <DropdownMenuContent
2893 align="end"
2894 side="top"
2895 sideOffset={sideOffset}
2896 container={context.portalContainer}
2897 className="w-56 data-[side=top]:mb-3.5"
2898 >
2899 <DropdownMenuLabel className="sr-only">Settings</DropdownMenuLabel>
2900 <DropdownMenuSub>
2901 <DropdownMenuSubTrigger>
2902 <span className="flex-1">Speed</span>
2903 <Badge variant="outline" className="rounded-sm">
2904 {mediaPlaybackRate}x
2905 </Badge>
2906 </DropdownMenuSubTrigger>
2907 <DropdownMenuSubContent>
2908 {speeds.map((speed) => (
2909 <DropdownMenuItem
2910 key={speed}
2911 className="justify-between"
2912 onSelect={() => onPlaybackRateChange(speed)}
2913 >
2914 {speed}x{mediaPlaybackRate === speed && <CheckIcon />}
2915 </DropdownMenuItem>
2916 ))}
2917 </DropdownMenuSubContent>
2918 </DropdownMenuSub>
2919 {context.isVideo && mediaRenditionList.length > 0 && (
2920 <DropdownMenuSub>
2921 <DropdownMenuSubTrigger>
2922 <span className="flex-1">Quality</span>
2923 <Badge variant="outline" className="rounded-sm">
2924 {selectedRenditionLabel}
2925 </Badge>
2926 </DropdownMenuSubTrigger>
2927 <DropdownMenuSubContent>
2928 <DropdownMenuItem
2929 className="justify-between"
2930 onSelect={() => onRenditionChange("auto")}
2931 >
2932 Auto
2933 {!selectedRenditionId && <CheckIcon />}
2934 </DropdownMenuItem>
2935 {mediaRenditionList
2936 .slice()
2937 .sort((a, b) => {
2938 const aHeight = a.height ?? 0;
2939 const bHeight = b.height ?? 0;
2940 return bHeight - aHeight;
2941 })
2942 .map((rendition) => {
2943 const label = rendition.height
2944 ? `${rendition.height}p`
2945 : rendition.width
2946 ? `${rendition.width}p`
2947 : (rendition.id ?? "Unknown");
2948
2949 const selected = rendition.id === selectedRenditionId;
2950
2951 return (
2952 <DropdownMenuItem
2953 key={rendition.id}
2954 className="justify-between"
2955 onSelect={() => onRenditionChange(rendition.id ?? "")}
2956 >
2957 {label}
2958 {selected && <CheckIcon />}
2959 </DropdownMenuItem>
2960 );
2961 })}
2962 </DropdownMenuSubContent>
2963 </DropdownMenuSub>
2964 )}
2965 <DropdownMenuSub>
2966 <DropdownMenuSubTrigger>
2967 <span className="flex-1">Captions</span>
2968 <Badge variant="outline" className="rounded-sm">
2969 {selectedSubtitleLabel}
2970 </Badge>
2971 </DropdownMenuSubTrigger>
2972 <DropdownMenuSubContent>
2973 <DropdownMenuItem
2974 className="justify-between"
2975 onSelect={onSubtitlesToggle}
2976 >
2977 Off
2978 {!isSubtitlesActive && <CheckIcon />}
2979 </DropdownMenuItem>
2980 {mediaSubtitlesList.map((subtitleTrack) => {
2981 const isSelected = mediaSubtitlesShowing.some(
2982 (showingSubtitle) =>
2983 showingSubtitle.label === subtitleTrack.label,
2984 );
2985 return (
2986 <DropdownMenuItem
2987 key={`${subtitleTrack.kind}-${subtitleTrack.label}-${subtitleTrack.language}`}
2988 className="justify-between"
2989 onSelect={() => onShowSubtitleTrack(subtitleTrack)}
2990 >
2991 {subtitleTrack.label}
2992 {isSelected && <CheckIcon />}
2993 </DropdownMenuItem>
2994 );
2995 })}
2996 {mediaSubtitlesList.length === 0 && (
2997 <DropdownMenuItem disabled>
2998 No captions available
2999 </DropdownMenuItem>
3000 )}
3001 </DropdownMenuSubContent>
3002 </DropdownMenuSub>
3003 </DropdownMenuContent>
3004 </DropdownMenu>
3005 );
3006}
3007
3008interface MediaPlayerPortalProps {
3009 container?: Element | DocumentFragment | null;
3010 children?: React.ReactNode;
3011}
3012
3013function MediaPlayerPortal(props: MediaPlayerPortalProps) {
3014 const { container: containerProp, children } = props;
3015
3016 const context = useMediaPlayerContext("MediaPlayerPortal");
3017 const container = containerProp ?? context.portalContainer;
3018
3019 if (!container) return null;
3020
3021 return ReactDOM.createPortal(children, container);
3022}
3023
3024interface MediaPlayerTooltipProps
3025 extends React.ComponentProps<typeof Tooltip>,
3026 Pick<React.ComponentProps<typeof TooltipContent>, "sideOffset"> {
3027 tooltip?: string;
3028 shortcut?: string | string[];
3029}
3030
3031function MediaPlayerTooltip(props: MediaPlayerTooltipProps) {
3032 const {
3033 tooltip,
3034 shortcut,
3035 delayDuration,
3036 sideOffset,
3037 children,
3038 ...tooltipProps
3039 } = props;
3040
3041 const context = useMediaPlayerContext("MediaPlayerTooltip");
3042 const tooltipDelayDuration = delayDuration ?? context.tooltipDelayDuration;
3043 const tooltipSideOffset = sideOffset ?? context.tooltipSideOffset;
3044
3045 if ((!tooltip && !shortcut) || context.withoutTooltip) return <>{children}</>;
3046
3047 return (
3048 <Tooltip {...tooltipProps} delayDuration={tooltipDelayDuration}>
3049 <TooltipTrigger
3050 className="text-foreground focus-visible:ring-ring/50"
3051 asChild
3052 >
3053 {children}
3054 </TooltipTrigger>
3055 <TooltipContent
3056 container={context.portalContainer}
3057 sideOffset={tooltipSideOffset}
3058 className="flex items-center gap-2 border bg-accent px-2 py-1 font-medium text-foreground data-[side=top]:mb-3.5 dark:bg-zinc-900 [&>span]:hidden"
3059 >
3060 <p>{tooltip}</p>
3061 {Array.isArray(shortcut) ? (
3062 <div className="flex items-center gap-1">
3063 {shortcut.map((shortcutKey) => (
3064 <kbd
3065 key={shortcutKey}
3066 className="select-none rounded border bg-secondary px-1.5 py-0.5 font-mono text-[11.2px] text-foreground shadow-xs"
3067 >
3068 <abbr title={shortcutKey} className="no-underline">
3069 {shortcutKey}
3070 </abbr>
3071 </kbd>
3072 ))}
3073 </div>
3074 ) : (
3075 shortcut && (
3076 <kbd
3077 key={shortcut}
3078 className="select-none rounded border bg-secondary px-1.5 py-px font-mono text-[11.2px] text-foreground shadow-xs"
3079 >
3080 <abbr title={shortcut} className="no-underline">
3081 {shortcut}
3082 </abbr>
3083 </kbd>
3084 )
3085 )}
3086 </TooltipContent>
3087 </Tooltip>
3088 );
3089}
3090
3091export {
3092 MediaPlayer,
3093 MediaPlayerAudio,
3094 MediaPlayerCaptions,
3095 MediaPlayerControls,
3096 MediaPlayerControlsOverlay,
3097 MediaPlayerDownload,
3098 MediaPlayerError,
3099 MediaPlayerFullscreen,
3100 MediaPlayerLoading,
3101 MediaPlayerLoop,
3102 MediaPlayerPiP,
3103 MediaPlayerPlay,
3104 MediaPlayerPlaybackSpeed,
3105 MediaPlayerPortal,
3106 type MediaPlayerProps,
3107 MediaPlayerSeek,
3108 MediaPlayerSeekBackward,
3109 MediaPlayerSeekForward,
3110 MediaPlayerSettings,
3111 MediaPlayerTime,
3112 MediaPlayerTooltip,
3113 MediaPlayerVideo,
3114 MediaPlayerVolume,
3115 MediaPlayerVolumeIndicator,
3116 useMediaSelector as useMediaPlayer,
3117 useStore as useMediaPlayerStore,
3118};
3119