feat: safari autoplay

This commit is contained in:
ner committed 2025-08-17 20:40:34 +03:00
1 parent 2e16746a40
commit f78af76da5
8 files changed
+85 -62

No files matched your search

@@ -1,4 +1,5 @@
import { useCaptionOptions } from '@vidstack/react'; import { useMemo } from 'react';
import { CaptionOption, useCaptionOptions } from '@vidstack/react';
import { ClosedCaptionsIcon, ClosedCaptionsOnIcon } from '@vidstack/react/icons'; import { ClosedCaptionsIcon, ClosedCaptionsOnIcon } from '@vidstack/react/icons';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -8,11 +9,24 @@ import PlayerMenu from '../Menu';
const CaptionsMenu = () => { const CaptionsMenu = () => {
const tracks = useCaptionOptions(); const tracks = useCaptionOptions();
const captions = useMemo(() => {
const record = tracks.reduce<Record<string, CaptionOption>>((record, track) => {
record[track.value] = track;
return record;
}, {});
return Object.values(record);
}, [tracks]);
return ( return (
<PlayerMenu <PlayerMenu
closeOnSelect closeOnSelect
value={tracks.selectedValue} value={tracks.selectedValue}
options={tracks.map((track) => ({ label: track.label, value: track.value, onSelect: () => track.select() }))} options={captions.map((track) => ({
label: track.label,
value: track.value,
onSelect: () => track.select()
}))}
> >
{tracks.selectedTrack ? ( {tracks.selectedTrack ? (
<ClosedCaptionsOnIcon className={cn('vds-icon !transform-none !size-5')} /> <ClosedCaptionsOnIcon className={cn('vds-icon !transform-none !size-5')} />
@@ -1,4 +1,4 @@
import React, { FC, forwardRef, MutableRefObject, ReactNode, useLayoutEffect, useRef } from 'react'; import React, { FC, forwardRef, MutableRefObject, ReactNode, useRef } from 'react';
import { create, InstanceProps } from 'react-modal-promise'; import { create, InstanceProps } from 'react-modal-promise';
import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso'; import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
import { Menu } from '@vidstack/react'; import { Menu } from '@vidstack/react';
@@ -20,29 +20,20 @@ const showMenu = create(
const virtuosoRef = useRef<VirtuosoHandle | null>(null); const virtuosoRef = useRef<VirtuosoHandle | null>(null);
const scrollRef = useRef<HTMLDivElement>(null) as MutableRefObject<HTMLDivElement>; const scrollRef = useRef<HTMLDivElement>(null) as MutableRefObject<HTMLDivElement>;
useLayoutEffect(() => {
const index = +value || 0;
if (!index || !virtuosoRef.current) return;
setTimeout(() => virtuosoRef.current?.scrollToIndex(index), 1000);
}, [value]);
return ( return (
<Modal <Modal
className='max-w-screen-xs rounded-xl p-2' className='max-w-screen-xs rounded-xl'
onClose={onResolve} onClose={onResolve}
scrollRef={scrollRef} scrollRef={scrollRef}
portal={(document.fullscreenElement || document.body) as HTMLElement} portal={(document.fullscreenElement || document.body) as HTMLElement}
> >
<Virtuoso <Virtuoso
useWindowScroll useWindowScroll
initialItemCount={20}
overscan={10} overscan={10}
initialItemCount={50} initialTopMostItemIndex={+value || 0}
ref={virtuosoRef} ref={virtuosoRef}
customScrollParent={scrollRef.current} customScrollParent={scrollRef.current}
defaultItemHeight={56}
fixedItemHeight={56}
data={options} data={options}
context={value} context={value}
components={components} components={components}
@@ -70,14 +61,14 @@ const components: VirtuosoProps<Option, string>['components'] = {
Item: ({ item: option, children, context, ...props }) => { Item: ({ item: option, children, context, ...props }) => {
if (!option) return null; if (!option) return null;
const index = props['data-index'];
return ( return (
<div {...props} key={option.label} title={option.label} onClick={() => option.onSelect(option.value)}>
{!index && <div className='h-2 w-full' />}
<div <div
{...props}
key={option.value}
title={option.label}
onClick={() => option.onSelect(option.value)}
className={cn( className={cn(
'!m-0 cursor-pointer line-clamp-2 rounded-sm bg-secondary text-left !px-2 !py-1 text-foreground !mb-2', '!m-0 cursor-pointer line-clamp-2 rounded-sm bg-secondary text-left !px-2 !py-1 text-foreground',
{ {
'bg-secondary-foreground text-secondary': context === option.value 'bg-secondary-foreground text-secondary': context === option.value
} }
@@ -85,11 +76,13 @@ const components: VirtuosoProps<Option, string>['components'] = {
> >
{option.label} {option.label}
</div> </div>
<div className='h-2 w-full' />
</div>
); );
}, },
List: forwardRef(function List({ children, ...props }, ref) { List: forwardRef(function List({ children, ...props }, ref) {
return ( return (
<div className='flex flex-col' {...props} ref={ref}> <div className='flex flex-col p-2' {...props} ref={ref}>
{children} {children}
</div> </div>
); );
@@ -12,8 +12,8 @@ import {
} from '@vidstack/react'; } from '@vidstack/react';
import { NextIcon } from '@vidstack/react/icons'; import { NextIcon } from '@vidstack/react/icons';
import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr'; import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr';
import { Loader } from 'lucide-react';
import { useCanPlay, useSetCanPlay } from '@/hooks/useCanPlay';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import Captions from './components/Captions'; import Captions from './components/Captions';
@@ -30,16 +30,8 @@ interface Stream {
const sample = { type: 'video/mp4', src: '/sample.mp4', name: 'Sample' }; const sample = { type: 'video/mp4', src: '/sample.mp4', name: 'Sample' };
const initialStream: Stream = {
magnet: '',
subtitles: [],
playlist: [sample]
};
export type PlayerControlRef = MutableRefObject<{ export type PlayerControlRef = MutableRefObject<{
sample: () => void;
play: (options: { sources: Sources; magnet: string }) => void; play: (options: { sources: Sources; magnet: string }) => void;
stop: () => void;
}>; }>;
interface Props { interface Props {
@@ -47,8 +39,13 @@ interface Props {
} }
const Player: FC<Props> = ({ controlRef }) => { const Player: FC<Props> = ({ controlRef }) => {
const [{ magnet, playlist, subtitles }, setStream] = useState<Stream>(initialStream); const [{ magnet, playlist, subtitles }, setStream] = useState<Stream>({
const [canPlay, setCanPlay] = useState(false); magnet: '',
subtitles: [],
playlist: [sample]
});
const canPlay = useCanPlay();
const setCanPlay = useSetCanPlay();
const { index, setIndex } = useSource({ magnet }); const { index, setIndex } = useSource({ magnet });
@@ -72,38 +69,46 @@ const Player: FC<Props> = ({ controlRef }) => {
player.current player.current
.play() .play()
.catch(() => {}) .catch(() => {})
.finally(() => setCanPlay(true)); .finally(() => {
if (source === sample) return;
setCanPlay(true);
});
}; };
useImperativeHandle(controlRef, () => ({ useImperativeHandle(controlRef, () => ({
sample() {
handlePlay();
setCanPlay(false);
},
play({ magnet, sources }) { play({ magnet, sources }) {
setStream({ magnet, ...sources }); setStream({ magnet, ...sources });
}, setCanPlay(false);
stop() {
setStream(initialStream);
} }
})); }));
const pending = !canPlay || source === sample; const pending = !canPlay;
return ( return (
<>
<MediaPlayer <MediaPlayer
playsInline
autoPlay
load='eager' load='eager'
preload='none' preload='none'
storage='movie-advisor' storage='movie-advisor'
ref={player} ref={player}
loop={pending}
src={(source as VideoSrc) || []} src={(source as VideoSrc) || []}
onCanPlay={handlePlay} onCanPlay={handlePlay}
className={cn('relative size-full select-none', { invisible: pending })} className={cn('relative size-full select-none', { invisible: pending })}
> >
<MediaProvider className='relative flex size-full justify-center [&>video]:!h-full'> <MediaProvider className='relative flex size-full justify-center [&>video]:!h-full'>
{subtitles.map((track, index) => ( {subtitles.map((track, index) => (
<Track key={track.name} src={track.src} kind='subtitles' label={track.name} type='srt' default={!index} /> <Track
key={track.name}
src={track.src}
kind='subtitles'
label={track.name}
type='srt'
default={!index}
id={track.name}
/>
))} ))}
</MediaProvider> </MediaProvider>
<PlyrLayout <PlyrLayout
@@ -127,16 +132,6 @@ const Player: FC<Props> = ({ controlRef }) => {
}} }}
/> />
</MediaPlayer> </MediaPlayer>
{pending && (
<div className='absolute left-0 top-0 flex size-full items-center justify-center'>
<div className='flex size-12 items-center justify-center rounded bg-black/60'>
<div className='animate-spin'>
<Loader color='white' />
</div>
</div>
</div>
)}
</>
); );
}; };
@@ -1,7 +1,9 @@
import { create, InstanceProps } from 'react-modal-promise'; import { create, InstanceProps } from 'react-modal-promise';
import { DialogContentProps } from '@radix-ui/react-dialog'; import { DialogContentProps } from '@radix-ui/react-dialog';
import { Loader } from 'lucide-react';
import { Modal } from '@/components/ui/dialog'; import { Modal } from '@/components/ui/dialog';
import { useCanPlay, useSetCanPlay } from '@/hooks/useCanPlay';
import { useStats } from './useStats'; import { useStats } from './useStats';
@@ -13,27 +15,40 @@ interface Props extends InstanceProps<void> {
} }
const showPlayerModal = create(({ onResolve, hash, backdrop, title, playerEntryId }: Props) => { const showPlayerModal = create(({ onResolve, hash, backdrop, title, playerEntryId }: Props) => {
const { isReady, preloadingProgress, downloadSpeed, peers } = useStats({ hash }); const canPlay = useCanPlay();
const setCanPlay = useSetCanPlay();
const { isReady, preloadingProgress, downloadSpeed } = useStats({ hash, canPlay });
const handlePlayerInteraction: DialogContentProps['onInteractOutside'] = (event) => { const handlePlayerInteraction: DialogContentProps['onInteractOutside'] = (event) => {
if (document.getElementById(playerEntryId)?.contains(event.target as Node)) event.preventDefault(); if (document.getElementById(playerEntryId)?.contains(event.target as Node)) event.preventDefault();
}; };
const handleClose = () => {
setCanPlay(false);
onResolve();
};
return ( return (
<Modal <Modal
className='overflow-hidden border-none bg-black p-0' className='overflow-hidden border-none bg-black p-0'
onClose={onResolve} onClose={handleClose}
onInteractOutside={handlePlayerInteraction} onInteractOutside={handlePlayerInteraction}
onPointerDownOutside={handlePlayerInteraction} onPointerDownOutside={handlePlayerInteraction}
> >
<div className='relative w-full overflow-hidden pt-[56.25%]'> <div className='relative w-full overflow-hidden pt-[56.25%]'>
{!isReady && ( <div className='absolute left-0 top-0 size-full' id={playerEntryId} />
{(!isReady || !canPlay) && (
<div className='absolute left-0 top-0 size-full'> <div className='absolute left-0 top-0 size-full'>
<img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} /> <img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} />
<div <div
className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/60 transition-all' className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/60 transition-all'
style={{ width: `${100 - preloadingProgress}%` }} style={{ width: `${100 - (canPlay ? 100 : preloadingProgress)}%` }}
/> />
<div className='absolute left-0 top-0 flex size-full items-center justify-center'>
<div className='animate-spin'>
<Loader color='white' />
</div>
</div>
<div className='absolute left-0 top-0 flex size-full flex-col items-center justify-between text-sm text-white/90'> <div className='absolute left-0 top-0 flex size-full flex-col items-center justify-between text-sm text-white/90'>
<div className='grid w-full items-center bg-black/80 p-2 text-center'> <div className='grid w-full items-center bg-black/80 p-2 text-center'>
<p>Buffering: {preloadingProgress.toFixed()}%</p> <p>Buffering: {preloadingProgress.toFixed()}%</p>
@@ -44,7 +59,6 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, playerEntryI
</div> </div>
</div> </div>
)} )}
<div className='absolute left-0 top-0 size-full' id={playerEntryId} />
</div> </div>
</Modal> </Modal>
); );
@@ -6,6 +6,7 @@ import { formatBytes } from '@/lib/utils';
interface Props { interface Props {
hash?: string; hash?: string;
canPlay: boolean;
} }
export enum StreamStatus { export enum StreamStatus {
@@ -14,14 +15,14 @@ export enum StreamStatus {
ready = 3 ready = 3
} }
export const useStats = ({ hash }: Props) => { export const useStats = ({ hash, canPlay }: Props) => {
const streamUrl = useStreamUrl(); const streamUrl = useStreamUrl();
const { data } = useQuery<Stream & { stat: StreamStatus }>({ const { data } = useQuery<Stream & { stat: StreamStatus }>({
enabled: Boolean(hash), enabled: Boolean(hash),
queryKey: ['stats', hash], queryKey: ['stats', hash],
refetchInterval: ({ state }) => { refetchInterval: ({ state }) => {
if (state.data?.stat === StreamStatus.ready) return false; if (state.data?.stat === StreamStatus.ready && canPlay) return false;
return 1000; return 1000;
}, },
@@ -11,7 +11,7 @@ const useFiles = ({ magnet }: Props) => {
return useMutation<Sources>({ return useMutation<Sources>({
mutationFn: () => mutationFn: () =>
fetch(`${streamUrl}&stat&preload`) fetch(`${streamUrl}&stat`)
.then((response) => { .then((response) => {
if (!response.ok) return Promise.reject('Download Failed: unable to retrieve the video'); if (!response.ok) return Promise.reject('Download Failed: unable to retrieve the video');
@@ -137,7 +137,6 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
onPlay={(options) => { onPlay={(options) => {
if (!playerControlRef.current) return; if (!playerControlRef.current) return;
playerControlRef.current.sample();
options.then((options) => playerControlRef.current.play(options)); options.then((options) => playerControlRef.current.play(options));
}} }}
/> />
+7
View File
@@ -0,0 +1,7 @@
import { atom, useAtomValue, useSetAtom } from 'jotai';
const canPlayAtom = atom<boolean>(false as boolean);
export const useCanPlay = () => useAtomValue(canPlayAtom);
export const useSetCanPlay = () => useSetAtom(canPlayAtom);