-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
293 lines (255 loc) · 7.65 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
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import {
useState,
createPortal,
forwardRef,
useEffect,
useMemo,
useReducer,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useMergeRefs, useRefEffect } from '@wordpress/compose';
import { __experimentalStyleProvider as StyleProvider } from '@wordpress/components';
/**
* Internal dependencies
*/
import { useBlockSelectionClearer } from '../block-selection-clearer';
import { useWritingFlow } from '../writing-flow';
const BODY_CLASS_NAME = 'editor-styles-wrapper';
const BLOCK_PREFIX = 'wp-block';
/**
* Clones stylesheets targetting the editor canvas to the given document. A
* stylesheet is considered targetting the editor a canvas if it contains the
* `editor-styles-wrapper`, `wp-block`, or `wp-block-*` class selectors.
*
* Ideally, this hook should be removed in the future and styles should be added
* explicitly as editor styles.
*
* @param {Document} doc The document to append cloned stylesheets to.
*/
function styleSheetsCompat( doc ) {
// Search the document for stylesheets targetting the editor canvas.
Array.from( document.styleSheets ).forEach( ( styleSheet ) => {
try {
// May fail for external styles.
// eslint-disable-next-line no-unused-expressions
styleSheet.cssRules;
} catch ( e ) {
return;
}
const { ownerNode, cssRules } = styleSheet;
if ( ! cssRules ) {
return;
}
// Generally, ignore inline styles. We add inline styles belonging to a
// stylesheet later, which may or may not match the selectors.
if ( ownerNode.tagName !== 'LINK' ) {
return;
}
// Don't try to add the reset styles, which were removed as a dependency
// from `edit-blocks` for the iframe since we don't need to reset admin
// styles.
if ( ownerNode.id === 'wp-reset-editor-styles-css' ) {
return;
}
const isMatch = Array.from( cssRules ).find(
( { selectorText } ) =>
selectorText &&
( selectorText.includes( `.${ BODY_CLASS_NAME }` ) ||
selectorText.includes( `.${ BLOCK_PREFIX }` ) )
);
if ( isMatch && ! doc.getElementById( ownerNode.id ) ) {
// Display warning once we have a way to add style dependencies to the editor.
// See: https://github.com/WordPress/gutenberg/pull/37466.
doc.head.appendChild( ownerNode.cloneNode( true ) );
// Add inline styles belonging to the stylesheet.
const inlineCssId = ownerNode.id.replace( '-css', '-inline-css' );
const inlineCssElement = document.getElementById( inlineCssId );
if ( inlineCssElement ) {
doc.head.appendChild( inlineCssElement.cloneNode( true ) );
}
}
} );
}
/**
* 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} doc Document to attach listeners to.
*/
function bubbleEvents( doc ) {
const { defaultView } = doc;
const { frameElement } = defaultView;
function bubbleEvent( event ) {
const prototype = Object.getPrototypeOf( event );
const constructorName = prototype.constructor.name;
const Constructor = window[ constructorName ];
const init = {};
for ( const key in event ) {
init[ key ] = event[ key ];
}
if ( event instanceof defaultView.MouseEvent ) {
const rect = frameElement.getBoundingClientRect();
init.clientX += rect.left;
init.clientY += rect.top;
}
const newEvent = new Constructor( event.type, init );
const cancelled = ! frameElement.dispatchEvent( newEvent );
if ( cancelled ) {
event.preventDefault();
}
}
const eventTypes = [ 'dragover' ];
for ( const name of eventTypes ) {
doc.addEventListener( name, bubbleEvent );
}
}
function useParsedAssets( html ) {
return useMemo( () => {
const doc = document.implementation.createHTMLDocument( '' );
doc.body.innerHTML = html;
return Array.from( doc.body.children );
}, [ html ] );
}
async function loadScript( head, { id, src } ) {
return new Promise( ( resolve, reject ) => {
const script = head.ownerDocument.createElement( 'script' );
script.id = id;
if ( src ) {
script.src = src;
script.onload = () => resolve();
script.onerror = () => reject();
} else {
resolve();
}
head.appendChild( script );
} );
}
function Iframe(
{ contentRef, children, head, tabIndex = 0, assets, ...props },
ref
) {
const [ , forceRender ] = useReducer( () => ( {} ) );
const [ iframeDocument, setIframeDocument ] = useState();
const [ bodyClasses, setBodyClasses ] = useState( [] );
const styles = useParsedAssets( assets?.styles );
const scripts = useParsedAssets( assets?.scripts );
const clearerRef = useBlockSelectionClearer();
const [ before, writingFlowRef, after ] = useWritingFlow();
const setRef = useRefEffect( ( node ) => {
function setDocumentIfReady() {
const { contentDocument, ownerDocument } = node;
const { readyState, documentElement } = contentDocument;
if ( readyState !== 'interactive' && readyState !== 'complete' ) {
return false;
}
bubbleEvents( contentDocument );
setIframeDocument( contentDocument );
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;
documentElement.removeChild( contentDocument.head );
documentElement.removeChild( contentDocument.body );
return true;
}
if ( setDocumentIfReady() ) {
return;
}
// Document is not immediately loaded in Firefox.
node.addEventListener( 'load', () => {
setDocumentIfReady();
} );
}, [] );
const headRef = useRefEffect( ( element ) => {
scripts
.reduce(
( promise, script ) =>
promise.then( () => loadScript( element, script ) ),
Promise.resolve()
)
.finally( () => {
// When script are loaded, re-render blocks to allow them
// to initialise.
forceRender();
} );
}, [] );
const bodyRef = useMergeRefs( [ contentRef, clearerRef, writingFlowRef ] );
useEffect( () => {
if ( iframeDocument ) {
styleSheetsCompat( iframeDocument );
}
}, [ iframeDocument ] );
head = (
<>
<style>{ 'body{margin:0}' }</style>
{ styles.map(
( { tagName, href, id, rel, media, textContent } ) => {
const TagName = tagName.toLowerCase();
if ( TagName === 'style' ) {
return (
<TagName { ...{ id } } key={ id }>
{ textContent }
</TagName>
);
}
return (
<TagName { ...{ href, id, rel, media } } key={ id } />
);
}
) }
{ head }
</>
);
return (
<>
{ tabIndex >= 0 && before }
<iframe
{ ...props }
ref={ useMergeRefs( [ ref, setRef ] ) }
tabIndex={ tabIndex }
title={ __( 'Editor canvas' ) }
>
{ iframeDocument &&
createPortal(
<>
<head ref={ headRef }>{ head }</head>
<body
ref={ bodyRef }
className={ classnames(
BODY_CLASS_NAME,
...bodyClasses
) }
>
<StyleProvider document={ iframeDocument }>
{ children }
</StyleProvider>
</body>
</>,
iframeDocument.documentElement
) }
</iframe>
{ tabIndex >= 0 && after }
</>
);
}
export default forwardRef( Iframe );