-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
52 lines (47 loc) · 1.52 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useEffect } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
/**
* Warns the user if there are unsaved changes before leaving the editor.
* Compatible with Post Editor and Site Editor.
*
* @return {WPComponent} The component.
*/
export default function UnsavedChangesWarning() {
const isDirty = useSelect( ( select ) => {
return () => {
const { __experimentalGetDirtyEntityRecords } = select( 'core' );
const dirtyEntityRecords = __experimentalGetDirtyEntityRecords();
return dirtyEntityRecords.length > 0;
};
}, [] );
/**
* Warns the user if there are unsaved changes before leaving the editor.
*
* @param {Event} event `beforeunload` event.
*
* @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 ( isDirty() ) {
event.returnValue = __(
'You have unsaved changes. If you proceed, they will be lost.'
);
return event.returnValue;
}
};
useEffect( () => {
window.addEventListener( 'beforeunload', warnIfUnsavedChanges );
return () => {
window.removeEventListener( 'beforeunload', warnIfUnsavedChanges );
};
}, [] );
return null;
}