feat: alt player

This commit is contained in:
ner committed 2025-08-17 18:31:42 +03:00
1 parent 6fc34e3797
commit 2e16746a40
16 files changed
+333 -207

No files matched your search

@@ -1,84 +0,0 @@
'use client';
import { FC, useEffect, useRef } from 'react';
import {
MediaPlayer,
MediaPlayerInstance,
MediaProvider,
PlayButton,
Track,
useMediaState,
VideoSrc
} from '@vidstack/react';
import { NextIcon } from '@vidstack/react/icons';
import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr';
import { cn } from '@/lib/utils';
import CaptionsMenu from './components/CaptionsMenu';
import PlaylistMenu from './components/PlaylistMenu';
import useSource from './useSource';
import '@vidstack/react/player/styles/plyr/theme.css';
interface Props {
magnet: string;
subtitles: Source[];
videos: Source[];
}
const Player: FC<Props> = ({ videos, subtitles, magnet }) => {
const { index, setIndex } = useSource({ magnet });
const player = useRef<MediaPlayerInstance>(null);
const isEnded = useMediaState('ended', player);
const hasNext = index + 1 < videos?.length;
useEffect(() => {
if (!isEnded || !hasNext) return;
setIndex((index) => index + 1);
}, [isEnded, hasNext, setIndex]);
const source = videos[index];
return (
<MediaPlayer
playsInline
load='eager'
storage='movie-advisor'
ref={player}
src={(source as VideoSrc) || []}
className='relative size-full select-none'
>
<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} />
))}
</MediaProvider>
<PlyrLayout
icons={plyrLayoutIcons}
slots={{
playLargeButton: null,
settingsMenu: null,
captionsButton: null,
afterPlayButton: hasNext && (
<PlayButton onClick={() => setIndex(index + 1)} className={cn('plyr__controls__item plyr__control')}>
<NextIcon className={cn('vds-icon')} />
<span className={cn('plyr__tooltip')}>Next</span>
</PlayButton>
),
afterVolumeSlider: <ul className='w-2' />,
beforeSettings: Boolean(subtitles.length) && <CaptionsMenu />,
settings: videos.length > 1 && (
<PlaylistMenu key={source?.src} source={source} sources={videos} onChange={setIndex} />
)
}}
/>
</MediaPlayer>
);
};
export default Player;
@@ -3,7 +3,7 @@ import { ClosedCaptionsIcon, ClosedCaptionsOnIcon } from '@vidstack/react/icons'
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import PlayerMenu from '../PlayerMenu'; import PlayerMenu from '../Menu';
const CaptionsMenu = () => { const CaptionsMenu = () => {
const tracks = useCaptionOptions(); const tracks = useCaptionOptions();
@@ -1,4 +1,4 @@
import React, { FC, forwardRef, MutableRefObject, ReactNode, useRef } from 'react'; import React, { FC, forwardRef, MutableRefObject, ReactNode, useLayoutEffect, 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,15 +20,29 @@ 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 className='max-w-screen-xs rounded-xl p-2' onClose={onResolve} scrollRef={scrollRef}> <Modal
className='max-w-screen-xs rounded-xl p-2'
onClose={onResolve}
scrollRef={scrollRef}
portal={(document.fullscreenElement || document.body) as HTMLElement}
>
<Virtuoso <Virtuoso
useWindowScroll useWindowScroll
initialTopMostItemIndex={+value || 0} overscan={10}
overscan={20} initialItemCount={50}
initialItemCount={20}
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}
@@ -63,7 +77,7 @@ const components: VirtuosoProps<Option, string>['components'] = {
title={option.label} title={option.label}
onClick={() => option.onSelect(option.value)} onClick={() => option.onSelect(option.value)}
className={cn( className={cn(
'!m-0 cursor-pointer whitespace-normal break-all rounded-sm bg-secondary text-left !px-2 !py-1 text-foreground', '!m-0 cursor-pointer line-clamp-2 rounded-sm bg-secondary text-left !px-2 !py-1 text-foreground !mb-2',
{ {
'bg-secondary-foreground text-secondary': context === option.value 'bg-secondary-foreground text-secondary': context === option.value
} }
@@ -75,7 +89,7 @@ const components: VirtuosoProps<Option, string>['components'] = {
}, },
List: forwardRef(function List({ children, ...props }, ref) { List: forwardRef(function List({ children, ...props }, ref) {
return ( return (
<div className='flex flex-col gap-2' {...props} ref={ref}> <div className='flex flex-col' {...props} ref={ref}>
{children} {children}
</div> </div>
); );
@@ -3,7 +3,7 @@ import { PlaylistIcon } from '@vidstack/react/icons';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import PlayerMenu from '../PlayerMenu'; import PlayerMenu from '../Menu';
interface Props { interface Props {
source: Source; source: Source;
@@ -1,58 +1,143 @@
import { useEffect, useRef } from 'react'; 'use client';
import { create, InstanceProps } from 'react-modal-promise';
import { FC, MutableRefObject, useEffect, useImperativeHandle, useRef, useState } from 'react';
import {
MediaPlayer,
MediaPlayerInstance,
MediaProvider,
PlayButton,
Track,
useMediaState,
VideoSrc
} from '@vidstack/react';
import { NextIcon } from '@vidstack/react/icons';
import { PlyrLayout, plyrLayoutIcons } from '@vidstack/react/player/layouts/plyr';
import { Loader } from 'lucide-react'; import { Loader } from 'lucide-react';
import dynamic from 'next/dynamic';
import { Modal } from '@/components/ui/dialog'; import { cn } from '@/lib/utils';
import { useToast } from '@/hooks/useToast';
import { formatBytes } from '@/lib/utils';
import useFiles from './useFiles'; import Captions from './components/Captions';
import { useStats } from './useStats'; import Playlist from './components/Playlist';
import useSource from './useSource';
const Player = dynamic(() => import('./Player')); import '@vidstack/react/player/styles/plyr/theme.css';
interface Props extends InstanceProps<void> { interface Stream {
magnet: string; magnet: string;
hash?: string; subtitles: Source[];
backdrop: string; playlist: Source[];
title: string;
} }
const showPlayer = create(({ onResolve, magnet, hash, backdrop, title }: Props) => { const sample = { type: 'video/mp4', src: '/sample.mp4', name: 'Sample' };
const { subtitles, videos } = useFiles({ magnet, onResolve });
const { isReady, preloadingProgress, downloadSpeed, peers } = useStats({ hash }); const initialStream: Stream = {
magnet: '',
subtitles: [],
playlist: [sample]
};
export type PlayerControlRef = MutableRefObject<{
sample: () => void;
play: (options: { sources: Sources; magnet: string }) => void;
stop: () => void;
}>;
interface Props {
controlRef: PlayerControlRef;
}
const Player: FC<Props> = ({ controlRef }) => {
const [{ magnet, playlist, subtitles }, setStream] = useState<Stream>(initialStream);
const [canPlay, setCanPlay] = useState(false);
const { index, setIndex } = useSource({ magnet });
const player = useRef<MediaPlayerInstance>(null);
const isEnded = useMediaState('ended', player);
const hasNext = index + 1 < playlist?.length;
useEffect(() => {
if (!isEnded || !hasNext) return;
setIndex((index) => index + 1);
}, [isEnded, hasNext, setIndex]);
const source = playlist[index];
const handlePlay = () => {
if (!player.current) return;
player.current
.play()
.catch(() => {})
.finally(() => setCanPlay(true));
};
useImperativeHandle(controlRef, () => ({
sample() {
handlePlay();
setCanPlay(false);
},
play({ magnet, sources }) {
setStream({ magnet, ...sources });
},
stop() {
setStream(initialStream);
}
}));
const pending = !canPlay || source === sample;
return ( return (
<Modal className='overflow-hidden border-none bg-black p-0' onClose={onResolve}> <>
<div className='relative w-full overflow-hidden pt-[56.25%]'> <MediaPlayer
<div className='absolute left-0 top-0 size-full'> load='eager'
<Player magnet={magnet} subtitles={subtitles} videos={videos} /> preload='none'
</div> storage='movie-advisor'
{!isReady && ( ref={player}
<div className='absolute left-0 top-0 size-full'> src={(source as VideoSrc) || []}
<img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} /> onCanPlay={handlePlay}
<div className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/60 transition-all'> className={cn('relative size-full select-none', { invisible: pending })}
{!preloadingProgress && !peers && ( >
<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} />
))}
</MediaProvider>
<PlyrLayout
className='hidden'
icons={plyrLayoutIcons}
slots={{
playLargeButton: null,
settingsMenu: null,
captionsButton: null,
afterPlayButton: hasNext && (
<PlayButton onClick={() => setIndex(index + 1)} className={cn('plyr__controls__item plyr__control')}>
<NextIcon className={cn('vds-icon')} />
<span className={cn('plyr__tooltip')}>Next</span>
</PlayButton>
),
afterVolumeSlider: <ul className='w-2' />,
beforeSettings: Boolean(subtitles.length) && <Captions />,
settings: playlist.length > 1 && (
<Playlist key={source?.src} source={source} sources={playlist} onChange={setIndex} />
)
}}
/>
</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'> <div className='animate-spin'>
<Loader color='white' /> <Loader color='white' />
</div> </div>
)}
</div>
{(downloadSpeed || peers) && (
<div className='absolute left-0 top-0 flex size-full flex-col items-center justify-center text-white'>
<div className='flex h-[90px] w-[230px] flex-col items-center justify-center gap-2 rounded-xl bg-black/80 p-4 shadow-2xl'>
<p className='text-white/90'>Buffering: {preloadingProgress.toFixed()}%</p>
<p className='text-white/90'>Download speed: {downloadSpeed || '0 B/s'}</p>
</div> </div>
</div> </div>
)} )}
</div> </>
)}
</div>
</Modal>
); );
}); };
export default showPlayer; export default Player;
@@ -1,63 +0,0 @@
import { useEffect, useRef } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useStreamUrl } from '@/hooks/useStreamUrl';
import { useToast } from '@/hooks/useToast';
export type Source = { name: string; src: string; type: string };
type Sources = { subtitles: Source[]; videos: Source[] };
interface Props {
magnet: string;
onResolve: () => void;
}
const useFiles = ({ magnet, onResolve }: Props) => {
const streamUrl = `${useStreamUrl()}/stream?link=${encodeURIComponent(magnet)}`;
const query = useQuery<Stream>({
queryKey: ['files', magnet],
queryFn: () => fetch(`${streamUrl}&stat&preload`).then((response) => response.json())
});
const data = (query.data?.file_stats || []).reduce<Sources>(
(sources, file) => {
if (file.path.endsWith('.mp4')) {
sources.videos.push({ src: `${streamUrl}&index=${file.id}&play`, name: file.path, type: 'video/mp4' });
}
if (file.path.endsWith('.srt')) {
sources.subtitles.push({ src: `${streamUrl}&index=${file.id}&play`, name: file.path, type: 'srt' });
}
return sources;
},
{ subtitles: [], videos: [] }
);
const isResolvedRef = useRef(false);
const { toast } = useToast();
useEffect(() => {
const close = () => {
if (isResolvedRef.current) return;
isResolvedRef.current = true;
onResolve();
};
if (query.error) {
toast({ description: 'Download Failed: unable to retrieve the video' });
close();
}
if (query.isFetched && !data.videos.length) {
toast({ description: 'This torrent doesn’t contain any compatible video files' });
close();
}
}, [query.isFetched, data.videos.length, query.error]);
return data;
};
export default useFiles;
@@ -10,7 +10,11 @@ const sourceStateAtom = atomWithStorage<SourceState>('current-video-source', {},
unstable_getOnInit: true unstable_getOnInit: true
}); });
const useSource = ({ magnet }: { magnet: string }) => { interface Props {
magnet: string;
}
const useSource = ({ magnet }: Props) => {
const [source, setSource] = useAtom(sourceStateAtom); const [source, setSource] = useAtom(sourceStateAtom);
const account = useAccount(); const account = useAccount();
@@ -0,0 +1,53 @@
import { create, InstanceProps } from 'react-modal-promise';
import { DialogContentProps } from '@radix-ui/react-dialog';
import { Modal } from '@/components/ui/dialog';
import { useStats } from './useStats';
interface Props extends InstanceProps<void> {
hash: string;
backdrop: string;
title: string;
playerEntryId: string;
}
const showPlayerModal = create(({ onResolve, hash, backdrop, title, playerEntryId }: Props) => {
const { isReady, preloadingProgress, downloadSpeed, peers } = useStats({ hash });
const handlePlayerInteraction: DialogContentProps['onInteractOutside'] = (event) => {
if (document.getElementById(playerEntryId)?.contains(event.target as Node)) event.preventDefault();
};
return (
<Modal
className='overflow-hidden border-none bg-black p-0'
onClose={onResolve}
onInteractOutside={handlePlayerInteraction}
onPointerDownOutside={handlePlayerInteraction}
>
<div className='relative w-full overflow-hidden pt-[56.25%]'>
{!isReady && (
<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}%` }}
/>
<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>
</div>
<div className='grid w-full items-center gap-2 bg-black/80 p-2 text-center'>
<p>Download speed: {downloadSpeed || '0 B/s'}</p>
</div>
</div>
</div>
)}
<div className='absolute left-0 top-0 size-full' id={playerEntryId} />
</div>
</Modal>
);
});
export default showPlayerModal;
@@ -9,8 +9,9 @@ import { cn, detectSafari, getMagnetHash } from '@/lib/utils';
import { providers } from '../../../../constants'; import { providers } from '../../../../constants';
import { useCastMagnet, usePrefix } from '../../../../hooks/useMagnetHosts'; import { useCastMagnet, usePrefix } from '../../../../hooks/useMagnetHosts';
import showPlayer from '../../../Player';
import showPlayerModal from './components/Player';
import useFiles from './useFiles';
import useMagnet from './useMagnet'; import useMagnet from './useMagnet';
interface Props { interface Props {
@@ -18,9 +19,11 @@ interface Props {
backdrop: string; backdrop: string;
title: string; title: string;
provider: string; provider: string;
onPlay: (options: Promise<{ sources: Sources; magnet: string }>) => void;
playerEntryId: string;
} }
const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => { const Actions: FC<Props> = ({ torrent, backdrop, title, provider, playerEntryId, onPlay }) => {
const prefix = usePrefix(); const prefix = usePrefix();
const cast = useCastMagnet(); const cast = useCastMagnet();
const streamUrl = useStreamUrl(); const streamUrl = useStreamUrl();
@@ -45,6 +48,8 @@ const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => {
const magnet = fetchMagnet.data || torrent.magnet; const magnet = fetchMagnet.data || torrent.magnet;
const fetchSources = useFiles({ magnet });
const hash = getMagnetHash(magnet); const hash = getMagnetHash(magnet);
const supportedForCast = prefix && !prefix.includes('{host}'); const supportedForCast = prefix && !prefix.includes('{host}');
@@ -59,7 +64,10 @@ const Actions: FC<Props> = ({ torrent, backdrop, title, provider }) => {
'flex-grow-0 px-3 bg-red-600', 'flex-grow-0 px-3 bg-red-600',
'hover:shadow-lg hover:shadow-red-600/60 duration-200 transition-all hover:bg-red-600' 'hover:shadow-lg hover:shadow-red-600/60 duration-200 transition-all hover:bg-red-600'
)} )}
onClick={() => showPlayer({ magnet, backdrop, title, hash })} onClick={() => {
showPlayerModal({ backdrop, title, hash, playerEntryId });
onPlay(fetchSources.mutateAsync().then((sources) => ({ sources, magnet })));
}}
title='Play' title='Play'
> >
<Play size={15} /> <Play size={15} />
@@ -0,0 +1,47 @@
import { useMutation } from '@tanstack/react-query';
import { useStreamUrl } from '@/hooks/useStreamUrl';
interface Props {
magnet: string;
}
const useFiles = ({ magnet }: Props) => {
const streamUrl = `${useStreamUrl()}/stream?link=${encodeURIComponent(magnet)}`;
return useMutation<Sources>({
mutationFn: () =>
fetch(`${streamUrl}&stat&preload`)
.then((response) => {
if (!response.ok) return Promise.reject('Download Failed: unable to retrieve the video');
return response.json();
})
.then(({ file_stats: stats }: Stream) => {
const sources = stats.reduce<Sources>(
(sources, file) => {
const src = `${streamUrl}&index=${file.id}&play`;
const name = file.path;
if (file.path.endsWith('.mp4')) {
sources.playlist.push({ src, name, type: 'video/mp4' });
}
if (file.path.endsWith('.srt')) {
sources.subtitles.push({ src, name, type: 'srt' });
}
return sources;
},
{ subtitles: [], playlist: [] }
);
if (!sources.playlist.length)
return Promise.reject('This torrent doesn’t contain any compatible video files');
return sources;
})
});
};
export default useFiles;
@@ -17,9 +17,22 @@ interface Props {
provider: string; provider: string;
year: number; year: number;
onChangeSort: (sort: Sort) => void; onChangeSort: (sort: Sort) => void;
onPlay: (options: Promise<{ sources: Sources; magnet: string }>) => void;
playerEntryId: string;
} }
const TorrentsTable: FC<Props> = ({ title, torrents, backdrop, sort, sortable, provider, year, onChangeSort }) => { const TorrentsTable: FC<Props> = ({
title,
torrents,
backdrop,
sort,
sortable,
provider,
year,
onChangeSort,
onPlay,
playerEntryId
}) => {
const colSpan = 5; const colSpan = 5;
return ( return (
@@ -68,7 +81,14 @@ const TorrentsTable: FC<Props> = ({ title, torrents, backdrop, sort, sortable, p
</TableCell> </TableCell>
<TableCell className='truncate p-2'>{torrent.seeders}</TableCell> <TableCell className='truncate p-2'>{torrent.seeders}</TableCell>
<TableCell className='p-1 pr-2 text-center'> <TableCell className='p-1 pr-2 text-center'>
<Actions title={title} backdrop={backdrop} torrent={torrent} provider={provider} /> <Actions
title={title}
backdrop={backdrop}
torrent={torrent}
provider={provider}
onPlay={onPlay}
playerEntryId={playerEntryId}
/>
</TableCell> </TableCell>
</TableRow> </TableRow>
</Fragment> </Fragment>
@@ -1,4 +1,5 @@
import React, { FormEvent, useState } from 'react'; import React, { FormEvent, useId, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { create, InstanceProps } from 'react-modal-promise'; import { create, InstanceProps } from 'react-modal-promise';
import { TabsContent } from '@radix-ui/react-tabs'; import { TabsContent } from '@radix-ui/react-tabs';
import { Loader } from 'lucide-react'; import { Loader } from 'lucide-react';
@@ -11,6 +12,7 @@ import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Sort } from '@/data/parsers'; import { Sort } from '@/data/parsers';
import Player, { PlayerControlRef } from './components/Player';
import TorrentsTable from './components/TorrentsTable'; import TorrentsTable from './components/TorrentsTable';
import { providers } from './constants'; import { providers } from './constants';
import useTorrents from './useTorrents'; import useTorrents from './useTorrents';
@@ -68,6 +70,12 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
} }
]; ];
const playerControlRef = useRef() as PlayerControlRef;
const playerEntryId = useId();
const playerEntryRef = useRef<HTMLDivElement>(null);
const handleSearch = (event: FormEvent) => { const handleSearch = (event: FormEvent) => {
event.preventDefault(); event.preventDefault();
@@ -78,6 +86,13 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
query.isFetched && !query.isLoading && !query.data?.length; query.isFetched && !query.isLoading && !query.data?.length;
return ( return (
<>
<div className='hidden' ref={playerEntryRef}>
{createPortal(
<Player controlRef={playerControlRef} />,
document.getElementById(playerEntryId) || playerEntryRef.current || document.body
)}
</div>
<Modal className='rounded-xl p-0' onClose={onResolve}> <Modal className='rounded-xl p-0' onClose={onResolve}>
<form className='p-2' tabIndex={1} onSubmit={handleSearch}> <form className='p-2' tabIndex={1} onSubmit={handleSearch}>
<ButtonsGroup className='h-10'> <ButtonsGroup className='h-10'>
@@ -104,7 +119,7 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
</TabsTrigger> </TabsTrigger>
))} ))}
</TabsList> </TabsList>
{tabs.map(({ provider, query }, index) => { {tabs.map(({ provider, query }) => {
const isEmpty = checkIsEmpty(query); const isEmpty = checkIsEmpty(query);
return ( return (
@@ -118,6 +133,13 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
onChangeSort={setSort} onChangeSort={setSort}
provider={provider.key} provider={provider.key}
torrents={query.data || []} torrents={query.data || []}
playerEntryId={playerEntryId}
onPlay={(options) => {
if (!playerControlRef.current) return;
playerControlRef.current.sample();
options.then((options) => playerControlRef.current.play(options));
}}
/> />
{(query.isLoading || query.isFetching) && ( {(query.isLoading || query.isFetching) && (
@@ -136,6 +158,7 @@ const showTorrentsModal = create(({ title: initialTitle, year, imdbID, backdrop,
})} })}
</Tabs> </Tabs>
</Modal> </Modal>
</>
); );
}); });
+18 -4
View File
@@ -3,6 +3,7 @@
import * as React from 'react'; import * as React from 'react';
import { CSSProperties, useState } from 'react'; import { CSSProperties, useState } from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog'; import * as DialogPrimitive from '@radix-ui/react-dialog';
import { DialogContentProps } from '@radix-ui/react-dialog';
import useScrollDelta from '@/hooks/useScrollDelta'; import useScrollDelta from '@/hooks/useScrollDelta';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -37,8 +38,9 @@ const DialogContent = React.forwardRef<
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
onClose?: () => void; onClose?: () => void;
scrollRef?: React.MutableRefObject<HTMLDivElement>; scrollRef?: React.MutableRefObject<HTMLDivElement>;
portal?: HTMLElement;
} }
>(({ className, children, onClose, scrollRef, ...props }, ref) => { >(({ className, children, onClose, scrollRef, portal, ...props }, ref) => {
const FULL_OPACITY = 1; const FULL_OPACITY = 1;
const position = React.useRef(0); const position = React.useRef(0);
@@ -101,7 +103,7 @@ const DialogContent = React.forwardRef<
}; };
return ( return (
<DialogPortal> <DialogPortal container={portal}>
<div className='fixed inset-0 z-50 size-full bg-black/80' data-overlay ref={wrapperRef}> <div className='fixed inset-0 z-50 size-full bg-black/80' data-overlay ref={wrapperRef}>
<DialogOverlay <DialogOverlay
ref={(element) => { ref={(element) => {
@@ -172,7 +174,10 @@ const Modal: React.FC<{
style?: CSSProperties; style?: CSSProperties;
onClose: () => void; onClose: () => void;
scrollRef?: React.MutableRefObject<HTMLDivElement>; scrollRef?: React.MutableRefObject<HTMLDivElement>;
}> = ({ children, onClose, className, style, scrollRef }) => { onInteractOutside?: DialogContentProps['onInteractOutside'];
onPointerDownOutside?: DialogContentProps['onPointerDownOutside'];
portal?: HTMLElement;
}> = ({ children, onClose, className, style, scrollRef, onInteractOutside, onPointerDownOutside, portal }) => {
const [open, setOpen] = useState(true); const [open, setOpen] = useState(true);
React.useLayoutEffect(() => { React.useLayoutEffect(() => {
@@ -194,7 +199,16 @@ const Modal: React.FC<{
<DialogHeader> <DialogHeader>
<DialogTitle /> <DialogTitle />
</DialogHeader> </DialogHeader>
<DialogContent style={style} scrollRef={scrollRef} forceMount onClose={handleClose} className={className}> <DialogContent
onInteractOutside={onInteractOutside}
onPointerDownOutside={onPointerDownOutside}
style={style}
scrollRef={scrollRef}
forceMount
onClose={handleClose}
className={className}
portal={portal}
>
{children} {children}
<DialogDescription className='hidden' /> <DialogDescription className='hidden' />
</DialogContent> </DialogContent>
BIN
View File
Binary file not shown.
Vendored
+5
View File
@@ -141,6 +141,11 @@ interface Source {
type: string; type: string;
} }
interface Sources {
playlist: Source[];
subtitles: Source[];
}
interface Subtitles { interface Subtitles {
name: string; name: string;
content: string; content: string;