Files
web_hghl_h5/src/components/drama-play/h5-play.tsx
T
2026-10-26 19:51:59 +07:00

348 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { BackButton } from "@/components/common/back-button";
import { pickPlayletCardTags } from "@/components/common/card-tags";
import { DecryptedImage } from "@/components/common/decrypted-image";
import {
dramaDetailHref,
playHref,
totalEpisodeOf,
updateStatusLabel,
type DramaDetail,
type RelatedDrama,
} from "@/components/drama-detail/data";
import { openAppDownload } from "@/components/download/download-dialog";
import { EpisodeDirectory } from "@/components/media-page/episode-directory";
import { DramaRecommend, HlAction, TagLinks, tagLinkItems } from "@/components/media-page/parts";
import { playbackRates, XgPlayer, type XgPlayerInstance } from "@/components/player/xg-player";
import { CheckIcon, ChevronIcon } from "./icons";
type Sheet = "speed" | null;
/** 播完自动下一集倒计时(秒) */
const AUTO_NEXT_SECONDS = 3;
/** 切集后自动起播标记(sessionStorage) */
const AUTOPLAY_NEXT_KEY = "hjsq-drama-autoplay-next";
function consumeAutoplayFlag() {
if (typeof window === "undefined") return false;
try {
if (sessionStorage.getItem(AUTOPLAY_NEXT_KEY) !== "1") return false;
sessionStorage.removeItem(AUTOPLAY_NEXT_KEY);
return true;
} catch {
return false;
}
}
function markAutoplayNext() {
try {
sessionStorage.setItem(AUTOPLAY_NEXT_KEY, "1");
} catch {
/* ignore */
}
}
type H5PlayProps = {
detail: DramaDetail;
episode: number;
src: string;
locked: boolean;
liked: boolean;
/** 点赞数 displayCountLike */
displayCountLike?: number;
collected: boolean;
/** 收藏数 countCollect */
countCollect?: number;
related?: RelatedDrama[];
onLike: () => void;
onCollect: () => void;
onShare: () => void;
onPlaySuccess?: () => void;
};
function LockedNotice() {
return (
<div className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-4 bg-black/70 text-center">
<p className="text-sm leading-5 text-white">本集暂未在官网开放</p>
<button
type="button"
onClick={openAppDownload}
className="cursor-pointer inline-flex h-9 items-center justify-center rounded-md bg-[#FFB020] px-6 text-sm font-semibold text-[#1A1206]"
>
下载APP观看完整剧集
</button>
</div>
);
}
function formatCount(value: number) {
return value >= 10000 ? `${(value / 10000).toFixed(1)}w` : String(value);
}
function BottomSheet({
open,
onClose,
label,
className = "",
children,
}: {
open: boolean;
onClose: () => void;
label: string;
className?: string;
children: ReactNode;
}) {
return (
<>
<div
aria-hidden="true"
onClick={onClose}
className={`fixed inset-0 z-40 bg-black/70 transition-opacity ${open ? "opacity-100" : "pointer-events-none opacity-0"}`}
/>
<div
role="dialog"
aria-modal="true"
aria-label={label}
aria-hidden={!open}
inert={!open}
className={`fixed inset-x-0 bottom-0 z-50 flex flex-col rounded-t-[20px] bg-[#1A1A1A] pb-[env(safe-area-inset-bottom)] transition-transform duration-300 ${
open ? "translate-y-0" : "translate-y-full"
} ${className}`}
>
{children}
</div>
</>
);
}
function SheetHead({ title, onClose, children }: { title: ReactNode; onClose: () => void; children?: ReactNode }) {
return (
<div className="flex items-center gap-3">
<button
type="button"
aria-label="收起"
onClick={onClose}
className="cursor-pointer flex size-6 items-center justify-center text-white"
>
<ChevronIcon direction="down" className="size-4" />
</button>
<h2 className="min-w-0 flex-1 text-center text-base leading-[22px] font-medium text-white">{title}</h2>
{children ?? <span className="size-6" />}
</div>
);
}
export function H5Play({
detail,
episode,
src,
locked,
liked,
displayCountLike,
collected,
countCollect,
related = [],
onLike,
onCollect,
onShare,
onPlaySuccess,
}: H5PlayProps) {
const router = useRouter();
const playerRef = useRef<XgPlayerInstance | null>(null);
const [rate, setRate] = useState(1);
const [sheet, setSheet] = useState<Sheet>(null);
const [introOpen, setIntroOpen] = useState(false);
/** null=未进入自动下一集;数字=剩余秒数 */
const [autoNextSeconds, setAutoNextSeconds] = useState<number | null>(null);
/** 自动切集进入本集时消费一次,用于起播 */
const [shouldAutoplay] = useState(consumeAutoplayFlag);
const closeSheet = () => setSheet(null);
const title = detail.title || "短剧";
const totalEpisode = totalEpisodeOf(detail);
const nextEpisode = episode + 1;
const hasNext = nextEpisode <= totalEpisode;
const nextHref = hasNext ? playHref(detail.id, nextEpisode, detail.slug) : null;
const prevHref = episode > 1 ? playHref(detail.id, episode - 1, detail.slug) : null;
const tags = tagLinkItems(pickPlayletCardTags(detail), "playlet");
const desc = detail.desc?.trim() || "";
useEffect(() => {
if (!sheet) return;
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") setSheet(null);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [sheet]);
// 换集后清倒计时
useEffect(() => {
setAutoNextSeconds(null);
}, [episode, src]);
// 倒计时结束跳转下一集并标记自动播放
useEffect(() => {
if (autoNextSeconds == null || !nextHref) return;
if (autoNextSeconds <= 0) {
markAutoplayNext();
router.push(nextHref);
return;
}
const timer = window.setTimeout(() => {
setAutoNextSeconds((value) => (value == null ? null : value - 1));
}, 1000);
return () => window.clearTimeout(timer);
}, [autoNextSeconds, nextHref, router]);
const goNextEpisode = () => {
if (!nextHref) return;
setAutoNextSeconds(null);
markAutoplayNext();
router.push(nextHref);
};
const handleEnded = () => {
if (!hasNext || locked) return;
setAutoNextSeconds(AUTO_NEXT_SECONDS);
};
const likeCount = displayCountLike ?? (Number(detail.displayCountLike) || 0);
const collectCount = countCollect ?? (Number(detail.countCollect) || 0);
return (
<div data-component="hl-drama-play-h5" className="flex flex-col bg-[#0C0B10] lg:hidden">
<div className="sticky top-0 z-30 aspect-[3/4] max-h-[72vh] w-full overflow-hidden bg-black">
{locked ? (
<DecryptedImage src={detail.cover} alt={`${title} 第${episode}集`} className="absolute inset-0 size-full object-cover" />
) : (
<XgPlayer
src={src}
poster={detail.cover}
playerRef={playerRef}
onReady={(player) => {
player.on("ratechange", () => setRate(player.playbackRate));
// 用户重新起播则取消自动下一集
player.on("playing", () => setAutoNextSeconds(null));
}}
onPlaySuccess={onPlaySuccess}
onEnded={handleEnded}
clickToPlay={!shouldAutoplay}
className="absolute inset-0"
options={{ ignores: ["playbackrate", "cssfullscreen"] }}
/>
)}
<div className="pointer-events-none absolute inset-x-0 top-0 h-20 bg-[linear-gradient(180deg,rgba(0,0,0,0.7)_0%,rgba(0,0,0,0)_100%)]" />
<div className="absolute inset-x-0 top-0 z-20 flex items-center gap-2 px-3 pt-[calc(8px+env(safe-area-inset-top))] pb-2">
<BackButton fallback={dramaDetailHref(detail)} />
<p className="min-w-0 flex-1 truncate text-sm leading-5 text-white/90">
第 {episode} / {totalEpisode} 集
</p>
<button
type="button"
onClick={() => setSheet("speed")}
className="cursor-pointer flex items-center gap-1 rounded bg-black/40 px-2 py-1 text-xs leading-[18px] font-medium text-white"
>
<img src="/images/speed.svg" alt="" className="size-4" />
{rate === 1 ? "1.0" : rate}x
</button>
</div>
{locked ? <LockedNotice /> : null}
{autoNextSeconds != null && hasNext ? (
<button
type="button"
onClick={goNextEpisode}
className="absolute inset-x-3 bottom-3 z-20 flex cursor-pointer items-center justify-between rounded-md bg-black/60 px-3 py-2 text-sm leading-5"
>
<span className="text-white">即将播放第 {nextEpisode} 集</span>
<span className="text-[#FFB020]">{autoNextSeconds}s</span>
</button>
) : null}
</div>
<div className="flex flex-col gap-6 px-4 pt-4 pb-10">
<article className="flex flex-col gap-3">
<p className="text-[11px] leading-4 tracking-[0.15em] text-[#FFB020]">
短剧 · {updateStatusLabel(detail.updateStatus)} · 共{totalEpisode}集
</p>
<h1 className="text-lg leading-7 font-bold text-white">
{title}
<span className="ml-2 text-[#FFB020]">第{episode}集</span>
</h1>
<TagLinks tags={tags} compact />
{desc ? (
<div className="flex items-end gap-1.5">
<p className={`min-w-0 flex-1 text-[13px] leading-[22px] text-[#A9A7B3] ${introOpen ? "" : "line-clamp-2"}`}>{desc}</p>
<button
type="button"
onClick={() => setIntroOpen((open) => !open)}
className="cursor-pointer shrink-0 text-xs leading-[22px] text-[#FFB020]"
>
{introOpen ? "收起" : "展开"}
</button>
</div>
) : null}
<div className="flex items-center gap-2">
<HlAction kind="like" label={formatCount(likeCount)} active={liked} onClick={onLike} compact />
<HlAction kind="collect" label={formatCount(collectCount)} active={collected} onClick={onCollect} compact />
<HlAction kind="share" label="分享" onClick={onShare} compact />
</div>
<nav aria-label="分集导航" className="grid grid-cols-2 gap-2 text-xs leading-[18px]">
{prevHref ? (
<Link href={prevHref} className="flex items-center gap-1 rounded-md border border-white/12 px-3 py-2 text-[#D8D6DF]">
<ChevronIcon direction="left" className="size-3.5" />
上一集 · 第{episode - 1}集
</Link>
) : (
<span />
)}
{nextHref ? (
<Link
href={nextHref}
className="flex items-center justify-end gap-1 rounded-md border border-white/12 px-3 py-2 text-[#D8D6DF]"
>
下一集 · 第{nextEpisode}集
<ChevronIcon direction="right" className="size-3.5" />
</Link>
) : null}
</nav>
</article>
<EpisodeDirectory detail={detail} current={episode} variant="h5" />
<DramaRecommend items={related} compact />
</div>
<BottomSheet open={sheet === "speed"} onClose={closeSheet} label="倍速" className="gap-3 px-4 py-[18px]">
<SheetHead title="倍速" onClose={closeSheet} />
<div role="listbox" aria-label="选择倍速" className="flex flex-col">
{playbackRates.map((item) => (
<button
key={item}
type="button"
role="option"
aria-selected={item === rate}
onClick={() => {
if (playerRef.current) playerRef.current.playbackRate = item;
setRate(item);
closeSheet();
}}
className={`cursor-pointer flex h-12 items-center justify-between text-base leading-[22px] ${item === rate ? "text-[#FFB020]" : "text-white"}`}
>
{item}x{item === rate ? <CheckIcon /> : null}
</button>
))}
</div>
</BottomSheet>
</div>
);
}