import React, { useRef } from 'react' import { StyledVideo, StyledVideoMask, StyledVideoPlay } from './VideoEmbed.theme' import { IVideoEmbed } from './VideoEmbed.interface' const VideoEmbed = ({ embed, poster, autoplay, controls, loop, muted, playsInline, className, style, ...props }: IVideoEmbed) => { const maskRef: any = useRef() const framed: boolean = false let videoId: any = [] let thumb: string = poster || '' let embedElement: string = '' if (embed && !framed) { if (embed.indexOf('/watch?v=') !== -1) { videoId = embed.split('/watch?v=') videoId = videoId[videoId.length - 1] if (embed.indexOf('&') !== -1) { videoId = videoId.split('&') videoId = videoId[0] } } else if (embed.indexOf('/') !== -1) { videoId = embed.split('/') videoId = videoId[videoId.length - 1] if (embed.indexOf('?') !== -1) { videoId = videoId.split('?') videoId = videoId[0] } } const videoAttrs = `autoPlay=${autoplay}&controls=${controls}&loop=${loop}&muted=${muted}&playsInline=${playsInline}` if (embed.indexOf('youtube') >= 0) { embedElement = `https://www.youtube.com/embed/${videoId}?${videoAttrs}&enablejsapi=1` if (!poster) { thumb = `https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg` } } else if (embed.indexOf('vimeo') >= 0) { embedElement = `https://player.vimeo.com/video/${videoId}?${videoAttrs}` if (!poster) { thumb = `https://i.vimeocdn.com/video/${videoId}_640.jpg` } } } const setFramed = () => { const iframe = document.createElement('iframe') iframe.setAttribute('frameborder', '0') iframe.setAttribute('allow', 'fullscreen; autoplay') iframe.setAttribute('allowfullscreen', '1') iframe.setAttribute('src', embedElement) maskRef.current.replaceWith(iframe) setTimeout(() => { iframe?.contentWindow?.postMessage( '{"event":"command","func":"playVideo","args":""}', '*' ) }, 500) } return ( { setFramed() }} > ) } export default VideoEmbed