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

Site Editor: Avoid content loss when switching between editors #41407

Merged
merged 2 commits into from
May 27, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,19 @@
*/
import Textarea from 'react-autosize-textarea';

/**
* WordPress dependencies
*/
/**
* WordPress dependencies
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
import { useEffect, useState, useRef } from '@wordpress/element';
import { useInstanceId } from '@wordpress/compose';
import { VisuallyHidden } from '@wordpress/components';

export default function CodeEditorTextArea( { value, onChange, onInput } ) {
const [ stateValue, setStateValue ] = useState( value );
const [ isDirty, setIsDirty ] = useState( false );
const instanceId = useInstanceId( CodeEditorTextArea );
const valueRef = useRef();

if ( ! isDirty && stateValue !== value ) {
setStateValue( value );
Expand All @@ -42,6 +37,7 @@ export default function CodeEditorTextArea( { value, onChange, onInput } ) {
onInput( newValue );
setStateValue( newValue );
setIsDirty( true );
valueRef.current = newValue;
};

/**
Expand All @@ -56,6 +52,15 @@ export default function CodeEditorTextArea( { value, onChange, onInput } ) {
}
};

// Ensure changes aren't lost when component unmounts.
useEffect( () => {
return () => {
if ( valueRef.current ) {
onChange( valueRef.current );
}
};
}, [] );

return (
<>
<VisuallyHidden
Expand Down