import { CSSProperties, FC, useEffect, useId, useRef, useState } from 'react'; import JSXStyle from 'styled-jsx/style'; export type TSectionVideo = { url: string; size: string; type: 'video'; play: 'on-click' | 'auto'; position: string; coverUrl: string | null; offsetX: number | null; opacity?: number; }; interface Props { container: HTMLDivElement; sectionId: string; media: TSectionVideo; } export const SectionVideo: FC = ({ container, sectionId, media }) => { const [video, setVideo] = useState(null); const [videoWrapper, setVideoWrapper] = useState(null); const [isVideoWidthOverflow, setIsVideoWidthOverflow] = useState(false); const { url, size, position, offsetX, coverUrl, play, opacity } = media; const [isPlaying, setIsPlaying] = useState(false); const [userPaused, setUserPaused] = useState(false); const [isClickedOnCover, setIsClickedOnCover] = useState(false); const handleCoverClick = () => { if (!video || play !== 'on-click') return; setIsClickedOnCover(true); if (isPlaying) { video.pause(); setUserPaused(true); } else { video.play(); setUserPaused(false); } }; useEffect(() => { if (!video || play !== 'on-click') return; const observer = new IntersectionObserver( ([entry]) => { if (userPaused || !isClickedOnCover) return; if (entry.isIntersecting) { video.play(); } else { video.pause(); } } ); observer.observe(container); return () => observer.disconnect(); }, [container, play, userPaused, isClickedOnCover]); useEffect(() => { if (!video || !videoWrapper) return; video.addEventListener('loadedmetadata', () => { const h = video.videoHeight; const w = video.videoWidth; const width = (videoWrapper.clientHeight / h) * w; if (width > videoWrapper.clientWidth) { setIsVideoWidthOverflow(true); } else { setIsVideoWidthOverflow(false); } }); }, [video, videoWrapper]); const isContainHeight = size === 'contain-height'; const hasOffsetX = offsetX !== null && size === 'contain'; return ( <>
{play === 'on-click' && !isClickedOnCover && (
{coverUrl && play === 'on-click' && ( Video cover )}
)}
); };