@hyperframes/studio 0.9.30 → 0.9.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/player.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  Player
3
- } from "./chunk-LRTUWOR4.js";
4
- import "./chunk-J3VJE463.js";
3
+ } from "./chunk-YKBN653R.js";
4
+ import "./chunk-52AJB4PN.js";
5
5
  import "./chunk-63DH4LRB.js";
6
6
  import "./chunk-MLKGABMK.js";
7
7
  export {
package/dist/ui.js CHANGED
@@ -30,7 +30,7 @@ import {
30
30
  fieldBase,
31
31
  fieldText,
32
32
  popupSurface
33
- } from "./chunk-J3VJE463.js";
33
+ } from "./chunk-52AJB4PN.js";
34
34
  import "./chunk-MLKGABMK.js";
35
35
  export {
36
36
  Button,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/studio",
3
- "version": "0.9.30",
3
+ "version": "0.9.32",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -60,12 +60,12 @@
60
60
  "dockview-react": "8.3.1",
61
61
  "gsap": "^3.13.0",
62
62
  "mediabunny": "^1.65.2",
63
- "@hyperframes/core": "0.9.30",
64
- "@hyperframes/parsers": "0.9.30",
65
- "@hyperframes/player": "0.9.30",
66
- "@hyperframes/sdk": "0.9.30",
67
- "@hyperframes/studio-server": "0.9.30",
68
- "@hyperframes/shader-transitions": "0.9.30"
63
+ "@hyperframes/parsers": "0.9.32",
64
+ "@hyperframes/shader-transitions": "0.9.32",
65
+ "@hyperframes/core": "0.9.32",
66
+ "@hyperframes/sdk": "0.9.32",
67
+ "@hyperframes/studio-server": "0.9.32",
68
+ "@hyperframes/player": "0.9.32"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@tailwindcss/vite": "^4.3.3",
@@ -82,7 +82,7 @@
82
82
  "vite": "^6.4.2",
83
83
  "vitest": "^4.1.11",
84
84
  "zustand": "^5.0.0",
85
- "@hyperframes/producer": "0.9.30"
85
+ "@hyperframes/producer": "0.9.32"
86
86
  },
87
87
  "peerDependencies": {
88
88
  "react": "19",
@@ -0,0 +1,100 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import { act } from "react";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { mountCompositionsTab } from "./compositionsTabTestUtils";
6
+
7
+ type PostedControl = { source: string; type: string; action: string; muted?: boolean };
8
+
9
+ function hoverPreview() {
10
+ const host = mountCompositionsTab();
11
+ const card = host.querySelector<HTMLElement>('[draggable="true"]');
12
+ if (!card) throw new Error("composition card did not render");
13
+ act(() => {
14
+ card.dispatchEvent(new Event("pointerover", { bubbles: true }));
15
+ vi.advanceTimersByTime(300);
16
+ });
17
+ const iframe = host.querySelector("iframe");
18
+ if (!iframe) throw new Error("hover preview did not mount");
19
+ // Stand-in for the frame's window. The document getter throws, as reading into
20
+ // an opaque-origin frame would, so any read the card made would fail the test.
21
+ const frameWindow = { postMessage: vi.fn() };
22
+ Object.defineProperty(iframe, "contentWindow", { configurable: true, get: () => frameWindow });
23
+ Object.defineProperty(iframe, "contentDocument", {
24
+ configurable: true,
25
+ get: () => {
26
+ throw new Error("the hover preview must not read the frame document");
27
+ },
28
+ });
29
+ return { iframe, frameWindow };
30
+ }
31
+
32
+ function fromFrame(source: unknown, data: Record<string, unknown>) {
33
+ act(() => {
34
+ window.dispatchEvent(
35
+ new MessageEvent("message", {
36
+ data: { source: "hf-preview", ...data },
37
+ source: source as MessageEventSource,
38
+ }),
39
+ );
40
+ });
41
+ }
42
+
43
+ const posted = (frameWindow: { postMessage: ReturnType<typeof vi.fn> }) =>
44
+ frameWindow.postMessage.mock.calls.map(([message]) => message as PostedControl);
45
+
46
+ let consoleError: ReturnType<typeof vi.spyOn>;
47
+
48
+ beforeEach(() => {
49
+ vi.useFakeTimers();
50
+ consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
51
+ });
52
+
53
+ afterEach(() => {
54
+ consoleError.mockRestore();
55
+ vi.useRealTimers();
56
+ });
57
+
58
+ describe("composition card hover preview", () => {
59
+ it("frames the composition in an opaque origin", () => {
60
+ const { iframe } = hoverPreview();
61
+ expect(iframe.getAttribute("sandbox")).toBe("allow-scripts");
62
+ expect(iframe.sandbox.contains("allow-scripts")).toBe(true);
63
+ expect(iframe.sandbox.contains("allow-same-origin")).toBe(false);
64
+ });
65
+
66
+ it("plays muted over the runtime bridge once the runtime is listening", () => {
67
+ const { frameWindow } = hoverPreview();
68
+ expect(frameWindow.postMessage).not.toHaveBeenCalled();
69
+
70
+ fromFrame(frameWindow, { type: "ready" });
71
+
72
+ expect(posted(frameWindow).map(({ source, type, action }) => [source, type, action])).toEqual([
73
+ ["hf-parent", "control", "set-muted"],
74
+ ["hf-parent", "control", "play"],
75
+ ]);
76
+ expect(posted(frameWindow)[0]?.muted).toBe(true);
77
+ for (const [, targetOrigin] of frameWindow.postMessage.mock.calls) {
78
+ expect(targetOrigin).toBe("*");
79
+ }
80
+ });
81
+
82
+ it("sizes the stage from the runtime's timeline message", () => {
83
+ const { iframe, frameWindow } = hoverPreview();
84
+ expect([iframe.style.width, iframe.style.height]).toEqual(["1920px", "1080px"]);
85
+
86
+ fromFrame(frameWindow, { type: "timeline", compositionWidth: 1080, compositionHeight: 1920 });
87
+
88
+ expect([iframe.style.width, iframe.style.height]).toEqual(["1080px", "1920px"]);
89
+ });
90
+
91
+ it("ignores runtime messages that come from another window", () => {
92
+ const { iframe, frameWindow } = hoverPreview();
93
+
94
+ fromFrame({ postMessage: vi.fn() }, { type: "ready" });
95
+ fromFrame(window, { type: "timeline", compositionWidth: 640, compositionHeight: 640 });
96
+
97
+ expect(frameWindow.postMessage).not.toHaveBeenCalled();
98
+ expect([iframe.style.width, iframe.style.height]).toEqual(["1920px", "1080px"]);
99
+ });
100
+ });
@@ -1,6 +1,6 @@
1
- import { describe, expect, it, vi } from "vitest";
1
+ import { describe, expect, it } from "vitest";
2
2
  import { resolveThumbnailSeekTime } from "../../player/components/CompositionThumbnail";
3
- import { resolveCompositionPreviewScale, syncIframePlayback } from "./CompositionsTab";
3
+ import { resolveCompositionPreviewScale } from "./CompositionsTab";
4
4
 
5
5
  describe("resolveCompositionPreviewScale", () => {
6
6
  it("scales a 16:9 stage to fit the composition card", () => {
@@ -52,25 +52,3 @@ describe("resolveThumbnailSeekTime", () => {
52
52
  expect(resolveThumbnailSeekTime(Number.NaN)).toBe(3);
53
53
  });
54
54
  });
55
-
56
- describe("syncIframePlayback", () => {
57
- it("mutes a composition-card preview before playing it", () => {
58
- const calls: string[] = [];
59
- const postMessage = vi.fn(() => calls.push("mute"));
60
- const player = {
61
- play: vi.fn(() => calls.push("play")),
62
- };
63
- const iframe = {
64
- contentWindow: { __player: player, postMessage },
65
- getRootNode: () => ({}),
66
- } as unknown as HTMLIFrameElement;
67
-
68
- expect(syncIframePlayback(iframe, true)).toBe(true);
69
- expect(postMessage).toHaveBeenCalledWith(
70
- expect.objectContaining({ action: "set-muted", muted: true }),
71
- "*",
72
- );
73
- expect(calls).toEqual(["mute", "play"]);
74
- expect(player.play).toHaveBeenCalledOnce();
75
- });
76
- });
@@ -1,5 +1,5 @@
1
1
  import { buildProjectApiPath } from "../../utils/projectRouting";
2
- import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
3
  import { useThumbnailLease } from "../../hooks/useThumbnailLease";
4
4
  import {
5
5
  thumbnailScheduler,
@@ -9,11 +9,10 @@ import {
9
9
  import {
10
10
  buildCompositionThumbnailUrl,
11
11
  compositionThumbnailRequest,
12
- resolveThumbnailSeekTime,
13
12
  THUMBNAIL_SEEK_TIME_SECONDS,
14
13
  } from "../../player/components/CompositionThumbnail";
15
14
  import { setPreviewMediaMuted } from "../../player/lib/timelineIframeHelpers";
16
- import { postFrameDisplayScale } from "../../player/lib/runtimeProtocol";
15
+ import { postFrameDisplayScale, postRuntimeControlMessage } from "../../player/lib/runtimeProtocol";
17
16
  import { usePlayerStore } from "../../player/store/playerStore";
18
17
  import { thumbnailRevisionOf } from "../../player/store/thumbnailSlice";
19
18
  import { encodePreviewPath } from "../../player/components/thumbnailUtils";
@@ -36,16 +35,8 @@ interface CompositionsTabProps {
36
35
  const DEFAULT_PREVIEW_STAGE = { width: 1920, height: 1080 };
37
36
  const CARD_W = 80;
38
37
  const CARD_H = 45;
39
- const THUMBNAIL_PLAYBACK_SYNC_ATTEMPTS = 10;
40
38
 
41
- type PreviewWindow = Window & {
42
- __player?: {
43
- play?: () => void;
44
- pause?: () => void;
45
- seek?: (time: number) => void;
46
- getDuration?: () => number;
47
- };
48
- };
39
+ const OPAQUE_ORIGIN_SCRIPTS_ONLY_SANDBOX = "allow-scripts";
49
40
 
50
41
  export function resolveCompositionPreviewScale(input: {
51
42
  cardWidth: number;
@@ -84,53 +75,26 @@ export function compositionCardThumbnailUrl(
84
75
  });
85
76
  }
86
77
 
87
- function parsePositiveNumber(value: string | null): number | null {
88
- if (value == null) return null;
89
- const parsed = Number.parseFloat(value);
90
- return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
78
+ function positiveDimension(value: unknown, fallback: number): number {
79
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
91
80
  }
92
81
 
93
- // fallow-ignore-next-line complexity
94
- function resolveIframeDuration(iframe: HTMLIFrameElement | null): number | null {
95
- try {
96
- const win = iframe?.contentWindow as PreviewWindow | null;
97
- const playerDuration = win?.__player?.getDuration?.();
98
- if (Number.isFinite(playerDuration) && playerDuration != null && playerDuration > 0) {
99
- return playerDuration;
100
- }
101
- } catch {
102
- /* cross-origin iframe */
103
- }
104
-
105
- try {
106
- const doc = iframe?.contentDocument;
107
- const root = doc?.querySelector("[data-composition-id]") ?? doc?.documentElement ?? null;
108
- return (
109
- parsePositiveNumber(root?.getAttribute("data-composition-duration") ?? null) ??
110
- parsePositiveNumber(root?.getAttribute("data-duration") ?? null)
111
- );
112
- } catch {
113
- return null;
114
- }
82
+ function stageSizeFromRuntimeTimelineMessage(
83
+ data: unknown,
84
+ ): { width: number; height: number } | null {
85
+ if (typeof data !== "object" || data === null) return null;
86
+ const message = data as Record<string, unknown>;
87
+ if (message.source !== "hf-preview" || message.type !== "timeline") return null;
88
+ return {
89
+ width: positiveDimension(message.compositionWidth, DEFAULT_PREVIEW_STAGE.width),
90
+ height: positiveDimension(message.compositionHeight, DEFAULT_PREVIEW_STAGE.height),
91
+ };
115
92
  }
116
93
 
117
- export function syncIframePlayback(iframe: HTMLIFrameElement | null, shouldPlay: boolean): boolean {
118
- try {
119
- const player = (iframe?.contentWindow as PreviewWindow | null)?.__player;
120
- if (!player) return false;
121
-
122
- if (shouldPlay) {
123
- setPreviewMediaMuted(iframe, true);
124
- player.play?.();
125
- return true;
126
- }
127
-
128
- player.pause?.();
129
- player.seek?.(resolveThumbnailSeekTime(resolveIframeDuration(iframe)));
130
- return true;
131
- } catch {
132
- return false;
133
- }
94
+ function muteThenPlayOverRuntimeBridge(iframe: HTMLIFrameElement | null): void {
95
+ if (!iframe) return;
96
+ setPreviewMediaMuted(iframe, true);
97
+ postRuntimeControlMessage(iframe.contentWindow, "play");
134
98
  }
135
99
 
136
100
  const imageUrlOf = (snapshot: ThumbnailSnapshot) =>
@@ -195,24 +159,8 @@ function CompCard({
195
159
  const [livePreviewLoaded, setLivePreviewLoaded] = useState(false);
196
160
  const iframeRef = useRef<HTMLIFrameElement | null>(null);
197
161
  const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
198
- const syncTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
199
162
  const draggedRef = useRef(false);
200
163
 
201
- const requestIframePlaybackSync = useCallback((shouldPlay: boolean) => {
202
- if (syncTimer.current) {
203
- clearTimeout(syncTimer.current);
204
- syncTimer.current = null;
205
- }
206
-
207
- const sync = (remainingAttempts: number) => {
208
- if (syncIframePlayback(iframeRef.current, shouldPlay) || remainingAttempts <= 0) return;
209
-
210
- syncTimer.current = setTimeout(() => sync(remainingAttempts - 1), 100);
211
- };
212
-
213
- sync(THUMBNAIL_PLAYBACK_SYNC_ATTEMPTS);
214
- }, []);
215
-
216
164
  const handleEnter = () => {
217
165
  hoverTimer.current = setTimeout(() => setHovered(true), 300);
218
166
  };
@@ -221,10 +169,6 @@ function CompCard({
221
169
  clearTimeout(hoverTimer.current);
222
170
  hoverTimer.current = null;
223
171
  }
224
- if (syncTimer.current) {
225
- clearTimeout(syncTimer.current);
226
- syncTimer.current = null;
227
- }
228
172
  setHovered(false);
229
173
  setLivePreviewLoaded(false);
230
174
  };
@@ -255,30 +199,35 @@ function CompCard({
255
199
  const thumbnailOffsetX = (CARD_W - stageSize.width * previewScale) / 2;
256
200
  const thumbnailOffsetY = (CARD_H - stageSize.height * previewScale) / 2;
257
201
 
258
- useEffect(() => {
259
- if (hovered) requestIframePlaybackSync(true);
260
- }, [hovered, requestIframePlaybackSync]);
261
-
262
202
  useEffect(() => {
263
203
  if (livePreviewLoaded) postFrameDisplayScale(iframeRef.current);
264
204
  }, [livePreviewLoaded, previewScale]);
265
205
 
266
206
  useEffect(() => {
267
207
  if (!hovered) return;
268
- const onRuntimeReady = (event: MessageEvent) => {
208
+ const onRuntimeMessage = (event: MessageEvent) => {
269
209
  const frame = iframeRef.current;
270
- if (frame && event.source === frame.contentWindow && event.data?.type === "ready") {
210
+ if (!frame || event.source !== frame.contentWindow) return;
211
+ const runtimeControlListenerInstalled =
212
+ event.data?.source === "hf-preview" && event.data.type === "ready";
213
+ if (runtimeControlListenerInstalled) {
271
214
  postFrameDisplayScale(frame);
215
+ muteThenPlayOverRuntimeBridge(frame);
216
+ return;
272
217
  }
218
+ const stage = stageSizeFromRuntimeTimelineMessage(event.data);
219
+ if (!stage) return;
220
+ setStageSize((current) =>
221
+ current.width === stage.width && current.height === stage.height ? current : stage,
222
+ );
273
223
  };
274
- window.addEventListener("message", onRuntimeReady);
275
- return () => window.removeEventListener("message", onRuntimeReady);
224
+ window.addEventListener("message", onRuntimeMessage);
225
+ return () => window.removeEventListener("message", onRuntimeMessage);
276
226
  }, [hovered]);
277
227
 
278
228
  useEffect(() => {
279
229
  return () => {
280
230
  if (hoverTimer.current) clearTimeout(hoverTimer.current);
281
- if (syncTimer.current) clearTimeout(syncTimer.current);
282
231
  };
283
232
  }, []);
284
233
 
@@ -342,7 +291,7 @@ function CompCard({
342
291
  <iframe
343
292
  ref={iframeRef}
344
293
  src={previewUrl}
345
- sandbox="allow-scripts allow-same-origin"
294
+ sandbox={OPAQUE_ORIGIN_SCRIPTS_ONLY_SANDBOX}
346
295
  className="absolute border-none pointer-events-none"
347
296
  style={{
348
297
  transformOrigin: "0 0",
@@ -352,21 +301,7 @@ function CompCard({
352
301
  top: thumbnailOffsetY,
353
302
  transform: `scale(${previewScale})`,
354
303
  }}
355
- onLoad={(e) => {
356
- try {
357
- const iframe = e.currentTarget;
358
- const root = iframe.contentDocument?.querySelector("[data-composition-id]");
359
- const width =
360
- Number(root?.getAttribute("data-width")) || DEFAULT_PREVIEW_STAGE.width;
361
- const height =
362
- Number(root?.getAttribute("data-height")) || DEFAULT_PREVIEW_STAGE.height;
363
- setStageSize({ width, height });
364
- setLivePreviewLoaded(true);
365
- requestIframePlaybackSync(true);
366
- } catch {
367
- setStageSize(DEFAULT_PREVIEW_STAGE);
368
- }
369
- }}
304
+ onLoad={() => setLivePreviewLoaded(true)}
370
305
  title={`${name} preview`}
371
306
  tabIndex={-1}
372
307
  />
@@ -92,8 +92,11 @@ export function Input({
92
92
  dirtyRef.current = true;
93
93
  setDraft(next);
94
94
  }}
95
- onBlur={() => commit(draft)}
95
+ onBlur={() => {
96
+ if (dirtyRef.current) commit(draft);
97
+ }}
96
98
  onKeyDown={(event) => {
99
+ if (event.nativeEvent.isComposing) return;
97
100
  if (event.key === "Enter") {
98
101
  event.preventDefault();
99
102
  commit(draft);
@@ -362,6 +362,91 @@ describe("NumberField", () => {
362
362
  });
363
363
 
364
364
  describe("Input", () => {
365
+ it.each(["Enter", "Escape"])("leaves %s to the active IME composition", (key) => {
366
+ const commits: string[] = [];
367
+ const trackCommit = vi.fn(track("text"));
368
+ const host = render(
369
+ <Input
370
+ value="hello"
371
+ aria-label="Name"
372
+ onCommit={(value) => commits.push(value)}
373
+ onTrack={trackCommit}
374
+ />,
375
+ );
376
+ const input = host.querySelector("input");
377
+ if (!input) throw new Error("Input did not render");
378
+
379
+ act(() => input.focus());
380
+ act(
381
+ () => void input.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true })),
382
+ );
383
+ type(input, "中");
384
+ const composingKey = new KeyboardEvent("keydown", {
385
+ key,
386
+ bubbles: true,
387
+ cancelable: true,
388
+ isComposing: true,
389
+ });
390
+ act(() => void input.dispatchEvent(composingKey));
391
+
392
+ expect(composingKey.defaultPrevented).toBe(false);
393
+ expect(document.activeElement).toBe(input);
394
+ expect(input.value).toBe("中");
395
+ expect(commits).toEqual([]);
396
+ expect(trackCommit).not.toHaveBeenCalled();
397
+ expect(designInputCalls()).toHaveLength(0);
398
+
399
+ act(() => void input.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })));
400
+ type(input, "中文");
401
+ fire(input, "keydown", { key: "Enter" });
402
+ expect(commits).toEqual(["中文"]);
403
+ expect(trackCommit).toHaveBeenCalledTimes(1);
404
+ expect(designInputCalls()).toHaveLength(1);
405
+ });
406
+
407
+ it.each(["Enter", "Escape"])("does not commit the draft again on blur after %s", (key) => {
408
+ const commits: string[] = [];
409
+ const trackCommit = vi.fn(track("text"));
410
+ const host = render(
411
+ <Input
412
+ value="hello"
413
+ aria-label="Name"
414
+ onCommit={(value) => commits.push(value)}
415
+ onTrack={trackCommit}
416
+ />,
417
+ );
418
+ const input = host.querySelector("input");
419
+ if (!input) throw new Error("Input did not render");
420
+
421
+ act(() => input.focus());
422
+ type(input, "world");
423
+ fire(input, "keydown", { key });
424
+ act(() => input.blur());
425
+
426
+ expect(commits).toEqual(key === "Enter" ? ["world"] : []);
427
+ expect(input.value).toBe(key === "Enter" ? "world" : "hello");
428
+ expect(trackCommit).toHaveBeenCalledTimes(key === "Enter" ? 1 : 0);
429
+ expect(designInputCalls()).toHaveLength(key === "Enter" ? 1 : 0);
430
+ });
431
+
432
+ it("commits a changed draft on blur without Enter", () => {
433
+ const commits: string[] = [];
434
+ const trackCommit = vi.fn(track("text"));
435
+ const host = render(
436
+ <Input value="hello" onCommit={(value) => commits.push(value)} onTrack={trackCommit} />,
437
+ );
438
+ const input = host.querySelector("input");
439
+ if (!input) throw new Error("Input did not render");
440
+
441
+ act(() => input.focus());
442
+ type(input, "world");
443
+ act(() => input.blur());
444
+
445
+ expect(commits).toEqual(["world"]);
446
+ expect(trackCommit).toHaveBeenCalledTimes(1);
447
+ expect(designInputCalls()).toHaveLength(1);
448
+ });
449
+
365
450
  it("commits a typed value on Enter, once, and not per keystroke", () => {
366
451
  const commits: string[] = [];
367
452
  const host = render(
@@ -26,6 +26,7 @@ import {
26
26
  type MutableRef,
27
27
  type UseTimelineElementVisibilityEditingInput,
28
28
  } from "./timelineTrackVisibility";
29
+ import { countOf } from "../utils/countOf";
29
30
 
30
31
  interface AudioGroupCarveInput extends UseTimelineElementVisibilityEditingInput {
31
32
  checkEditable?: (elements: readonly TimelineElement[]) => boolean;
@@ -181,7 +182,7 @@ export async function createAudioGroupAndAssignMembers({
181
182
  // then persists `sources: [groupId]` on success, so a quiet no-op leaves the
182
183
  // carve aimed at a group that does not exist.
183
184
  if (elements.length < 2) {
184
- throw new Error(`Cannot group ${elements.length} clip(s): a group needs at least two`);
185
+ throw new Error(`Cannot group ${countOf(elements.length, "clip")}: a group needs at least two`);
185
186
  }
186
187
  if (!GROUP_ID_PATTERN.test(groupId)) {
187
188
  throw new Error(`Invalid audio group id ${JSON.stringify(groupId)}`);
@@ -25,6 +25,7 @@ import {
25
25
  } from "./gsapShared";
26
26
  import { useStableHandlers } from "./useStableHandlers";
27
27
  import { progressAtTime, runEaseOf, timeAtProgress, warpsTime } from "../utils/gsapKeyframeEases";
28
+ import { countOf } from "../utils/countOf";
28
29
 
29
30
  type RecordedKeyframe = {
30
31
  percentage: number;
@@ -375,7 +376,7 @@ export function useGestureCommit({
375
376
  }
376
377
  trackPreviewEditResult("gesture_recording", recordingMethodRef.current, outcome.finish());
377
378
  }
378
- showToast(`Recorded ${sortedPcts.length} keyframes`, "info");
379
+ showToast(`Recorded ${countOf(sortedPcts.length, "keyframe")}`, "info");
379
380
  } catch (err) {
380
381
  console.error("[GR:error]", err);
381
382
  showToast(`Gesture commit failed: ${err}`, "error");
@@ -9,6 +9,7 @@ import { isLinkedSelectionOn } from "../utils/linkedClipPreferences";
9
9
  import { buildAtomicCutIntents, runAtomicCutTransaction } from "../utils/razorSplitTransaction";
10
10
  import type { RecordEditInput } from "./timelineEditingHelpers";
11
11
  import { useFreezeFrame } from "./useFreezeFrame";
12
+ import { countOf } from "../utils/countOf";
12
13
 
13
14
  interface UseRazorSplitOptions {
14
15
  projectId: string | null;
@@ -138,7 +139,10 @@ export function useRazorSplit({
138
139
  const result = await runCut(splittable, splitTime, "all");
139
140
  if (!result) return;
140
141
  if (result.syncFailed) return;
141
- showToast(`Split ${result.splitCount} clips at ${splitTime.toFixed(2)}s`, "info");
142
+ showToast(
143
+ `Split ${countOf(result.splitCount, "clip")} at ${splitTime.toFixed(2)}s`,
144
+ "info",
145
+ );
142
146
  } catch (error) {
143
147
  const message = error instanceof Error ? error.message : "Failed to split clips";
144
148
  showToast(message, "error");
@@ -156,6 +156,34 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
156
156
  expect(body.targets).toHaveLength(elements.length);
157
157
  });
158
158
 
159
+ it("a refused delete names its count: 1 clip, 2 clips", async () => {
160
+ vi.stubGlobal(
161
+ "fetch",
162
+ vi.fn(async (input: RequestInfo | URL) =>
163
+ String(input).includes("/file-mutations/remove-elements/")
164
+ ? new Response("{}", { status: 500 })
165
+ : new Response(JSON.stringify({ content: html }), { status: 200 }),
166
+ ),
167
+ );
168
+ const showToast = vi.fn();
169
+ const { elements, b, getHook } = mountDeleteHarness({
170
+ handleTimelineGroupMove: vi.fn(),
171
+ showToast,
172
+ });
173
+
174
+ await act(async () => {
175
+ await getHook().handleTimelineElementDelete(b);
176
+ });
177
+ await act(async () => {
178
+ await getHook().handleTimelineElementsDelete(elements.slice(0, 2));
179
+ });
180
+
181
+ expect(showToast.mock.calls.map(([message]) => message)).toEqual([
182
+ "Failed to delete 1 clip from index.html",
183
+ "Failed to delete 2 clips from index.html",
184
+ ]);
185
+ });
186
+
159
187
  it("shows exactly one toast when a ripple fails to persist after a committed delete", async () => {
160
188
  const handleTimelineGroupMove = vi.fn().mockRejectedValue(new Error("persist failed"));
161
189
  const showToast = vi.fn();
@@ -25,6 +25,7 @@ import type {
25
25
  TimelineGroupMoveChange,
26
26
  } from "./useTimelineGroupEditing";
27
27
  import { studioApiFetch } from "../utils/studioApiFetch";
28
+ import { countOf } from "../utils/countOf";
28
29
 
29
30
  /** Apply already-resolved ripple changes to the surviving elements for the
30
31
  * optimistic store update after a delete. Pure — no IO. */
@@ -139,7 +140,9 @@ export function useTimelineDeleteOps({
139
140
  },
140
141
  );
141
142
  if (!removeResponse.ok) {
142
- throw new Error(`Failed to delete ${sameFile.length} clips from ${targetPath}`);
143
+ throw new Error(
144
+ `Failed to delete ${countOf(sameFile.length, "clip")} from ${targetPath}`,
145
+ );
143
146
  }
144
147
  const removeData = (await removeResponse.json()) as { content?: string };
145
148
  const removedContent =
@@ -0,0 +1,10 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { countOf } from "./countOf";
3
+
4
+ describe("countOf", () => {
5
+ it("names one thing in the singular and two in the plural", () => {
6
+ expect(countOf(1, "clip")).toBe("1 clip");
7
+ expect(countOf(2, "clip")).toBe("2 clips");
8
+ expect(countOf(0, "keyframe")).toBe("0 keyframes");
9
+ });
10
+ });
@@ -0,0 +1,3 @@
1
+ export function countOf(n: number, word: string): string {
2
+ return `${n} ${n === 1 ? word : `${word}s`}`;
3
+ }