-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
251 lines (217 loc) · 6.29 KB
/
index.js
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/**
* WordPress dependencies
*/
import {
renderToString,
useRef,
useState,
useEffect,
} from '@wordpress/element';
/**
* Internal dependencies
*/
import FocusableIframe from '../focusable-iframe';
const observeAndResizeJS = `
( function() {
var observer;
if ( ! window.MutationObserver || ! document.body || ! window.parent ) {
return;
}
function sendResize() {
var clientBoundingRect = document.body.getBoundingClientRect();
window.parent.postMessage( {
action: 'resize',
width: clientBoundingRect.width,
height: clientBoundingRect.height,
}, '*' );
}
observer = new MutationObserver( sendResize );
observer.observe( document.body, {
attributes: true,
attributeOldValue: false,
characterData: true,
characterDataOldValue: false,
childList: true,
subtree: true
} );
window.addEventListener( 'load', sendResize, true );
// Hack: Remove viewport unit styles, as these are relative
// the iframe root and interfere with our mechanism for
// determining the unconstrained page bounds.
function removeViewportStyles( ruleOrNode ) {
if( ruleOrNode.style ) {
[ 'width', 'height', 'minHeight', 'maxHeight' ].forEach( function( style ) {
if ( /^\\d+(vmin|vmax|vh|vw)$/.test( ruleOrNode.style[ style ] ) ) {
ruleOrNode.style[ style ] = '';
}
} );
}
}
Array.prototype.forEach.call( document.querySelectorAll( '[style]' ), removeViewportStyles );
Array.prototype.forEach.call( document.styleSheets, function( stylesheet ) {
Array.prototype.forEach.call( stylesheet.cssRules || stylesheet.rules, removeViewportStyles );
} );
document.body.style.position = 'absolute';
document.body.style.width = '100%';
document.body.setAttribute( 'data-resizable-iframe-connected', '' );
sendResize();
// Resize events can change the width of elements with 100% width, but we don't
// get an DOM mutations for that, so do the resize when the window is resized, too.
window.addEventListener( 'resize', sendResize, true );
} )();`;
const style = `
body {
margin: 0;
}
html,
body,
body > div,
body > div iframe {
width: 100%;
}
html.wp-has-aspect-ratio,
body.wp-has-aspect-ratio,
body.wp-has-aspect-ratio > div,
body.wp-has-aspect-ratio > div iframe {
height: 100%;
overflow: hidden; /* If it has an aspect ratio, it shouldn't scroll. */
}
body > div > * {
margin-top: 0 !important; /* Has to have !important to override inline styles. */
margin-bottom: 0 !important;
}
`;
export default function Sandbox( {
html = '',
title = '',
type,
styles = [],
scripts = [],
onFocus,
} ) {
const ref = useRef();
const [ width, setWidth ] = useState( 0 );
const [ height, setHeight ] = useState( 0 );
function isFrameAccessible() {
try {
return !! ref.current.contentDocument.body;
} catch ( e ) {
return false;
}
}
function trySandbox( forceRerender = false ) {
if ( ! isFrameAccessible() ) {
return;
}
const { contentDocument, ownerDocument } = ref.current;
const { body } = contentDocument;
if (
! forceRerender &&
null !== body.getAttribute( 'data-resizable-iframe-connected' )
) {
return;
}
// put the html snippet into a html document, and then write it to the iframe's document
// we can use this in the future to inject custom styles or scripts.
// Scripts go into the body rather than the head, to support embedded content such as Instagram
// that expect the scripts to be part of the body.
const htmlDoc = (
<html
lang={ ownerDocument.documentElement.lang }
className={ type }
>
<head>
<title>{ title }</title>
<style dangerouslySetInnerHTML={ { __html: style } } />
{ styles.map( ( rules, i ) => (
<style
key={ i }
dangerouslySetInnerHTML={ { __html: rules } }
/>
) ) }
</head>
<body
data-resizable-iframe-connected="data-resizable-iframe-connected"
className={ type }
>
<div dangerouslySetInnerHTML={ { __html: html } } />
<script
type="text/javascript"
dangerouslySetInnerHTML={ {
__html: observeAndResizeJS,
} }
/>
{ scripts.map( ( src ) => (
<script key={ src } src={ src } />
) ) }
</body>
</html>
);
// writing the document like this makes it act in the same way as if it was
// loaded over the network, so DOM creation and mutation, script execution, etc.
// all work as expected
contentDocument.open();
contentDocument.write( '<!DOCTYPE html>' + renderToString( htmlDoc ) );
contentDocument.close();
}
useEffect( () => {
trySandbox();
function tryNoForceSandbox() {
trySandbox( false );
}
function checkMessageForResize( event ) {
const iframe = ref.current;
// Verify that the mounted element is the source of the message
if ( ! iframe || iframe.contentWindow !== event.source ) {
return;
}
// Attempt to parse the message data as JSON if passed as string
let data = event.data || {};
if ( 'string' === typeof data ) {
try {
data = JSON.parse( data );
} catch ( e ) {}
}
// Update the state only if the message is formatted as we expect,
// i.e. as an object with a 'resize' action.
if ( 'resize' !== data.action ) {
return;
}
setWidth( data.width );
setHeight( data.height );
}
const { ownerDocument } = ref.current;
const { defaultView } = ownerDocument;
// This used to be registered using <iframe onLoad={} />, but it made the iframe blank
// after reordering the containing block. See these two issues for more details:
// https://github.com/WordPress/gutenberg/issues/6146
// https://github.com/facebook/react/issues/18752
ref.current.addEventListener( 'load', tryNoForceSandbox, false );
defaultView.addEventListener( 'message', checkMessageForResize );
return () => {
ref.current?.removeEventListener(
'load',
tryNoForceSandbox,
false
);
defaultView.addEventListener( 'message', checkMessageForResize );
};
}, [] );
useEffect( () => {
trySandbox();
}, [ title, type, styles, scripts ] );
useEffect( () => {
trySandbox( true );
}, [ html ] );
return (
<FocusableIframe
iframeRef={ ref }
title={ title }
className="components-sandbox"
sandbox="allow-scripts allow-same-origin allow-presentation"
onFocus={ onFocus }
width={ Math.ceil( width ) }
height={ Math.ceil( height ) }
/>
);
}