-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
95 lines (77 loc) · 2.01 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
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import CodeEditor from './editor';
import Placeholder from '../placeholder';
import Spinner from '../spinner';
function loadScript() {
return new Promise( ( resolve, reject ) => {
const handles = [ 'wp-codemirror', 'code-editor', 'htmlhint', 'csslint', 'jshint' ];
// Don't load htmlhint-kses unless we need it
if ( window._wpGutenbergCodeEditorSettings.htmlhint.kses ) {
handles.push( 'htmlhint-kses' );
}
const script = document.createElement( 'script' );
script.src = `/wp-admin/load-scripts.php?load=${ handles.join( ',' ) }`;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild( script );
} );
}
function loadStyle() {
return new Promise( ( resolve, reject ) => {
const handles = [ 'wp-codemirror', 'code-editor' ];
const style = document.createElement( 'link' );
style.rel = 'stylesheet';
style.href = `/wp-admin/load-styles.php?load=${ handles.join( ',' ) }`;
style.onload = resolve;
style.onerror = reject;
document.head.appendChild( style );
} );
}
let hasAlreadyLoadedAssets = false;
function loadAssets() {
if ( hasAlreadyLoadedAssets ) {
return Promise.resolve();
}
return Promise.all( [ loadScript(), loadStyle() ] ).then( () => {
hasAlreadyLoadedAssets = true;
} );
}
class LazyCodeEditor extends Component {
constructor() {
super( ...arguments );
this.state = {
status: 'pending',
};
}
componentDidMount() {
loadAssets().then(
() => {
this.setState( { status: 'success' } );
},
() => {
this.setState( { status: 'error' } );
}
);
}
render() {
if ( this.state.status === 'pending' ) {
return (
<Placeholder>
<Spinner />
</Placeholder>
);
}
if ( this.state.status === 'error' ) {
return <Placeholder>{ __( 'An unknown error occurred.' ) }</Placeholder>;
}
return <CodeEditor { ...this.props } />;
}
}
export default LazyCodeEditor;