import React, { useRef } from 'react' import { StyledVideo, StyledVideoMask, StyledVideoPlay } from './Video.theme' import { IVideo } from './Video.interface' const Video = ({ src, poster, autoplay, controls, loop, muted, playsInline, className, style, ...props }: IVideo) => { const maskRef: any = useRef() const videoRef: any = useRef() let isPlaying: boolean = false const setFramed = () => { const video = document.createElement('video') const source = document.createElement('source') autoplay && video.setAttribute('autoPlay', '') controls && video.setAttribute('controls', '') loop && video.setAttribute('loop', '') muted && video.setAttribute('muted', '') playsInline && video.setAttribute('playsInline', '') source.setAttribute('src', src || '') source.setAttribute('type', 'video/mp4') video.appendChild(source) video.pause() video.onplaying = function () { isPlaying = true } video.onpause = function () { isPlaying = false } maskRef.current.replaceWith(video) let observerObj = new IntersectionObserver( (entries, observer) => { const element: any = entries[0].target if (entries[0].isIntersecting) { if ( element.paused && !isPlaying && element.getAttribute('autoplay') != undefined ) { element.muted = true element.play() } } else { if (!element.paused && isPlaying) { element.pause() } } }, { rootMargin: '0px', threshold: 0.3 } ) setTimeout(() => { observerObj.observe(video) }, 500) } return ( { setFramed() }} > ) } export default Video