Skip to content

Commit

Permalink
Allow CodeEditor to be focused via the focus prop
Browse files Browse the repository at this point in the history
  • Loading branch information
noisysocks committed Jan 8, 2018
1 parent 7e7cbcc commit 37445c7
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
6 changes: 5 additions & 1 deletion blocks/library/html/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,11 @@ registerBlockType( 'core/html', {
{ preview ? (
<SandBox html={ attributes.content } />
) : (
<CodeEditor value={ attributes.content } onChange={ content => setAttributes( { content } ) } />
<CodeEditor
value={ attributes.content }
focus={ !! focus }
onChange={ content => setAttributes( { content } ) }
/>
) }
</div>
) ),
Expand Down
7 changes: 7 additions & 0 deletions components/code-editor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ The source code to load into the code editor.
- Type: `string`
- Required: Yes

### focus

Whether or not the code editor should be focused.

- Type: `boolean`
- Required: No

### onChange

The function called when the user has modified the source code via the
Expand Down
21 changes: 18 additions & 3 deletions components/code-editor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,20 @@ class CodeEditor extends Component {

this.editor.on( 'blur', this.onBlur );
this.editor.on( 'keyHandled', this.onKeyHandled );

// TODO: We shouldn't need this RAF...
window.requestAnimationFrame( () => {
this.updateFocus();
} );
}

componentWillReceiveProps( { value } ) {
if ( this.props.value !== value && this.editor.getValue() !== value ) {
this.editor.setValue( value );
componentDidUpdate( prevProps ) {
if ( this.props.value !== prevProps.value && this.editor.getValue() !== this.props.value ) {
this.editor.setValue( this.props.value );
}

if ( this.props.focus !== prevProps.focus ) {
this.updateFocus();
}
}

Expand All @@ -46,6 +55,12 @@ class CodeEditor extends Component {
event.stopImmediatePropagation();
}

updateFocus() {
if ( this.props.focus && ! this.editor.hasFocus() ) {
this.editor.focus();
}
}

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

0 comments on commit 37445c7

Please sign in to comment.