Skip to content

Commit

Permalink
Widget Screen: Fix unsaved changes notification (#31757)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mamaduka authored May 21, 2021
1 parent cc41feb commit 8f98406
Showing 1 changed file with 12 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { __ } from '@wordpress/i18n';
import { useEffect } from '@wordpress/element';
import { useSelect } from '@wordpress/data';

/**
* Internal dependencies
*/
import { store as editWidgetsStore } from '../../store';

/**
* Warns the user if there are unsaved changes before leaving the editor.
*
Expand All @@ -14,12 +19,11 @@ import { useSelect } from '@wordpress/data';
* @return {WPComponent} The component.
*/
export default function UnsavedChangesWarning() {
const getIsDirty = useSelect( ( select ) => {
return () => {
const { __experimentalGetDirtyEntityRecords } = select( 'core' );
const dirtyEntityRecords = __experimentalGetDirtyEntityRecords();
return dirtyEntityRecords.length > 0;
};
const isDirty = useSelect( ( select ) => {
const { getEditedWidgetAreas } = select( editWidgetsStore );
const editedWidgetAreas = getEditedWidgetAreas();

return editedWidgetAreas?.length > 0;
}, [] );

useEffect( () => {
Expand All @@ -31,11 +35,7 @@ export default function UnsavedChangesWarning() {
* @return {?string} Warning prompt message, if unsaved changes exist.
*/
const warnIfUnsavedChanges = ( event ) => {
// We need to call the selector directly in the listener to avoid race
// conditions with `BrowserURL` where `componentDidUpdate` gets the
// new value of `isEditedPostDirty` before this component does,
// causing this component to incorrectly think a trashed post is still dirty.
if ( getIsDirty() ) {
if ( isDirty ) {
event.returnValue = __(
'You have unsaved changes. If you proceed, they will be lost.'
);
Expand All @@ -48,7 +48,7 @@ export default function UnsavedChangesWarning() {
return () => {
window.removeEventListener( 'beforeunload', warnIfUnsavedChanges );
};
}, [ getIsDirty ] );
}, [ isDirty ] );

return null;
}

0 comments on commit 8f98406

Please sign in to comment.