Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Babel Plugin Async Load: Lazy load react components when necessary #8017

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,27 @@ module.exports = function( api ) {
isDefault: false,
},
],
[
'@wordpress/babel-plugin-async-load',
{
siteURLSource: '_wpSiteURL',
components: [
{
module: '@wordpress/components',
component: 'CodeEditor',
scripts: [
'wp-codemirror',
'code-editor',
'htmlhint',
'htmlhint-kses',
'csslint',
'jshint',
],
styles: [ 'wp-codemirror', 'code-editor' ],
},
],
},
],
],
env: {
production: {
Expand Down
106 changes: 0 additions & 106 deletions components/code-editor/editor.js

This file was deleted.

143 changes: 77 additions & 66 deletions components/code-editor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,94 +2,105 @@
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { UP, DOWN } from '@wordpress/keycodes';

/**
* Internal dependencies
*/
import CodeEditor from './editor';
import Placeholder from '../../packages/components/src/placeholder';
import Spinner from '../../packages/components/src/spinner';
class CodeEditor extends Component {
constructor() {
super( ...arguments );

function loadScript() {
return new Promise( ( resolve, reject ) => {
const handles = [ 'wp-codemirror', 'code-editor', 'htmlhint', 'csslint', 'jshint' ];
this.onFocus = this.onFocus.bind( this );
this.onBlur = this.onBlur.bind( this );
this.onCursorActivity = this.onCursorActivity.bind( this );
this.onKeyHandled = this.onKeyHandled.bind( this );
}

// Don't load htmlhint-kses unless we need it
if ( window._wpGutenbergCodeEditorSettings.htmlhint.kses ) {
handles.push( 'htmlhint-kses' );
componentDidMount() {
const settings = this.props.settings || window._wpGutenbergCodeEditorSettings;
const instance = wp.codeEditor.initialize( this.textarea, settings );
this.editor = instance.codemirror;

this.editor.on( 'focus', this.onFocus );
this.editor.on( 'blur', this.onBlur );
this.editor.on( 'cursorActivity', this.onCursorActivity );
this.editor.on( 'keyHandled', this.onKeyHandled );

// Pass a reference to the editor back up.
if ( this.props.editorRef ) {
this.props.editorRef( this.editor );
}

const script = document.createElement( 'script' );
script.src = `${ wpApiSettings.schema.url }/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' ];
this.updateFocus();
}

const style = document.createElement( 'link' );
style.rel = 'stylesheet';
style.href = `${ wpApiSettings.schema.url }/wp-admin/load-styles.php?load=${ handles.join( ',' ) }`;
style.onload = resolve;
style.onerror = reject;
componentDidUpdate( prevProps ) {
if ( this.props.value !== prevProps.value && this.editor.getValue() !== this.props.value ) {
this.editor.setValue( this.props.value );
}

document.head.appendChild( style );
} );
}
if ( this.props.focus !== prevProps.focus ) {
this.updateFocus();
}
}

let hasAlreadyLoadedAssets = false;
componentWillUnmount() {
this.editor.on( 'focus', this.onFocus );
this.editor.off( 'blur', this.onBlur );
this.editor.off( 'cursorActivity', this.onCursorActivity );
this.editor.off( 'keyHandled', this.onKeyHandled );

function loadAssets() {
if ( hasAlreadyLoadedAssets ) {
return Promise.resolve();
this.editor.toTextArea();
this.editor = null;
}

return Promise.all( [ loadScript(), loadStyle() ] ).then( () => {
hasAlreadyLoadedAssets = true;
} );
}
onFocus() {
if ( this.props.onFocus ) {
this.props.onFocus();
}
}

class LazyCodeEditor extends Component {
constructor() {
super( ...arguments );
onBlur( editor ) {
if ( this.props.onChange ) {
this.props.onChange( editor.getValue() );
}
}

this.state = {
status: 'pending',
};
onCursorActivity( editor ) {
this.lastCursor = editor.getCursor();
}

componentDidMount() {
loadAssets().then(
() => {
this.setState( { status: 'success' } );
},
() => {
this.setState( { status: 'error' } );
onKeyHandled( editor, name, event ) {
/*
* Pressing UP/DOWN should only move focus to another block if the cursor is
* at the start or end of the editor.
*
* We do this by stopping UP/DOWN from propagating if:
* - We know what the cursor was before this event; AND
* - This event caused the cursor to move
*/
if ( event.keyCode === UP || event.keyCode === DOWN ) {
const areCursorsEqual = ( a, b ) => a.line === b.line && a.ch === b.ch;
if ( this.lastCursor && ! areCursorsEqual( editor.getCursor(), this.lastCursor ) ) {
event.stopImmediatePropagation();
}
);
}
}

render() {
if ( this.state.status === 'pending' ) {
return (
<Placeholder>
<Spinner />
</Placeholder>
);
updateFocus() {
if ( this.props.focus && ! this.editor.hasFocus() ) {
// Need to wait for the next frame to be painted before we can focus the editor
window.requestAnimationFrame( () => {
this.editor.focus();
} );
}

if ( this.state.status === 'error' ) {
return <Placeholder>{ __( 'An unknown error occurred.' ) }</Placeholder>;
if ( ! this.props.focus && this.editor.hasFocus() ) {
document.activeElement.blur();
}
}

return <CodeEditor { ...this.props } />;
render() {
return <textarea ref={ ( ref ) => ( this.textarea = ref ) } defaultValue={ this.props.value } />;
}
}

export default LazyCodeEditor;
export default CodeEditor;
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { set, noop } from 'lodash';
/**
* Internal dependencies
*/
import CodeEditor from '../editor';
import CodeEditor from '../';

describe( 'CodeEditor', () => {
it( 'should render without an error', () => {
Expand Down
4 changes: 4 additions & 0 deletions lib/client-assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ function gutenberg_register_scripts_and_styles() {
filemtime( gutenberg_dir_path() . 'build/compose/index.js' ),
true
);
wp_add_inline_script(
'wp-compose',
sprintf( 'window._wpSiteURL = %s;', json_encode( site_url() ) )
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wonder if this is something where we could just assign onto the component prototype itself, rather than having to have this be part of the transform.

i.e.

sprintf( 'wp.components.CodeEditor.siteURL = %s;', json_encode( site_url() ) )

);
wp_register_script(
'wp-keycodes',
gutenberg_url( 'build/keycodes/index.js' ),
Expand Down
4 changes: 4 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
},
"devDependencies": {
"@babel/core": "7.0.0-beta.52",
"@wordpress/babel-plugin-async-load": "file:packages/babel-plugin-async-load",
"@wordpress/babel-plugin-import-jsx-pragma": "file:packages/babel-plugin-import-jsx-pragma",
"@wordpress/babel-plugin-makepot": "file:packages/babel-plugin-makepot",
"@wordpress/babel-preset-default": "file:packages/babel-preset-default",
Expand Down
1 change: 1 addition & 0 deletions packages/babel-plugin-async-load/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
Loading