-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
390 lines (356 loc) · 10.9 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import {
useState,
createPortal,
forwardRef,
useMemo,
useEffect,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
useResizeObserver,
useMergeRefs,
useRefEffect,
useDisabled,
} from '@wordpress/compose';
import { __experimentalStyleProvider as StyleProvider } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import { useBlockSelectionClearer } from '../block-selection-clearer';
import { useWritingFlow } from '../writing-flow';
import { getCompatibilityStyles } from './get-compatibility-styles';
import { store as blockEditorStore } from '../../store';
import calculateScale from '../../utils/calculate-scale';
function bubbleEvent( event, Constructor, frame ) {
const init = {};
for ( const key in event ) {
init[ key ] = event[ key ];
}
// Check if the event is a MouseEvent generated within the iframe.
// If so, adjust the coordinates to be relative to the position of
// the iframe. This ensures that components such as Draggable
// receive coordinates relative to the window, instead of relative
// to the iframe. Without this, the Draggable event handler would
// result in components "jumping" position as soon as the user
// drags over the iframe.
if ( event instanceof frame.contentDocument.defaultView.MouseEvent ) {
const rect = frame.getBoundingClientRect();
init.clientX += rect.left;
init.clientY += rect.top;
}
const newEvent = new Constructor( event.type, init );
if ( init.defaultPrevented ) {
newEvent.preventDefault();
}
const cancelled = ! frame.dispatchEvent( newEvent );
if ( cancelled ) {
event.preventDefault();
}
}
/**
* Bubbles some event types (keydown, keypress, and dragover) to parent document
* document to ensure that the keyboard shortcuts and drag and drop work.
*
* Ideally, we should remove event bubbling in the future. Keyboard shortcuts
* should be context dependent, e.g. actions on blocks like Cmd+A should not
* work globally outside the block editor.
*
* @param {Document} iframeDocument Document to attach listeners to.
*/
function useBubbleEvents( iframeDocument ) {
return useRefEffect( () => {
const { defaultView } = iframeDocument;
if ( ! defaultView ) {
return;
}
const { frameElement } = defaultView;
const html = iframeDocument.documentElement;
const eventTypes = [ 'dragover', 'mousemove' ];
const handlers = {};
for ( const name of eventTypes ) {
handlers[ name ] = ( event ) => {
const prototype = Object.getPrototypeOf( event );
const constructorName = prototype.constructor.name;
const Constructor = window[ constructorName ];
bubbleEvent( event, Constructor, frameElement );
};
html.addEventListener( name, handlers[ name ] );
}
return () => {
for ( const name of eventTypes ) {
html.removeEventListener( name, handlers[ name ] );
}
};
} );
}
function Iframe( {
contentRef,
children,
tabIndex = 0,
shouldZoom = false,
readonly,
forwardedRef: ref,
title = __( 'Editor canvas' ),
...props
} ) {
const { resolvedAssets, isPreviewMode, isZoomOutMode } = useSelect(
( select ) => {
const { getSettings, __unstableGetEditorMode } =
select( blockEditorStore );
const settings = getSettings();
return {
resolvedAssets: settings.__unstableResolvedAssets,
isPreviewMode: settings.__unstableIsPreviewMode,
isZoomOutMode: __unstableGetEditorMode() === 'zoom-out',
};
},
[]
);
const { styles = '', scripts = '' } = resolvedAssets;
const [ iframeDocument, setIframeDocument ] = useState();
const [ bodyClasses, setBodyClasses ] = useState( [] );
const clearerRef = useBlockSelectionClearer();
const [ before, writingFlowRef, after ] = useWritingFlow();
const [
contentResizeListener,
{ height: contentHeight, width: contentWidth },
] = useResizeObserver();
// When zoom-out mode is enabled, the iframe is scaled down to fit the
// content within the viewport.
// At 1000px wide, the iframe is scaled to 45%.
// At 400px wide, the iframe is scaled to 90%.
const scale =
isZoomOutMode && shouldZoom
? calculateScale(
{
maxWidth: 1000,
minWidth: 400,
maxScale: 0.45,
minScale: 0.9,
},
contentWidth
)
: 1;
const frameSize = isZoomOutMode ? 100 : 0;
const setRef = useRefEffect( ( node ) => {
node._load = () => {
setIframeDocument( node.contentDocument );
};
let iFrameDocument;
// Prevent the default browser action for files dropped outside of dropzones.
function preventFileDropDefault( event ) {
event.preventDefault();
}
function onLoad() {
const { contentDocument, ownerDocument } = node;
const { documentElement } = contentDocument;
iFrameDocument = contentDocument;
documentElement.classList.add( 'block-editor-iframe__html' );
clearerRef( documentElement );
// Ideally ALL classes that are added through get_body_class should
// be added in the editor too, which we'll somehow have to get from
// the server in the future (which will run the PHP filters).
setBodyClasses(
Array.from( ownerDocument.body.classList ).filter(
( name ) =>
name.startsWith( 'admin-color-' ) ||
name.startsWith( 'post-type-' ) ||
name === 'wp-embed-responsive'
)
);
contentDocument.dir = ownerDocument.dir;
for ( const compatStyle of getCompatibilityStyles() ) {
if ( contentDocument.getElementById( compatStyle.id ) ) {
continue;
}
contentDocument.head.appendChild(
compatStyle.cloneNode( true )
);
if ( ! isPreviewMode ) {
// eslint-disable-next-line no-console
console.warn(
`${ compatStyle.id } was added to the iframe incorrectly. Please use block.json or enqueue_block_assets to add styles to the iframe.`,
compatStyle
);
}
}
iFrameDocument.addEventListener(
'dragover',
preventFileDropDefault,
false
);
iFrameDocument.addEventListener(
'drop',
preventFileDropDefault,
false
);
}
node.addEventListener( 'load', onLoad );
return () => {
delete node._load;
node.removeEventListener( 'load', onLoad );
iFrameDocument?.removeEventListener(
'dragover',
preventFileDropDefault
);
iFrameDocument?.removeEventListener(
'drop',
preventFileDropDefault
);
};
}, [] );
const disabledRef = useDisabled( { isDisabled: ! readonly } );
const bodyRef = useMergeRefs( [
useBubbleEvents( iframeDocument ),
contentRef,
clearerRef,
writingFlowRef,
disabledRef,
] );
// Correct doctype is required to enable rendering in standards
// mode. Also preload the styles to avoid a flash of unstyled
// content.
const html = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script>window.frameElement._load()</script>
<style>
html{
height: auto !important;
min-height: 100%;
}
body {
margin: 0;
/* Default background color in case zoom out mode background
colors the html element */
background: white;
}
</style>
${ styles }
${ scripts }
</head>
<body>
<script>document.currentScript.parentElement.remove()</script>
</body>
</html>`;
const [ src, cleanup ] = useMemo( () => {
const _src = URL.createObjectURL(
new window.Blob( [ html ], { type: 'text/html' } )
);
return [ _src, () => URL.revokeObjectURL( _src ) ];
}, [ html ] );
useEffect( () => cleanup, [ cleanup ] );
// We need to counter the margin created by scaling the iframe. If the scale
// is e.g. 0.45, then the top + bottom margin is 0.55 (1 - scale). Just the
// top or bottom margin is 0.55 / 2 ((1 - scale) / 2).
const marginFromScaling = ( contentHeight * ( 1 - scale ) ) / 2;
useEffect( () => {
if ( iframeDocument && scale !== 1 ) {
iframeDocument.documentElement.style.transform = `scale( ${ scale } )`;
iframeDocument.documentElement.style.marginTop = `${ frameSize }px`;
iframeDocument.documentElement.style.marginBottom = `${
-marginFromScaling * 2 + frameSize
}px`;
return () => {
iframeDocument.documentElement.style.transform = '';
iframeDocument.documentElement.style.marginTop = '';
iframeDocument.documentElement.style.marginBottom = '';
};
}
}, [ scale, frameSize, marginFromScaling, iframeDocument ] );
// Make sure to not render the before and after focusable div elements in view
// mode. They're only needed to capture focus in edit mode.
const shouldRenderFocusCaptureElements = tabIndex >= 0 && ! isPreviewMode;
return (
<>
{ shouldRenderFocusCaptureElements && before }
{ /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */ }
<iframe
{ ...props }
style={ {
border: 0,
...props.style,
height: props.style?.height,
transition: 'all .3s',
} }
ref={ useMergeRefs( [ ref, setRef ] ) }
tabIndex={ tabIndex }
// Correct doctype is required to enable rendering in standards
// mode. Also preload the styles to avoid a flash of unstyled
// content.
src={ src }
title={ title }
onKeyDown={ ( event ) => {
if ( props.onKeyDown ) {
props.onKeyDown( event );
}
// If the event originates from inside the iframe, it means
// it bubbled through the portal, but only with React
// events. We need to to bubble native events as well,
// though by doing so we also trigger another React event,
// so we need to stop the propagation of this event to avoid
// duplication.
else if (
event.currentTarget.ownerDocument !==
event.target.ownerDocument
) {
event.stopPropagation();
bubbleEvent(
event,
window.KeyboardEvent,
event.currentTarget
);
}
} }
>
{ iframeDocument &&
createPortal(
// We want to prevent React events from bubbling throught the iframe
// we bubble these manually.
/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */
<body
ref={ bodyRef }
className={ classnames(
'block-editor-iframe__body',
'editor-styles-wrapper',
...bodyClasses
) }
>
{ contentResizeListener }
<StyleProvider document={ iframeDocument }>
{ children }
</StyleProvider>
</body>,
iframeDocument.documentElement
) }
</iframe>
{ shouldRenderFocusCaptureElements && after }
</>
);
}
function IframeIfReady( props, ref ) {
const isInitialised = useSelect(
( select ) =>
select( blockEditorStore ).getSettings().__internalIsInitialized,
[]
);
// We shouldn't render the iframe until the editor settings are initialised.
// The initial settings are needed to get the styles for the srcDoc, which
// cannot be changed after the iframe is mounted. srcDoc is used to to set
// the initial iframe HTML, which is required to avoid a flash of unstyled
// content.
if ( ! isInitialised ) {
return null;
}
return <Iframe { ...props } forwardedRef={ ref } />;
}
export default forwardRef( IframeIfReady );