UNPKG

@revenuecat/purchases-ui-js

Version:

Web components for Paywalls. Powered by RevenueCat

79 lines (78 loc) 2.8 kB
/** * Decorative / background `<video>` autoplay helpers (Safari, WebKit, cold load). * `Video.svelte` uses `applyInlineVideoPlaybackFlags`, `subscribeDecorativeVideoAutoplayAttempts`, * and its own richer `play().catch(...)` handling. */ /** Sets `muted` and `playsInline` for autoplay-heavy inline video. */ export function applyInlineVideoPlaybackFlags(el, options) { el.muted = options.preferMuted || options.mutedPlaybackOverride; el.playsInline = true; } /** * One programmatic `play()`; on rejection while unmuted, force muted playback and retry once. * Honors `cancelled()` and ignores detached elements before mutating reactive state. */ export function tryDecorativeAutoplayWithMuteFallback(el, context) { const { cancelled, preferMuted, getMutedOverride, setMutedOverride } = context; if (cancelled() || !el.paused) return; applyInlineVideoPlaybackFlags(el, { preferMuted, mutedPlaybackOverride: getMutedOverride(), }); if (el.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) return; const playPromise = el.play(); if (playPromise === undefined) return; playPromise.catch(() => { if (cancelled() || !el.isConnected) return; if (!preferMuted && !getMutedOverride()) { setMutedOverride(true); applyInlineVideoPlaybackFlags(el, { preferMuted, mutedPlaybackOverride: true, }); void el.play().catch(() => { }); } }); } /** * Registers `loadeddata` / `canplay` (when needed), microtasks, rAF, and `window` `load` * retries for cold-start autoplay scheduling. */ export function subscribeDecorativeVideoAutoplayAttempts(el, tryPlay, isCancelled) { const guardedTryPlay = () => { if (!isCancelled()) tryPlay(); }; const onReady = () => guardedTryPlay(); if (el.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) { el.addEventListener("loadeddata", onReady); el.addEventListener("canplay", onReady); } else { queueMicrotask(guardedTryPlay); } queueMicrotask(guardedTryPlay); requestAnimationFrame(() => { guardedTryPlay(); }); const onWindowLoad = () => guardedTryPlay(); if (typeof document !== "undefined" && typeof window !== "undefined") { if (document.readyState === "complete") { queueMicrotask(guardedTryPlay); } else { window.addEventListener("load", onWindowLoad); } } return () => { el.removeEventListener("loadeddata", onReady); el.removeEventListener("canplay", onReady); if (typeof window !== "undefined") { window.removeEventListener("load", onWindowLoad); } }; }