@hyperframes/studio 0.9.59 → 0.9.61

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.
Files changed (47) hide show
  1. package/dist/assets/{hyperframes-player-bya4hgms.js → hyperframes-player-Cm0hYGm2.js} +1 -1
  2. package/dist/assets/{index-Bxh5lW0C.js → index-BGrNWeLK.js} +199 -199
  3. package/dist/assets/{index--dcfSUzI.js → index-REqr_dLu.js} +1 -1
  4. package/dist/assets/{pausedVideoDecoder-BKym1jA6.js → pausedVideoDecoder-DqLDSq8J.js} +1 -1
  5. package/dist/{chunk-5EEM5WO4.js → chunk-3KCEIESB.js} +1 -1
  6. package/dist/{chunk-G6FJSL7X.js → chunk-JTUKMELR.js} +34 -6
  7. package/dist/index.d.ts +28 -1
  8. package/dist/index.html +1 -1
  9. package/dist/index.js +689 -177
  10. package/dist/player.js +2 -2
  11. package/dist/ui.js +1 -1
  12. package/package.json +8 -8
  13. package/src/captions/components/CaptionOverlay.sealed.test.ts +273 -0
  14. package/src/captions/components/CaptionOverlay.tsx +112 -57
  15. package/src/captions/components/CaptionOverlayUtils.ts +319 -33
  16. package/src/captions/components/CaptionPropertyPanel.tsx +17 -0
  17. package/src/components/editor/LayersPanel.opaque.test.ts +2 -2
  18. package/src/components/editor/previewDrafts.test.ts +2 -2
  19. package/src/components/editor/previewGestureStartRead.test.ts +2 -2
  20. package/src/components/editor/previewLayers.test.ts +2 -2
  21. package/src/components/editor/previewOverlayRects.test.ts +2 -2
  22. package/src/components/editor/previewPointerTargets.test.ts +2 -2
  23. package/src/components/editor/previewSelection.test.ts +2 -2
  24. package/src/components/editor/useColorGradingController.sealed.test.ts +165 -0
  25. package/src/components/editor/useColorGradingController.ts +20 -1
  26. package/src/components/editor/useColorGradingPreviews.ts +127 -43
  27. package/src/components/nle/NLEPreview.test.ts +24 -0
  28. package/src/components/nle/NLEPreview.tsx +2 -6
  29. package/src/components/nle/previewStage.ts +11 -1
  30. package/src/components/panels/VariablesPanel.test.tsx +90 -1
  31. package/src/components/panels/VariablesPanel.tsx +41 -17
  32. package/src/components/panels/renderHandoff.test.ts +86 -0
  33. package/src/components/panels/renderHandoff.ts +28 -0
  34. package/src/components/ui/Menu.test.tsx +77 -0
  35. package/src/components/ui/Menu.tsx +47 -4
  36. package/src/components/ui/Popover.tsx +5 -2
  37. package/src/elementAnimations.test.ts +13 -0
  38. package/src/hooks/useCaptionDetection.ts +175 -54
  39. package/src/hooks/usePersistentEditHistory.test.ts +84 -0
  40. package/src/hooks/usePersistentEditHistory.ts +36 -3
  41. package/src/index.ts +1 -0
  42. package/src/player/hooks/useShadowPreviewReload.ts +7 -0
  43. package/src/player/hooks/useTimelinePlayer.shadowReload.test.ts +20 -0
  44. package/src/utils/gsapUndoRestore.sealed.test.ts +73 -0
  45. package/src/utils/gsapUndoRestore.ts +66 -0
  46. package/src/utils/studioPendingEdits.test.ts +20 -0
  47. package/src/utils/studioPendingEdits.ts +11 -4
@@ -5,7 +5,16 @@ import { useCaptionStore } from "../captions/store";
5
5
  import { acceptStudioRuntimeMessage } from "../player/lib/runtimeProtocol";
6
6
  import { useCaptionSync } from "../captions/hooks/useCaptionSync";
7
7
  import { parseCaptionComposition } from "../captions/parser";
8
+ import type { CaptionModel } from "../captions/types";
8
9
  import { studioApiFetch } from "../utils/studioApiFetch";
10
+ import { MAX_DESCRIBE_HANDLES } from "@hyperframes/core/runtime/editing-port";
11
+ import { previewComputedStyles, previewFrameOpaque } from "../player/lib/previewChannel";
12
+ import {
13
+ describePreviewElements,
14
+ previewAncestors,
15
+ queryPreviewElements,
16
+ type PreviewElement,
17
+ } from "../player/lib/previewElements";
9
18
 
10
19
  interface UseCaptionDetectionParams {
11
20
  projectId: string | null;
@@ -18,6 +27,91 @@ interface UseCaptionDetectionParams {
18
27
  setRightCollapsed: (collapsed: boolean) => void;
19
28
  }
20
29
 
30
+ // The parser's GROUP_SELECTOR and WORD_SELECTOR, the elements it reads.
31
+ const GROUP_SELECTOR = ".caption-group, .caption-line, .caption-block";
32
+ const WORD_SELECTOR = ".word, .caption-word";
33
+
34
+ const attribute = (el: PreviewElement | null | undefined, name: string) =>
35
+ el?.attributes.find(([key]) => key === name)?.[1] ?? null;
36
+
37
+ /** The styles `parseCaptionComposition` reads off its first word and group. */
38
+ const CAPTION_STYLES = [
39
+ "font-size",
40
+ "font-weight",
41
+ "font-family",
42
+ "color",
43
+ "text-transform",
44
+ "letter-spacing",
45
+ "background-color",
46
+ "border-radius",
47
+ "padding-top",
48
+ "padding-right",
49
+ "padding-bottom",
50
+ "padding-left",
51
+ ];
52
+
53
+ async function frameStyles(iframe: HTMLIFrameElement, handle: string | undefined) {
54
+ if (!handle) return null;
55
+ const styles = await previewComputedStyles(iframe, { handle }, CAPTION_STYLES);
56
+ if (!styles) return null;
57
+ const camel = (name: string) => name.replace(/-(\w)/g, (_, c: string) => c.toUpperCase());
58
+ return Object.fromEntries(CAPTION_STYLES.map((name) => [camel(name), styles[name] ?? ""]));
59
+ }
60
+
61
+ /** A frame's caption groups and words rebuilt in order in a detached document, with a stand-in
62
+ * `getComputedStyle` for the parser; null past one query's matches or with no answer. */
63
+ async function frameCaptionDom(
64
+ iframe: HTMLIFrameElement,
65
+ ): Promise<{ doc: Document; win: Window } | null> {
66
+ const [all, groups, words] = await Promise.all(
67
+ [`${GROUP_SELECTOR}, ${WORD_SELECTOR}`, GROUP_SELECTOR, WORD_SELECTOR].map((selector) =>
68
+ queryPreviewElements(iframe, selector),
69
+ ),
70
+ );
71
+ if (!all || !groups || !words || all.truncated) return null;
72
+ const handles = all.matches.map((match) => match.handle);
73
+ const chains: Array<string[] | null> = [];
74
+ for (let i = 0; i < handles.length; i += MAX_DESCRIBE_HANDLES) {
75
+ const part = await previewAncestors(iframe, handles.slice(i, i + MAX_DESCRIBE_HANDLES));
76
+ if (!part) return null;
77
+ chains.push(...part);
78
+ }
79
+ const isGroup = new Set(groups.matches.map((match) => match.handle));
80
+ const isWord = new Set(words.matches.map((match) => match.handle));
81
+ const doc = document.implementation.createHTMLDocument("");
82
+ const mirrored = new Map<string, Element>();
83
+ handles.forEach((handle, i) => {
84
+ const el = doc.createElement("span");
85
+ if (isGroup.has(handle)) el.classList.add("caption-group");
86
+ if (isWord.has(handle)) el.classList.add("word");
87
+ const parent = chains[i]?.find((ancestor) => mirrored.has(ancestor));
88
+ (parent ? mirrored.get(parent)! : doc.body).append(el);
89
+ mirrored.set(handle, el);
90
+ });
91
+ const firstWord = words.matches[0]?.handle;
92
+ const firstGroup = groups.matches[0]?.handle;
93
+ const styles = new Map<Element | undefined, Record<string, string> | null>([
94
+ [mirrored.get(firstWord ?? ""), await frameStyles(iframe, firstWord)],
95
+ [mirrored.get(firstGroup ?? ""), await frameStyles(iframe, firstGroup)],
96
+ ]);
97
+ const win = { getComputedStyle: (el: Element) => styles.get(el) ?? {} } as unknown as Window;
98
+ return { doc, win };
99
+ }
100
+
101
+ async function frameCaptionModel(
102
+ iframe: HTMLIFrameElement,
103
+ content: string,
104
+ ): Promise<CaptionModel | null> {
105
+ const [root] = (await queryPreviewElements(iframe, "[data-composition-id]"))?.matches ?? [];
106
+ const rootEl = root ? (await describePreviewElements(iframe, [root.handle]))?.[0] : null;
107
+ const frame = await frameCaptionDom(iframe);
108
+ if (!frame) return null;
109
+ const w = parseInt(attribute(rootEl, "data-width") ?? "1920", 10);
110
+ const h = parseInt(attribute(rootEl, "data-height") ?? "1080", 10);
111
+ const dur = parseFloat(attribute(rootEl, "data-duration") ?? "0");
112
+ return parseCaptionComposition(frame.doc, frame.win, content, w, h, dur);
113
+ }
114
+
21
115
  export function useCaptionDetection({
22
116
  projectId,
23
117
  activeCompPath,
@@ -52,6 +146,51 @@ export function useCaptionDetection({
52
146
  if (!projectId) return;
53
147
 
54
148
  let activating = false;
149
+ // A detection still in flight when the composition changes must not enter edit mode for the old one.
150
+ let disposed = false;
151
+
152
+ const pickCaptionSource = (hostSrcs: Array<string | null>, captionCompId: string | null) => {
153
+ const host = hostSrcs.find((src) => src && src.includes("captions"));
154
+ if (host) return host;
155
+ for (const [id, src] of compIdToSrc) {
156
+ if (id.includes("caption") || src.includes("caption")) return src;
157
+ }
158
+ if (activeCompPath?.includes("captions")) return activeCompPath;
159
+ return captionCompId === null ? null : compIdToSrc.get(captionCompId) || null;
160
+ };
161
+
162
+ const loadCaptions = (
163
+ srcPath: string,
164
+ parse: (content: string) => Promise<CaptionModel | null>,
165
+ ) =>
166
+ studioApiFetch(buildProjectApiPath(projectId, `/files/${encodeURIComponent(srcPath)}`))
167
+ .then((r) => r.json())
168
+ .then(async (data: { content?: string }) => {
169
+ if (disposed || !data.content || useCaptionStore.getState().isEditMode) return;
170
+ const model = await parse(data.content);
171
+ if (disposed || !model || useCaptionStore.getState().isEditMode) return;
172
+ const store = useCaptionStore.getState();
173
+ store.setModel(model);
174
+ store.setSourceFilePath(srcPath);
175
+ store.setEditMode(true);
176
+ captionSync.loadOverrides();
177
+ })
178
+ .catch(() => {});
179
+
180
+ const frameCaptionSource = async (iframe: HTMLIFrameElement) => {
181
+ if (!(await queryPreviewElements(iframe, ".caption-group"))?.matches.length) return null;
182
+ const hosts = await queryPreviewElements(
183
+ iframe,
184
+ "[data-composition-src], [data-composition-file]",
185
+ );
186
+ const handles = (hosts?.matches ?? []).slice(0, MAX_DESCRIBE_HANDLES).map((m) => m.handle);
187
+ const described = handles.length ? await describePreviewElements(iframe, handles) : [];
188
+ const hostSrcs = (described ?? []).map(
189
+ (el) => attribute(el, "data-composition-src") || attribute(el, "data-composition-file"),
190
+ );
191
+ const captionComp = await queryPreviewElements(iframe, '[data-composition-id*="caption"]');
192
+ return pickCaptionSource(hostSrcs, captionComp?.matches[0]?.source.compositionId ?? null);
193
+ };
55
194
 
56
195
  const tryActivateCaptions = () => {
57
196
  const captionState = useCaptionStore.getState();
@@ -61,6 +200,19 @@ export function useCaptionDetection({
61
200
  }
62
201
 
63
202
  const iframe = previewIframeRef.current;
203
+ if (iframe && previewFrameOpaque(iframe)) {
204
+ activating = true;
205
+ void frameCaptionSource(iframe)
206
+ .then((src) =>
207
+ src && !disposed
208
+ ? loadCaptions(src, (content) => frameCaptionModel(iframe, content))
209
+ : null,
210
+ )
211
+ .finally(() => {
212
+ activating = false;
213
+ });
214
+ return;
215
+ }
64
216
  let doc: Document | null = null;
65
217
  let win: Window | null = null;
66
218
  try {
@@ -74,63 +226,31 @@ export function useCaptionDetection({
74
226
  const groups = doc.querySelectorAll(".caption-group");
75
227
  if (groups.length === 0) return;
76
228
 
77
- let captionSrcPath: string | null = null;
78
-
79
- const compHosts = doc.querySelectorAll("[data-composition-src], [data-composition-file]");
80
- for (const host of compHosts) {
81
- const src =
82
- host.getAttribute("data-composition-src") || host.getAttribute("data-composition-file");
83
- if (src && src.includes("captions")) {
84
- captionSrcPath = src;
85
- break;
86
- }
87
- }
88
-
89
- if (!captionSrcPath) {
90
- for (const [id, src] of compIdToSrc) {
91
- if (id.includes("caption") || src.includes("caption")) {
92
- captionSrcPath = src;
93
- break;
94
- }
95
- }
96
- }
97
-
98
- if (!captionSrcPath && activeCompPath?.includes("captions")) {
99
- captionSrcPath = activeCompPath;
100
- }
101
-
102
- if (!captionSrcPath) {
103
- const captionComp = doc.querySelector('[data-composition-id*="caption"]');
104
- if (captionComp) {
105
- const compId = captionComp.getAttribute("data-composition-id") || "";
106
- captionSrcPath = compIdToSrc.get(compId) || null;
107
- }
108
- }
109
-
229
+ const hostSrcs = [
230
+ ...doc.querySelectorAll("[data-composition-src], [data-composition-file]"),
231
+ ].map(
232
+ (host) =>
233
+ host.getAttribute("data-composition-src") || host.getAttribute("data-composition-file"),
234
+ );
235
+ const captionComp = doc.querySelector('[data-composition-id*="caption"]');
236
+ const captionCompId = captionComp
237
+ ? captionComp.getAttribute("data-composition-id") || ""
238
+ : null;
239
+ const captionSrcPath = pickCaptionSource(hostSrcs, captionCompId);
110
240
  if (!captionSrcPath) return;
111
241
 
112
242
  activating = true;
113
- const srcPath = captionSrcPath;
114
- studioApiFetch(buildProjectApiPath(projectId, `/files/${encodeURIComponent(srcPath)}`))
115
- .then((r) => r.json())
116
- .then((data: { content?: string }) => {
117
- if (!data.content || !doc || !win || useCaptionStore.getState().isEditMode) return;
118
- const root = doc.querySelector("[data-composition-id]");
119
- const w = parseInt(root?.getAttribute("data-width") ?? "1920", 10);
120
- const h = parseInt(root?.getAttribute("data-height") ?? "1080", 10);
121
- const dur = parseFloat(root?.getAttribute("data-duration") ?? "0");
122
- const model = parseCaptionComposition(doc, win, data.content, w, h, dur);
123
- if (!model) return;
124
- const store = useCaptionStore.getState();
125
- store.setModel(model);
126
- store.setSourceFilePath(srcPath);
127
- store.setEditMode(true);
128
- captionSync.loadOverrides();
129
- })
130
- .catch(() => {})
131
- .finally(() => {
132
- activating = false;
133
- });
243
+ const frameDoc = doc;
244
+ const frameWin = win;
245
+ void loadCaptions(captionSrcPath, async (content) => {
246
+ const root = frameDoc.querySelector("[data-composition-id]");
247
+ const w = parseInt(root?.getAttribute("data-width") ?? "1920", 10);
248
+ const h = parseInt(root?.getAttribute("data-height") ?? "1080", 10);
249
+ const dur = parseFloat(root?.getAttribute("data-duration") ?? "0");
250
+ return parseCaptionComposition(frameDoc, frameWin, content, w, h, dur);
251
+ }).finally(() => {
252
+ activating = false;
253
+ });
134
254
  };
135
255
 
136
256
  const handleMessage = (e: MessageEvent) => {
@@ -146,6 +266,7 @@ export function useCaptionDetection({
146
266
  tryActivateCaptions();
147
267
 
148
268
  return () => {
269
+ disposed = true;
149
270
  window.removeEventListener("message", handleMessage);
150
271
  };
151
272
  }, [activeCompPath, projectId, compIdToSrc, captionSync, previewIframeRef, livePreviewIframe]);
@@ -724,3 +724,87 @@ it("stores DOM targets in existing history and retains them through undo and red
724
724
  await act(() => hook().redo({ readFile }));
725
725
  expect(history.list().at(-1)?.targets).toEqual(targets);
726
726
  });
727
+
728
+ it("three quick drags are three entries in the list as soon as each drag's saves are in", async () => {
729
+ const { hook, save, history } = await studio();
730
+ const moves = [
731
+ ["A", "B"],
732
+ ["B", "C"],
733
+ ["C", "D"],
734
+ ] as const;
735
+ for (const [i, [before, after]] of moves.entries()) {
736
+ // A drag claims under its own key with no idle limit, as a plain move does, and settles after its save.
737
+ const drag = beginStudioPendingEdit(() => () => {});
738
+ save(after);
739
+ const saved = hook().recordEdit({
740
+ label: "Move layer",
741
+ coalesceKey: `move:${i}`,
742
+ coalesceMs: Number.POSITIVE_INFINITY,
743
+ files: { "index.html": { before, after } },
744
+ });
745
+ drag.settle(saved);
746
+ await act(() => saved);
747
+ }
748
+ await vi.waitFor(() =>
749
+ expect(history.list().filter((entry) => entry.label === "Move layer")).toHaveLength(3),
750
+ );
751
+ });
752
+
753
+ it("the next drag's claim reaches the server after the settled drag's empty claim, however slow that one is", async () => {
754
+ const { hook, save } = await studio();
755
+ const forward = globalThis.fetch;
756
+ const arrived: string[] = [];
757
+ let release = () => {};
758
+ const held = new Promise<void>((resolve) => (release = resolve));
759
+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
760
+ const claim = url.endsWith("/claim")
761
+ ? (JSON.parse(String(init?.body)) as { paths: string[] })
762
+ : null;
763
+ if (claim && !claim.paths.length) await held;
764
+ if (claim) arrived.push(claim.paths.length ? "claim" : "empty");
765
+ return forward(url, init);
766
+ });
767
+ const drag = (i: number, before: string, after: string) => {
768
+ const pending = beginStudioPendingEdit(() => () => {});
769
+ save(after);
770
+ const saved = hook().recordEdit({
771
+ label: "Move layer",
772
+ coalesceKey: `move:${i}`,
773
+ coalesceMs: Number.POSITIVE_INFINITY,
774
+ files: { "index.html": { before, after } },
775
+ });
776
+ pending.settle(saved);
777
+ return saved;
778
+ };
779
+ await act(() => drag(0, "A", "B"));
780
+ const next = drag(1, "B", "C");
781
+ await new Promise((resolve) => setTimeout(resolve, 20));
782
+ release();
783
+ await act(() => next);
784
+ expect(arrived.slice(0, 3)).toEqual(["claim", "empty", "claim"]);
785
+ });
786
+
787
+ it("a gesture that writes twice under one key stays one entry once it settles", async () => {
788
+ const { hook, save, history } = await studio();
789
+ const resize = beginStudioPendingEdit(() => () => {});
790
+ const writes = (async () => {
791
+ for (const [before, after] of [
792
+ ["A", "B"],
793
+ ["B", "C"],
794
+ ] as const) {
795
+ save(after);
796
+ await hook().recordEdit({
797
+ label: "Resize layer",
798
+ coalesceKey: "tx:resize",
799
+ coalesceMs: Number.POSITIVE_INFINITY,
800
+ files: { "index.html": { before, after } },
801
+ });
802
+ }
803
+ })();
804
+ resize.settle(writes);
805
+ await act(() => writes);
806
+ await vi.waitFor(() =>
807
+ expect(history.list().filter((entry) => entry.label === "Resize layer")).toHaveLength(1),
808
+ );
809
+ expect(history.list().find((entry) => entry.label === "Resize layer")?.files.length).toBe(1);
810
+ });
@@ -3,7 +3,10 @@ import type { HistoryListItem, HistoryResult } from "@hyperframes/studio-server"
3
3
  import { studioFileContentVersion, studioWriteHeaders } from "../utils/studioFileVersion";
4
4
  import type { RestoreFiles } from "../utils/gsapUndoRestore";
5
5
  import { studioApiFetch } from "../utils/studioApiFetch";
6
- import { setStudioPendingEditClaimClock } from "../utils/studioPendingEdits";
6
+ import {
7
+ setStudioPendingEditClaimClock,
8
+ setStudioPendingEditsSettled,
9
+ } from "../utils/studioPendingEdits";
7
10
  import type { RecordEditInput } from "../utils/studioFileHistory";
8
11
  import { generateId } from "../utils/generateId";
9
12
 
@@ -41,6 +44,7 @@ interface HistoryView {
41
44
  forward: NextStep | null;
42
45
  }
43
46
 
47
+ const APP_KEEPS_NO_HISTORY = 404;
44
48
  const EMPTY: HistoryView = { entries: [], back: null, forward: null };
45
49
  /** ponytail: the newest entries' content is kept; older ones step through the server only. */
46
50
  const OWN_ENTRIES_KEPT = 100;
@@ -201,12 +205,28 @@ function redoneAt(view: HistoryView): number | null {
201
205
  return view.entries.find((entry) => entry.id === undo?.undoes)?.endedAt ?? null;
202
206
  }
203
207
 
208
+ function closeHeldClaimWithAClaimOfNothing(
209
+ projectId: string,
210
+ heldClaimRef: { current: { paths: string[]; at: number } | null },
211
+ refresh: () => Promise<void>,
212
+ ): Promise<void> {
213
+ if (!heldClaimRef.current) return Promise.resolve();
214
+ heldClaimRef.current = null;
215
+ return post(historyUrl(projectId, "/claim"), { label: "Edited in Studio", paths: [] }).then(
216
+ (reply) => {
217
+ if (reply.ok) void refresh();
218
+ },
219
+ );
220
+ }
221
+
204
222
  /** Studio's undo over the server's project history: an edit claims what it wrote; Cmd+Z steps the person's. */
223
+ // fallow-ignore-next-line complexity
205
224
  export function usePersistentEditHistory({ projectId }: UsePersistentEditHistoryOptions) {
206
225
  const [view, setView] = useState<HistoryView>(EMPTY);
207
226
  const [loaded, setLoaded] = useState(false);
208
227
  // A coalescing claim the server just took, until `refresh()` brings its entry into `view`.
209
228
  const heldClaimRef = useRef<{ paths: string[]; at: number } | null>(null);
229
+ const claimsAfterTheClose = useRef<Promise<void>>(Promise.resolve());
210
230
  const projectIdRef = useRef(projectId);
211
231
  projectIdRef.current = projectId;
212
232
  const [own] = useState(createOwnHistory);
@@ -239,11 +259,24 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistory
239
259
  return () => setStudioPendingEditClaimClock(null);
240
260
  }, [own]);
241
261
 
262
+ useEffect(() => {
263
+ if (!projectId) return;
264
+ setStudioPendingEditsSettled(() => {
265
+ claimsAfterTheClose.current = closeHeldClaimWithAClaimOfNothing(
266
+ projectId,
267
+ heldClaimRef,
268
+ refresh,
269
+ );
270
+ });
271
+ return () => setStudioPendingEditsSettled(null);
272
+ }, [projectId, refresh]);
273
+
242
274
  const recordEdit = useCallback(
243
275
  async ({ label, coalesceKey, coalesceMs, files, targets, created = [] }: RecordEditInput) => {
244
276
  if (!projectId) return;
245
277
  const paths = [...Object.keys(files), ...created];
246
278
  own.overtake();
279
+ await claimsAfterTheClose.current;
247
280
  const reply = await post(historyUrl(projectId, "/claim"), {
248
281
  label,
249
282
  paths,
@@ -286,8 +319,8 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistory
286
319
  );
287
320
  heldClaimRef.current = null;
288
321
  void refresh();
289
- // 404: this app keeps no history, so there is nothing to step.
290
- if (!posted.ok && posted.status === 404) return { ok: false, reason: "empty" };
322
+ if (!posted.ok && posted.status === APP_KEEPS_NO_HISTORY)
323
+ return { ok: false, reason: "empty" };
291
324
  if (!posted.ok) return { ok: false, reason: "failed", message: posted.error };
292
325
  const reply = posted.body as HistoryResult;
293
326
  if (!reply.ok) {
package/src/index.ts CHANGED
@@ -117,6 +117,7 @@ export { ImageThumbnail } from "./player/components/ImageThumbnail";
117
117
  export type { ImageThumbnailProps } from "./player/components/ImageThumbnail";
118
118
  export { useRenderClipContent } from "./hooks/useRenderClipContent";
119
119
  export { useThumbnailStill } from "./hooks/useThumbnailStill";
120
+ export { fetchParsedAnimations, getAnimationsForElement } from "./hooks/useGsapTweenCache";
120
121
  export type { ThumbnailStill, UseThumbnailStillOptions } from "./hooks/useThumbnailStill";
121
122
  export type { UseRenderClipContentOptions } from "./hooks/useRenderClipContent";
122
123
  export type { ThumbnailPriority } from "./player/lib/thumbnailScheduler";
@@ -86,6 +86,11 @@ function shadowPagePhase(iframe: HTMLIFrameElement | null): string {
86
86
  const pageGotTo = (iframe: HTMLIFrameElement | null) =>
87
87
  shadowPlayerReachable(iframe) ? "" : ` Its page had got to: ${shadowPagePhase(iframe)}.`;
88
88
 
89
+ function hyperframesPlayerOf(iframe: HTMLIFrameElement): Element | null {
90
+ const root = iframe.getRootNode();
91
+ return root instanceof ShadowRoot ? root.host : null;
92
+ }
93
+
89
94
  function isDocumentHidden(): boolean {
90
95
  return typeof document !== "undefined" && document.visibilityState === "hidden";
91
96
  }
@@ -293,6 +298,7 @@ export function useShadowPreviewReload({
293
298
  // The store takes the new document's timeline only now that it is the one on screen, and reads it there.
294
299
  const retired = iframeRef.current;
295
300
  iframeRef.current = shadow;
301
+ hyperframesPlayerOf(shadow)?.toggleAttribute("inert", false);
296
302
  pending.commit();
297
303
  shadowIframeRef.current = null;
298
304
  attachIframeShortcutListeners();
@@ -403,6 +409,7 @@ export function useShadowPreviewReload({
403
409
 
404
410
  const setShadowIframeNode = useCallback((node: HTMLIFrameElement | null) => {
405
411
  shadowIframeRef.current = node;
412
+ if (node) hyperframesPlayerOf(node)?.toggleAttribute("inert", true);
406
413
  const gen = budgetGenRef.current;
407
414
  if (!node || !shadowFrameLeftPageRef.current || gen == null || gen !== shadowGenRef.current)
408
415
  return;
@@ -227,6 +227,26 @@ describe("shadow reload readiness and failure", () => {
227
227
  unmount(root);
228
228
  });
229
229
 
230
+ // The player turns pointer events back on for its frame, so a reload's frame would take the live one's clicks.
231
+ it("keeps a reload's player out of clicks and focus until it is promoted, then gives them back", () => {
232
+ const { getApi, gen, root } = beginReload();
233
+ const shadow = makeShadowWithSpies();
234
+ const player = document.createElement("hyperframes-player");
235
+ player.attachShadow({ mode: "open" }).append(shadow.iframe);
236
+ document.body.append(player);
237
+
238
+ act(() => getApi().setShadowIframeNode(shadow.iframe));
239
+ expect(player.hasAttribute("inert")).toBe(true);
240
+
241
+ act(() => {
242
+ getApi().onShadowIframeLoad(gen);
243
+ getApi().onShadowReadyChange(gen, true);
244
+ });
245
+ expect(getApi().iframeRef.current).toBe(shadow.iframe);
246
+ expect(player.hasAttribute("inert")).toBe(false);
247
+ unmount(root);
248
+ });
249
+
230
250
  it("keeps a playing film playing through a reload, from where the live frame had reached", () => {
231
251
  const { getApi, root } = renderTimelinePlayerHarness();
232
252
  const { adapter: liveAdapter, win } = makeAdapterWindow();
@@ -0,0 +1,73 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import { beforeEach, describe, expect, it, vi } from "vitest";
4
+
5
+ const channel = vi.hoisted(() => ({ request: vi.fn() }));
6
+ vi.mock("../player/lib/previewChannel", () => ({
7
+ previewFrameOpaque: () => true,
8
+ previewRequest: channel.request,
9
+ }));
10
+ import { applyUndoRestoreToPreview } from "./gsapUndoRestore";
11
+
12
+ const page = (body: string) => `<html><body>${body}</body></html>`;
13
+ const box = (left: number) => `<div data-hf-id="box" style="left: ${left}px">t</div>`;
14
+ const script = (text: string) => `<script>gsap.timeline().to("#t", ${text});</script>`;
15
+
16
+ function undo(previous: string, restored: string) {
17
+ const reload = vi.fn();
18
+ const iframe = document.createElement("iframe");
19
+ const files = { "index.html": { previous: page(previous), restored: page(restored) } };
20
+ return { reload, strategy: applyUndoRestoreToPreview(iframe, null, files, 2, reload), iframe };
21
+ }
22
+
23
+ const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
24
+
25
+ beforeEach(() => channel.request.mockReset());
26
+
27
+ describe("undo on a sealed preview", () => {
28
+ it("sends the restored attributes to the frame instead of reloading", async () => {
29
+ channel.request.mockResolvedValue({ applied: true });
30
+ const { reload, strategy, iframe } = undo(box(90), box(0));
31
+ expect(strategy).toBe("soft");
32
+ expect(channel.request).toHaveBeenCalledWith(iframe, "restore-attributes", {
33
+ scopes: [
34
+ {
35
+ file: null,
36
+ elements: [
37
+ {
38
+ key: "hf:box",
39
+ attributes: [
40
+ ["data-hf-id", "box"],
41
+ ["style", "left: 0px"],
42
+ ],
43
+ },
44
+ ],
45
+ },
46
+ ],
47
+ scripted: false,
48
+ time: 2,
49
+ });
50
+ await settled();
51
+ expect(reload).not.toHaveBeenCalled();
52
+ });
53
+
54
+ it("reloads when the frame refuses or does not answer", async () => {
55
+ for (const reply of [{ applied: false }, null]) {
56
+ channel.request.mockResolvedValue(reply);
57
+ const { reload } = undo(box(90), box(0));
58
+ await settled();
59
+ expect(reload).toHaveBeenCalledOnce();
60
+ }
61
+ });
62
+
63
+ it("says the files keep a GSAP script, and reloads at once when the script itself changed", () => {
64
+ channel.request.mockResolvedValue({ applied: true });
65
+ undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 1 }"));
66
+ expect(channel.request.mock.calls[0]![2]).toMatchObject({ scripted: true });
67
+ channel.request.mockReset();
68
+ const { reload, strategy } = undo(box(90) + script("{ x: 1 }"), box(0) + script("{ x: 2 }"));
69
+ expect(strategy).toBe("full");
70
+ expect(reload).toHaveBeenCalledOnce();
71
+ expect(channel.request).not.toHaveBeenCalled();
72
+ });
73
+ });
@@ -15,6 +15,8 @@ import { ensureHfIds, isCompositionTemplate } from "@hyperframes/parsers/hf-ids"
15
15
  import { findAuthoredElement, parseSavedSource } from "./authoredSource";
16
16
  import { STUDIO_EDIT_ATTRS } from "../components/editor/manualEditsSeekReapply";
17
17
  import { markScenesStale } from "../player/sceneSwap";
18
+ import { previewFrameOpaque, previewRequest } from "../player/lib/previewChannel";
19
+ import type { EditingParams } from "@hyperframes/core/runtime/editing-port";
18
20
  import { STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR } from "../components/editor/manualEditsTypes";
19
21
  import { countStudioPreviewChange, studioGestureDraws } from "../components/editor/manualEditsDom";
20
22
 
@@ -356,6 +358,68 @@ function repaintWhileReloading(win: PreviewWindow, doc: Document, restored?: str
356
358
  );
357
359
  }
358
360
 
361
+ type SealedRestore = Omit<EditingParams<"restore-attributes">, "time">;
362
+
363
+ const restoredAttributes = (el: Element): [string, string][] =>
364
+ el.getAttributeNames().map((name) => [name, el.getAttribute(name) ?? ""]);
365
+
366
+ // The preview server stamps data-hf-id on every page it serves.
367
+ const stamped = (html: string) => (html.includes("data-hf-id") ? html : ensureHfIds(html));
368
+
369
+ type SealedFile = { scripted: boolean; elements: SealedRestore["scopes"][number]["elements"] };
370
+
371
+ /** One file's changed elements with their restored attributes, or null when it needs a reload. */
372
+ function sealedFile(file: UndoRestoreFile, isActive: boolean): SealedFile | null {
373
+ // A changed script is re-run in the frame, which a sealed preview cannot be asked to do yet.
374
+ if (extractGsapScriptText(file.restored) !== extractGsapScriptText(file.previous)) return null;
375
+ const prevDoc = parseRestoreSource(stamped(file.previous));
376
+ const nextDoc = parseRestoreSource(stamped(file.restored));
377
+ const scripted = restoreScripted(prevDoc, nextDoc, isActive);
378
+ const keys = diffRestoreDocs(prevDoc, nextDoc);
379
+ const restoredByKey = identityElementMap(nextDoc);
380
+ if (scripted === null || !keys || !restoredByKey) return null;
381
+ const elements = keys.map((key) => ({
382
+ key,
383
+ attributes: restoredAttributes(restoredByKey.get(key)!),
384
+ }));
385
+ return { scripted, elements };
386
+ }
387
+
388
+ /** A sealed preview's in-place restore from the files alone, or null when it needs a reload. */
389
+ function sealedRestore(activeDocPath: string, files: RestoreFiles): SealedRestore | null {
390
+ const restore: SealedRestore = { scopes: [], scripted: false };
391
+ for (const [path, file] of Object.entries(files)) {
392
+ const isActive = path === activeDocPath;
393
+ const found = sealedFile(file, isActive);
394
+ if (!found) return null;
395
+ restore.scripted ||= found.scripted;
396
+ if (found.elements.length)
397
+ restore.scopes.push({ file: isActive ? null : path, elements: found.elements });
398
+ }
399
+ return restore.scopes.length ? restore : null;
400
+ }
401
+
402
+ /** Sends the restore to a sealed preview; a refusal, or no answer, reloads it. */
403
+ function applySealedRestore(
404
+ iframe: HTMLIFrameElement,
405
+ activeDocPath: string,
406
+ files: RestoreFiles,
407
+ currentTime: number,
408
+ reloadPreview: () => void,
409
+ ): "soft" | "full" {
410
+ const restore = sealedRestore(activeDocPath, files);
411
+ if (!restore) {
412
+ reloadPreview();
413
+ return "full";
414
+ }
415
+ void previewRequest(iframe, "restore-attributes", { ...restore, time: currentTime }).then(
416
+ (reply) => {
417
+ if (!reply?.applied) reloadPreview();
418
+ },
419
+ );
420
+ return "soft";
421
+ }
422
+
359
423
  /**
360
424
  * Soft-apply an undo/redo restore to the live preview WITHOUT a full iframe
361
425
  * remount (which blanks the frame black and re-flashes the WebGL context). Eligible
@@ -402,6 +466,8 @@ export function applyUndoRestoreToPreview(
402
466
  markScenesStale(iframe, paths);
403
467
  reload();
404
468
  };
469
+ if (iframe && files && previewFrameOpaque(iframe))
470
+ return applySealedRestore(iframe, activeDocPath, files, currentTime, reloadPreview);
405
471
  const doc = iframe?.contentDocument;
406
472
  const win = iframe?.contentWindow as PreviewWindow | null;
407
473
  const plan = doc && files && win ? planRestoreTargets(doc, activeDocPath, files) : null;