Skip to content

Open source CapCut alternative.

TypeScript

perf(site): media previews load only once scrolled into view

David Leaa74fabb10bd
diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsx
index 03dbf66b..1aaaf274 100644
--- a/site/src/cut/components/AssetRefs.tsx
+++ b/site/src/cut/components/AssetRefs.tsx
@@ -9,6 +9,7 @@ import {
type AssetRef,
} from "@/cut/lib/assetRef";
import { useRefFor, useRefCandidates } from "@/cut/lib/assetRef";
+import { useInView } from "@/cut/hooks/useInView";
import { revealRef } from "@/cut/lib/refReveal";
import { formatTime } from "@/cut/lib/time";
import { useEditor } from "@/cut/lib/store";
@@ -32,8 +33,11 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri
? s.assets.find((a) => a.id === item.id)?.peaks
: undefined
);
+ // Chips render for every past message; the media loads only once on screen.
+ const [thumbRef, seen] = useInView<HTMLDivElement>();
return (
<div
+ ref={thumbRef}
className={cn(
"relative shrink-0 overflow-hidden rounded-lg border border-border bg-muted",
className
@@ -41,15 +45,17 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri
>
{item.kind === "video" ? (
<video
- src={`${item.url}#t=0.1`}
+ src={seen ? `${item.url}#t=0.1` : undefined}
preload="metadata"
muted
playsInline
className="size-full object-cover"
/>
) : item.kind === "image" ? (
- // eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images
- <img src={item.url} alt={item.name} loading="lazy" className="size-full object-cover" />
+ seen ? (
+ // eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images
+ <img src={item.url} alt={item.name} loading="lazy" className="size-full object-cover" />
+ ) : null
) : item.kind === "text" ? (
<div className="grid size-full place-items-center bg-gradient-to-br from-slate-100 to-slate-50 text-slate-500">
<FileText className="size-4.5" />
diff --git a/site/src/cut/components/ChatAssets.tsx b/site/src/cut/components/ChatAssets.tsx
index 831cb815..7570220c 100644
--- a/site/src/cut/components/ChatAssets.tsx
+++ b/site/src/cut/components/ChatAssets.tsx
@@ -14,6 +14,7 @@ import {
type AssetRefKind,
} from "@/cut/lib/assetRef";
import { useElapsed } from "@/cut/hooks/useElapsed";
+import { useInView } from "@/cut/hooks/useInView";
import { useGenerate } from "@/cut/lib/generate";
import { lightboxItemFromRef, useLightbox } from "@/cut/lib/lightbox";
import { usePreviewAudio } from "@/cut/lib/previewAudio";
@@ -116,7 +117,7 @@ export function ChatVideoJobCard({ jobId }: { jobId: string }) {
{elapsed && <span className="tabular-nums text-muted-foreground/80">{elapsed}</span>}
</>
) : (
- <HostedErrorText error={job.error} />
+ <HostedErrorText error={job.error} link={false} />
)}
</div>
</div>
@@ -198,12 +199,16 @@ const scrimButton = scrimIconButton;
* sized so portrait and landscape both sit comfortably in the chat column. */
function MediaCard({ item, asset }: ChatCardProps) {
const videoRef = useRef<HTMLVideoElement>(null);
+ // Chat scrollback holds every card ever made; media loads only once the
+ // card actually scrolls into view.
+ const [tileRef, seen] = useInView<HTMLDivElement>();
const ref = liveRef(item, asset);
const ratio =
asset?.width && asset?.height ? asset.width / asset.height : item.kind === "image" ? 1 : 16 / 10;
const width = Math.round(Math.min(248, Math.max(132, 210 * ratio)));
return (
<div
+ ref={tileRef}
className="ai-chat-asset group relative shrink-0 cursor-grab overflow-hidden rounded-xl border border-border bg-muted transition-colors hover:border-input"
style={{ width, aspectRatio: ratio }}
title={`${ref.name} — double-click to expand · drag to the timeline`}
@@ -224,17 +229,17 @@ function MediaCard({ item, asset }: ChatCardProps) {
// Native first frame as the poster — full-resolution, no blurry thumb.
<video
ref={videoRef}
- src={`${ref.url}#t=0.1`}
+ src={seen ? `${ref.url}#t=0.1` : undefined}
preload="metadata"
muted
loop
playsInline
className="size-full object-cover"
/>
- ) : (
+ ) : seen ? (
// eslint-disable-next-line @next/next/no-img-element -- engine/static file, not Next-optimizable
<img src={ref.url} alt={ref.name} loading="lazy" className="size-full object-cover" />
- )}
+ ) : null}
{item.kind === "video" && ref.duration !== undefined && (
<span className="absolute right-1.5 bottom-1.5 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9px] text-white tabular-nums">
{formatTime(ref.duration)}
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index e89bedda..6f09fbfd 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -13,6 +13,7 @@ import {
useAssetDrop,
} from "@/cut/lib/assetRef";
import { useElapsed } from "@/cut/hooks/useElapsed";
+import { useInView } from "@/cut/hooks/useInView";
import { genPulseOverlay, useGenPulse } from "@/cut/lib/genNotify";
import { signInUrl, useGenerate, useSignedIn, type GenerateJob } from "@/cut/lib/generate";
import { useLightbox } from "@/cut/lib/lightbox";
@@ -290,6 +291,8 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
const elapsed = useElapsed(job.status === "running" ? job.startedAt : null);
const tileRef = useRef<HTMLDivElement>(null);
const videoRef = useRef<HTMLVideoElement>(null);
+ // Render history keeps every settled job; a preview loads only on screen.
+ const [inViewRef, seen] = useInView<HTMLButtonElement>();
if (job.status !== "done" || !asset) {
return (
@@ -359,6 +362,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
}}
>
<button
+ ref={inViewRef}
className="block w-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
draggable
onDragStart={(e) => {
@@ -379,7 +383,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
loop
playsInline
preload="metadata"
- src={`${asset.url}#t=0.1`}
+ src={seen ? `${asset.url}#t=0.1` : undefined}
className="aspect-[16/10] w-full bg-black object-cover"
/>
</button>
diff --git a/site/src/cut/hooks/useInView.ts b/site/src/cut/hooks/useInView.ts
new file mode 100644
index 00000000..874185e0
--- /dev/null
+++ b/site/src/cut/hooks/useInView.ts
@@ -0,0 +1,29 @@
+"use client";
+
+import { useEffect, useRef, useState, type RefObject } from "react";
+
+/**
+ * Whether the element has been scrolled into view at least once. Media
+ * previews mount wherever history renders — chat scrollback, attachment
+ * chips, render history — so their `src` gates on this: a reload fetches only
+ * what's actually on screen instead of every file the project ever made.
+ */
+export function useInView<T extends HTMLElement>(): [RefObject<T | null>, boolean] {
+ const ref = useRef<T>(null);
+ const [seen, setSeen] = useState(false);
+ useEffect(() => {
+ if (seen) return;
+ const el = ref.current;
+ if (!el) return;
+ const io = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((e) => e.isIntersecting)) setSeen(true);
+ },
+ // Start loading just before the tile scrolls in, so it's ready on arrival.
+ { rootMargin: "150px" }
+ );
+ io.observe(el);
+ return () => io.disconnect();
+ }, [seen]);
+ return [ref, seen];
+}