diff options
Diffstat (limited to 'components/watch')
19 files changed, 1855 insertions, 1004 deletions
diff --git a/components/watch/new-player/components/bufferingIndicator.tsx b/components/watch/new-player/components/bufferingIndicator.tsx new file mode 100644 index 0000000..4793d55 --- /dev/null +++ b/components/watch/new-player/components/bufferingIndicator.tsx @@ -0,0 +1,15 @@ +import { Spinner } from "@vidstack/react"; + +export default function BufferingIndicator() { + return ( + <div className="pointer-events-none absolute inset-0 z-50 flex h-full w-full items-center justify-center"> + <Spinner.Root + className="text-white opacity-0 transition-opacity duration-200 ease-linear media-buffering:animate-spin media-buffering:opacity-100" + size={84} + > + <Spinner.Track className="opacity-25" width={8} /> + <Spinner.TrackFill className="opacity-75" width={8} /> + </Spinner.Root> + </div> + ); +} diff --git a/components/watch/new-player/components/buttons.tsx b/components/watch/new-player/components/buttons.tsx new file mode 100644 index 0000000..18c2b42 --- /dev/null +++ b/components/watch/new-player/components/buttons.tsx @@ -0,0 +1,277 @@ +import { useWatchProvider } from "@/lib/context/watchPageProvider"; +import { + CaptionButton, + FullscreenButton, + isTrackCaptionKind, + MuteButton, + PIPButton, + PlayButton, + Tooltip, + useMediaState, + type TooltipPlacement, + useMediaRemote, + useMediaStore, +} from "@vidstack/react"; +import { + ClosedCaptionsIcon, + ClosedCaptionsOnIcon, + FullscreenExitIcon, + FullscreenIcon, + MuteIcon, + PauseIcon, + PictureInPictureExitIcon, + PictureInPictureIcon, + PlayIcon, + ReplayIcon, + TheatreModeExitIcon, + TheatreModeIcon, + VolumeHighIcon, + VolumeLowIcon, +} from "@vidstack/react/icons"; +import { useRouter } from "next/router"; +import { Navigation } from "../player"; + +export interface MediaButtonProps { + tooltipPlacement: TooltipPlacement; + navigation?: Navigation; + host?: boolean; +} + +export const buttonClass = + "group ring-media-focus relative inline-flex h-10 w-10 cursor-pointer items-center justify-center rounded-md outline-none ring-inset hover:bg-white/20 data-[focus]:ring-4"; + +export const tooltipClass = + "animate-out fade-out slide-out-to-bottom-2 data-[visible]:animate-in data-[visible]:fade-in data-[visible]:slide-in-from-bottom-4 z-10 rounded-sm bg-black/90 px-2 py-0.5 text-sm font-medium text-white parent-data-[open]:hidden"; + +export function Play({ tooltipPlacement }: MediaButtonProps) { + const isPaused = useMediaState("paused"), + ended = useMediaState("ended"), + tooltipText = isPaused ? "Play" : "Pause", + Icon = ended ? ReplayIcon : isPaused ? PlayIcon : PauseIcon; + return ( + <Tooltip.Root> + <Tooltip.Trigger asChild> + <PlayButton className={buttonClass}> + <Icon className="w-8 h-8" /> + </PlayButton> + </Tooltip.Trigger> + <Tooltip.Content className={tooltipClass} placement={tooltipPlacement}> + {tooltipText} + </Tooltip.Content> + </Tooltip.Root> + ); +} + +export function MobilePlayButton({ tooltipPlacement, host }: MediaButtonProps) { + const isPaused = useMediaState("paused"), + ended = useMediaState("ended"), + Icon = ended ? ReplayIcon : isPaused ? PlayIcon : PauseIcon; + return ( + <Tooltip.Root> + <Tooltip.Trigger asChild> + <PlayButton + className={`${ + host ? "" : "pointer-events-none" + } group ring-media-focus relative inline-flex h-16 w-16 media-paused:cursor-pointer cursor-default items-center justify-center rounded-full outline-none`} + > + <Icon className="w-10 h-10" /> + </PlayButton> + </Tooltip.Trigger> + {/* <Tooltip.Content + className="animate-out fade-out slide-out-to-bottom-2 data-[visible]:animate-in data-[visible]:fade-in data-[visible]:slide-in-from-bottom-4 z-10 rounded-sm bg-black/90 px-2 py-0.5 text-sm font-medium text-white parent-data-[open]:hidden" + placement={tooltipPlacement} + > + {tooltipText} + </Tooltip.Content> */} + </Tooltip.Root> + ); +} + +export function Mute({ tooltipPlacement }: MediaButtonProps) { + const volume = useMediaState("volume"), + isMuted = useMediaState("muted"); + return ( + <Tooltip.Root> + <Tooltip.Trigger asChild> + <MuteButton className={buttonClass}> + {isMuted || volume == 0 ? ( + <MuteIcon className="w-8 h-8" /> + ) : volume < 0.5 ? ( + <VolumeLowIcon className="w-8 h-8" /> + ) : ( + <VolumeHighIcon className="w-8 h-8" /> + )} + </MuteButton> + </Tooltip.Trigger> + <Tooltip.Content className={tooltipClass} placement={tooltipPlacement}> + {isMuted ? "Unmute" : "Mute"} + </Tooltip.Content> + </Tooltip.Root> + ); +} + +export function Caption({ tooltipPlacement }: MediaButtonProps) { + const track = useMediaState("textTrack"), + isOn = track && isTrackCaptionKind(track); + return ( + <Tooltip.Root> + <Tooltip.Trigger asChild> + <CaptionButton className={buttonClass}> + {isOn ? ( + <ClosedCaptionsOnIcon className="w-8 h-8" /> + ) : ( + <ClosedCaptionsIcon className="w-8 h-8" /> + )} + </CaptionButton> + </Tooltip.Trigger> + <Tooltip.Content className={tooltipClass} placement={tooltipPlacement}> + {isOn ? "Closed-Captions On" : "Closed-Captions Off"} + </Tooltip.Content> + </Tooltip.Root> + ); +} + +export function TheaterButton({ tooltipPlacement }: MediaButtonProps) { + const playerState = useMediaState("currentTime"), + isPlaying = useMediaState("playing"); + + const { setPlayerState, setTheaterMode, theaterMode } = useWatchProvider(); + + return ( + <Tooltip.Root> + <Tooltip.Trigger asChild> + <button + type="button" + className={buttonClass} + onClick={() => { + setPlayerState((prev: any) => ({ + ...prev, + currentTime: playerState, + isPlaying: isPlaying, + })); + setTheaterMode((prev: any) => !prev); + }} + > + {!theaterMode ? ( + <TheatreModeIcon className="w-8 h-8" /> + ) : ( + <TheatreModeExitIcon className="w-8 h-8" /> + )} + </button> + </Tooltip.Trigger> + <Tooltip.Content className={tooltipClass} placement={tooltipPlacement}> + Theatre Mode + </Tooltip.Content> + </Tooltip.Root> + ); +} + +export function PIP({ tooltipPlacement }: MediaButtonProps) { + const isActive = useMediaState("pictureInPicture"); + return ( + <Tooltip.Root> + <Tooltip.Trigger asChild> + <PIPButton className={buttonClass}> + {isActive ? ( + <PictureInPictureExitIcon className="w-8 h-8" /> + ) : ( + <PictureInPictureIcon className="w-8 h-8" /> + )} + </PIPButton> + </Tooltip.Trigger> + <Tooltip.Content className={tooltipClass} placement={tooltipPlacement}> + {isActive ? "Exit PIP" : "Enter PIP"} + </Tooltip.Content> + </Tooltip.Root> + ); +} + +export function PlayNextButton({ + tooltipPlacement, + navigation, +}: MediaButtonProps) { + // const remote = useMediaRemote(); + const router = useRouter(); + const { dataMedia, track } = useWatchProvider(); + return ( + <button + title="next-button" + type="button" + onClick={() => { + if (navigation?.next) { + router.push( + `/en/anime/watch/${dataMedia.id}/${track.provider}?id=${ + navigation?.next?.id + }&num=${navigation?.next?.number}${ + track?.isDub ? `&dub=${track?.isDub}` : "" + }` + ); + } + }} + className="next-button hidden" + > + Next Episode + </button> + ); +} + +export function SkipOpButton({ tooltipPlacement }: MediaButtonProps) { + const remote = useMediaRemote(); + const { track } = useWatchProvider(); + const op = track?.skip?.find((item: any) => item.text === "Opening"); + + return ( + <button + type="button" + onClick={() => { + remote.seek(op?.endTime); + }} + className="op-button hidden hover:bg-white/80 bg-white px-4 py-2 text-primary font-karla font-semibold rounded-md" + > + Skip Opening + </button> + ); +} + +export function SkipEdButton({ tooltipPlacement }: MediaButtonProps) { + const remote = useMediaRemote(); + const { duration } = useMediaStore(); + const { track } = useWatchProvider(); + const ed = track?.skip?.find((item: any) => item.text === "Ending"); + + const endTime = + Math.round(duration) === ed?.endTime ? ed?.endTime - 1 : ed?.endTime; + + // console.log(endTime); + + return ( + <button + title="ed-button" + type="button" + onClick={() => remote.seek(endTime)} + className="ed-button hidden cursor-pointer hover:bg-white/80 bg-white px-4 py-2 text-primary font-karla font-semibold rounded-md" + > + Skip Ending + </button> + ); +} + +export function Fullscreen({ tooltipPlacement }: MediaButtonProps) { + const isActive = useMediaState("fullscreen"); + return ( + <Tooltip.Root> + <Tooltip.Trigger asChild> + <FullscreenButton className={buttonClass}> + {isActive ? ( + <FullscreenExitIcon className="w-8 h-8" /> + ) : ( + <FullscreenIcon className="w-8 h-8" /> + )} + </FullscreenButton> + </Tooltip.Trigger> + <Tooltip.Content className={tooltipClass} placement={tooltipPlacement}> + {isActive ? "Exit Fullscreen" : "Enter Fullscreen"} + </Tooltip.Content> + </Tooltip.Root> + ); +} diff --git a/components/watch/new-player/components/chapter-title.tsx b/components/watch/new-player/components/chapter-title.tsx new file mode 100644 index 0000000..779f826 --- /dev/null +++ b/components/watch/new-player/components/chapter-title.tsx @@ -0,0 +1,11 @@ +import { ChapterTitle, type ChapterTitleProps } from "@vidstack/react"; +import { ChevronLeftIcon, ChevronRightIcon } from "@vidstack/react/icons"; + +export function ChapterTitleComponent() { + return ( + <span className="inline-block flex-1 overflow-hidden text-ellipsis whitespace-nowrap px-2 text-sm font-medium text-white"> + <span className="mr-1 text-txt">•</span> + <ChapterTitle className="ml-1" /> + </span> + ); +} diff --git a/components/watch/new-player/components/layouts/captions.module.css b/components/watch/new-player/components/layouts/captions.module.css new file mode 100644 index 0000000..338b96e --- /dev/null +++ b/components/watch/new-player/components/layouts/captions.module.css @@ -0,0 +1,80 @@ +.captions { + @apply font-roboto font-medium; + /* Recommended settings in the WebVTT spec (https://www.w3.org/TR/webvtt1). */ + /* --cue-color: var(--media-cue-color, white); */ + /* --cue-color: white; */ + /* z-index: 20; */ + /* --cue-bg-color: var(--media-cue-bg, rgba(0, 0, 0, 0.7)); */ + + /* bg color white */ + --cue-bg-color: rgba(255, 255, 255, 0.9); + --cue-font-size: calc(var(--overlay-height) / 100 * 5); + --cue-line-height: calc(var(--cue-font-size) * 1.2); + --cue-padding-x: 0.5em; + --cue-padding-y: 0.1em; + + /* remove background blur */ + + /* --cue-text-shadow: 0 0 5px black; */ + + font-size: var(--cue-font-size); + word-spacing: normal; + text-shadow: 0px 2px 8px rgba(0, 0, 0, 1); + /* contain: layout style; */ +} + +.captions[data-dir="rtl"] :global([data-part="cue-display"]) { + direction: rtl; +} + +.captions[aria-hidden="true"] { + display: none; +} + +/************************************************************************************************* + * Cue Display + *************************************************************************************************/ + +/* +* Most of the cue styles are set automatically by our [media-captions](https://github.com/vidstack/media-captions) +* library via CSS variables. They are inferred from the VTT, SRT, or SSA file cue settings. You're +* free to ignore them and style the captions as desired, but we don't recommend it unless the +* captions file contains no cue settings. Otherwise, you might be breaking accessibility. +*/ +.captions :global([data-part="cue-display"]) { + position: absolute; + direction: ltr; + overflow: visible; + contain: content; + top: var(--cue-top); + left: var(--cue-left); + right: var(--cue-right); + bottom: var(--cue-bottom); + width: var(--cue-width, auto); + height: var(--cue-height, auto); + transform: var(--cue-transform); + text-align: var(--cue-text-align); + writing-mode: var(--cue-writing-mode, unset); + white-space: pre-line; + unicode-bidi: plaintext; + min-width: min-content; + min-height: min-content; +} + +.captions :global([data-part="cue"]) { + display: inline-block; + contain: content; + /* border-radius: 2px; */ + /* backdrop-filter: unset; */ + padding: var(--cue-padding-y) var(--cue-padding-x); + line-height: var(--cue-line-height); + /* background-color: var(--cue-bg-color); */ + color: var(--cue-color); + white-space: pre-wrap; + outline: var(--cue-outline); + text-shadow: var(--cue-text-shadow); +} + +.captions :global([data-part="cue-display"][data-vertical] [data-part="cue"]) { + padding: var(--cue-padding-x) var(--cue-padding-y); +} diff --git a/components/watch/new-player/components/layouts/video-layout.module.css b/components/watch/new-player/components/layouts/video-layout.module.css new file mode 100644 index 0000000..14540f6 --- /dev/null +++ b/components/watch/new-player/components/layouts/video-layout.module.css @@ -0,0 +1,13 @@ +.controls { + /* + * These CSS variables are supported out of the box to easily apply offsets to all popups. + * You can also offset via props on `Tooltip.Content`, `Menu.Content`, and slider previews. + */ + --media-tooltip-y-offset: 30px; + --media-menu-y-offset: 30px; +} + +.controls :global(.volume-slider) { + --media-slider-preview-offset: 30px; + margin-left: 1.5px; +} diff --git a/components/watch/new-player/components/layouts/video-layout.tsx b/components/watch/new-player/components/layouts/video-layout.tsx new file mode 100644 index 0000000..fa1f6c3 --- /dev/null +++ b/components/watch/new-player/components/layouts/video-layout.tsx @@ -0,0 +1,173 @@ +import captionStyles from "./captions.module.css"; +import styles from "./video-layout.module.css"; + +import { + Captions, + Controls, + Gesture, + Spinner, + useMediaState, +} from "@vidstack/react"; + +import * as Buttons from "../buttons"; +import * as Menus from "../menus"; +import * as Sliders from "../sliders"; +import { TimeGroup } from "../time-group"; +import { Title } from "../title"; +import { ChapterTitleComponent } from "../chapter-title"; +import { useWatchProvider } from "@/lib/context/watchPageProvider"; +import { Navigation } from "../../player"; +import BufferingIndicator from "../bufferingIndicator"; +import { useEffect, useState } from "react"; + +export interface VideoLayoutProps { + thumbnails?: string; + navigation?: Navigation; + host?: boolean; +} + +function isMobileDevice() { + if (typeof window !== "undefined") { + return ( + typeof window.orientation !== "undefined" || + navigator.userAgent.indexOf("IEMobile") !== -1 + ); + } + return false; +} + +export function VideoLayout({ + thumbnails, + navigation, + host = true, +}: VideoLayoutProps) { + const [isMobile, setIsMobile] = useState(false); + + const { track } = useWatchProvider(); + const isFullscreen = useMediaState("fullscreen"); + + useEffect(() => { + setIsMobile(isMobileDevice()); + }, []); + + return ( + <> + <Gestures host={host} /> + <Captions + className={`${captionStyles.captions} media-preview:opacity-0 media-controls:bottom-[85px] media-captions:opacity-100 absolute inset-0 bottom-2 z-10 select-none break-words opacity-0 transition-[opacity,bottom] duration-300`} + /> + <Controls.Root + className={`${styles.controls} media-paused:bg-black/10 duration-200 media-controls:opacity-100 absolute inset-0 z-10 flex h-full w-full flex-col bg-gradient-to-t from-black/30 via-transparent to-black/30 opacity-0 transition-opacity`} + > + <Controls.Group className="flex justify-between items-center w-full px-2 pt-2"> + <Title navigation={navigation} /> + <div className="flex-1" /> + {/* <Menus.Episodes placement="left start" /> */} + </Controls.Group> + <div className="flex-1" /> + + {/* {isPaused && ( */} + <Controls.Group + className={`media-paused:opacity-100 media-paused:scale-100 backdrop-blur-sm scale-[160%] opacity-0 duration-200 ease-out flex shadow bg-white/10 rounded-full absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2`} + > + <Buttons.MobilePlayButton tooltipPlacement="top center" host={host} /> + </Controls.Group> + {/* )} */} + + <div className="pointer-events-none absolute inset-0 z-50 flex h-full w-full items-center justify-center"> + <Spinner.Root + className="text-white opacity-0 transition-opacity duration-200 ease-linear media-buffering:animate-spin media-buffering:opacity-100" + size={84} + > + <Spinner.Track className="opacity-25" width={8} /> + <Spinner.TrackFill className="opacity-75" width={8} /> + </Spinner.Root> + </div> + {/* </Controls.Group> */} + + <Controls.Group className="flex px-4"> + <div className="flex-1" /> + {host && ( + <> + <Buttons.SkipOpButton tooltipPlacement="top end" /> + <Buttons.SkipEdButton tooltipPlacement="top end" /> + <Buttons.PlayNextButton + navigation={navigation} + tooltipPlacement="top end" + /> + </> + )} + </Controls.Group> + + <Controls.Group className="flex w-full items-center px-2"> + <Sliders.Time thumbnails={thumbnails} host={host} /> + </Controls.Group> + <Controls.Group className="-mt-0.5 flex w-full items-center px-2 pb-2"> + <Buttons.Play tooltipPlacement="top start" /> + <Buttons.Mute tooltipPlacement="top" /> + <Sliders.Volume /> + <TimeGroup /> + <ChapterTitleComponent /> + <div className="flex-1" /> + {track?.subtitles && <Buttons.Caption tooltipPlacement="top" />} + <Menus.Settings placement="top end" tooltipPlacement="top" /> + {!isMobile && !isFullscreen && ( + <Buttons.TheaterButton tooltipPlacement="top" /> + )} + <Buttons.PIP tooltipPlacement="top" /> + <Buttons.Fullscreen tooltipPlacement="top end" /> + </Controls.Group> + </Controls.Root> + </> + ); +} + +function Gestures({ host }: { host?: boolean }) { + const isMobile = isMobileDevice(); + return ( + <> + {isMobile ? ( + <> + {host && ( + <Gesture + className="absolute inset-0 z-10" + event="dblpointerup" + action="toggle:paused" + /> + )} + <Gesture + className="absolute inset-0" + event="pointerup" + action="toggle:controls" + /> + </> + ) : ( + <> + {host && ( + <Gesture + className="absolute inset-0" + event="pointerup" + action="toggle:paused" + /> + )} + <Gesture + className="absolute inset-0 z-10" + event="dblpointerup" + action="toggle:fullscreen" + /> + </> + )} + + <Gesture + className="absolute top-0 left-0 w-1/5 h-full z-20" + event="dblpointerup" + action="seek:-10" + /> + <Gesture + className="absolute top-0 right-0 w-1/5 h-full z-20" + event="dblpointerup" + action="seek:10" + /> + </> + ); +} diff --git a/components/watch/new-player/components/menus.tsx b/components/watch/new-player/components/menus.tsx new file mode 100644 index 0000000..de2b302 --- /dev/null +++ b/components/watch/new-player/components/menus.tsx @@ -0,0 +1,387 @@ +// @ts-nocheck + +import type { ReactElement } from "react"; + +// import EpiDataDummy from "@/components/test/episodeDummy.json"; + +import { + Menu, + Tooltip, + useCaptionOptions, + type MenuPlacement, + type TooltipPlacement, + useVideoQualityOptions, + useMediaState, + usePlaybackRateOptions, +} from "@vidstack/react"; +import { + ChevronLeftIcon, + ChevronRightIcon, + ClosedCaptionsIcon, + SettingsMenuIcon, + RadioButtonIcon, + RadioButtonSelectedIcon, + SettingsIcon, + // EpisodesIcon, + SettingsSwitchIcon, + // PlaybackSpeedCircleIcon, + OdometerIcon, +} from "@vidstack/react/icons"; + +import { buttonClass, tooltipClass } from "./buttons"; +import { useWatchProvider } from "@/lib/context/watchPageProvider"; +import React from "react"; + +export interface SettingsProps { + placement: MenuPlacement; + tooltipPlacement: TooltipPlacement; +} + +export const menuClass = + "fixed bottom-0 animate-out fade-out slide-out-to-bottom-2 data-[open]:animate-in data-[open]:fade-in data-[open]:slide-in-from-bottom-4 flex h-[var(--menu-height)] max-h-[200px] lg:max-h-[400px] min-w-[260px] flex-col overflow-y-auto overscroll-y-contain rounded-md border border-white/10 bg-black/95 p-2.5 font-sans text-[15px] font-medium outline-none backdrop-blur-sm transition-[height] duration-300 will-change-[height] data-[resizing]:overflow-hidden"; + +export const submenuClass = + "hidden w-full flex-col items-start justify-center outline-none data-[keyboard]:mt-[3px] data-[open]:inline-block"; + +export const contentMenuClass = + "flex cust-scroll h-[var(--menu-height)] max-h-[180px] lg:max-h-[400px] min-w-[260px] flex-col overflow-y-auto overscroll-y-contain rounded-md border border-white/10 bg-secondary p-2 font-sans text-[15px] font-medium outline-none backdrop-blur-sm transition-[height] duration-300 will-change-[height] data-[resizing]:overflow-hidden"; + +export function Settings({ placement, tooltipPlacement }: SettingsProps) { + const { track } = useWatchProvider(); + const isSubtitleAvailable = track?.epiData?.subtitles?.length > 0; + + return ( + <Menu.Root className="parent"> + <Tooltip.Root> + <Tooltip.Trigger asChild> + <Menu.Button className={buttonClass}> + <SettingsIcon className="h-8 w-8 transform transition-transform duration-200 ease-out group-data-[open]:rotate-90" /> + </Menu.Button> + </Tooltip.Trigger> + <Tooltip.Content className={tooltipClass} placement={tooltipPlacement}> + Settings + </Tooltip.Content> + </Tooltip.Root> + {/* <Menu.Content className={menuClass} placement={placement}> + {isSubtitleAvailable && <CaptionSubmenu />} + <QualitySubmenu /> + </Menu.Content> */} + <Menu.Content className={contentMenuClass} placement={placement}> + <AutoPlay /> + <AutoNext /> + <SpeedSubmenu /> + {isSubtitleAvailable && <CaptionSubmenu />} + <QualitySubmenu /> + </Menu.Content> + </Menu.Root> + ); +} + +// export function Episodes({ placement }: { placement: MenuPlacement }) { +// return ( +// <Menu.Root className="parent"> +// <Tooltip.Root> +// <Tooltip.Trigger asChild> +// <Menu.Button className={buttonClass}> +// <EpisodesIcon className="w-10 h-10" /> +// </Menu.Button> +// </Tooltip.Trigger> +// </Tooltip.Root> +// <Menu.Content +// className={`bg-secondary/95 border border-white/10 max-h-[240px] overflow-y-scroll cust-scroll rounded overflow-hidden z-30 -translate-y-5 -translate-x-2`} +// placement={placement} +// > +// <EpisodeSubmenu /> +// </Menu.Content> +// </Menu.Root> +// ); +// } + +function SpeedSubmenu() { + const options = usePlaybackRateOptions(), + hint = + options.selectedValue === "1" ? "Normal" : options.selectedValue + "x"; + return ( + <Menu.Root> + <SubmenuButton + label="Playback Rate" + hint={hint} + icon={OdometerIcon} + disabled={options.disabled} + > + Speed ({hint}) + </SubmenuButton> + <Menu.Content className={submenuClass}> + <Menu.RadioGroup + className="w-full flex flex-col" + value={options.selectedValue} + > + {options.map(({ label, value, select }) => ( + <Radio value={value} onSelect={select} key={value}> + {label} + </Radio> + ))} + </Menu.RadioGroup> + </Menu.Content> + </Menu.Root> + ); +} + +function CaptionSubmenu() { + const options = useCaptionOptions(), + hint = options.selectedTrack?.label ?? "Off"; + return ( + <Menu.Root> + <SubmenuButton + label="Captions" + hint={hint} + disabled={options.disabled} + icon={ClosedCaptionsIcon} + /> + <Menu.Content className={submenuClass}> + <Menu.RadioGroup + className="w-full flex flex-col" + value={options.selectedValue} + > + {options.map(({ label, value, select }) => ( + <Radio value={value} onSelect={select} key={value}> + {label} + </Radio> + ))} + </Menu.RadioGroup> + </Menu.Content> + </Menu.Root> + ); +} + +// function EpisodeSubmenu() { +// return ( +// // <div className="h-full w-[320px]"> +// <div className="flex flex-col h-full w-[360px] font-karla"> +// {/* {EpiDataDummy.map((epi, index) => ( */} +// <div +// key={index} +// className={`flex gap-1 hover:bg-secondary px-3 py-2 ${ +// index === 0 +// ? "pt-4" +// // : index === EpiDataDummy.length - 1 +// ? "pb-4" +// : "" +// }`} +// > +// <Image +// src={epi.img} +// alt="thumbnail" +// width={100} +// height={100} +// className="object-cover w-[120px] h-[64px] rounded-md" +// /> +// <div className="flex flex-col pl-2"> +// <h1 className="font-semibold">{epi.title}</h1> +// <p className="line-clamp-2 text-sm font-light"> +// {epi?.description} +// </p> +// </div> +// </div> +// ))} +// </div> +// // </div> +// ); +// } + +function AutoPlay() { + const [options, setOptions] = React.useState([ + { + label: "On", + value: "on", + selected: false, + }, + { + label: "Off", + value: "off", + selected: true, + }, + ]); + + const { autoplay, setAutoPlay } = useWatchProvider(); + + // console.log({ autoplay }); + + return ( + <Menu.Root> + <SubmenuButton + label="Autoplay Video" + hint={ + autoplay + ? options.find((option) => option.value === autoplay)?.value + : options.find((option) => option.selected)?.value + } + icon={SettingsSwitchIcon} + /> + <Menu.Content className={submenuClass}> + <Menu.RadioGroup + className="w-full flex flex-col" + value={ + autoplay + ? options.find((option) => option.value === autoplay)?.value + : options.find((option) => option.selected)?.value + } + onChange={(value) => { + setOptions((options) => + options.map((option) => + option.value === value + ? { ...option, selected: true } + : { ...option, selected: false } + ) + ); + setAutoPlay(value); + localStorage.setItem("autoplay", value); + }} + > + {options.map((option) => ( + <Radio key={option.value} value={option.value}> + {option.label} + </Radio> + ))} + </Menu.RadioGroup> + </Menu.Content> + </Menu.Root> + ); +} + +function AutoNext() { + const [options, setOptions] = React.useState([ + { + label: "On", + value: "on", + selected: false, + }, + { + label: "Off", + value: "off", + selected: true, + }, + ]); + + const { autoNext, setAutoNext } = useWatchProvider(); + + return ( + <Menu.Root> + <SubmenuButton + label="Autoplay Next" + hint={ + autoNext + ? options.find((option) => option.value === autoNext)?.value + : options.find((option) => option.selected)?.value + } + icon={SettingsSwitchIcon} + /> + <Menu.Content className={submenuClass}> + <Menu.RadioGroup + className="w-full flex flex-col" + value={ + autoNext + ? options.find((option) => option.value === autoNext)?.value + : options.find((option) => option.selected)?.value + } + onChange={(value) => { + setOptions((options) => + options.map((option) => + option.value === value + ? { ...option, selected: true } + : { ...option, selected: false } + ) + ); + setAutoNext(value); + localStorage.setItem("autoNext", value); + }} + > + {options.map((option) => ( + <Radio key={option.value} value={option.value}> + {option.label} + </Radio> + ))} + </Menu.RadioGroup> + </Menu.Content> + </Menu.Root> + ); +} + +function QualitySubmenu() { + const options = useVideoQualityOptions({ sort: "descending" }), + autoQuality = useMediaState("autoQuality"), + currentQualityText = options.selectedQuality?.height + "p" ?? "", + hint = !autoQuality ? currentQualityText : `Auto (${currentQualityText})`; + + // console.log({ options }); + + return ( + <Menu.Root> + <SubmenuButton + label="Quality" + hint={hint} + disabled={options.disabled} + icon={SettingsMenuIcon} + /> + <Menu.Content className={submenuClass}> + <Menu.RadioGroup + className="w-full flex flex-col" + value={options.selectedValue} + > + {options.map(({ label, value, bitrateText, select }) => ( + <Radio value={value} onSelect={select} key={value}> + {label} + </Radio> + ))} + </Menu.RadioGroup> + </Menu.Content> + </Menu.Root> + ); +} + +export interface RadioProps extends Menu.RadioProps {} + +function Radio({ children, ...props }: RadioProps) { + return ( + <Menu.Radio + className="ring-media-focus group relative flex w-full cursor-pointer select-none items-center justify-start rounded-sm p-2.5 outline-none data-[hocus]:bg-white/10 data-[focus]:ring-[3px]" + {...props} + > + <RadioButtonIcon className="h-4 w-4 text-white group-data-[checked]:hidden" /> + <RadioButtonSelectedIcon + className="text-media-brand hidden h-4 w-4 group-data-[checked]:block" + type="radio-button-selected" + /> + <span className="ml-2">{children}</span> + </Menu.Radio> + ); +} + +export interface SubmenuButtonProps { + label: string; + hint: string; + disabled?: boolean; + icon: ReactElement; +} + +function SubmenuButton({ + label, + hint, + icon: Icon, + disabled, +}: SubmenuButtonProps) { + return ( + <Menu.Button + className="ring-media-focus data-[open]:bg-secondary parent left-0 z-10 flex w-full cursor-pointer select-none items-center justify-start rounded-sm p-2.5 outline-none ring-inset data-[open]:sticky data-[open]:-top-2.5 data-[hocus]:bg-white/10 data-[focus]:ring-[3px]" + disabled={disabled} + > + <ChevronLeftIcon className="parent-data-[open]:block -ml-0.5 mr-1.5 hidden h-[18px] w-[18px]" /> + <div className="contents parent-data-[open]:hidden"> + <Icon className="w-5 h-5" /> + </div> + <span className="ml-1.5 parent-data-[open]:ml-0">{label}</span> + <span className="ml-auto text-sm text-white/50">{hint}</span> + <ChevronRightIcon className="parent-data-[open]:hidden ml-0.5 h-[18px] w-[18px] text-sm text-white/50" /> + </Menu.Button> + ); +} diff --git a/components/watch/new-player/components/sliders.tsx b/components/watch/new-player/components/sliders.tsx new file mode 100644 index 0000000..f31e28a --- /dev/null +++ b/components/watch/new-player/components/sliders.tsx @@ -0,0 +1,73 @@ +import { TimeSlider, VolumeSlider } from "@vidstack/react"; + +export function Volume() { + return ( + <VolumeSlider.Root className="volume-slider group relative mx-[7.5px] inline-flex h-10 w-full max-w-[80px] cursor-pointer touch-none select-none items-center outline-none aria-hidden:hidden"> + <VolumeSlider.Track className="relative ring-media-focus z-0 h-[5px] w-full rounded-sm bg-white/30 group-data-[focus]:ring-[3px]"> + <VolumeSlider.TrackFill className="bg-white absolute h-full w-[var(--slider-fill)] rounded-sm will-change-[width]" /> + </VolumeSlider.Track> + + <VolumeSlider.Preview + className="flex flex-col items-center opacity-0 transition-opacity duration-200 data-[visible]:opacity-100" + noClamp + > + <VolumeSlider.Value className="rounded-sm bg-black px-2 py-px text-[13px] font-medium" /> + </VolumeSlider.Preview> + <VolumeSlider.Thumb className="absolute left-[var(--slider-fill)] top-1/2 z-20 h-[15px] w-[15px] -translate-x-1/2 -translate-y-1/2 rounded-full border border-[#cacaca] bg-white opacity-0 ring-white/40 transition-opacity group-data-[active]:opacity-100 group-data-[dragging]:ring-4 will-change-[left]" /> + </VolumeSlider.Root> + ); +} + +export interface TimeSliderProps { + thumbnails?: string; + host?: boolean; +} + +export function Time({ thumbnails, host }: TimeSliderProps) { + return ( + <TimeSlider.Root + className={`${ + host ? "" : "pointer-events-none" + } time-slider group relative mx-[7.5px] inline-flex h-10 w-full cursor-pointer touch-none select-none items-center outline-none`} + > + <TimeSlider.Chapters className="relative flex h-full w-full items-center rounded-[1px]"> + {(cues, forwardRef) => + cues.map((cue) => ( + <div + className="last-child:mr-0 group/slider relative mr-0.5 flex h-full w-full items-center rounded-[1px]" + style={{ contain: "layout style" }} + key={cue.startTime} + ref={forwardRef} + > + <TimeSlider.Track className="relative ring-media-focus z-0 h-[5px] group-hover/slider:h-[10px] transition-all duration-100 w-full rounded-sm bg-white/30 group-data-[focus]:ring-[3px]"> + <TimeSlider.TrackFill className="bg-white absolute h-full w-[var(--chapter-fill)] rounded-sm will-change-[width]" /> + <TimeSlider.Progress className="absolute z-10 h-full w-[var(--chapter-progress)] rounded-sm bg-white/50 will-change-[width]" /> + </TimeSlider.Track> + </div> + )) + } + </TimeSlider.Chapters> + {/* <TimeSlider.Track className="relative ring-media-focus z-0 h-[5px] w-full rounded-sm bg-white/30 group-data-[focus]:ring-[3px]"> + <TimeSlider.TrackFill className="bg-white absolute h-full w-[var(--slider-fill)] rounded-sm will-change-[width]" /> + <TimeSlider.Progress className="absolute z-10 h-full w-[var(--slider-progress)] rounded-sm bg-white/40 will-change-[width]" /> + </TimeSlider.Track> */} + + <TimeSlider.Thumb className="absolute left-[var(--slider-fill)] top-1/2 z-20 h-[15px] w-[15px] -translate-x-1/2 -translate-y-1/2 rounded-full border border-[#cacaca] bg-white opacity-0 ring-white/40 transition-opacity group-data-[active]:opacity-100 group-data-[dragging]:ring-4 will-change-[left]" /> + + <TimeSlider.Preview className="flex flex-col items-center opacity-0 transition-opacity duration-200 data-[visible]:opacity-100 pointer-events-none"> + {thumbnails ? ( + <TimeSlider.Thumbnail.Root + src={thumbnails} + className="block h-[var(--thumbnail-height)] max-h-[160px] min-h-[80px] w-[var(--thumbnail-width)] min-w-[120px] max-w-[180px] overflow-hidden border border-white bg-black" + > + <TimeSlider.Thumbnail.Img /> + </TimeSlider.Thumbnail.Root> + ) : null} + + <TimeSlider.ChapterTitle className="mt-2 text-sm" /> + + <TimeSlider.Value className="text-[13px]" /> + </TimeSlider.Preview> + </TimeSlider.Root> + ); +} diff --git a/components/watch/new-player/components/time-group.tsx b/components/watch/new-player/components/time-group.tsx new file mode 100644 index 0000000..45fc795 --- /dev/null +++ b/components/watch/new-player/components/time-group.tsx @@ -0,0 +1,11 @@ +import { Time } from "@vidstack/react"; + +export function TimeGroup() { + return ( + <div className="ml-1.5 flex items-center text-sm font-medium"> + <Time className="time" type="current" /> + <div className="mx-1 text-white/80">/</div> + <Time className="time" type="duration" /> + </div> + ); +} diff --git a/components/watch/new-player/components/title.tsx b/components/watch/new-player/components/title.tsx new file mode 100644 index 0000000..6233061 --- /dev/null +++ b/components/watch/new-player/components/title.tsx @@ -0,0 +1,35 @@ +import { useWatchProvider } from "@/lib/context/watchPageProvider"; +import { useMediaRemote } from "@vidstack/react"; +import { ChevronLeftIcon } from "@vidstack/react/icons"; +import { Navigation } from "../player"; + +type TitleProps = { + navigation?: Navigation; +}; + +export function Title({ navigation }: TitleProps) { + const { dataMedia } = useWatchProvider(); + const remote = useMediaRemote(); + + return ( + <div className="media-fullscreen:flex hidden text-start flex-1 text-sm font-medium text-white"> + {/* <p className="pt-4 h-full"> + </p> */} + <button + type="button" + className="flex items-center gap-2 text-sm font-karla w-full" + onClick={() => remote.toggleFullscreen()} + > + <ChevronLeftIcon className="font-extrabold w-7 h-7" /> + <span className="max-w-[75%] text-base xl:text-2xl font-semibold whitespace-nowrap overflow-hidden text-ellipsis"> + {dataMedia?.title?.romaji} + </span> + <span className="text-base xl:text-2xl font-normal">/</span> + <span className="text-base xl:text-2xl font-normal"> + Episode {navigation?.playing.number} + </span> + {/* <span className="absolute top-5 left-[1s0%] w-[24%] h-[1px] bg-white" /> */} + </button> + </div> + ); +} diff --git a/components/watch/new-player/player.module.css b/components/watch/new-player/player.module.css new file mode 100644 index 0000000..f2f5b39 --- /dev/null +++ b/components/watch/new-player/player.module.css @@ -0,0 +1,50 @@ +.player { + --media-brand: #f5f5f5; + --media-focus-ring-color: #4e9cf6; + --media-focus-ring: 0 0 0 3px var(--media-focus-ring-color); + + --media-tooltip-y-offset: 30px; + --media-menu-y-offset: 30px; + + background-color: black; + border-radius: var(--media-border-radius); + color: #f5f5f5; + contain: layout; + font-family: sans-serif; + overflow: hidden; +} + +.player[data-focus]:not([data-playing]) { + box-shadow: var(--media-focus-ring); +} + +.player video { + height: 100%; + object-fit: contain; + display: block; +} + +.player video, +.poster { + border-radius: var(--media-border-radius); +} + +.poster { + display: block; + position: absolute; + top: 0; + left: 0; + opacity: 0; + width: 100%; + height: 100%; +} + +.poster[data-visible] { + opacity: 1; +} + +.poster img { + width: 100%; + height: 100%; + object-fit: cover; +} diff --git a/components/watch/new-player/player.tsx b/components/watch/new-player/player.tsx new file mode 100644 index 0000000..b98ff79 --- /dev/null +++ b/components/watch/new-player/player.tsx @@ -0,0 +1,471 @@ +import "@vidstack/react/player/styles/base.css"; + +import { useEffect, useRef, useState } from "react"; + +import style from "./player.module.css"; + +import { + MediaPlayer, + MediaProvider, + useMediaStore, + useMediaRemote, + type MediaPlayerInstance, + Track, + MediaTimeUpdateEventDetail, + MediaTimeUpdateEvent, +} from "@vidstack/react"; +import { VideoLayout } from "./components/layouts/video-layout"; +import { useWatchProvider } from "@/lib/context/watchPageProvider"; +import { useRouter } from "next/router"; +import { Subtitle } from "types/episodes/TrackData"; +import useWatchStorage from "@/lib/hooks/useWatchStorage"; +import { Sessions } from "types/episodes/Sessions"; +import { useAniList } from "@/lib/anilist/useAnilist"; + +export interface Navigation { + prev: Prev; + playing: Playing; + next: Next; +} + +export interface Prev { + id: string; + title: string; + img: string; + number: number; + description: string; +} + +export interface Playing { + id: string; + title: string; + description: string; + img: string; + number: number; +} + +export interface Next { + id: string; + title: string; + description: string; + img: string; + number: number; +} + +type VidStackProps = { + id: string; + navigation: Navigation; + userData: UserData; + sessions: Sessions; +}; + +export type UserData = { + id?: string; + userProfileId?: string; + aniId: string; + watchId: string; + title: string; + aniTitle: string; + image: string; + episode: number; + duration: number; + timeWatched: number; + provider: string; + nextId: string; + nextNumber: number; + dub: boolean; + createdAt: string; +}; + +type SkipData = { + startTime: number; + endTime: number; + text: string; +}; + +export default function VidStack({ + id, + navigation, + userData, + sessions, +}: VidStackProps) { + let player = useRef<MediaPlayerInstance>(null); + + const { + aspectRatio, + setAspectRatio, + track, + playerState, + dataMedia, + autoNext, + } = useWatchProvider(); + + const { qualities, duration } = useMediaStore(player); + + const [getSettings, updateSettings] = useWatchStorage(); + const { marked, setMarked } = useWatchProvider(); + + const { markProgress } = useAniList(sessions); + + const remote = useMediaRemote(player); + + const { defaultQuality = null } = track ?? {}; + + const [chapters, setChapters] = useState<string>(""); + + const router = useRouter(); + + useEffect(() => { + if (qualities.length > 0) { + const sourceQuality = qualities.reduce( + (max, obj) => (obj.height > max.height ? obj : max), + qualities[0] + ); + const aspectRatio = calculateAspectRatio( + sourceQuality.width, + sourceQuality.height + ); + + setAspectRatio(aspectRatio); + } + }, [qualities]); + + const [isPlaying, setIsPlaying] = useState(false); + let interval: any; + + useEffect(() => { + const plyr = player.current; + + function handlePlay() { + // console.log("Player is playing"); + setIsPlaying(true); + } + + function handlePause() { + // console.log("Player is paused"); + setIsPlaying(false); + } + + function handleEnd() { + // console.log("Player ended"); + setIsPlaying(false); + } + + plyr?.addEventListener("play", handlePlay); + plyr?.addEventListener("pause", handlePause); + plyr?.addEventListener("ended", handleEnd); + + return () => { + plyr?.removeEventListener("play", handlePlay); + plyr?.removeEventListener("pause", handlePause); + plyr?.removeEventListener("ended", handleEnd); + }; + }, [id, duration]); + + useEffect(() => { + if (isPlaying) { + interval = setInterval(async () => { + const currentTime = player.current?.currentTime + ? Math.round(player.current?.currentTime) + : 0; + + const parsedImage = navigation?.playing?.img?.includes("null") + ? dataMedia?.coverImage?.extraLarge + : navigation?.playing?.img; + + if (sessions?.user?.name) { + // console.log("updating user data"); + await fetch("/api/user/update/episode", { + method: "PUT", + body: JSON.stringify({ + name: sessions?.user?.name, + id: String(dataMedia?.id), + watchId: navigation?.playing?.id, + title: + navigation.playing?.title || + dataMedia.title?.romaji || + dataMedia.title?.english, + aniTitle: dataMedia.title?.romaji || dataMedia.title?.english, + image: parsedImage, + number: Number(navigation.playing?.number), + duration: duration, + timeWatched: currentTime, + provider: track?.provider, + nextId: navigation?.next?.id, + nextNumber: Number(navigation?.next?.number), + dub: track?.isDub ? true : false, + }), + }); + } + + updateSettings(navigation?.playing?.id, { + aniId: String(dataMedia.id), + watchId: navigation?.playing?.id, + title: + navigation.playing?.title || + dataMedia.title?.romaji || + dataMedia.title?.english, + aniTitle: dataMedia.title?.romaji || dataMedia.title?.english, + image: parsedImage, + episode: Number(navigation.playing?.number), + duration: duration, + timeWatched: currentTime, // update timeWatched with currentTime + provider: track?.provider, + nextId: navigation?.next?.id, + nextNumber: navigation?.next?.number, + dub: track?.isDub ? true : false, + createdAt: new Date().toISOString(), + }); + // console.log("update"); + }, 5000); + } else { + clearInterval(interval); + } + + return () => { + clearInterval(interval); + }; + }, [isPlaying, sessions?.user?.name, track?.isDub, duration]); + + useEffect(() => { + const autoplay = localStorage.getItem("autoplay") || "off"; + + return player.current!.subscribe(({ canPlay }) => { + // console.log("can play?", "->", canPlay); + if (canPlay) { + if (autoplay === "on") { + if (playerState?.currentTime === 0) { + remote.play(); + } else { + if (playerState?.isPlaying) { + remote.play(); + } else { + remote.pause(); + } + } + } else { + if (playerState?.isPlaying) { + remote.play(); + } else { + remote.pause(); + } + } + remote.seek(playerState?.currentTime); + } + }); + }, [playerState?.currentTime, playerState?.isPlaying]); + + useEffect(() => { + const chapter = track?.skip, + videoDuration = Math.round(duration); + + let vtt = "WEBVTT\n\n"; + + let lastEndTime = 0; + + if (chapter && chapter?.length > 0) { + chapter.forEach((item: SkipData) => { + let startMinutes = Math.floor(item.startTime / 60); + let startSeconds = item.startTime % 60; + let endMinutes = Math.floor(item.endTime / 60); + let endSeconds = item.endTime % 60; + + let start = `${startMinutes.toString().padStart(2, "0")}:${startSeconds + .toString() + .padStart(2, "0")}`; + let end = `${endMinutes.toString().padStart(2, "0")}:${endSeconds + .toString() + .padStart(2, "0")}`; + + vtt += `${start} --> ${end}\n${item.text}\n\n`; + if (item.endTime > lastEndTime) { + lastEndTime = item.endTime; + } + }); + + if (lastEndTime < videoDuration) { + let startMinutes = Math.floor(lastEndTime / 60); + let startSeconds = lastEndTime % 60; + let endMinutes = Math.floor(videoDuration / 60); + let endSeconds = videoDuration % 60; + + let start = `${startMinutes.toString().padStart(2, "0")}:${startSeconds + .toString() + .padStart(2, "0")}`; + let end = `${endMinutes.toString().padStart(2, "0")}:${endSeconds + .toString() + .padStart(2, "0")}`; + + vtt += `${start} --> ${end}\n\n\n`; + } + + const vttBlob = new Blob([vtt], { type: "text/vtt" }); + const vttUrl = URL.createObjectURL(vttBlob); + + setChapters(vttUrl); + } + return () => { + setChapters(""); + }; + }, [track?.skip, duration]); + + useEffect(() => { + return () => { + if (player.current) { + player.current.destroy(); + } + }; + }, []); + + function onEnded() { + if (!navigation?.next?.id) return; + if (autoNext === "on") { + const nextButton = document.querySelector(".next-button"); + + let timeoutId: ReturnType<typeof setTimeout>; + + const stopTimeout = () => { + clearTimeout(timeoutId); + nextButton?.classList.remove("progress"); + }; + + nextButton?.classList.remove("hidden"); + nextButton?.classList.add("progress"); + + timeoutId = setTimeout(() => { + console.log("time is up!"); + if (navigation?.next) { + router.push( + `/en/anime/watch/${dataMedia.id}/${track.provider}?id=${ + navigation?.next?.id + }&num=${navigation?.next?.number}${ + track?.isDub ? `&dub=${track?.isDub}` : "" + }` + ); + } + }, 7000); + + nextButton?.addEventListener("mouseover", stopTimeout); + } + } + + function onLoadedMetadata() { + const seek: any = getSettings(navigation?.playing?.id); + if (playerState?.currentTime !== 0) return; + const seekTime = seek?.timeWatched; + const percentage = duration !== 0 ? seekTime / Math.round(duration) : 0; + const percentagedb = + duration !== 0 ? userData?.timeWatched / Math.round(duration) : 0; + + if (percentage >= 0.9 || percentagedb >= 0.9) { + remote.seek(0); + console.log("Video started from the beginning"); + } else if (userData?.timeWatched) { + remote.seek(userData?.timeWatched); + } else { + remote.seek(seekTime); + } + } + + let mark = 0; + function onTimeUpdate(detail: MediaTimeUpdateEventDetail) { + if (sessions) { + let currentTime = detail.currentTime; + const percentage = currentTime / duration; + + if (percentage >= 0.9) { + // use >= instead of > + if (mark < 1 && marked < 1) { + mark = 1; + setMarked(1); + console.log("marking progress"); + markProgress(dataMedia.id, navigation.playing.number); + } + } + } + + const opButton = document.querySelector(".op-button"); + const edButton = document.querySelector(".ed-button"); + + const op: SkipData = track?.skip.find( + (item: SkipData) => item.text === "Opening" + ), + ed = track?.skip.find((item: SkipData) => item.text === "Ending"); + + if ( + op && + detail.currentTime > op.startTime && + detail.currentTime < op.endTime + ) { + opButton?.classList.remove("hidden"); + } else { + opButton?.classList.add("hidden"); + } + + if ( + ed && + detail.currentTime > ed.startTime && + detail.currentTime < ed.endTime + ) { + edButton?.classList.remove("hidden"); + } else { + edButton?.classList.add("hidden"); + } + } + + function onSeeked(currentTime: number) { + const nextButton = document.querySelector(".next-button"); + // console.log({ currentTime, duration }); + if (currentTime !== duration) { + nextButton?.classList.add("hidden"); + } + } + + return ( + <MediaPlayer + key={id} + className={`${style.player} player`} + title={ + navigation?.playing?.title || + `Episode ${navigation?.playing?.number}` || + "Loading..." + } + load="idle" + crossorigin="anonymous" + src={{ + src: defaultQuality?.url, + type: "application/vnd.apple.mpegurl", + }} + onTimeUpdate={onTimeUpdate} + playsinline + aspectRatio={aspectRatio} + onEnd={onEnded} + onSeeked={onSeeked} + onLoadedMetadata={onLoadedMetadata} + ref={player} + > + <MediaProvider> + {track && + track?.subtitles && + track?.subtitles?.map((track: Subtitle) => ( + <Track {...track} key={track.src} /> + ))} + {chapters?.length > 0 && ( + <Track key={chapters} src={chapters} kind="chapters" default={true} /> + )} + </MediaProvider> + <VideoLayout thumbnails={track?.thumbnails} navigation={navigation} /> + </MediaPlayer> + ); +} + +export function calculateAspectRatio(width: number, height: number) { + if (width === 0 && height === 0) { + return "16/9"; + } + + const gcd = (a: number, b: number): any => (b === 0 ? a : gcd(b, a % b)); + const divisor = gcd(width, height); + const aspectRatio = `${width / divisor}/${height / divisor}`; + return aspectRatio; +} diff --git a/components/watch/new-player/tracks.tsx b/components/watch/new-player/tracks.tsx new file mode 100644 index 0000000..abc1fb5 --- /dev/null +++ b/components/watch/new-player/tracks.tsx @@ -0,0 +1,184 @@ +export const textTracks = [ + // Subtitles + // { + // src: "https://media-files.vidstack.io/sprite-fight/subs/english.vtt", + // label: "English", + // language: "en-US", + // kind: "subtitles", + // default: true, + // }, + // { + // src: "https://media-files.vidstack.io/sprite-fight/subs/spanish.vtt", + // label: "Spanish", + // language: "es-ES", + // kind: "subtitles", + // }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/ara-3.vtt", + label: "Arabic", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/chi-4.vtt", + label: "Chinese - Chinese Simplified", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/chi-5.vtt", + label: "Chinese - Chinese Traditional", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/hrv-6.vtt", + label: "Croatian", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/cze-7.vtt", + label: "Czech", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/dan-8.vtt", + label: "Danish", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/dut-9.vtt", + label: "Dutch", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/32/6d/326d5416033fe39a1540b11908f191fe/326d5416033fe39a1540b11908f191fe.vtt", + label: "English", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/fin-10.vtt", + label: "Finnish", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/fre-11.vtt", + label: "French", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/ger-12.vtt", + label: "German", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/gre-13.vtt", + label: "Greek", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/heb-14.vtt", + label: "Hebrew", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/hun-15.vtt", + label: "Hungarian", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/ind-16.vtt", + label: "Indonesian", + kind: "subtitles", + default: true, + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/ita-17.vtt", + label: "Italian", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/jpn-18.vtt", + label: "Japanese", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/kor-19.vtt", + label: "Korean", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/may-20.vtt", + label: "Malay", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/nob-21.vtt", + label: "Norwegian BokmĂĄl - Norwegian Bokmal", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/pol-22.vtt", + label: "Polish", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/por-23.vtt", + label: "Portuguese", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/por-24.vtt", + label: "Portuguese - Brazilian Portuguese", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/rum-25.vtt", + label: "Romanian", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/rus-26.vtt", + label: "Russian", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/spa-27.vtt", + label: "Spanish", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/spa-28.vtt", + label: "Spanish - European Spanish", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/swe-29.vtt", + label: "Swedish", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/tha-30.vtt", + label: "Thai", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/tur-31.vtt", + label: "Turkish", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/ukr-32.vtt", + label: "Ukrainian", + kind: "subtitles", + }, + { + src: "https://ccb.megaresources.co/3c/0f/3c0fbf6aafc60b02d3be402099638403/vie-33.vtt", + label: "Vietnamese", + kind: "subtitles", + }, + // // Chapters + // { + // src: "https://media-files.vidstack.io/sprite-fight/chapters.vtt", + // kind: "chapters", + // language: "en-US", + // default: true, + // }, +] as const; diff --git a/components/watch/player/artplayer.js b/components/watch/player/artplayer.js deleted file mode 100644 index 666c103..0000000 --- a/components/watch/player/artplayer.js +++ /dev/null @@ -1,387 +0,0 @@ -import { useEffect, useRef } from "react"; -import Artplayer from "artplayer"; -import Hls from "hls.js"; -import { useWatchProvider } from "@/lib/context/watchPageProvider"; -import artplayerPluginHlsQuality from "artplayer-plugin-hls-quality"; - -export default function NewPlayer({ - playerRef, - option, - getInstance, - provider, - track, - defSub, - defSize, - subtitles, - subSize, - res, - quality, - ...rest -}) { - const artRef = useRef(null); - const { setTheaterMode, setPlayerState, setAutoPlay } = useWatchProvider(); - - function playM3u8(video, url, art) { - if (Hls.isSupported()) { - if (art.hls) art.hls.destroy(); - const hls = new Hls(); - hls.loadSource(url); - hls.attachMedia(video); - art.hls = hls; - art.on("destroy", () => hls.destroy()); - } else if (video.canPlayType("application/vnd.apple.mpegurl")) { - video.src = url; - } else { - art.notice.show = "Unsupported playback format: m3u8"; - } - } - - useEffect(() => { - Artplayer.PLAYBACK_RATE = [0.5, 0.75, 1, 1.15, 1.2, 1.5, 1.7, 2]; - - const art = new Artplayer({ - ...option, - container: artRef.current, - type: "m3u8", - customType: { - m3u8: playM3u8, - }, - ...(subtitles?.length > 0 && { - subtitle: { - url: `${defSub}`, - // type: "vtt", - encoding: "utf-8", - default: true, - name: "English", - escape: false, - style: { - color: "#FFFF", - fontSize: `${defSize?.size}`, - fontFamily: localStorage.getItem("font") - ? localStorage.getItem("font") - : "Arial", - textShadow: localStorage.getItem("subShadow") - ? JSON.parse(localStorage.getItem("subShadow")).value - : "0px 0px 10px #000000", - }, - }, - }), - - plugins: [ - artplayerPluginHlsQuality({ - // Show quality in setting - setting: true, - - // Get the resolution text from level - getResolution: (level) => level.height + "P", - - // I18n - title: "Quality", - auto: "Auto", - }), - ], - - settings: [ - // provider === "gogoanime" && - { - html: "Autoplay Next", - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" viewBox="0 0 24 24"><path fill="currentColor" d="M4.05 16.975q-.5.35-1.025.05t-.525-.9v-8.25q0-.6.525-.888t1.025.038l6.2 4.15q.45.3.45.825t-.45.825l-6.2 4.15Zm10 0q-.5.35-1.025.05t-.525-.9v-8.25q0-.6.525-.888t1.025.038l6.2 4.15q.45.3.45.825t-.45.825l-6.2 4.15Z"></path></svg>', - tooltip: "ON/OFF", - switch: localStorage.getItem("autoplay") === "true" ? true : false, - onSwitch: function (item) { - // setPlayNext(!item.switch); - localStorage.setItem("autoplay", !item.switch); - return !item.switch; - }, - }, - { - html: "Autoplay Video", - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" viewBox="0 0 24 24"><path fill="currentColor" d="M4.05 16.975q-.5.35-1.025.05t-.525-.9v-8.25q0-.6.525-.888t1.025.038l6.2 4.15q.45.3.45.825t-.45.825l-6.2 4.15Zm10 0q-.5.35-1.025.05t-.525-.9v-8.25q0-.6.525-.888t1.025.038l6.2 4.15q.45.3.45.825t-.45.825l-6.2 4.15Z"></path></svg>', - // icon: '<svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" viewBox="0 0 24 24"><path fill="currentColor" d="M5.59 7.41L7 6l6 6l-6 6l-1.41-1.41L10.17 12L5.59 7.41m6 0L13 6l6 6l-6 6l-1.41-1.41L16.17 12l-4.58-4.59Z"></path></svg>', - tooltip: "ON/OFF", - switch: - localStorage.getItem("autoplay_video") === "true" ? true : false, - onSwitch: function (item) { - setAutoPlay(!item.switch); - localStorage.setItem("autoplay_video", !item.switch); - return !item.switch; - }, - }, - { - html: "Alternative Quality", - width: 250, - tooltip: `${res}`, - selector: quality?.alt, - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" viewBox="0 0 512 512"><path fill="currentColor" d="M381.25 112a48 48 0 0 0-90.5 0H48v32h242.75a48 48 0 0 0 90.5 0H464v-32ZM176 208a48.09 48.09 0 0 0-45.25 32H48v32h82.75a48 48 0 0 0 90.5 0H464v-32H221.25A48.09 48.09 0 0 0 176 208Zm160 128a48.09 48.09 0 0 0-45.25 32H48v32h242.75a48 48 0 0 0 90.5 0H464v-32h-82.75A48.09 48.09 0 0 0 336 336Z"></path></svg>', - onSelect: function (item) { - art.switchQuality(item.url, item.html); - localStorage.setItem("quality", item.html); - return item.html; - }, - }, - { - html: "Server", - width: 250, - tooltip: `${quality?.server[0].html}`, - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" viewBox="0 0 32 32"><path fill="currentColor" d="m24.6 24.4l2.6 2.6l-2.6 2.6L26 31l4-4l-4-4zm-2.2 0L19.8 27l2.6 2.6L21 31l-4-4l4-4z"></path><circle cx="11" cy="8" r="1" fill="currentColor"></circle><circle cx="11" cy="16" r="1" fill="currentColor"></circle><circle cx="11" cy="24" r="1" fill="currentColor"></circle><path fill="currentColor" d="M24 3H8c-1.1 0-2 .9-2 2v22c0 1.1.9 2 2 2h7v-2H8v-6h18V5c0-1.1-.9-2-2-2zm0 16H8v-6h16v6zm0-8H8V5h16v6z"></path></svg>', - selector: quality?.server, - onSelect: function (item) { - art.switchQuality(item.url, item.html); - localStorage.setItem("quality", item.html); - return item.html; - }, - }, - subtitles?.length > 0 && { - html: "Subtitles", - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="2em" height="2em" viewBox="0 0 24 24"><path fill="currentColor" d="M4 20q-.825 0-1.413-.588T2 18V6q0-.825.588-1.413T4 4h16q.825 0 1.413.588T22 6v12q0 .825-.588 1.413T20 20H4Zm2-4h8v-2H6v2Zm10 0h2v-2h-2v2ZM6 12h2v-2H6v2Zm4 0h8v-2h-8v2Z"></path></svg>', - width: 300, - tooltip: "Settings", - selector: [ - { - html: "Display", - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="35" height="26" viewBox="0 -960 960 960"><path d="M480.169-341.796q65.754 0 111.894-46.31 46.141-46.309 46.141-112.063t-46.31-111.894q-46.309-46.141-112.063-46.141t-111.894 46.31q-46.141 46.309-46.141 112.063t46.31 111.894q46.309 46.141 112.063 46.141zm-.371-48.307q-45.875 0-77.785-32.112-31.91-32.112-31.91-77.987 0-45.875 32.112-77.785 32.112-31.91 77.987-31.91 45.875 0 77.785 32.112 31.91 32.112 31.91 77.987 0 45.875-32.112 77.785-32.112 31.91-77.987 31.91zm.226 170.102q-130.921 0-239.6-69.821-108.679-69.82-167.556-186.476-2.687-4.574-3.892-10.811Q67.77-493.347 67.77-500t1.205-12.891q1.205-6.237 3.892-10.811Q131.745-640.358 240.4-710.178q108.655-69.821 239.576-69.821t239.6 69.821q108.679 69.82 167.556 186.476 2.687 4.574 3.892 10.811 1.205 6.238 1.205 12.891t-1.205 12.891q-1.205 6.237-3.892 10.811Q828.255-359.642 719.6-289.822q-108.655 69.821-239.576 69.821zM480-500zm-.112 229.744q117.163 0 215.048-62.347Q792.821-394.949 844.308-500q-51.487-105.051-149.26-167.397-97.772-62.347-214.936-62.347-117.163 0-215.048 62.347Q167.179-605.051 115.282-500q51.897 105.051 149.67 167.397 97.772 62.347 214.936 62.347z"></path></svg>', - tooltip: "Show", - switch: true, - onSwitch: function (item) { - item.tooltip = item.switch ? "Hide" : "Show"; - art.subtitle.show = !item.switch; - return !item.switch; - }, - }, - { - html: "Font Size", - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="35" height="26" viewBox="0 -960 960 960"><path d="M619.861-177.694q-15.655 0-26.475-10.918-10.821-10.918-10.821-26.516v-492.309H415.128q-15.598 0-26.516-10.959-10.918-10.959-10.918-26.615 0-15.655 10.918-26.475 10.918-10.82 26.516-10.82h409.744q15.598 0 26.516 10.958 10.918 10.959 10.918 26.615 0 15.656-10.918 26.476-10.918 10.82-26.516 10.82H657.435v492.309q0 15.598-10.959 26.516-10.959 10.918-26.615 10.918zm-360 0q-15.655 0-26.475-10.918-10.821-10.918-10.821-26.516v-292.309h-87.437q-15.598 0-26.516-10.959-10.918-10.959-10.918-26.615 0-15.655 10.918-26.475 10.918-10.82 26.516-10.82h249.744q15.598 0 26.516 10.958 10.918 10.959 10.918 26.615 0 15.656-10.918 26.476-10.918 10.82-26.516 10.82h-87.437v292.309q0 15.598-10.959 26.516-10.959 10.918-26.615 10.918z"></path></svg>', - selector: subSize, - onSelect: function (item) { - if (item.html === "Small") { - art.subtitle.style({ fontSize: "16px" }); - localStorage.setItem( - "subSize", - JSON.stringify({ - size: "16px", - html: "Small", - }) - ); - } else if (item.html === "Medium") { - art.subtitle.style({ fontSize: "36px" }); - localStorage.setItem( - "subSize", - JSON.stringify({ - size: "36px", - html: "Medium", - }) - ); - } else if (item.html === "Large") { - art.subtitle.style({ fontSize: "56px" }); - localStorage.setItem( - "subSize", - JSON.stringify({ - size: "56px", - html: "Large", - }) - ); - } - }, - }, - { - html: "Language", - icon: '<svg xmlns="http://www.w3.org/2000/svg" width="35" height="26" viewBox="0 -960 960 960"><path d="M528.282-110.771q-21.744 0-31.308-14.013t-2.205-34.295l135.952-359.307q5.304-14.793 20.292-25.126 14.988-10.334 31.152-10.334 15.398 0 30.85 10.388 15.451 10.387 20.932 25.125l137.128 357.485q8.025 20.949-1.83 35.513-9.855 14.564-33.24 14.564-10.366 0-19.392-6.616-9.025-6.615-12.72-16.242l-30.997-91.808H594.769l-33.381 91.869q-3.645 9.181-13.148 15.989-9.504 6.808-19.958 6.808zm87.871-179.281h131.64l-64.615-180.717h-2.41l-64.615 180.717zM302.104-608.384q14.406 25.624 31.074 48.184 16.669 22.559 37.643 47.021 41.333-44.128 68.628-90.461t46.038-97.897H111.499q-15.674 0-26.278-10.615-10.603-10.616-10.603-26.308t10.615-26.307q10.616-10.616 26.308-10.616h221.537v-36.923q0-15.692 10.615-26.307 10.616-10.616 26.308-10.616t26.307 10.616q10.616 10.615 10.616 26.307v36.923h221.537q15.692 0 26.307 10.616 10.616 10.615 10.616 26.307 0 15.692-10.616 26.308-10.615 10.615-26.307 10.615h-69.088q-19.912 64.153-53.237 125.74-33.325 61.588-82.341 116.412l89.384 90.974-27.692 75.179-115.486-112.922-158.948 158.947q-10.615 10.616-25.667 10.616-15.051 0-25.666-11.026-11.026-10.615-11.026-25.666 0-15.052 11.026-26.077l161.614-161.358q-24.666-28.308-45.551-57.307-20.884-29-37.756-60.103-10.641-19.871-1.346-34.717t33.038-14.846q9.088 0 18.429 5.73 9.34 5.731 13.956 13.577z"></path></svg>', - tooltip: "English", - selector: [...subtitles], - onSelect: function (item) { - art.subtitle.switch(item.url, { - name: item.html, - }); - return item.html; - }, - }, - { - html: "Font Family", - tooltip: localStorage.getItem("font") - ? localStorage.getItem("font") - : "Arial", - selector: [ - { html: "Arial" }, - { html: "Comic Sans MS" }, - { html: "Verdana" }, - { html: "Tahoma" }, - { html: "Trebuchet MS" }, - { html: "Times New Roman" }, - { html: "Georgia" }, - { html: "Impact " }, - { html: "AndalĂ© Mono" }, - { html: "Palatino" }, - { html: "Baskerville" }, - { html: "Garamond" }, - { html: "Courier New" }, - { html: "Brush Script MT" }, - ], - onSelect: function (item) { - art.subtitle.style({ fontFamily: item.html }); - localStorage.setItem("font", item.html); - return item.html; - }, - }, - { - html: "Font Shadow", - tooltip: localStorage.getItem("subShadow") - ? JSON.parse(localStorage.getItem("subShadow")).shadow - : "Default", - selector: [ - { html: "None", value: "none" }, - { - html: "Uniform", - value: - "2px 2px 0px #000, -2px -2px 0px #000, 2px -2px 0px #000, -2px 2px 0px #000", - }, - { html: "Raised", value: "-1px 2px 3px rgba(0, 0, 0, 1)" }, - { html: "Depressed", value: "-2px -3px 3px rgba(0, 0, 0, 1)" }, - { html: "Glow", value: "0 0 10px rgba(0, 0, 0, 0.8)" }, - { - html: "Block", - value: - "-3px 3px 4px rgba(0, 0, 0, 1),2px 2px 4px rgba(0, 0, 0, 1),1px -1px 3px rgba(0, 0, 0, 1),-3px -2px 4px rgba(0, 0, 0, 1)", - }, - ], - onSelect: function (item) { - art.subtitle.style({ textShadow: item.value }); - localStorage.setItem( - "subShadow", - JSON.stringify({ shadow: item.html, value: item.value }) - ); - return item.html; - }, - }, - ], - }, - ].filter(Boolean), - controls: [ - { - name: "theater-button", - index: 11, - position: "right", - tooltip: "Theater (t)", - html: '<i class="theater"><svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="M19 3H1a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h18a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1zm-1 12H2V5h16v10z"></path></svg></i>', - click: function (...args) { - setPlayerState((prev) => ({ - ...prev, - currentTime: art.currentTime, - isPlaying: art.playing, - })); - setTheaterMode((prev) => !prev); - }, - }, - { - index: 10, - name: "fast-rewind", - position: "left", - html: '<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="M17.959 4.571L10.756 9.52s-.279.201-.279.481s.279.479.279.479l7.203 4.951c.572.38 1.041.099 1.041-.626V5.196c0-.727-.469-1.008-1.041-.625zm-9.076 0L1.68 9.52s-.279.201-.279.481s.279.479.279.479l7.203 4.951c.572.381 1.041.1 1.041-.625v-9.61c0-.727-.469-1.008-1.041-.625z"></path></svg>', - tooltip: "Backward 5s", - click: function () { - art.backward = 5; - }, - }, - { - index: 11, - name: "fast-forward", - position: "left", - html: '<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="M9.244 9.52L2.041 4.571C1.469 4.188 1 4.469 1 5.196v9.609c0 .725.469 1.006 1.041.625l7.203-4.951s.279-.199.279-.478c0-.28-.279-.481-.279-.481zm9.356.481c0 .279-.279.478-.279.478l-7.203 4.951c-.572.381-1.041.1-1.041-.625V5.196c0-.727.469-1.008 1.041-.625L18.32 9.52s.28.201.28.481z"></path></svg>', - tooltip: "Forward 5s", - click: function () { - art.forward = 5; - }, - }, - ], - }); - - if ("mediaSession" in navigator) { - art.on("video:timeupdate", () => { - const session = navigator.mediaSession; - if (!session) return; - session.setPositionState({ - duration: art.duration, - playbackRate: art.playbackRate, - position: art.currentTime, - }); - }); - - navigator.mediaSession.setActionHandler("play", () => { - art.play(); - }); - - navigator.mediaSession.setActionHandler("pause", () => { - art.pause(); - }); - - navigator.mediaSession.setActionHandler("previoustrack", () => { - if (track?.prev) { - router.push( - `/en/anime/watch/${id}/${provider}?id=${encodeURIComponent( - track?.prev?.id - )}&num=${track?.prev?.number}` - ); - } - }); - - navigator.mediaSession.setActionHandler("nexttrack", () => { - if (track?.next) { - router.push( - `/en/anime/watch/${id}/${provider}?id=${encodeURIComponent( - track?.next?.id - )}&num=${track?.next?.number}` - ); - } - }); - } - - playerRef.current = art; - - art.events.proxy(document, "keydown", (event) => { - // Check if the focus is on an input field or textarea - const isInputFocused = - document.activeElement.tagName === "INPUT" || - document.activeElement.tagName === "TEXTAREA"; - - if (!isInputFocused) { - if (event.key === "f" || event.key === "F") { - art.fullscreen = !art.fullscreen; - } - - if (event.key === "t" || event.key === "T") { - setPlayerState((prev) => ({ - ...prev, - currentTime: art.currentTime, - isPlaying: art.playing, - })); - setTheaterMode((prev) => !prev); - } - } - }); - - art.events.proxy(document, "keypress", (event) => { - // Check if the focus is on an input field or textarea - const isInputFocused = - document.activeElement.tagName === "INPUT" || - document.activeElement.tagName === "TEXTAREA"; - - if (!isInputFocused && event.code === "Space") { - event.preventDefault(); - art.playing ? art.pause() : art.play(); - } - }); - - if (getInstance && typeof getInstance === "function") { - getInstance(art); - } - - return () => { - if (art && art.destroy) { - art.destroy(false); - } - }; - - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - return <div ref={artRef} {...rest}></div>; -} diff --git a/components/watch/player/component/controls/quality.js b/components/watch/player/component/controls/quality.js deleted file mode 100644 index 08dbd0e..0000000 --- a/components/watch/player/component/controls/quality.js +++ /dev/null @@ -1,15 +0,0 @@ -import artplayerPluginHlsQuality from "artplayer-plugin-hls-quality"; - -export const QualityPlugins = [ - artplayerPluginHlsQuality({ - // Show quality in setting - setting: true, - - // Get the resolution text from level - getResolution: (level) => level.height + "P", - - // I18n - title: "Quality", - auto: "Auto", - }), -]; diff --git a/components/watch/player/component/overlay.js b/components/watch/player/component/overlay.js deleted file mode 100644 index 1d5ac27..0000000 --- a/components/watch/player/component/overlay.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @type {import("artplayer/types/icons".Icons)} - */ -export const icons = { - screenshot: - '<svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 20 20"><path fill="currentColor" d="M10 8a3 3 0 1 0 0 6a3 3 0 0 0 0-6zm8-3h-2.4a.888.888 0 0 1-.789-.57l-.621-1.861A.89.89 0 0 0 13.4 2H6.6c-.33 0-.686.256-.789.568L5.189 4.43A.889.889 0 0 1 4.4 5H2C.9 5 0 5.9 0 7v9c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-8 11a5 5 0 0 1-5-5a5 5 0 1 1 10 0a5 5 0 0 1-5 5zm7.5-7.8a.7.7 0 1 1 0-1.4a.7.7 0 0 1 0 1.4z"></path></svg>', - play: '<svg xmlns="http://www.w3.org/2000/svg" width="25px" height="25px" viewBox="0 0 20 20"><path fill="currentColor" d="M15 10.001c0 .299-.305.514-.305.514l-8.561 5.303C5.51 16.227 5 15.924 5 15.149V4.852c0-.777.51-1.078 1.135-.67l8.561 5.305c-.001 0 .304.215.304.514z"></path></svg>', - pause: - '<svg xmlns="http://www.w3.org/2000/svg" width="25px" height="25px" viewBox="0 0 20 20"><path fill="currentColor" d="M15 3h-2c-.553 0-1 .048-1 .6v12.8c0 .552.447.6 1 .6h2c.553 0 1-.048 1-.6V3.6c0-.552-.447-.6-1-.6zM7 3H5c-.553 0-1 .048-1 .6v12.8c0 .552.447.6 1 .6h2c.553 0 1-.048 1-.6V3.6c0-.552-.447-.6-1-.6z"></path></svg>', - volume: - '<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="M19 13.805c0 .657-.538 1.195-1.195 1.195H1.533c-.88 0-.982-.371-.229-.822l16.323-9.055C18.382 4.67 19 5.019 19 5.9v7.905z"></path></svg>', - fullscreenOff: - '<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="M3.28 2.22a.75.75 0 0 0-1.06 1.06L5.44 6.5H2.75a.75.75 0 0 0 0 1.5h4.5A.75.75 0 0 0 8 7.25v-4.5a.75.75 0 0 0-1.5 0v2.69L3.28 2.22Zm10.22.53a.75.75 0 0 0-1.5 0v4.5c0 .414.336.75.75.75h4.5a.75.75 0 0 0 0-1.5h-2.69l3.22-3.22a.75.75 0 0 0-1.06-1.06L13.5 5.44V2.75ZM3.28 17.78l3.22-3.22v2.69a.75.75 0 0 0 1.5 0v-4.5a.75.75 0 0 0-.75-.75h-4.5a.75.75 0 0 0 0 1.5h2.69l-3.22 3.22a.75.75 0 1 0 1.06 1.06Zm10.22-3.22l3.22 3.22a.75.75 0 1 0 1.06-1.06l-3.22-3.22h2.69a.75.75 0 0 0 0-1.5h-4.5a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 0 1.5 0v-2.69Z"></path></svg>', - fullscreenOn: - '<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="m13.28 7.78l3.22-3.22v2.69a.75.75 0 0 0 1.5 0v-4.5a.75.75 0 0 0-.75-.75h-4.5a.75.75 0 0 0 0 1.5h2.69l-3.22 3.22a.75.75 0 0 0 1.06 1.06ZM2 17.25v-4.5a.75.75 0 0 1 1.5 0v2.69l3.22-3.22a.75.75 0 0 1 1.06 1.06L4.56 16.5h2.69a.75.75 0 0 1 0 1.5h-4.5a.747.747 0 0 1-.75-.75Zm10.22-3.97l3.22 3.22h-2.69a.75.75 0 0 0 0 1.5h4.5a.747.747 0 0 0 .75-.75v-4.5a.75.75 0 0 0-1.5 0v2.69l-3.22-3.22a.75.75 0 1 0-1.06 1.06ZM3.5 4.56l3.22 3.22a.75.75 0 0 0 1.06-1.06L4.56 3.5h2.69a.75.75 0 0 0 0-1.5h-4.5a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 0 1.5 0V4.56Z"></path></svg>', -}; - -export const backButton = { - name: "back-button", - index: 10, - position: "top", - html: "<div class='parent-player-title'><div></div><div className='flex gap-2'><p className='pt-1'><ChevronLeftIcon className='w-7 h-7'/></p><div class='flex flex-col text-white'><p className='font-outfit font-bold text-2xl'>Komi-san wa, Komyushou desu.</p><p className=''>Episode 1</p></div></div></div>", - // tooltip: "Your Button", - click: function (...args) { - console.info("click", args); - }, - mounted: function (...args) { - console.info("mounted", args); - }, -}; - -export const seekBackward = { - index: 10, - name: "fast-rewind", - position: "left", - html: '<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="M17.959 4.571L10.756 9.52s-.279.201-.279.481s.279.479.279.479l7.203 4.951c.572.38 1.041.099 1.041-.626V5.196c0-.727-.469-1.008-1.041-.625zm-9.076 0L1.68 9.52s-.279.201-.279.481s.279.479.279.479l7.203 4.951c.572.381 1.041.1 1.041-.625v-9.61c0-.727-.469-1.008-1.041-.625z"></path></svg>', - tooltip: "Backward 5s", - click: function () { - art.backward = 5; - }, -}; - -export const seekForward = { - index: 11, - name: "fast-forward", - position: "left", - html: '<svg xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 20 20"><path fill="currentColor" d="M9.244 9.52L2.041 4.571C1.469 4.188 1 4.469 1 5.196v9.609c0 .725.469 1.006 1.041.625l7.203-4.951s.279-.199.279-.478c0-.28-.279-.481-.279-.481zm9.356.481c0 .279-.279.478-.279.478l-7.203 4.951c-.572.381-1.041.1-1.041-.625V5.196c0-.727.469-1.008 1.041-.625L18.32 9.52s.28.201.28.481z"></path></svg>', - tooltip: "Forward 5s", - click: function () { - art.forward = 5; - }, -}; - -// /** -// * @type {import("artplayer/types/component").ComponentOption} -// */ -// export const diff --git a/components/watch/player/playerComponent.js b/components/watch/player/playerComponent.js deleted file mode 100644 index 665919b..0000000 --- a/components/watch/player/playerComponent.js +++ /dev/null @@ -1,527 +0,0 @@ -import React, { useEffect, useState } from "react"; -import NewPlayer from "./artplayer"; -import { icons } from "./component/overlay"; -import { useWatchProvider } from "@/lib/context/watchPageProvider"; -import { useRouter } from "next/router"; -import { useAniList } from "@/lib/anilist/useAnilist"; -import Loading from "@/components/shared/loading"; - -export function calculateAspectRatio(width, height) { - const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); - const divisor = gcd(width, height); - const aspectRatio = `${width / divisor}/${height / divisor}`; - return aspectRatio; -} - -const fontSize = [ - { - html: "Small", - size: "16px", - }, - { - html: "Medium", - size: "36px", - }, - { - html: "Large", - size: "56px", - }, -]; - -export default function PlayerComponent({ - playerRef, - session, - id, - info, - watchId, - proxy, - dub, - timeWatched, - skip, - track, - data, - provider, - className, -}) { - const { - aspectRatio, - setAspectRatio, - playerState, - setPlayerState, - autoplay, - marked, - setMarked, - } = useWatchProvider(); - - const router = useRouter(); - - const { markProgress } = useAniList(session); - - const [url, setUrl] = useState(""); - const [resolution, setResolution] = useState("auto"); - const [source, setSource] = useState([]); - const [subSize, setSubSize] = useState({ size: "16px", html: "Small" }); - const [defSize, setDefSize] = useState(); - const [subtitle, setSubtitle] = useState(); - const [defSub, setDefSub] = useState(); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(false); - - useEffect(() => { - setLoading(true); - const resol = localStorage.getItem("quality"); - const sub = JSON.parse(localStorage.getItem("subSize")); - if (resol) { - setResolution(resol); - } - - const size = fontSize.map((i) => { - const isDefault = !sub ? i.html === "Small" : i.html === sub?.html; - return { - ...(isDefault && { default: true }), - html: i.html, - size: i.size, - }; - }); - - const defSize = size?.find((i) => i?.default === true); - setDefSize(defSize); - setSubSize(size); - - async function compiler() { - try { - const referer = JSON.stringify(data?.headers); - const source = data?.sources?.map((items) => { - const isDefault = - provider !== "gogoanime" - ? items.quality === "default" || items.quality === "auto" - : resolution === "auto" - ? items.quality === "default" || items.quality === "auto" - : items.quality === resolution; - return { - ...(isDefault && { default: true }), - html: items.quality === "default" ? "main" : items.quality, - url: `${proxy}/proxy/m3u8/${encodeURIComponent( - String(items.url) - )}/${encodeURIComponent(String(referer))}`, - }; - }); - - const defSource = source?.find((i) => i?.default === true); - - if (defSource) { - setUrl(defSource.url); - } - - const subtitle = data?.subtitles - ?.filter( - (subtitle) => - subtitle.lang !== "Thumbnails" && subtitle.lang !== "thumbnails" - ) - ?.map((subtitle) => { - const isEnglish = - subtitle.lang === "English" || - subtitle.lang === "English / English (US)"; - return { - ...(isEnglish && { default: true }), - url: subtitle.url, - html: `${subtitle.lang}`, - }; - }); - - if (subtitle) { - const defSub = data?.subtitles.find( - (i) => i.lang === "English" || i.lang === "English / English (US)" - ); - - setDefSub(defSub?.url); - - setSubtitle(subtitle); - } - - const alt = source?.filter( - (i) => - i?.html !== "main" && - i?.html !== "auto" && - i?.html !== "default" && - i?.html !== "backup" - ); - const server = source?.filter( - (i) => - i?.html === "main" || - i?.html === "auto" || - i?.html === "default" || - i?.html === "backup" - ); - - setSource({ alt, server }); - setLoading(false); - } catch (error) { - console.error(error); - } - } - compiler(); - - return () => { - setUrl(""); - setSource([]); - setSubtitle([]); - setLoading(true); - }; - - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [provider, data]); - - /** - * @param {import("artplayer")} art - */ - function getInstance(art) { - art.on("ready", () => { - const autoplay = localStorage.getItem("autoplay_video") || false; - - // check media queries for mobile devices - const isMobile = window.matchMedia("(max-width: 768px)").matches; - - // console.log(art.fullscreen); - - if (isMobile) { - art.controls.remove("theater-button"); - // art.controls.remove("fast-rewind"); - // art.controls.remove("fast-forward"); - } - - if (autoplay === "true" || autoplay === true) { - if (playerState.currentTime === 0) { - art.play(); - } else { - if (playerState.isPlaying) { - art.play(); - } else { - art.pause(); - } - } - } else { - if (playerState.isPlaying) { - art.play(); - } else { - art.pause(); - } - } - art.seek = playerState.currentTime; - }); - - art.on("ready", () => { - if (playerState.currentTime !== 0) return; - const seek = art.storage.get(id); - const seekTime = seek?.timeWatched || 0; - const duration = art.duration; - const percentage = seekTime / duration; - const percentagedb = timeWatched / duration; - - if (subSize) { - art.subtitle.style.fontSize = subSize?.size; - } - - if (percentage >= 0.9 || percentagedb >= 0.9) { - art.currentTime = 0; - console.log("Video started from the beginning"); - } else if (timeWatched) { - art.currentTime = timeWatched; - } else { - art.currentTime = seekTime; - } - }); - - art.on("error", (error, reconnectTime) => { - if (error && reconnectTime >= 5) { - setError(true); - console.error("Error while loading video:", error); - } - }); - - art.on("play", () => { - art.notice.show = ""; - setPlayerState({ ...playerState, isPlaying: true }); - }); - art.on("pause", () => { - art.notice.show = ""; - setPlayerState({ ...playerState, isPlaying: false }); - }); - - art.on("resize", () => { - art.subtitle.style({ - fontSize: art.height * 0.05 + "px", - }); - }); - - let mark = 0; - - art.on("video:timeupdate", async () => { - if (!session) return; - - var currentTime = art.currentTime; - const duration = art.duration; - const percentage = currentTime / duration; - - if (percentage >= 0.9) { - // use >= instead of > - if (mark < 1 && marked < 1) { - mark = 1; - setMarked(1); - markProgress(info.id, track.playing.number); - } - } - }); - - art.on("video:playing", () => { - if (!session) return; - const intervalId = setInterval(async () => { - await fetch("/api/user/update/episode", { - method: "PUT", - body: JSON.stringify({ - name: session?.user?.name, - id: String(info?.id), - watchId: watchId, - title: - track.playing?.title || info.title?.romaji || info.title?.english, - aniTitle: info.title?.romaji || info.title?.english, - image: track.playing?.img || info?.coverImage?.extraLarge, - number: Number(track.playing?.number), - duration: art.duration, - timeWatched: art.currentTime, - provider: provider, - nextId: track.next?.id, - nextNumber: Number(track.next?.number), - dub: dub ? true : false, - }), - }); - // console.log("updating db", { track }); - }, 5000); - - art.on("video:pause", () => { - clearInterval(intervalId); - }); - - art.on("video:ended", () => { - clearInterval(intervalId); - }); - - art.on("destroy", () => { - clearInterval(intervalId); - // console.log("clearing interval"); - }); - }); - - art.on("video:playing", () => { - const interval = setInterval(async () => { - art.storage.set(watchId, { - aniId: String(info.id), - watchId: watchId, - title: - track.playing?.title || info.title?.romaji || info.title?.english, - aniTitle: info.title?.romaji || info.title?.english, - image: track?.playing?.img || info?.coverImage?.extraLarge, - episode: Number(track.playing?.number), - duration: art.duration, - timeWatched: art.currentTime, - provider: provider, - nextId: track?.next?.id, - nextNumber: track?.next?.number, - dub: dub ? true : false, - createdAt: new Date().toISOString(), - }); - }, 5000); - - art.on("video:pause", () => { - clearInterval(interval); - }); - - art.on("video:ended", () => { - clearInterval(interval); - }); - - art.on("destroy", () => { - clearInterval(interval); - }); - }); - - art.on("video:loadedmetadata", () => { - // get raw video width and height - // console.log(art.video.videoWidth, art.video.videoHeight); - const aspect = calculateAspectRatio( - art.video.videoWidth, - art.video.videoHeight - ); - - setAspectRatio(aspect); - }); - - art.on("video:timeupdate", () => { - var currentTime = art.currentTime; - // console.log(art.currentTime); - - if ( - skip?.op && - currentTime >= skip.op.interval.startTime && - currentTime <= skip.op.interval.endTime - ) { - // Add the layer if it's not already added - if (!art.controls["op"]) { - // Remove the other control if it's already added - if (art.controls["ed"]) { - art.controls.remove("ed"); - } - - // Add the control - art.controls.add({ - name: "op", - position: "top", - html: '<button class="skip-button">Skip Opening</button>', - click: function (...args) { - art.seek = skip.op.interval.endTime; - }, - }); - } - } else if ( - skip?.ed && - currentTime >= skip.ed.interval.startTime && - currentTime <= skip.ed.interval.endTime - ) { - // Add the layer if it's not already added - if (!art.controls["ed"]) { - // Remove the other control if it's already added - if (art.controls["op"]) { - art.controls.remove("op"); - } - - // Add the control - art.controls.add({ - name: "ed", - position: "top", - html: '<button class="skip-button">Skip Ending</button>', - click: function (...args) { - art.seek = skip.ed.interval.endTime; - }, - }); - } - } else { - // Remove the controls if they're added - if (art.controls["op"]) { - art.controls.remove("op"); - } - if (art.controls["ed"]) { - art.controls.remove("ed"); - } - } - }); - - art.on("video:ended", () => { - if (!track?.next) return; - if (localStorage.getItem("autoplay") === "true") { - art.controls.add({ - name: "next-button", - position: "top", - html: '<div class="vid-con"><button class="next-button progress">Play Next</button></div>', - click: function (...args) { - if (track?.next) { - router.push( - `/en/anime/watch/${ - info?.id - }/${provider}?id=${encodeURIComponent(track?.next?.id)}&num=${ - track?.next?.number - }${dub ? `&dub=${dub}` : ""}` - ); - } - }, - }); - - const button = document.querySelector(".next-button"); - - function stopTimeout() { - clearTimeout(timeoutId); - button.classList.remove("progress"); - } - - let timeoutId = setTimeout(() => { - art.controls.remove("next-button"); - if (track?.next) { - router.push( - `/en/anime/watch/${info?.id}/${provider}?id=${encodeURIComponent( - track?.next?.id - )}&num=${track?.next?.number}${dub ? `&dub=${dub}` : ""}` - ); - } - }, 7000); - - button.addEventListener("mouseover", stopTimeout); - } - }); - } - - /** - * @type {import("artplayer/types/option").Option} - */ - const option = { - url: url, - autoplay: autoplay ? true : false, - autoSize: false, - playbackRate: true, - fullscreen: true, - autoOrientation: true, - icons: icons, - setting: true, - screenshot: true, - hotkey: true, - pip: true, - airplay: true, - lock: true, - }; - - return ( - <div - id={id} - className={`${className} bg-black`} - style={{ aspectRatio: aspectRatio }} - > - <div className="flex-center w-full h-full"> - {!data?.error && !url && ( - <div className="flex-center w-full h-full"> - <Loading /> - </div> - )} - {!error ? ( - !loading && track && url && !data?.error ? ( - <NewPlayer - playerRef={playerRef} - res={resolution} - quality={source} - option={option} - provider={provider} - track={track} - defSize={defSize} - defSub={defSub} - subSize={subSize} - subtitles={subtitle} - getInstance={getInstance} - style={{ - width: "100%", - height: "100%", - }} - /> - ) : ( - <p className="text-center"> - {data?.status === 404 && "Not Found"} - <br /> - {data?.error} - </p> - ) - ) : ( - <p className="text-center"> - Something went wrong while loading the video, <br /> - please try from other source - </p> - )} - </div> - </div> - ); -} diff --git a/components/watch/primary/details.js b/components/watch/primary/details.tsx index 4af12ac..f20f8cf 100644 --- a/components/watch/primary/details.js +++ b/components/watch/primary/details.tsx @@ -2,7 +2,20 @@ import { useEffect, useState } from "react"; import { useAniList } from "../../../lib/anilist/useAnilist"; import Skeleton from "react-loading-skeleton"; import DisqusComments from "../../disqus"; -import Image from "next/image"; +import { AniListInfoTypes } from "types/info/AnilistInfoTypes"; +import { SessionTypes } from "pages/en"; + +type DetailsProps = { + info: AniListInfoTypes; + session: SessionTypes; + epiNumber: number; + description: string; + id: string; + onList: boolean; + setOnList: (value: boolean) => void; + handleOpen: () => void; + disqus: string; +}; export default function Details({ info, @@ -14,10 +27,14 @@ export default function Details({ setOnList, handleOpen, disqus, -}) { +}: DetailsProps) { const [showComments, setShowComments] = useState(false); const { markPlanning } = useAniList(session); + const [showDesc, setShowDesc] = useState(false); + + const truncatedDesc = truncateText(description, 420); + function handlePlan() { if (onList === false) { markPlanning(info.id); @@ -32,6 +49,10 @@ export default function Details({ } else { setShowComments(true); } + return () => { + setShowComments(false); + setShowDesc(false); + }; }, [id]); return ( @@ -133,12 +154,28 @@ export default function Details({ ))} </div> {/* <div className={`bg-secondary rounded-md mt-3 mx-3`}> */} - <div className={`bg-secondary rounded-md mt-3`}> + <div className={`relative bg-secondary rounded-md mt-3`}> {info && ( - <p - dangerouslySetInnerHTML={{ __html: description }} - className={`p-5 text-sm font-light font-roboto text-[#e4e4e4] `} - /> + <> + <p + dangerouslySetInnerHTML={{ + __html: showDesc + ? description + : description?.length > 420 + ? truncatedDesc + : description, + }} + className={`p-5 text-sm font-light font-roboto text-[#e4e4e4] `} + /> + {!showDesc && description?.length > 120 && ( + <span + onClick={() => setShowDesc((prev) => !prev)} + className="flex justify-center items-end rounded-md pb-5 font-semibold font-karla cursor-pointer w-full h-full bg-gradient-to-t from-secondary hover:from-20% to-transparent absolute inset-0" + > + Read More + </span> + )} + </> )} </div> {/* {<div className="mt-5 px-5"></div>} */} @@ -177,7 +214,6 @@ export default function Details({ <DisqusComments key={id} post={{ - id: id, title: info.title.romaji, url: window.location.href, episode: epiNumber, @@ -191,3 +227,8 @@ export default function Details({ </div> ); } + +function truncateText(txt: string, length: number) { + const text = txt.replace(/(<([^>]+)>)/gi, ""); + return text.length > length ? text.slice(0, length) + "..." : text; +} diff --git a/components/watch/secondary/episodeLists.js b/components/watch/secondary/episodeLists.tsx index a676be0..2c23f25 100644 --- a/components/watch/secondary/episodeLists.js +++ b/components/watch/secondary/episodeLists.tsx @@ -3,6 +3,19 @@ import Image from "next/image"; import Link from "next/link"; import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { useRouter } from "next/router"; +import { AniListInfoTypes } from "types/info/AnilistInfoTypes"; +import { Episode } from "types/api/Episode"; + +type EpisodeListsProps = { + info: AniListInfoTypes; + map: any; + providerId: string; + watchId: string; + episode: Episode[]; + artStorage: any; + track: any; + dub: string; +}; export default function EpisodeLists({ info, @@ -13,7 +26,7 @@ export default function EpisodeLists({ artStorage, track, dub, -}) { +}: EpisodeListsProps) { const progress = info.mediaListEntry?.progress; const router = useRouter(); @@ -45,8 +58,8 @@ export default function EpisodeLists({ router.push( `/en/anime/watch/${info.id}/${providerId}?id=${ - selectedEpisode.id - }&num=${selectedEpisode.number}${dub ? `&dub=${dub}` : ""}` + selectedEpisode?.id + }&num=${selectedEpisode?.number}${dub ? `&dub=${dub}` : ""}` ); }} className="flex items-center text-sm gap-5 rounded-[3px] bg-secondary py-1 px-3 pr-8 font-karla appearance-none cursor-pointer outline-none focus:ring-1 focus:ring-action group-hover:ring-1 group-hover:ring-action" @@ -64,7 +77,7 @@ export default function EpisodeLists({ <div className="flex flex-col gap-5 lg:pl-5 py-2 scrollbar-thin px-2 scrollbar-thumb-[#313131] scrollbar-thumb-rounded-full"> {episode && episode.length > 0 ? ( map?.some( - (item) => + (item: any) => (item?.img || item?.image) && !item?.img?.includes("https://s4.anilist.co/") ) > 0 ? ( @@ -74,7 +87,14 @@ export default function EpisodeLists({ let prog = (time / duration) * 100; if (prog > 90) prog = 100; - const mapData = map?.find((i) => i.number === item.number); + const mapData = map?.find((i: any) => i.number === item.number); + + const parsedImage = mapData + ? mapData?.img?.includes("null") || + mapData?.image?.includes("null") + ? info.coverImage?.extraLarge + : mapData?.img || mapData?.image + : info.coverImage?.extraLarge || null; return ( <Link href={`/en/anime/watch/${ @@ -93,11 +113,7 @@ export default function EpisodeLists({ <div className="relative"> {/* <div className="absolute inset-0 w-full h-full z-40" /> */} <Image - src={ - mapData?.img || - mapData?.image || - info?.coverImage?.extraLarge - } + src={parsedImage || info?.coverImage?.extraLarge} draggable={false} alt="Anime Cover" width={1000} |