UNPKG

@wethegit/react-autoplay-video

Version:

Viewport-aware auto-playing video component for use in React projects.

89 lines (88 loc) 2.52 kB
import { jsx as c, jsxs as x, Fragment as A } from "react/jsx-runtime"; import { createContext as w, useState as _, useMemo as V, useCallback as N, useEffect as h, useId as j, useRef as C } from "react"; function R(e = 0, i = !1, t = !1) { const [v, s] = _(!1), [n, y] = _(), d = V( () => typeof e == "number" ? { threshold: e } : e, [e] ), l = N( ([u], p) => { const r = u.isIntersecting || t && u.boundingClientRect.top < 0; s(r), i && r && p.unobserve(u.target); }, [i, t] ), o = V(() => { if (typeof IntersectionObserver == "function") return new IntersectionObserver(l, d); }, [d, l]); return h(() => { if (!(!n || !o)) return o.observe(n), () => { o && o.unobserve(n); }; }, [o, n]), [y, v, n]; } w({}); function E(e = []) { if (!e || !Array.isArray(e) || !e.length) return; const i = []; return e.forEach((t) => { typeof t == "string" && i.push(t); }), i.flat().join(" "); } const f = { "autoplay-video-util-visually-hidden": "autoplay-video-module__autoplay-video-util-visually-hidden__8V1fsw", "autoplay-video": "autoplay-video-module__autoplay-video__MGv7xR", "autoplay-video__media": "autoplay-video-module__autoplay-video__media__yVnB8-" }; function B({ className: e, description: i = "", paused: t = !1, posterImg: v, prefersReducedMotion: s = !1, renderReducedMotionFallback: n, src: y, loop: d = !0, ...l }) { const [o, u] = _(!1), [p, r] = R(0), b = j(), m = C(null), I = () => { const a = m?.current; a && a.pause(); }, g = () => { const a = m?.current; !a || t || a.play(); }; return h(() => { r && u(!0); }, [r]), h(() => { o && (t ? I() : r && !t ? g() : I()); }, [r, o, t, s]), /* @__PURE__ */ c( "div", { className: E([f["autoplay-video"], e]), ...l, ref: p, children: s && typeof n == "function" ? /* @__PURE__ */ c("div", { className: f["autoplay-video__media"], children: n() }) : /* @__PURE__ */ x(A, { children: [ i && /* @__PURE__ */ c("p", { id: b, className: f["visually-hidden"], children: i }), /* @__PURE__ */ c( "video", { "aria-describedby": b, autoPlay: !0, className: f["autoplay-video__media"], loop: d, muted: !0, playsInline: !0, poster: v, ref: m, src: o ? y : void 0 } ) ] }) } ); } export { B as AutoplayVideo };