import arrowsMaximizeIcon from '@tabler/icons/outline/arrows-maximize.svg'; import arrowsMinimizeIcon from '@tabler/icons/outline/arrows-minimize.svg'; import playerPauseIcon from '@tabler/icons/outline/player-pause.svg'; import playerPlayIcon from '@tabler/icons/outline/player-play.svg'; import volume3Icon from '@tabler/icons/outline/volume-3.svg'; import volumeIcon from '@tabler/icons/outline/volume.svg'; import clsx from 'clsx'; import { debounce, throttle } from 'es-toolkit'; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { defineMessages, useIntl } from 'react-intl'; import Blurhash from 'soapbox/components/blurhash.tsx'; import SvgIcon from 'soapbox/components/ui/svg-icon.tsx'; import { useIsMobile } from 'soapbox/hooks/useIsMobile.ts'; import { isPanoramic, isPortrait, minimumAspectRatio, maximumAspectRatio } from 'soapbox/utils/media-aspect-ratio.ts'; import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen.ts'; const DEFAULT_HEIGHT = 300; type Position = { x: number; y: number }; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, pause: { id: 'video.pause', defaultMessage: 'Pause' }, mute: { id: 'video.mute', defaultMessage: 'Mute sound' }, unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' }, fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' }, exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' }, }); export const formatTime = (secondsNum: number): string => { let hours: number | string = Math.floor(secondsNum / 3600); let minutes: number | string = Math.floor((secondsNum - (hours * 3600)) / 60); let seconds: number | string = secondsNum - (hours * 3600) - (minutes * 60); if (hours < 10) hours = '0' + hours; if (minutes < 10) minutes = '0' + minutes; if (seconds < 10) seconds = '0' + seconds; return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`; }; export const findElementPosition = (el: HTMLElement) => { let box; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0, }; } const docEl = document.documentElement; const body = document.body; const clientLeft = docEl.clientLeft || body.clientLeft || 0; const scrollLeft = window.pageXOffset || body.scrollLeft; const left = (box.left + scrollLeft) - clientLeft; const clientTop = docEl.clientTop || body.clientTop || 0; const scrollTop = window.pageYOffset || body.scrollTop; const top = (box.top + scrollTop) - clientTop; return { left: Math.round(left), top: Math.round(top), }; }; export const getPointerPosition = (el: HTMLElement, event: MouseEvent & TouchEvent): Position => { const box = findElementPosition(el); const boxW = el.offsetWidth; const boxH = el.offsetHeight; const boxY = box.top; const boxX = box.left; let pageY = event.pageY; let pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } return { y: Math.max(0, Math.min(1, (pageY - boxY) / boxH)), x: Math.max(0, Math.min(1, (pageX - boxX) / boxW)), }; }; export const fileNameFromURL = (str: string) => { const url = new URL(str); const pathname = url.pathname; const index = pathname.lastIndexOf('/'); return pathname.substring(index + 1); }; interface IVideo { preview?: string; src: string; alt?: string; width?: number; height?: number; startTime?: number; detailed?: boolean; autoFocus?: boolean; inline?: boolean; cacheWidth?: (width: number) => void; visible?: boolean; blurhash?: string; link?: React.ReactNode; aspectRatio?: number; displayMedia?: string; } const Video: React.FC = ({ width, visible = false, detailed = false, autoFocus = false, cacheWidth, startTime, src, height, alt, inline, aspectRatio = 16 / 9, link, blurhash, preview, }) => { const intl = useIntl(); const isMobile = useIsMobile(); const player = useRef(null); const video = useRef(null); const seek = useRef(null); const slider = useRef(null); const timeoutRef = useRef(null); const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0); const [volume, setVolume] = useState(0); const [preVolume, setPreVolume] = useState(1); const [paused, setPaused] = useState(true); const [dragging, setDragging] = useState(false); const [containerWidth, setContainerWidth] = useState(width); const [fullscreen, setFullscreen] = useState(false); const [hovered, setHovered] = useState(false); const [volumeHovered, setVolumeHovered] = useState(false); const [seekHovered, setSeekHovered] = useState(false); const [muted, setMuted] = useState(true); const [buffer, setBuffer] = useState(0); const setDimensions = () => { if (player.current) { const { offsetWidth } = player.current; if (cacheWidth) { cacheWidth(offsetWidth); } setContainerWidth(offsetWidth); } }; useLayoutEffect(() => { setDimensions(); }, [player.current]); useEffect(() => { if (video.current) { setVolume(video.current.volume); setMuted(video.current.muted); } }, [video.current]); const handleClickRoot: React.MouseEventHandler = e => e.stopPropagation(); const handlePlay = () => { setPaused(false); }; const handlePause = () => { setPaused(true); }; const handleTimeUpdate = () => { if (!video.current) return; const { duration, currentTime } = video.current; setCurrentTime(Math.floor(currentTime)); setDuration(Number.isNaN(duration) || (duration === Infinity) ? 0 : Math.floor(duration)); }; const handleVolumeMouseDown: React.MouseEventHandler = e => { document.addEventListener('mousemove', handleMouseVolSlide, true); document.addEventListener('mouseup', handleVolumeMouseUp, true); document.addEventListener('touchmove', handleMouseVolSlide, true); document.addEventListener('touchend', handleVolumeMouseUp, true); handleMouseVolSlide(e); e.preventDefault(); e.stopPropagation(); }; const handleVolumeMouseUp = () => { document.removeEventListener('mousemove', handleMouseVolSlide, true); document.removeEventListener('mouseup', handleVolumeMouseUp, true); document.removeEventListener('touchmove', handleMouseVolSlide, true); document.removeEventListener('touchend', handleVolumeMouseUp, true); }; const handleMouseVolSlide = throttle(e => { if (slider.current) { const { x } = getPointerPosition(slider.current, e); if (!isNaN(x)) { let slideamt = x; if (x > 1) { slideamt = 1; } else if (x < 0) { slideamt = 0; } if (video.current) { video.current.volume = slideamt; const isMuted = slideamt <= 0; video.current.muted = isMuted; setMuted(isMuted); } setVolume(slideamt); } } }, 60); const handleMouseDown: React.MouseEventHandler = e => { document.addEventListener('mousemove', handleMouseMove, true); document.addEventListener('mouseup', handleMouseUp, true); document.addEventListener('touchmove', handleMouseMove, true); document.addEventListener('touchend', handleMouseUp, true); setDragging(true); video.current?.pause(); handleMouseMove(e); e.preventDefault(); e.stopPropagation(); }; const handleMouseUp = () => { document.removeEventListener('mousemove', handleMouseMove, true); document.removeEventListener('mouseup', handleMouseUp, true); document.removeEventListener('touchmove', handleMouseMove, true); document.removeEventListener('touchend', handleMouseUp, true); setDragging(false); video.current?.play(); }; const handleMouseMove = throttle(e => { if (seek.current && video.current) { const { x } = getPointerPosition(seek.current, e); const currentTime = Math.floor(video.current.duration * x); if (!isNaN(currentTime)) { video.current.currentTime = currentTime; setCurrentTime(currentTime); } } }, 60); const seekBy = (time: number) => { if (video.current) { const currentTime = video.current.currentTime + time; if (!isNaN(currentTime)) { setCurrentTime(currentTime); video.current.currentTime = currentTime; } } }; const handleVideoKeyDown: React.KeyboardEventHandler = e => { // On the video element or the seek bar, we can safely use the space bar // for playback control because there are no buttons to press if (e.key === ' ') { e.preventDefault(); e.stopPropagation(); togglePlay(); } }; const handleKeyDown: React.KeyboardEventHandler = e => { const frameTime = 1 / 25; switch (e.key) { case 'k': e.preventDefault(); e.stopPropagation(); togglePlay(); break; case 'm': e.preventDefault(); e.stopPropagation(); toggleMute(); break; case 'f': e.preventDefault(); e.stopPropagation(); toggleFullscreen(); break; case 'j': e.preventDefault(); e.stopPropagation(); seekBy(-10); break; case 'l': e.preventDefault(); e.stopPropagation(); seekBy(10); break; case ',': e.preventDefault(); e.stopPropagation(); seekBy(-frameTime); break; case '.': e.preventDefault(); e.stopPropagation(); seekBy(frameTime); break; } // If we are in fullscreen mode, we don't want any hotkeys // interacting with the UI that's not visible if (fullscreen) { e.preventDefault(); e.stopPropagation(); if (e.key === 'Escape') { exitFullscreen(); } } }; const togglePlay = (e?: React.MouseEvent) => { e?.stopPropagation(); setPaused(!paused); if (paused) { video.current?.play(); } else { video.current?.pause(); } }; const toggleFullscreen = () => { if (isFullscreen()) { exitFullscreen(); } else if (player.current) { requestFullscreen(player.current); } }; const handleResize = useCallback(debounce(() => { setDimensions(); }, 250, { edges: ['trailing'], }), [player.current, cacheWidth]); const handleScroll = useCallback(throttle(() => { if (!video.current) return; const { top, height } = video.current.getBoundingClientRect(); const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0); if (!paused && !inView) { setPaused(true); video.current.pause(); } }, 150, { edges: ['trailing'] }), [video.current, paused]); const handleFullscreenChange = useCallback(() => { setFullscreen(isFullscreen()); }, []); const handleSeekEnter = () => { setSeekHovered(true); }; const handleSeekLeave = () => { setSeekHovered(false); }; const handleVolumeEnter = (e: React.MouseEvent) => { if (isMobile) return; setVolumeHovered(true); }; const handleVolumeLeave = (e: React.MouseEvent) => { if (isMobile) return; setVolumeHovered(false); }; const handleClickStart = () => { setHovered(true); if (timeoutRef.current) { clearTimeout(timeoutRef.current); timeoutRef.current = null; } timeoutRef.current = setTimeout(() => { setHovered(false); }, 2 * 1000); }; const handleOnMouseMove = () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } handleClickStart(); }; const toggleMute = () => { if (video.current) { const muted = !video.current.muted; setMuted(muted); video.current.muted = muted; if (muted) { setPreVolume(video.current.volume); video.current.volume = 0; setVolume(0); } else { video.current.volume = preVolume; setVolume(preVolume); } } }; const handleLoadedData = () => { if (video.current && startTime) { video.current.currentTime = startTime; video.current.play(); } }; const handleProgress = () => { if (video.current && video.current.buffered.length > 0) { setBuffer(video.current.buffered.end(0) / video.current.duration * 100); } }; const handleVolumeChange = () => { if (video.current) { setVolume(video.current.volume); setMuted(video.current.muted); } }; const handleTogglePlay = () => { if (!isMobile || paused || hovered) togglePlay(); }; const progress = (currentTime / duration) * 100; const playerStyle: React.CSSProperties = {}; const startTimeout = () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => { setHovered(false); timeoutRef.current = null; }, 1000); }; if (inline && containerWidth) { width = containerWidth; const minSize = containerWidth / (16 / 9); if (isPanoramic(aspectRatio)) { height = Math.max(Math.floor(containerWidth / maximumAspectRatio), minSize); } else if (isPortrait(aspectRatio)) { height = Math.max(Math.floor(containerWidth / minimumAspectRatio), minSize); } else { height = Math.floor(containerWidth / aspectRatio); } playerStyle.height = height || DEFAULT_HEIGHT; } useEffect(() => { document.addEventListener('fullscreenchange', handleFullscreenChange, true); document.addEventListener('webkitfullscreenchange', handleFullscreenChange, true); document.addEventListener('mozfullscreenchange', handleFullscreenChange, true); document.addEventListener('MSFullscreenChange', handleFullscreenChange, true); window.addEventListener('scroll', handleScroll); window.addEventListener('resize', handleResize, { passive: true }); return () => { window.removeEventListener('scroll', handleScroll); window.removeEventListener('resize', handleResize); document.removeEventListener('fullscreenchange', handleFullscreenChange, true); document.removeEventListener('webkitfullscreenchange', handleFullscreenChange, true); document.removeEventListener('mozfullscreenchange', handleFullscreenChange, true); document.removeEventListener('MSFullscreenChange', handleFullscreenChange, true); }; }, []); useEffect(() => { if (!visible) { video.current?.pause(); } }, [visible]); return (
{!fullscreen && ( )}