Skip to content

Commit

Permalink
Merge pull request #5755 from WordPress/fix/post-text-editor
Browse files Browse the repository at this point in the history
Fix autosave while editing a post using the Text Mode editor
  • Loading branch information
noisysocks authored Mar 29, 2018
2 parents 7a0150b + af209c2 commit f2777d7
Showing 1 changed file with 33 additions and 19 deletions.
52 changes: 33 additions & 19 deletions editor/components/post-text-editor/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/**
* External dependencies
*/
import { connect } from 'react-redux';
import Textarea from 'react-autosize-textarea';
import { connect } from 'react-redux';

/**
* WordPress dependencies
Expand All @@ -18,41 +18,55 @@ import { getEditedPostContent } from '../../store/selectors';
import { editPost, resetBlocks, checkTemplateValidity } from '../../store/actions';

class PostTextEditor extends Component {
constructor( props ) {
constructor() {
super( ...arguments );

this.onChange = this.onChange.bind( this );
this.onPersist = this.onPersist.bind( this );
this.startEditing = this.startEditing.bind( this );
this.edit = this.edit.bind( this );
this.stopEditing = this.stopEditing.bind( this );

this.state = {
initialValue: props.value,
value: null,
isDirty: false,
};
}

onChange( event ) {
this.props.onChange( event.target.value );
componentWillReceiveProps( nextProps ) {
// If we receive a new value while we're editing (but before we've made
// changes), go ahead and clobber the local state
if ( this.props.value !== nextProps.value && this.state.value && ! this.state.isDirty ) {
this.setState( { value: nextProps.value } );
}
}

startEditing() {
// Copying the post content into local state ensures that edits won't be
// clobbered by changes to global editor state
this.setState( { value: this.props.value } );
}

onPersist( event ) {
const { value } = event.target;
if ( value !== this.state.initialValue ) {
this.props.onPersist( value );
edit( event ) {
const value = event.target.value;
this.props.onChange( value );
this.setState( { value, isDirty: true } );
}

this.setState( {
initialValue: value,
} );
stopEditing() {
if ( this.state.isDirty ) {
this.props.onPersist( this.state.value );
}

this.setState( { value: null, isDirty: false } );
}

render() {
const { value } = this.props;

return (
<Textarea
autoComplete="off"
value={ value }
onChange={ this.onChange }
onBlur={ this.onPersist }
value={ this.state.value || this.props.value }
onFocus={ this.startEditing }
onChange={ this.edit }
onBlur={ this.stopEditing }
className="editor-post-text-editor"
/>
);
Expand Down

0 comments on commit f2777d7

Please sign in to comment.