Skip to content

Commit

Permalink
Merge pull request #1163 from WordPress/fix/freeform-block-unnecessar…
Browse files Browse the repository at this point in the history
…y-focus-or-blur

Update freeform block to apply focus/blur fix
  • Loading branch information
tiny-james authored Jun 15, 2017
2 parents 38e3fdc + a7f2b97 commit 90d7ea1
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions blocks/library/freeform/freeform-block.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export default class FreeformBlock extends wp.element.Component {
this.onSelectionChange = this.onSelectionChange.bind( this );
this.onChange = this.onChange.bind( this );
this.onFocus = this.onFocus.bind( this );
this.isEndOfEditor = this.isEndOfEditor.bind( this );
this.updateFocus = this.updateFocus.bind( this );
this.updateContent = this.updateContent.bind( this );
this.setContent = this.setContent.bind( this );
Expand Down Expand Up @@ -200,16 +201,39 @@ export default class FreeformBlock extends wp.element.Component {
}
}

isEndOfEditor() {
const range = this.editor.selection.getRng();
if ( range.endOffset !== range.endContainer.textContent.length || ! range.collapsed ) {
return false;
}
const start = range.endContainer;
const body = this.editor.getBody();
let element = start;
while ( element !== body ) {
const child = element;
element = element.parentNode;
if ( element.lastChild !== child ) {
return false;
}
}
return true;
}

updateFocus() {
const { focus } = this.props;
const isActive = this.isActive();

if ( focus ) {
this.editor.focus();
if ( ! isActive ) {
this.editor.focus();
}

// Offset = -1 means we should focus the end of the editable
if ( focus.offset === -1 ) {
if ( focus.offset === -1 && ! this.isEndOfEditor() ) {
this.editor.selection.select( this.editor.getBody(), true );
this.editor.selection.collapse( false );
}
} else {
} else if ( isActive ) {
this.editor.getBody().blur();
}
}
Expand Down

0 comments on commit 90d7ea1

Please sign in to comment.