Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): share artifact video playback and cleanup

David Led5af0d2e8194
diff --git a/site/src/cut/components/share/HlsVideo.tsx b/site/src/cut/components/ArtifactVideo.tsx
similarity index 66%
rename from site/src/cut/components/share/HlsVideo.tsx
rename to site/src/cut/components/ArtifactVideo.tsx
index e97316cc..8352b13f 100644
--- a/site/src/cut/components/share/HlsVideo.tsx
+++ b/site/src/cut/components/ArtifactVideo.tsx
@@ -1,37 +1,26 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState, type RefObject, type VideoHTMLAttributes } from "react";
/** How many fatal errors playback may recover from before it is treated as
* broken. A real network blip resolves in one or two; anything past this is a
* permanent failure wearing a transient error's clothes. */
const MAX_RECOVERIES = 3;
-/**
- * A `<video>` playing an HLS master playlist.
- *
- * Safari and iOS play HLS natively, so they get the URL directly and hls.js
- * never loads — attaching it there would replace a well-tuned platform player
- * with a worse one. Everywhere else (Chrome and Android have no native HLS)
- * hls.js is imported on demand, so its weight lands only on the browsers that
- * need it and never on the initial page.
- */
-export function HlsVideo({
- src,
- poster,
- className,
- onError,
- onPlaying,
-}: {
+export type ArtifactVideoProps = Omit<VideoHTMLAttributes<HTMLVideoElement>, "src" | "onError"> & {
src: string;
- poster?: string;
- className?: string;
+ format: "hls" | "file";
+ videoRef?: RefObject<HTMLVideoElement | null>;
onError?: () => void;
- /** Fires once playback is actually running, so a caller can avoid replacing
- * a video someone is watching. */
- onPlaying?: () => void;
-}) {
- const ref = useRef<HTMLVideoElement>(null);
+ active?: boolean;
+};
+
+/** Playback owns its decoder, buffers and teardown independently of an editor. */
+export function ArtifactVideo({
+ src, format, videoRef, onError, active = true, controls = true, autoPlay = false, preload = "metadata", ...props
+}: ArtifactVideoProps) {
+ const ownRef = useRef<HTMLVideoElement>(null);
+ const ref = videoRef ?? ownRef;
const [failed, setFailed] = useState(false);
// Held in a ref so the effect below does not depend on it. A caller passing an
// inline arrow — the normal way to write this — would otherwise hand over a
@@ -43,7 +32,7 @@ export function HlsVideo({
useEffect(() => {
const video = ref.current;
- if (!video) return;
+ if (!video || !active) return;
setFailed(false);
let live = true;
@@ -56,7 +45,7 @@ export function HlsVideo({
// Native HLS. Checked before loading the library so Safari/iOS take this
// path — canPlayType answers for the platform player, not for hls.js.
- if (video.canPlayType("application/vnd.apple.mpegurl")) {
+ if (format === "file" || video.canPlayType("application/vnd.apple.mpegurl")) {
// The platform player reports through the element, and this is the only
// channel it has: without it an expired token 403s every segment, the
// video stalls on a black frame, and nothing upstream ever learns that
@@ -66,6 +55,9 @@ export function HlsVideo({
return () => {
live = false;
video.removeEventListener("error", giveUp);
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
};
}
@@ -107,24 +99,42 @@ export function HlsVideo({
hls.loadSource(src);
hls.attachMedia(ref.current);
destroy = () => hls.destroy();
- });
+ }).catch(giveUp);
return () => {
live = false;
destroy?.();
+ video.pause();
+ video.removeAttribute("src");
+ video.load();
+ };
+ }, [src, format, ref, active]);
+
+ useEffect(() => {
+ const video = ref.current;
+ if (!video) return;
+ if (!active) video.pause();
+ const hide = () => { if (document.hidden) video.pause(); };
+ const observer = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => {
+ if (entries.some((entry) => !entry.isIntersecting)) video.pause();
+ });
+ observer?.observe(video);
+ document.addEventListener("visibilitychange", hide);
+ return () => {
+ observer?.disconnect();
+ document.removeEventListener("visibilitychange", hide);
};
- }, [src]);
+ }, [active, ref]);
return (
<video
+ {...props}
ref={ref}
- poster={poster}
- controls
+ controls={controls}
playsInline
- preload="metadata"
- className={className}
- onPlaying={onPlaying}
- aria-label={failed ? "Video unavailable" : undefined}
+ autoPlay={active && autoPlay}
+ preload={preload}
+ aria-label={failed ? "Video unavailable" : props["aria-label"]}
/>
);
}
diff --git a/site/src/cut/components/PlatformPreview.tsx b/site/src/cut/components/PlatformPreview.tsx
index 3f4e9d59..a7a53889 100644
--- a/site/src/cut/components/PlatformPreview.tsx
+++ b/site/src/cut/components/PlatformPreview.tsx
@@ -1,5 +1,7 @@
"use client";
+import { ArtifactVideo } from "./ArtifactVideo";
+
import { useEffect, useRef, useState } from "react";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { exportFileUrl } from "@/cut/lib/exportClient";
@@ -143,8 +145,10 @@ export function PlatformPreviewDialog({
: undefined
}
>
- <video
- ref={videoRef}
+ <ArtifactVideo
+ format="file"
+ controls={false}
+ videoRef={videoRef}
crossOrigin={MEDIA_CORS}
src={url}
className="absolute inset-0 size-full object-cover"
diff --git a/site/src/cut/components/share/MobileShare.tsx b/site/src/cut/components/share/MobileShare.tsx
index 9ac88f8e..18be7d87 100644
--- a/site/src/cut/components/share/MobileShare.tsx
+++ b/site/src/cut/components/share/MobileShare.tsx
@@ -5,7 +5,7 @@ import { Clapperboard, FileText, Images, Loader2, MessageSquare, Captions } from
import { Button } from "@/components/ui/button";
import type { ProjectDoc, ShareFeatures, StoredAsset } from "@/cut/lib/types";
import { BottomSheet } from "./BottomSheet";
-import { HlsVideo } from "./HlsVideo";
+import { ArtifactVideo } from "../ArtifactVideo";
/**
* The share as a phone should see it: the cut playing as one video, with the
@@ -41,17 +41,18 @@ const MAX_STREAM_POLL_MS = 60_000;
* on this visit and a reload is the honest way to find out otherwise. */
const MAX_STREAM_POLLS = 12;
-export function MobileShare({
- token,
- projectId,
- name,
- features,
-}: {
+type MobileShareProps = {
token: string;
projectId: string;
name: string;
features: ShareFeatures;
-}) {
+};
+
+export function MobileShare(props: MobileShareProps) {
+ return <MobileShareContent key={`${props.token}:${props.projectId}`} {...props} />;
+}
+
+function MobileShareContent({ token, projectId, name, features }: MobileShareProps) {
const api = useCallback(
(path: string) => `/api/cut-shared/${encodeURIComponent(token)}${path}`,
[token]
@@ -169,7 +170,8 @@ export function MobileShare({
<div className="flex min-h-0 flex-1 items-center justify-center bg-black">
{stream.state === "ready" ? (
- <HlsVideo
+ <ArtifactVideo
+ format="hls"
src={stream.url}
className="max-h-full max-w-full"
onError={onStreamError}
@@ -180,7 +182,8 @@ export function MobileShare({
// the path directly. It 404s on its own when the project has no proxy
// — or when the share hides Subtitles and this render has them burned
// in — which is the case that shows "preparing".
- <video
+ <ArtifactVideo
+ format="file"
src={stream.url}
controls
playsInline