forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoverlay-manager.ts
More file actions
84 lines (70 loc) · 2.41 KB
/
overlay-manager.ts
File metadata and controls
84 lines (70 loc) · 2.41 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
let iframeReference: HTMLIFrameElement = null;
let iframeRenderedAt = 0;
export function resetOverlay() {
try {
// We add a delay to unmounting the iframe if the iframe has only just
// appeared. We want to do this, because we want to prevent a flicker for
// the user, which is a bad perceivement.
const delay = Date.now() - iframeRenderedAt > 1000 ? 0 : 1000;
setTimeout(() => {
if (iframeReference) {
iframeReference.style.opacity = '0';
setTimeout(() => {
if (iframeReference.parentNode) {
document.body.removeChild(iframeReference);
}
}, 500);
}
}, delay);
} catch (e) {
/* nothing */
}
}
const setIframeStyle = (iframe: HTMLIFrameElement, showFullScreen: boolean) => {
iframe.setAttribute(
'style',
showFullScreen
? `position: fixed; top: 0; left: 0; width: 100%; height: 100%; border: none; z-index: 214748366;opacity: 1;transition: opacity 0.15s ease-in;`
: `position: fixed; top: 10px; left: 10px; height: 45px; width: 45px; border-radius: 2px; border: none; z-index: 214748366; opacity: 0;transition: opacity 0.15s ease-in;`
);
};
function createIframe(showFullScreen: boolean): Promise<HTMLIFrameElement> {
return new Promise(resolve => {
iframeRenderedAt = Date.now();
if (iframeReference) {
document.body.appendChild(iframeReference);
requestAnimationFrame(() => {
iframeReference.style.opacity = '1';
});
setIframeStyle(iframeReference, showFullScreen);
resolve(iframeReference);
return;
}
const iframe = document.createElement('iframe');
setIframeStyle(iframe, showFullScreen);
iframe.setAttribute('id', 'frame');
iframeReference = iframe;
document.body.appendChild(iframe);
requestAnimationFrame(() => {
iframe.style.opacity = '1';
});
if (iframe.contentDocument) {
resolve(iframe);
} else if (document.getElementById('frame')) {
document.getElementById('frame').onload = () => {
resolve(iframe);
};
} else {
resolve(iframe);
}
});
}
export async function createOverlay(html: string, showFullScreen: boolean) {
const iframe: HTMLIFrameElement = await createIframe(showFullScreen);
const isMounted = !!document.getElementById('frame');
if (!isMounted) {
document.body.appendChild(iframe);
}
iframe.contentDocument.body.innerHTML = html;
return iframe;
}