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 { cn } from '@/lib/utils';
@@ -8,11 +9,24 @@ import PlayerMenu from '../Menu';
const CaptionsMenu = () => {
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 (
<PlayerMenu
closeOnSelect
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 ? (
<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 { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
import { Menu } from '@vidstack/react';
@@ -20,29 +20,20 @@ const showMenu = create(
const virtuosoRef = useRef<VirtuosoHandle | null>(null);
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 (
<Modal
className='max-w-screen-xs rounded-xl p-2'
className='max-w-screen-xs rounded-xl'
onClose={onResolve}
scrollRef={scrollRef}
portal={(document.fullscreenElement || document.body) as HTMLElement}
>
<Virtuoso
useWindowScroll
initialItemCount={20}
overscan={10}
initialItemCount={50}
initialTopMostItemIndex={+value || 0}
ref={virtuosoRef}
customScrollParent={scrollRef.current}
defaultItemHeight={56}
fixedItemHeight={56}
data={options}
context={value}
components={components}
@@ -70,14 +61,14 @@ const components: VirtuosoProps<Option, string>['components'] = {
Item: ({ item: option, children, context, ...props }) => {
if (!option) return null;
const index = props['data-index'];
return (
<div {...props} key={option.label} title={option.label} onClick={() => option.onSelect(option.value)}>
{!index && <div className='h-2 w-full' />}
<div
{...props}
key={option.value}
title={option.label}
onClick={() => option.onSelect(option.value)}
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
}
@@ -85,11 +76,13 @@ const components: VirtuosoProps<Option, string>['components'] = {
>
{option.label}
</div>
<div className='h-2 w-full' />
</div>
);
},
List: forwardRef(function List({ children, ...props }, ref) {
return (
<div className='flex flex-col' {...props} ref={ref}>
<div className='flex flex-col p-2' {...props} ref={ref}>
{children}
</div>
);
@@ -12,8 +12,8 @@ import {
} from '@vidstack/react';
import { NextIcon } from '@vidstack/react/icons';
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 Captions from './components/Captions';
@@ -30,16 +30,8 @@ interface Stream {
const sample = { type: 'video/mp4', src: '/sample.mp4', name: 'Sample' };
const initialStream: Stream = {
magnet: '',
subtitles: [],
playlist: [sample]
};
export type PlayerControlRef = MutableRefObject<{
sample: () => void;
play: (options: { sources: Sources; magnet: string }) => void;
stop: () => void;
}>;
interface Props {
@@ -47,8 +39,13 @@ interface Props {
}
const Player: FC<Props> = ({ controlRef }) => {
const [{ magnet, playlist, subtitles }, setStream] = useState<Stream>(initialStream);
const [canPlay, setCanPlay] = useState(false);
const [{ magnet, playlist, subtitles }, setStream] = useState<Stream>({
magnet: '',
subtitles: [],
playlist: [sample]
});
const canPlay = useCanPlay();
const setCanPlay = useSetCanPlay();
const { index, setIndex } = useSource({ magnet });
@@ -72,38 +69,46 @@ const Player: FC<Props> = ({ controlRef }) => {
player.current
.play()
.catch(() => {})
.finally(() => setCanPlay(true));
.finally(() => {
if (source === sample) return;
setCanPlay(true);
});
};
useImperativeHandle(controlRef, () => ({
sample() {
handlePlay();
setCanPlay(false);
},
play({ magnet, sources }) {
setStream({ magnet, ...sources });
},
stop() {
setStream(initialStream);
setCanPlay(false);
}
}));
const pending = !canPlay || source === sample;
const pending = !canPlay;
return (
<>
<MediaPlayer
playsInline
autoPlay
load='eager'
preload='none'
storage='movie-advisor'
ref={player}
loop={pending}
src={(source as VideoSrc) || []}
onCanPlay={handlePlay}
className={cn('relative size-full select-none', { invisible: pending })}
>
<MediaProvider className='relative flex size-full justify-center [&>video]:!h-full'>
{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>
<PlyrLayout
@@ -127,16 +132,6 @@ const Player: FC<Props> = ({ controlRef }) => {
}}
/>
</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 { DialogContentProps } from '@radix-ui/react-dialog';
import { Loader } from 'lucide-react';
import { Modal } from '@/components/ui/dialog';
import { useCanPlay, useSetCanPlay } from '@/hooks/useCanPlay';
import { useStats } from './useStats';
@@ -13,27 +15,40 @@ interface Props extends InstanceProps<void> {
}
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) => {
if (document.getElementById(playerEntryId)?.contains(event.target as Node)) event.preventDefault();
};
const handleClose = () => {
setCanPlay(false);
onResolve();
};
return (
<Modal
className='overflow-hidden border-none bg-black p-0'
onClose={onResolve}
onClose={handleClose}
onInteractOutside={handlePlayerInteraction}
onPointerDownOutside={handlePlayerInteraction}
>
<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'>
<img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} />
<div
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='grid w-full items-center bg-black/80 p-2 text-center'>
<p>Buffering: {preloadingProgress.toFixed()}%</p>
@@ -44,7 +59,6 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, playerEntryI
</div>
</div>
)}
<div className='absolute left-0 top-0 size-full' id={playerEntryId} />
</div>
</Modal>
);
@@ -6,6 +6,7 @@ import { formatBytes } from '@/lib/utils';
interface Props {
hash?: string;
canPlay: boolean;
}
export enum StreamStatus {
@@ -14,14 +15,14 @@ export enum StreamStatus {
ready = 3
}
export const useStats = ({ hash }: Props) => {
export const useStats = ({ hash, canPlay }: Props) => {
const streamUrl = useStreamUrl();
const { data } = useQuery<Stream & { stat: StreamStatus }>({
enabled: Boolean(hash),
queryKey: ['stats', hash],
refetchInterval: ({ state }) => {
if (state.data?.stat === StreamStatus.ready) return false;
if (state.data?.stat === StreamStatus.ready && canPlay) return false;
return 1000;
},
@@ -11,7 +11,7 @@ const useFiles = ({ magnet }: Props) => {
return useMutation<Sources>({
mutationFn: () =>
fetch(`${streamUrl}&stat&preload`)
fetch(`${streamUrl}&stat`)
.then((response) => {
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) => {
if (!playerControlRef.current) return;
playerControlRef.current.sample();
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);