|
| 1 | +import { IframeHTMLAttributes } from "react"; |
| 2 | + |
| 3 | +type VideoType = "bilibili" | "youtube"; |
| 4 | + |
| 5 | +interface VideoEmbedProps { |
| 6 | + type: VideoType; |
| 7 | + id: string; |
| 8 | +} |
| 9 | + |
| 10 | +// 响应式容器的基础样式 |
| 11 | +const containerStyle: React.CSSProperties = { |
| 12 | + position: "relative", |
| 13 | + paddingBottom: "56.25%", // 16:9 宽高比 |
| 14 | + height: 0, |
| 15 | + overflow: "hidden", |
| 16 | + borderRadius: "8px", |
| 17 | + boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)", |
| 18 | +}; |
| 19 | + |
| 20 | +// iframe 基础样式 |
| 21 | +const iframeStyle: React.CSSProperties = { |
| 22 | + position: "absolute", |
| 23 | + top: 0, |
| 24 | + left: 0, |
| 25 | + width: "100%", |
| 26 | + height: "100%", |
| 27 | + border: "none", |
| 28 | +}; |
| 29 | + |
| 30 | +// 获取平台相关配置 |
| 31 | +const getPlatformConfig = ( |
| 32 | + type: VideoType, |
| 33 | + id: string |
| 34 | +): { |
| 35 | + url: string; |
| 36 | + title: string; |
| 37 | + props: IframeHTMLAttributes<HTMLIFrameElement>; |
| 38 | +} | null => { |
| 39 | + const commonProps = { |
| 40 | + allowFullScreen: true, |
| 41 | + loading: "lazy" as const, |
| 42 | + }; |
| 43 | + |
| 44 | + switch (type) { |
| 45 | + case "bilibili": |
| 46 | + return { |
| 47 | + url: `https://player.bilibili.com/player.html?isOutside=true&bvid=${id}`, |
| 48 | + title: "Bilibili 视频播放器", |
| 49 | + props: { |
| 50 | + ...commonProps, |
| 51 | + scrolling: "no", |
| 52 | + frameBorder: 0, |
| 53 | + }, |
| 54 | + }; |
| 55 | + |
| 56 | + case "youtube": |
| 57 | + return { |
| 58 | + url: `https://www.youtube.com/embed/${id}?rel=0`, |
| 59 | + title: "YouTube 视频播放器", |
| 60 | + props: { |
| 61 | + ...commonProps, |
| 62 | + width: 560, |
| 63 | + height: 315, |
| 64 | + allow: |
| 65 | + "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture", |
| 66 | + referrerPolicy: "strict-origin-when-cross-origin", |
| 67 | + }, |
| 68 | + }; |
| 69 | + |
| 70 | + default: |
| 71 | + return null; |
| 72 | + } |
| 73 | +}; |
| 74 | + |
| 75 | +function VideoEmbed({ type, id }: VideoEmbedProps) { |
| 76 | + const platformConfig = getPlatformConfig(type, id); |
| 77 | + |
| 78 | + if (!platformConfig) return null; |
| 79 | + |
| 80 | + return ( |
| 81 | + <div style={containerStyle}> |
| 82 | + <iframe |
| 83 | + src={platformConfig.url} |
| 84 | + title={platformConfig.title} |
| 85 | + style={iframeStyle} |
| 86 | + {...platformConfig.props} |
| 87 | + /> |
| 88 | + </div> |
| 89 | + ); |
| 90 | +} |
| 91 | + |
| 92 | +export default VideoEmbed; |
0 commit comments