Skip to content

Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.

feat: enhance video playback handling with eager loading and Sentry integration (#267)

Vlad Sazonaue79e86007e66
diff --git a/e2e/about.test.ts b/e2e/about.test.ts
index 211306f..ec438b3 100644
--- a/e2e/about.test.ts
+++ b/e2e/about.test.ts
@@ -118,7 +118,7 @@ test.describe("About page", () => {
await expect(video).toHaveAttribute("poster", VIDEO_DEMO_FALLBACK_IMG);
await expect(video).toHaveAttribute("loop");
await expect(video).toHaveAttribute("playsinline");
- await expect(video).toHaveAttribute("preload", "none");
+ await expect(video).toHaveAttribute("preload", "metadata");
// Check Features section
const featuresSection = main.locator("#features").filter({ visible: true });
diff --git a/src/app/[locale]/about/components/hero-demo-video.tsx b/src/app/[locale]/about/components/hero-demo-video.tsx
index 6b83cf1..7fb7f57 100644
--- a/src/app/[locale]/about/components/hero-demo-video.tsx
+++ b/src/app/[locale]/about/components/hero-demo-video.tsx
@@ -46,6 +46,9 @@ export function HeroDemoVideo() {
// the browser frame is wide and short of the fold on a phone, where half of it is
// never on screen at once; a sliver is enough to mean the demo is being looked at
inViewThreshold={0.15}
+ // this one is on screen at load, so waiting for the observer only delays the
+ // fetch and leaves iOS a `<video>` with no resource to autoplay
+ eager
/>
);
}
diff --git a/src/components/__tests__/video.test.tsx b/src/components/__tests__/video.test.tsx
index 897b057..6fc5ba3 100644
--- a/src/components/__tests__/video.test.tsx
+++ b/src/components/__tests__/video.test.tsx
@@ -9,6 +9,14 @@ import {
} from "react-intersection-observer/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+vi.mock("@sentry/nextjs", () => {
+ return {
+ captureException: vi.fn(),
+ };
+});
+
+import * as Sentry from "@sentry/nextjs";
+
import { AutoPlayVideo } from "../video";
/**
@@ -44,6 +52,10 @@ beforeEach(() => {
vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {
return undefined;
});
+
+ // the module factory above hands back the same `vi.fn` to every test, and
+ // `restoreAllMocks` only undoes spies
+ vi.mocked(Sentry.captureException).mockClear();
});
afterEach(() => {
@@ -90,6 +102,27 @@ describe("AutoPlayVideo", () => {
expect(container.querySelectorAll("source")).toHaveLength(0);
});
+ it("holds the url back and preloads nothing until the video is in view", () => {
+ render(<AutoPlayVideo src={SRC} posterImg={POSTER} testId="demo" />);
+
+ const video = screen.getByTestId<HTMLVideoElement>("demo");
+
+ expect(video.getAttribute("src")).toBeNull();
+ expect(video.getAttribute("preload")).toBe("none");
+ });
+
+ it("carries the url from the first render when it is eager", () => {
+ render(<AutoPlayVideo src={SRC} posterImg={POSTER} testId="demo" eager />);
+
+ const video = screen.getByTestId<HTMLVideoElement>("demo");
+
+ // an element that is on screen at load has to have a resource and be loading it
+ // before WebKit will start it on its own, and the media fragment is one more seek
+ // to serve before playback — the poster already covers the frame it was there for
+ expect(video.getAttribute("src")).toBe(SRC);
+ expect(video.getAttribute("preload")).toBe("metadata");
+ });
+
it("plays without a play button when the browser allows it", () => {
renderVideo();
@@ -165,6 +198,79 @@ describe("AutoPlayVideo", () => {
expect(play).not.toHaveBeenCalled();
});
+ it("reports a refusal with the element state that explains it", async () => {
+ play.mockRejectedValue(NOT_ALLOWED);
+
+ renderVideo();
+
+ await screen.findByTestId("demo-play-button");
+
+ expect(Sentry.captureException).toHaveBeenCalledTimes(1);
+
+ const [error, context] = vi.mocked(Sentry.captureException).mock
+ .calls[0] as [unknown, { level: string; tags: Record<string, unknown> }];
+
+ expect(error).toBe(NOT_ALLOWED);
+ // the visitor's own iOS setting, not a fault of ours — the play button handles it
+ expect(context.level).toBe("warning");
+ expect(context.tags.video_play_trigger).toBe("autoplay");
+ expect(context.tags.video_error_name).toBe("NotAllowedError");
+ });
+
+ it("says nothing about a play that was only interrupted", async () => {
+ play.mockRejectedValue(new DOMException("interrupted", "AbortError"));
+
+ renderVideo();
+
+ await act(async () => {
+ return undefined;
+ });
+
+ // one per scroll past a video; Sentry would be all of them and nothing else
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+ });
+
+ it("reports a refusal that follows a real tap as an error", async () => {
+ play.mockRejectedValue(NOT_ALLOWED);
+
+ renderVideo();
+
+ const button = await screen.findByTestId("demo-play-button");
+
+ await act(async () => {
+ return button.click();
+ });
+
+ // the page's own attempt is reported once and the tap separately: a browser that
+ // turns down a gesture is a different problem from one honouring a setting
+ expect(Sentry.captureException).toHaveBeenCalledTimes(2);
+
+ const [, context] = vi.mocked(Sentry.captureException).mock.calls[1] as [
+ unknown,
+ { level: string; tags: Record<string, unknown> },
+ ];
+
+ expect(context.level).toBe("error");
+ expect(context.tags.video_play_trigger).toBe("user-gesture");
+ });
+
+ it("reports each trigger once however many times the retry fires", async () => {
+ play.mockRejectedValue(NOT_ALLOWED);
+
+ renderVideo();
+
+ await screen.findByTestId("demo-play-button");
+
+ const video = screen.getByTestId<HTMLVideoElement>("demo");
+
+ await act(async () => {
+ video.dispatchEvent(new Event("canplay"));
+ video.dispatchEvent(new Event("canplay"));
+ });
+
+ expect(Sentry.captureException).toHaveBeenCalledTimes(1);
+ });
+
it("starts the video and drops the button when it is pressed", async () => {
play.mockRejectedValue(NOT_ALLOWED);
diff --git a/src/components/video.tsx b/src/components/video.tsx
index cc5471e..da0a038 100644
--- a/src/components/video.tsx
+++ b/src/components/video.tsx
@@ -1,11 +1,26 @@
"use client";
+import * as Sentry from "@sentry/nextjs";
import { Play } from "lucide-react";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import { useInView } from "react-intersection-observer";
import { cn } from "@/lib/utils";
+/**
+ * What asked for playback. A refusal of the page's own attempt is usually an iOS
+ * setting the visitor chose; a refusal right after they tapped the play button is not,
+ * so the two are worth telling apart in Sentry.
+ */
+type PlayTrigger = "autoplay" | "user-gesture";
+
+interface ReportPlayFailureArgs {
+ /** Whatever `play()` rejected with. */
+ error: unknown;
+ /** What asked for the playback that was turned down. */
+ trigger: PlayTrigger;
+}
+
interface SharedVideoProps extends React.ComponentPropsWithRef<"div"> {
src: string;
posterImg?: string;
@@ -31,6 +46,19 @@ interface AutoPlayVideoProps extends SharedVideoProps {
* @default 0.5
*/
inViewThreshold?: number;
+ /**
+ * Put the URL on the element from the first render instead of waiting for the
+ * IntersectionObserver, and let the browser fetch metadata for it.
+ *
+ * For a video that is on screen at load — the hero — the lazy path buys nothing and
+ * costs the only start that is reliable on iOS: WebKit's own autoplay-when-visible,
+ * which needs an element that has a resource and has begun loading it. Everything
+ * below the fold stays lazy; six demo clips fetching metadata during the marketing
+ * page's load is not free.
+ *
+ * @default false
+ */
+ eager?: boolean;
}
/**
@@ -57,6 +85,7 @@ export function AutoPlayVideo({
renderReducedMotionFallback,
playButtonLabel,
inViewThreshold = 0.5,
+ eager = false,
testId = "",
...props
}: AutoPlayVideoProps) {
@@ -64,12 +93,19 @@ export function AutoPlayVideo({
const playLabel = playButtonLabel || description || "Play video";
const videoRef = useRef<HTMLVideoElement | null>(null);
- const [srcAdded, setSrcAdded] = useState(false);
+ const [lazySrcAdded, setLazySrcAdded] = useState(false);
+ const srcAdded = eager || lazySrcAdded;
// iOS refuses to start a video on its own in Low Power Mode, in Low Data Mode, and
// with "Auto-Play Video Previews" switched off under Accessibility > Motion. None of
// that is ours to override, so a refusal turns the poster into a play button rather
// than leaving a still frame that looks broken.
const [autoplayRefused, setAutoplayRefused] = useState(false);
+ // iOS turns down every attempt for as long as the setting behind it is on, and the
+ // `canplay` retry below means several attempts per mount. The first one carries the
+ // whole signal; the rest would only be volume. Kept per trigger rather than per
+ // element so a refusal that follows the visitor's own tap — the interesting one — is
+ // still reported after the page's attempt has already been turned down.
+ const reportedPlayTriggersRef = useRef(new Set<PlayTrigger>());
const descriptionID = useId();
const { ref, inView } = useInView({
@@ -97,7 +133,45 @@ export function AutoPlayVideo({
videoRef.current?.pause();
}
- function playVideo() {
+ /**
+ * Send a refusal to Sentry with the element state that explains it.
+ *
+ * The state is the point: `NotAllowedError` on its own says nothing about *why*, and
+ * the readiness fields separate "iOS will not start videos on this phone" from
+ * "there was nothing loaded to start".
+ */
+ function reportPlayFailure({ error, trigger }: ReportPlayFailureArgs) {
+ if (reportedPlayTriggersRef.current.has(trigger)) return;
+ reportedPlayTriggersRef.current.add(trigger);
+
+ const video = videoRef.current;
+
+ Sentry.captureException(error, {
+ // a refusal of our own attempt is usually Low Power Mode, Low Data Mode or
+ // "Auto-Play Video Previews" off — the visitor's setting, not our bug, and the
+ // play button already handles it. One that follows their tap is a real fault.
+ level: trigger === "user-gesture" ? "error" : "warning",
+ tags: {
+ video_play_trigger: trigger,
+ video_eager: eager,
+ video_error_name:
+ error instanceof DOMException ? error.name : "unknown",
+ },
+ extra: {
+ src,
+ eager,
+ // 0 here means nothing was loaded, which is a different bug from a refusal
+ readyState: video?.readyState,
+ networkState: video?.networkState,
+ currentSrc: video?.currentSrc,
+ // React only ever sets the property; WebKit reads the attribute
+ muted: video?.muted,
+ hasMutedAttribute: video?.hasAttribute("muted"),
+ },
+ });
+ }
+
+ function playVideo(trigger: PlayTrigger = "autoplay") {
const video = videoRef.current;
if (!video || paused) return;
@@ -113,6 +187,7 @@ export function AutoPlayVideo({
// `AbortError` is this attempt being cut short — by the load it just kicked
// off, or by the pause that follows scrolling away — not the browser refusing.
// The `canplay` handler below asks again once there is something to play.
+ // Routine, and on every scroll past a video, so it is not reported either.
if (error instanceof DOMException && error.name === "AbortError")
return;
@@ -121,15 +196,19 @@ export function AutoPlayVideo({
// playing video is worse than no button at all
if (!video.paused) return;
+ reportPlayFailure({ error, trigger });
+
setAutoplayRefused(true);
},
);
}
// Lazy-load video source when component enters viewport
- // This improves initial page load performance by deferring video loading
+ // This improves initial page load performance by deferring video loading.
+ // Left unconditional: an `eager` video already has its URL and ignores `lazySrc`, so
+ // the flag flipping underneath it changes nothing that is rendered.
useEffect(() => {
- if (inView) setSrcAdded(true);
+ if (inView) setLazySrcAdded(true);
}, [inView]);
// Control video playback based on viewport visibility and paused state
@@ -146,9 +225,9 @@ export function AutoPlayVideo({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [inView, srcAdded, paused, prefersReducedMotion]);
- // `preload="none"` means the first `play()` above usually lands on an element with
- // nothing decoded yet. Asking again on `canplay` is what turns that into playback
- // without guessing at a delay, and it covers a stall mid-scroll for free.
+ // On the lazy path the first `play()` above lands on an element with nothing decoded
+ // yet. Asking again on `canplay` is what turns that into playback without guessing at
+ // a delay, and it covers a stall mid-scroll — on either path — for free.
useEffect(() => {
const video = videoRef.current;
if (!video) return;
@@ -171,7 +250,7 @@ export function AutoPlayVideo({
if (!video) return;
function handleClick() {
- if (video?.paused) playVideo();
+ if (video?.paused) playVideo("user-gesture");
else video?.pause();
}
@@ -182,6 +261,8 @@ export function AutoPlayVideo({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ const lazySrc = lazySrcAdded ? `${src}#t=0.001` : undefined;
+
return (
<div
ref={ref}
@@ -206,15 +287,19 @@ export function AutoPlayVideo({
muted
loop={loop}
playsInline
- preload="none"
+ preload={eager ? "metadata" : "none"}
poster={posterImg}
// The URL goes on the element rather than into a `<source>` child, because
- // this one arrives after the element is already in the DOM: a media element
- // that has finished picking a resource does not go back and look at a
- // `<source>` appended afterwards, while assigning `src` restarts that pick
- // by itself. `#t=0.001` keeps iOS on the first frame instead of a blank
- // element while the poster loads.
- src={srcAdded ? `${src}#t=0.001` : undefined}
+ // on the lazy path it arrives after the element is already in the DOM: a
+ // media element that has finished picking a resource does not go back and
+ // look at a `<source>` appended afterwards, while assigning `src` restarts
+ // that pick by itself.
+ //
+ // The lazy URL carries `#t=0.001` to keep iOS on the first frame instead of
+ // a blank element while the poster loads. The eager one does not: the
+ // fragment is a seek the element has to serve before it can play, which is
+ // exactly the extra piece of start-up state the eager path exists to remove.
+ src={eager ? src : lazySrc}
data-testid={testId}
/>
{autoplayRefused ? (
@@ -222,7 +307,7 @@ export function AutoPlayVideo({
type="button"
aria-label={playLabel}
onClick={() => {
- return playVideo();
+ return playVideo("user-gesture");
}}
className="absolute inset-0 flex items-center justify-center backdrop-blur-[1px]"
data-testid={testId ? `${testId}-play-button` : undefined}