Skip to content

Open source CapCut alternative.

TypeScript

fix(site): play hover previews only on real mouse moves

David Lea4bb056ac3a3
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index 5d182ac3..d1b7c8c4 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -4,6 +4,7 @@ import { useEffect, useRef } from "react";
import { Copy, Film, Loader2, Maximize2, Plus, RotateCw, Sparkles, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { useHoverPlay } from "@/cut/hooks/useHoverPlay";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";
import { FOCUS_RING, PICKED_RING, useAssetPick } from "@/cut/lib/assetPick";
@@ -322,7 +323,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
const pulse = useGenPulse("video", job.assetId);
const elapsed = useElapsed(job.status === "running" ? job.startedAt : null);
const tileRef = useRef<HTMLDivElement>(null);
- const videoRef = useRef<HTMLVideoElement>(null);
+ const { ref: videoRef, handlers: hoverPlay } = useHoverPlay();
const { picked, pick } = useAssetPick(job.assetId ?? "");
// Render history keeps every settled job; a preview loads only on screen.
const [inViewRef, seen] = useInView<HTMLButtonElement>();
@@ -386,25 +387,7 @@ function JobRow({ job, handle }: { job: GenerateJob; handle?: string }) {
ref={tileRef}
data-pick-id={job.assetId ?? undefined}
className={cn("gen-job group relative overflow-hidden rounded-lg", picked && PICKED_RING)}
- onMouseEnter={() => {
- const v = videoRef.current;
- if (!v) return;
- // Preview with sound; if the browser blocks unmuted autoplay, fall
- // back to a silent preview.
- v.muted = false;
- void v.play().catch(() => {
- v.muted = true;
- void v.play().catch(() => {});
- });
- }}
- onMouseLeave={() => {
- const v = videoRef.current;
- if (v) {
- v.pause();
- v.currentTime = 0.1;
- v.muted = true;
- }
- }}
+ {...hoverPlay}
>
<button
ref={inViewRef}
diff --git a/site/src/cut/components/MediaCardShell.tsx b/site/src/cut/components/MediaCardShell.tsx
index 527b13a8..bb068dbb 100644
--- a/site/src/cut/components/MediaCardShell.tsx
+++ b/site/src/cut/components/MediaCardShell.tsx
@@ -1,11 +1,12 @@
"use client";
-import { useRef, type ReactNode, type RefObject } from "react";
+import { type ReactNode, type RefObject } from "react";
import type { AssetRef, AssetRefScope } from "@/cut/lib/assetRef";
import { clearAssetDrag } from "@/cut/lib/assetDrag";
import { useLightbox, type LightboxItem } from "@/cut/lib/lightbox";
import { useRevealFlash } from "@/cut/lib/refReveal";
import { useRefCopy } from "@/cut/lib/refCopy";
+import { useHoverPlay } from "@/cut/hooks/useHoverPlay";
/** The card behind every media tile: a Project Files card and a Library card
* draw their own faces inside it, and this is the one place that says what a
@@ -51,7 +52,7 @@ export function MediaCardShell({
}) => ReactNode;
}) {
const { flash, attachReveal } = useRevealFlash(scope, id);
- const videoRef = useRef<HTMLVideoElement>(null);
+ const { ref: videoRef, handlers: hoverPlay } = useHoverPlay(restTime, "silent");
const copyRef = useRefCopy(refs);
return (
<div
@@ -81,17 +82,8 @@ export function MediaCardShell({
}
onDragStart={onDragStart}
onDragEnd={clearAssetDrag}
- onMouseEnter={() => {
- onHover?.();
- void videoRef.current?.play().catch(() => {});
- }}
- onMouseLeave={() => {
- const v = videoRef.current;
- if (v) {
- v.pause();
- v.currentTime = restTime;
- }
- }}
+ onMouseEnter={onHover}
+ {...hoverPlay}
>
{children({ flash, videoRef })}
</div>
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index 2065ee01..3ccc18d4 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -62,6 +62,7 @@ import {
type Residency,
} from "@/cut/lib/queries";
import { useDeleteKey } from "@/cut/hooks/useDeleteKey";
+import { useHoverPlay } from "@/cut/hooks/useHoverPlay";
import { useInView } from "@/cut/hooks/useInView";
import { useTabTitle } from "@/cut/hooks/useTabTitle";
import { useNewProjectTarget } from "@/cut/lib/newProject";
@@ -1290,7 +1291,10 @@ function CardPreview({
residency: Residency;
offline?: boolean;
}) {
- const videoRef = useRef<HTMLVideoElement>(null);
+ // The proxy starts at the edit's first frame; the source starts at the clip's
+ // trim-in, so both posters show what actually plays first.
+ const posterT = p.hasPreview ? 0 : p.previewStart ?? 0.1;
+ const { ref: videoRef, handlers: hoverPlay } = useHoverPlay(posterT, "silent");
const [tileRef, seen] = useInView<HTMLDivElement>();
// The frame this card drew last time, so coming back from a project shows the
// picture at once instead of a grey rectangle while the media loads.
@@ -1355,10 +1359,6 @@ function CardPreview({
);
}
- // The proxy starts at the edit's first frame; the source starts at the clip's
- // trim-in, so both posters show what actually plays first.
- const posterT = p.hasPreview ? 0 : p.previewStart ?? 0.1;
-
// A still-image project with no rendered proxy posters as the image itself.
if (!p.hasPreview && p.previewIsImage) {
return (
@@ -1381,14 +1381,7 @@ function CardPreview({
<div
ref={tileRef}
className="absolute inset-0"
- onMouseEnter={() => void videoRef.current?.play().catch(() => {})}
- onMouseLeave={() => {
- const v = videoRef.current;
- if (v) {
- v.pause();
- v.currentTime = posterT;
- }
- }}
+ {...hoverPlay}
>
{seen && (
<video
diff --git a/site/src/cut/components/StockVideosPanel.tsx b/site/src/cut/components/StockVideosPanel.tsx
index 92b61300..cf0f243a 100644
--- a/site/src/cut/components/StockVideosPanel.tsx
+++ b/site/src/cut/components/StockVideosPanel.tsx
@@ -1,9 +1,10 @@
"use client";
-import { useRef, useState } from "react";
+import { useState } from "react";
import { ChevronRight, Maximize2, Search } from "lucide-react";
import { clearRefDrag, refFromStockVideo, setRefDragData } from "@/cut/lib/assetRef";
import { useRefCopy } from "@/cut/lib/refCopy";
+import { useHoverPlay } from "@/cut/hooks/useHoverPlay";
import { setObjectDragImage } from "@/cut/lib/assetDrag";
import { useLightbox } from "@/cut/lib/lightbox";
import { useRevealEffect, useRevealFlash } from "@/cut/lib/refReveal";
@@ -211,7 +212,7 @@ function Grid({ items }: { items: StockVideo[] }) {
* (footage as an editable prompt, a character as character mode), and it drags
* as a video ref (chat attachment, generation start frame, timeline drop). */
function StockTile({ item }: { item: StockVideo }) {
- const videoRef = useRef<HTMLVideoElement>(null);
+ const { ref: videoRef, handlers: hoverPlay } = useHoverPlay(0);
const { flash, attachReveal } = useRevealFlash("stock", item.id);
const copyRef = useRefCopy(() => [refFromStockVideo(item)]);
return (
@@ -224,25 +225,7 @@ function StockTile({ item }: { item: StockVideo }) {
"group relative overflow-hidden rounded-lg",
flash && PICKED_RING
)}
- onMouseEnter={() => {
- const v = videoRef.current;
- if (!v) return;
- // Preview with sound; if the browser blocks unmuted autoplay, fall
- // back to a silent preview.
- v.muted = false;
- void v.play().catch(() => {
- v.muted = true;
- void v.play().catch(() => {});
- });
- }}
- onMouseLeave={() => {
- const v = videoRef.current;
- if (v) {
- v.pause();
- v.currentTime = 0;
- v.muted = true;
- }
- }}
+ {...hoverPlay}
>
<button
className={cn("block w-full", FOCUS_RING)}
diff --git a/site/src/cut/hooks/useHoverPlay.test.ts b/site/src/cut/hooks/useHoverPlay.test.ts
new file mode 100644
index 00000000..849418dc
--- /dev/null
+++ b/site/src/cut/hooks/useHoverPlay.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from "bun:test";
+
+import { isRealHover } from "./useHoverPlay";
+
+const MOVE = { pointerType: "mouse", movementX: 3, movementY: 0 } as const;
+
+describe("isRealHover", () => {
+ test("a moving mouse over a focused page plays", () => {
+ expect(isRealHover(MOVE, true)).toBe(true);
+ });
+
+ test("a pointer crossing an unfocused window stays still", () => {
+ expect(isRealHover(MOVE, false)).toBe(false);
+ });
+
+ test("a tile sliding under a parked pointer stays still", () => {
+ expect(isRealHover({ ...MOVE, movementX: 0, movementY: 0 }, true)).toBe(false);
+ });
+
+ test("a touch stays still", () => {
+ expect(isRealHover({ ...MOVE, pointerType: "touch" }, true)).toBe(false);
+ });
+});
diff --git a/site/src/cut/hooks/useHoverPlay.ts b/site/src/cut/hooks/useHoverPlay.ts
index f5582105..b20b28e5 100644
--- a/site/src/cut/hooks/useHoverPlay.ts
+++ b/site/src/cut/hooks/useHoverPlay.ts
@@ -1,32 +1,54 @@
"use client";
-import { useRef } from "react";
+import { useRef, type PointerEvent } from "react";
+
+/** Whether hover playback unmutes: a preview with sound, or a silent loop. */
+export type HoverAudio = "sound" | "silent";
+
+type HoverMove = Pick<PointerEvent, "pointerType" | "movementX" | "movementY">;
+
+/**
+ * A hover is the person moving a mouse over a focused page. Browsers also send
+ * pointer events to an unfocused window under the cursor and when layout slides
+ * a tile under a parked pointer (a render landing in chat); neither may start
+ * a preview, least of all one with sound.
+ */
+export function isRealHover(e: HoverMove, focused: boolean) {
+ if (!focused || e.pointerType === "touch") {
+ return false;
+ }
+ return e.movementX !== 0 || e.movementY !== 0;
+}
/**
- * Hover-to-play for a muted <video> poster: entering plays with sound, leaving
- * pauses, re-mutes, and returns to the first frame. Sound needs a prior page
- * interaction; if the browser refuses it, playback falls back to silent rather
- * than not starting at all. Attach `ref` to the <video> and spread `handlers`
- * on the hover target (the tile, not the video, so scrims stay hoverable).
+ * Hover-to-play for a muted <video> poster: moving over it plays (with sound
+ * when asked; if the browser refuses sound, playback falls back to silent),
+ * leaving pauses, re-mutes, and returns to `restTime`. Attach `ref` to the
+ * <video> and spread `handlers` on the hover target (the tile, not the video,
+ * so scrims stay hoverable).
*/
-export function useHoverPlay() {
+export function useHoverPlay(restTime = 0.1, audio: HoverAudio = "sound") {
const ref = useRef<HTMLVideoElement>(null);
const handlers = {
- onMouseEnter: () => {
+ onPointerMove: (e: PointerEvent) => {
const v = ref.current;
- if (!v) return;
- v.muted = false;
+ if (!v || !v.paused || !isRealHover(e, document.hasFocus())) {
+ return;
+ }
+ v.muted = audio === "silent";
void v.play().catch(() => {
v.muted = true;
void v.play().catch(() => {});
});
},
- onMouseLeave: () => {
+ onPointerLeave: () => {
const v = ref.current;
- if (!v) return;
+ if (!v) {
+ return;
+ }
v.pause();
v.muted = true;
- v.currentTime = 0.1;
+ v.currentTime = restTime;
},
};
return { ref, handlers };