From 1fe6a2a50d6df42123d97ab7d767eee731d461bb Mon Sep 17 00:00:00 2001 From: Martti Malmi Date: Wed, 13 Dec 2023 11:37:14 +0200 Subject: [PATCH] pause / play vid with useInView --- .../app/src/Element/Embed/MediaElement.tsx | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/packages/app/src/Element/Embed/MediaElement.tsx b/packages/app/src/Element/Embed/MediaElement.tsx index 71a5e873..84eb0753 100644 --- a/packages/app/src/Element/Embed/MediaElement.tsx +++ b/packages/app/src/Element/Embed/MediaElement.tsx @@ -1,8 +1,9 @@ import { ProxyImg } from "@/Element/ProxyImg"; import useImgProxy from "@/Hooks/useImgProxy"; import { IMeta } from "@snort/system"; -import React, { CSSProperties, useMemo, useRef } from "react"; +import React, { CSSProperties, useEffect, useMemo, useRef } from "react"; import classNames from "classnames"; +import { useInView } from "react-intersection-observer"; interface MediaElementProps { mime: string; @@ -13,17 +14,30 @@ interface MediaElementProps { export function MediaElement(props: MediaElementProps) { const { proxy } = useImgProxy(); - const ref = useRef(null); + const imageRef = useRef(null); + const { ref: videoContainerRef, inView } = useInView({ threshold: 1 }); + const videoRef = useRef(null); const autoplay = window.innerWidth >= 768; + useEffect(() => { + if (!autoplay || !videoRef.current) { + return; + } + if (inView) { + videoRef.current.play(); + } else { + videoRef.current.pause(); + } + }, [inView]); + const style = useMemo(() => { const style = {} as CSSProperties; - if (props.meta?.height && props.meta.width && ref.current) { - const scale = ref.current.offsetWidth / props.meta.width; + if (props.meta?.height && props.meta.width && imageRef.current) { + const scale = imageRef.current.offsetWidth / props.meta.width; style.height = `${props.meta.height * scale}px`; } return style; - }, [ref.current]); + }, [imageRef.current]); if (props.mime.startsWith("image/")) { return ( @@ -34,7 +48,7 @@ export function MediaElement(props: MediaElementProps) { onClick={props.onMediaClick} className={classNames("max-h-[80vh]", { "md:max-h-80": !props.meta })} style={style} - ref={ref} + ref={imageRef} /> ); @@ -42,9 +56,9 @@ export function MediaElement(props: MediaElementProps) { return