Skip to content

Commit c62bd4c

Browse files
committed
fix(studio): harden preview recovery
1 parent 3af9a7d commit c62bd4c

4 files changed

Lines changed: 151 additions & 17 deletions

File tree

‎packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,23 @@ function mount(onSelect = vi.fn(), onAddToTimeline = vi.fn()) {
4242
describe("composition card drag", () => {
4343
it("uses a cached image instead of eagerly mounting a live preview iframe", () => {
4444
const { host } = mount();
45-
expect(host.querySelector('img[src*="/thumbnail/"]')).not.toBeNull();
45+
const thumbnail = host.querySelector<HTMLImageElement>('img[src*="/thumbnail/"]');
46+
expect(thumbnail).not.toBeNull();
47+
expect(new URL(thumbnail?.src ?? "").searchParams.get("t")).toBe("3.00");
4648
expect(host.querySelector("iframe")).toBeNull();
4749
});
4850

51+
it("shows a fallback when the cached thumbnail fails", () => {
52+
const { host } = mount();
53+
const thumbnail = host.querySelector<HTMLImageElement>('img[src*="/thumbnail/"]');
54+
if (!thumbnail) throw new Error("composition thumbnail did not render");
55+
56+
act(() => thumbnail.dispatchEvent(new Event("error")));
57+
58+
expect(host.textContent).toContain("Preview unavailable");
59+
expect(host.querySelector('img[src*="/thumbnail/"]')).toBeNull();
60+
});
61+
4962
it("mounts one live preview only after sustained hover and removes it on leave", () => {
5063
vi.useFakeTimers();
5164
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -61,6 +74,7 @@ describe("composition card drag", () => {
6174
card.dispatchEvent(new Event("pointerout", { bubbles: true }));
6275
});
6376
expect(host.querySelector("iframe")).toBeNull();
77+
expect(vi.getTimerCount()).toBe(0);
6478
} finally {
6579
consoleError.mockRestore();
6680
vi.useRealTimers();

‎packages/studio/src/components/sidebar/CompositionsTab.tsx‎

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ function CompCard({
132132
const [hovered, setHovered] = useState(false);
133133
const [stageSize, setStageSize] = useState(DEFAULT_PREVIEW_STAGE);
134134
const [livePreviewLoaded, setLivePreviewLoaded] = useState(false);
135+
const [thumbnailFailed, setThumbnailFailed] = useState(false);
135136
const iframeRef = useRef<HTMLIFrameElement | null>(null);
136137
const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
137138
const syncTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -160,15 +161,19 @@ function CompCard({
160161
clearTimeout(hoverTimer.current);
161162
hoverTimer.current = null;
162163
}
164+
if (syncTimer.current) {
165+
clearTimeout(syncTimer.current);
166+
syncTimer.current = null;
167+
}
163168
setHovered(false);
164169
setLivePreviewLoaded(false);
165170
};
166171
const name = comp.replace(/^compositions\//, "").replace(/\.html$/, "");
167172
const previewUrl = `/api/projects/${projectId}/preview/comp/${comp}`;
168173
const thumbnailUrl = buildCompositionThumbnailUrl({
169174
previewUrl,
170-
seekTime: 0,
171-
duration: THUMBNAIL_SEEK_TIME_SECONDS * 2,
175+
seekTime: THUMBNAIL_SEEK_TIME_SECONDS,
176+
duration: 0,
172177
origin: window.location.origin,
173178
});
174179
const previewScale = resolveCompositionPreviewScale({
@@ -225,16 +230,23 @@ function CompCard({
225230
}`}
226231
>
227232
<div className="w-20 h-[45px] rounded overflow-hidden bg-neutral-900 flex-shrink-0 relative">
228-
<img
229-
src={thumbnailUrl}
230-
alt=""
231-
draggable={false}
232-
loading="lazy"
233-
decoding="async"
234-
className={`absolute inset-0 h-full w-full object-contain transition-opacity ${
235-
livePreviewLoaded ? "opacity-0" : "opacity-100"
236-
}`}
237-
/>
233+
{thumbnailFailed ? (
234+
<div className="absolute inset-0 flex items-center justify-center px-1 text-center text-[8px] leading-tight text-neutral-600">
235+
Preview unavailable
236+
</div>
237+
) : (
238+
<img
239+
src={thumbnailUrl}
240+
alt=""
241+
draggable={false}
242+
loading="lazy"
243+
decoding="async"
244+
onError={() => setThumbnailFailed(true)}
245+
className={`absolute inset-0 h-full w-full object-contain transition-opacity ${
246+
livePreviewLoaded ? "opacity-0" : "opacity-100"
247+
}`}
248+
/>
249+
)}
238250
{hovered && (
239251
<iframe
240252
ref={iframeRef}
@@ -353,7 +365,7 @@ export const CompositionsTab = memo(function CompositionsTab({
353365
<div className="flex-1 overflow-y-auto">
354366
{compositions.map((comp) => (
355367
<CompCard
356-
key={comp}
368+
key={`${projectId}:${comp}`}
357369
projectId={projectId}
358370
comp={comp}
359371
isActive={activeComposition === comp}

‎packages/studio/src/player/components/Player.test.ts‎

Lines changed: 109 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,79 @@
11
// @vitest-environment happy-dom
22

3-
import { describe, expect, it } from "vitest";
3+
import { act, createElement } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, describe, expect, it, vi } from "vitest";
46
import {
57
hasUnloadedAssets,
8+
Player,
69
readPreviewErrorMessage,
710
shouldShowCompositionLoadingOverlay,
811
} from "./Player";
912

13+
vi.mock("@hyperframes/player", () => ({}));
14+
15+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
16+
17+
let root: Root | null = null;
18+
let lifecycleLog: string[] = [];
19+
20+
class TestHyperframesPlayer extends HTMLElement {
21+
readonly iframeElement = document.createElement("iframe");
22+
23+
constructor() {
24+
super();
25+
26+
const addIframeListener = this.iframeElement.addEventListener.bind(this.iframeElement);
27+
this.iframeElement.addEventListener = ((type, listener, options) => {
28+
lifecycleLog.push(`iframe:${type}`);
29+
addIframeListener(type, listener, options);
30+
}) as typeof this.iframeElement.addEventListener;
31+
32+
const addPlayerListener = this.addEventListener.bind(this);
33+
this.addEventListener = ((type, listener, options) => {
34+
lifecycleLog.push(`player:${type}`);
35+
addPlayerListener(type, listener, options);
36+
}) as typeof this.addEventListener;
37+
38+
const setPlayerAttribute = this.setAttribute.bind(this);
39+
this.setAttribute = (name, value) => {
40+
if (name === "src") lifecycleLog.push("src");
41+
setPlayerAttribute(name, value);
42+
};
43+
}
44+
}
45+
46+
if (!customElements.get("hyperframes-player")) {
47+
customElements.define("hyperframes-player", TestHyperframesPlayer);
48+
}
49+
50+
afterEach(() => {
51+
if (root) act(() => root?.unmount());
52+
root = null;
53+
lifecycleLog = [];
54+
document.body.innerHTML = "";
55+
});
56+
57+
async function mountPlayer() {
58+
const host = document.createElement("div");
59+
document.body.append(host);
60+
root = createRoot(host);
61+
await act(async () => {
62+
root?.render(
63+
createElement(Player, {
64+
directUrl: "/api/projects/demo/preview",
65+
onLoad: vi.fn(),
66+
suppressLoadingOverlay: true,
67+
}),
68+
);
69+
await Promise.resolve();
70+
});
71+
72+
const player = host.querySelector<TestHyperframesPlayer>("hyperframes-player");
73+
if (!player) throw new Error("player did not mount");
74+
return { host, player };
75+
}
76+
1077
function createAudioIframe() {
1178
const iframe = document.createElement("iframe");
1279
document.body.appendChild(iframe);
@@ -32,6 +99,47 @@ describe("preview errors", () => {
3299
"The composition preview did not become ready.",
33100
);
34101
});
102+
103+
it("attaches lifecycle listeners before navigating the player", async () => {
104+
await mountPlayer();
105+
const srcIndex = lifecycleLog.indexOf("src");
106+
107+
expect(srcIndex).toBeGreaterThan(-1);
108+
for (const listener of [
109+
"iframe:load",
110+
"player:click",
111+
"player:shadertransitionstate",
112+
"player:ready",
113+
"player:error",
114+
]) {
115+
expect(lifecycleLog.indexOf(listener)).toBeGreaterThan(-1);
116+
expect(lifecycleLog.indexOf(listener)).toBeLessThan(srcIndex);
117+
}
118+
});
119+
120+
it("retries a failed preview with a fresh player URL", async () => {
121+
const { host, player } = await mountPlayer();
122+
123+
act(() => {
124+
player.dispatchEvent(
125+
new CustomEvent("error", {
126+
detail: { message: "Composition timeline not found after 8s" },
127+
}),
128+
);
129+
});
130+
131+
expect(host.querySelector('[data-testid="composition-preview-error"]')).not.toBeNull();
132+
const retry = Array.from(host.querySelectorAll("button")).find(
133+
(button) => button.textContent === "Retry preview",
134+
);
135+
if (!retry) throw new Error("retry action did not render");
136+
137+
act(() => retry.click());
138+
139+
const retryUrl = new URL(player.getAttribute("src") ?? "", window.location.origin);
140+
expect(retryUrl.searchParams.get("_hfStudioRetry")).toBe("1");
141+
expect(host.querySelector('[data-testid="composition-preview-error"]')).toBeNull();
142+
});
35143
});
36144

37145
describe("composition loading overlay", () => {

‎scripts/studio-runtime-smoke.test.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88

99
function bodyOf(method, path) {
1010
const response = studioSmokeApiResponse(method, `http://localhost:5199${path}`);
11-
assert.ok(response && response !== null);
11+
assert.ok(response);
1212
return JSON.parse(response.body);
1313
}
1414

@@ -49,7 +49,7 @@ describe("Studio runtime smoke fixtures", () => {
4949
"GET",
5050
"http://localhost:5199/api/projects/smoke-test/thumbnail/index.html?t=3",
5151
);
52-
assert.ok(response && response !== null);
52+
assert.ok(response);
5353
assert.equal(response.contentType, "image/svg+xml");
5454
});
5555

0 commit comments

Comments
 (0)