-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathgsapSoftReload.ts
More file actions
69 lines (60 loc) · 1.97 KB
/
Copy pathgsapSoftReload.ts
File metadata and controls
69 lines (60 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
type IframeWindow = Window & {
__timelines?: Record<string, { kill?: () => void; pause?: () => void }>;
__player?: { getTime?: () => number; seek?: (t: number) => void };
__hfForceTimelineRebind?: () => void;
__hfSuppressSceneMutations?: <T>(fn: () => T) => T;
__hfStudioManualEditsApply?: () => void;
gsap?: { timeline?: (...args: unknown[]) => unknown };
};
function findGsapScriptElement(doc: Document): HTMLScriptElement | null {
const scripts = doc.querySelectorAll<HTMLScriptElement>("script:not([src])");
for (const script of scripts) {
const text = script.textContent || "";
if (
text.includes("gsap.timeline") ||
text.includes("__timelines") ||
text.includes(".to(") ||
text.includes(".set(")
)
return script;
}
return null;
}
export function applySoftReload(iframe: HTMLIFrameElement | null, scriptText: string): boolean {
if (!iframe || !scriptText) return false;
const win = iframe.contentWindow as IframeWindow | null;
const doc = iframe.contentDocument;
if (!win || !doc) return false;
if (!win.gsap || !win.__hfForceTimelineRebind) return false;
const oldScriptEl = findGsapScriptElement(doc);
if (!oldScriptEl) return false;
const currentTime = win.__player?.getTime?.() ?? 0;
const doReload = () => {
const timelines = win.__timelines;
if (timelines) {
for (const key of Object.keys(timelines)) {
try {
timelines[key]?.kill?.();
} catch {}
delete timelines[key];
}
}
oldScriptEl.remove();
const newScript = doc.createElement("script");
newScript.textContent = `(function(){${scriptText}\n})();`;
doc.body.appendChild(newScript);
win.__hfForceTimelineRebind?.();
win.__player?.seek?.(currentTime);
win.__hfStudioManualEditsApply?.();
};
try {
if (win.__hfSuppressSceneMutations) {
win.__hfSuppressSceneMutations(doReload);
} else {
doReload();
}
return true;
} catch {
return false;
}
}