Skip to content
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 @@ -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;
}