-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
use-mark-persistent.js
40 lines (35 loc) · 1.12 KB
/
use-mark-persistent.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
/**
* WordPress dependencies
*/
import { useLayoutEffect, useRef } from '@wordpress/element';
import { useDispatch } from '@wordpress/data';
/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../store';
export function useMarkPersistent( { html, value } ) {
const previousTextRef = useRef();
const hasActiveFormats = !! value.activeFormats?.length;
const { __unstableMarkLastChangeAsPersistent } =
useDispatch( blockEditorStore );
// Must be set synchronously to make sure it applies to the last change.
useLayoutEffect( () => {
// Ignore mount.
if ( ! previousTextRef.current ) {
previousTextRef.current = value.text;
return;
}
// Text input, so don't create an undo level for every character.
// Create an undo level after 1 second of no input.
if ( previousTextRef.current !== value.text ) {
const timeout = window.setTimeout( () => {
__unstableMarkLastChangeAsPersistent();
}, 1000 );
previousTextRef.current = value.text;
return () => {
window.clearTimeout( timeout );
};
}
__unstableMarkLastChangeAsPersistent();
}, [ html, hasActiveFormats ] );
}