-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuseDebouncedSyncDocument.ts
62 lines (53 loc) · 1.68 KB
/
useDebouncedSyncDocument.ts
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
53
54
55
56
57
58
59
60
61
62
import { useCallback } from 'react';
import { PlateEditor } from '@udecode/plate';
import {
useSyncDocument,
UseSyncDocumentOptions,
} from '~/lib/editor/useSyncDocument';
import { useGlobalEvent } from '~/lib/globalEvents';
import { useBeforeUnload } from '~/lib/useBeforeUnload';
import { useDebounce } from '~/lib/useDebounce';
import { documentDataForUpload } from './documentDataForUpload';
export interface UseDebouncedSyncDocumentOptions
extends UseSyncDocumentOptions {
editor: PlateEditor | null;
}
export const useDebouncedSyncDocument = ({
editor,
...options
}: UseDebouncedSyncDocumentOptions) => {
const syncDocumentState = useSyncDocument(options);
const { updateDocument, isDirty: updateIsDirty } = syncDocumentState;
const [debouncedUpdateTitle, titleIsDirty] = useDebounce(
(title: string) => updateDocument({ title }),
750,
[updateDocument]
);
const setTitle = useCallback(
(title: string) => {
const normalizedTitle = title.replace(/[\n\r]+/g, '');
debouncedUpdateTitle(normalizedTitle);
},
[debouncedUpdateTitle]
);
const [debouncedUpdateBody, bodyIsDirty] = useDebounce(
() => editor && updateDocument(documentDataForUpload(editor)),
750,
[editor, updateDocument]
);
/**
* When an upload becomes complete, this affects what data is sent to the
* server even though the editor value hasn't changed.
*/
useGlobalEvent('s3File:uploadComplete', debouncedUpdateBody, [
debouncedUpdateBody,
]);
const isDirty = updateIsDirty || titleIsDirty || bodyIsDirty;
useBeforeUnload(isDirty);
return {
...syncDocumentState,
setTitle,
onBodyChange: debouncedUpdateBody,
isDirty,
};
};