2024-05-22 15:57:17 +02:00
|
|
|
import { useState, useEffect, useCallback, RefObject, useRef } from 'react';
|
2020-05-02 17:41:07 +02:00
|
|
|
import { FormNote, defaultFormNote, ResourceInfos } from './types';
|
2020-11-07 17:59:37 +02:00
|
|
|
import AsyncActionQueue from '@joplin/lib/AsyncActionQueue';
|
2020-05-02 17:41:07 +02:00
|
|
|
import { handleResourceDownloadMode } from './resourceHandling';
|
2023-07-26 18:36:21 +02:00
|
|
|
import { splitHtml } from '@joplin/renderer/HtmlToHtml';
|
2020-11-20 18:04:47 +02:00
|
|
|
import Setting from '@joplin/lib/models/Setting';
|
|
|
|
import usePrevious from '../../hooks/usePrevious';
|
2024-10-27 23:19:38 +02:00
|
|
|
import attachedResources, { clearResourceCache } from '@joplin/lib/utils/attachedResources';
|
2024-05-22 15:57:17 +02:00
|
|
|
import { MarkupToHtml } from '@joplin/renderer';
|
2021-01-22 19:41:11 +02:00
|
|
|
import Note from '@joplin/lib/models/Note';
|
2021-01-23 17:51:19 +02:00
|
|
|
import ResourceFetcher from '@joplin/lib/services/ResourceFetcher';
|
2024-03-02 16:25:27 +02:00
|
|
|
import { NoteEntity } from '@joplin/lib/services/database/types';
|
2024-04-01 16:34:22 +02:00
|
|
|
import { focus } from '@joplin/lib/utils/focusHandler';
|
2024-05-22 15:57:17 +02:00
|
|
|
import Logger from '@joplin/utils/Logger';
|
2024-05-28 12:30:56 +02:00
|
|
|
import eventManager, { EventName } from '@joplin/lib/eventManager';
|
|
|
|
import DecryptionWorker from '@joplin/lib/services/DecryptionWorker';
|
2024-11-08 17:32:05 +02:00
|
|
|
import useQueuedAsyncEffect from '@joplin/lib/hooks/useQueuedAsyncEffect';
|
2024-05-22 15:57:17 +02:00
|
|
|
|
|
|
|
const logger = Logger.create('useFormNote');
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
export interface OnLoadEvent {
|
2020-11-12 21:29:22 +02:00
|
|
|
formNote: FormNote;
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
|
2023-08-18 10:31:45 +02:00
|
|
|
export interface HookDependencies {
|
2020-11-12 21:29:22 +02:00
|
|
|
noteId: string;
|
2024-11-08 17:32:05 +02:00
|
|
|
editorId: string;
|
2020-11-12 21:29:22 +02:00
|
|
|
isProvisional: boolean;
|
2024-05-21 02:28:19 +02:00
|
|
|
titleInputRef: RefObject<HTMLInputElement>;
|
2024-04-05 13:16:49 +02:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
|
2020-11-12 21:29:22 +02:00
|
|
|
editorRef: any;
|
|
|
|
onBeforeLoad(event: OnLoadEvent): void;
|
|
|
|
onAfterLoad(event: OnLoadEvent): void;
|
2024-11-10 16:04:46 +02:00
|
|
|
builtInEditorVisible: boolean;
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
|
2024-05-22 15:57:17 +02:00
|
|
|
type MapFormNoteCallback = (previousFormNote: FormNote)=> FormNote;
|
|
|
|
export type OnSetFormNote = (newFormNote: FormNote|MapFormNoteCallback)=> void;
|
2024-05-21 02:28:19 +02:00
|
|
|
|
2024-05-28 12:30:56 +02:00
|
|
|
function installResourceChangeHandler(onResourceChangeHandler: ()=> void) {
|
2020-05-02 17:41:07 +02:00
|
|
|
ResourceFetcher.instance().on('downloadComplete', onResourceChangeHandler);
|
|
|
|
ResourceFetcher.instance().on('downloadStarted', onResourceChangeHandler);
|
|
|
|
DecryptionWorker.instance().on('resourceDecrypted', onResourceChangeHandler);
|
2024-05-28 12:30:56 +02:00
|
|
|
eventManager.on(EventName.ResourceChange, onResourceChangeHandler);
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
|
2024-05-28 12:30:56 +02:00
|
|
|
function uninstallResourceChangeHandler(onResourceChangeHandler: ()=> void) {
|
2020-05-02 17:41:07 +02:00
|
|
|
ResourceFetcher.instance().off('downloadComplete', onResourceChangeHandler);
|
|
|
|
ResourceFetcher.instance().off('downloadStarted', onResourceChangeHandler);
|
|
|
|
DecryptionWorker.instance().off('resourceDecrypted', onResourceChangeHandler);
|
2024-05-28 12:30:56 +02:00
|
|
|
eventManager.off(EventName.ResourceChange, onResourceChangeHandler);
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
|
2020-11-12 21:13:28 +02:00
|
|
|
function resourceInfosChanged(a: ResourceInfos, b: ResourceInfos): boolean {
|
2020-06-07 12:01:33 +02:00
|
|
|
if (Object.keys(a).length !== Object.keys(b).length) return true;
|
|
|
|
|
|
|
|
for (const id in a) {
|
|
|
|
const r1 = a[id];
|
|
|
|
const r2 = b[id];
|
|
|
|
if (!r2) return true;
|
|
|
|
if (r1.item.updated_time !== r2.item.updated_time) return true;
|
|
|
|
if (r1.item.encryption_applied !== r2.item.encryption_applied) return true;
|
|
|
|
if (r1.item.is_shared !== r2.item.is_shared) return true;
|
|
|
|
if (r1.localState.fetch_status !== r2.localState.fetch_status) return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-11-08 17:32:05 +02:00
|
|
|
type InitNoteStateCallback = (note: NoteEntity, isNew: boolean)=> Promise<FormNote>;
|
2024-11-10 16:04:46 +02:00
|
|
|
const useRefreshFormNoteOnChange = (formNoteRef: RefObject<FormNote>, editorId: string, noteId: string, initNoteState: InitNoteStateCallback, builtInEditorVisible: boolean) => {
|
2024-11-08 17:32:05 +02:00
|
|
|
// Increasing the value of this counter cancels any ongoing note refreshes and starts
|
|
|
|
// a new refresh.
|
|
|
|
const [formNoteRefreshScheduled, setFormNoteRefreshScheduled] = useState<number>(0);
|
2024-11-10 16:04:46 +02:00
|
|
|
const prevBuiltInEditorVisible = usePrevious<boolean>(builtInEditorVisible);
|
2024-11-08 17:32:05 +02:00
|
|
|
|
|
|
|
useQueuedAsyncEffect(async (event) => {
|
|
|
|
if (formNoteRefreshScheduled <= 0) return;
|
|
|
|
if (formNoteRef.current.hasChanged) {
|
|
|
|
logger.info('Form note changed between scheduling a refresh and the refresh itself. Cancelling the refresh.');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.info('Sync has finished and note has never been changed - reloading it');
|
|
|
|
|
|
|
|
const loadNote = async () => {
|
|
|
|
const n = await Note.load(noteId);
|
|
|
|
if (event.cancelled || formNoteRef.current.hasChanged) return;
|
|
|
|
|
|
|
|
// Normally should not happened because if the note has been deleted via sync
|
|
|
|
// it would not have been loaded in the editor (due to note selection changing
|
|
|
|
// on delete)
|
|
|
|
if (!n) {
|
|
|
|
logger.warn('Trying to reload note that has been deleted:', noteId);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
await initNoteState(n, false);
|
|
|
|
if (event.cancelled) return;
|
|
|
|
setFormNoteRefreshScheduled(0);
|
|
|
|
};
|
|
|
|
|
|
|
|
await loadNote();
|
|
|
|
}, [formNoteRefreshScheduled, noteId, editorId, initNoteState]);
|
|
|
|
|
|
|
|
const refreshFormNote = useCallback(() => {
|
|
|
|
// Increase the counter to cancel any ongoing refresh attempts
|
|
|
|
// and start a new one.
|
|
|
|
setFormNoteRefreshScheduled(formNoteRefreshScheduled + 1);
|
|
|
|
}, [formNoteRefreshScheduled]);
|
|
|
|
|
2024-11-10 16:04:46 +02:00
|
|
|
// When switching from the plugin editor to the built-in editor, we refresh the note since the
|
|
|
|
// plugin may have modified it via the data API.
|
|
|
|
useEffect(() => {
|
|
|
|
if (prevBuiltInEditorVisible !== builtInEditorVisible && builtInEditorVisible) {
|
|
|
|
refreshFormNote();
|
|
|
|
}
|
|
|
|
}, [builtInEditorVisible, prevBuiltInEditorVisible, refreshFormNote]);
|
|
|
|
|
|
|
|
|
2024-11-08 17:32:05 +02:00
|
|
|
useEffect(() => {
|
|
|
|
if (!noteId) return ()=>{};
|
|
|
|
|
|
|
|
let cancelled = false;
|
|
|
|
|
|
|
|
type ChangeEventSlice = { itemId: string; changeId: string };
|
|
|
|
const listener = ({ itemId, changeId }: ChangeEventSlice) => {
|
|
|
|
// If this change came from the current editor, it should already be
|
|
|
|
// handled by calls to `setFormNote`. If events from the current editor
|
|
|
|
// aren't ignored, most user-activated note changes (e.g. a keypress)
|
|
|
|
// cause the note to refresh. (Undesired refreshes can cause the cursor to jump).
|
|
|
|
const isExternalChange = !(changeId ?? 'unknown').endsWith(editorId);
|
|
|
|
if (itemId === noteId && !cancelled && isExternalChange) {
|
|
|
|
if (formNoteRef.current.hasChanged) return;
|
|
|
|
refreshFormNote();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
eventManager.on(EventName.ItemChange, listener);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
eventManager.off(EventName.ItemChange, listener);
|
|
|
|
cancelled = true;
|
|
|
|
};
|
|
|
|
}, [formNoteRef, noteId, editorId, refreshFormNote]);
|
|
|
|
};
|
|
|
|
|
2020-11-12 21:13:28 +02:00
|
|
|
export default function useFormNote(dependencies: HookDependencies) {
|
2024-11-10 16:04:46 +02:00
|
|
|
const {
|
|
|
|
noteId, isProvisional, titleInputRef, editorRef, onBeforeLoad, onAfterLoad, builtInEditorVisible, editorId,
|
|
|
|
} = dependencies;
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
const [formNote, setFormNote] = useState<FormNote>(defaultFormNote());
|
|
|
|
const [isNewNote, setIsNewNote] = useState(false);
|
|
|
|
const previousNoteId = usePrevious(formNote.id);
|
|
|
|
const [resourceInfos, setResourceInfos] = useState<ResourceInfos>({});
|
|
|
|
|
2024-05-22 15:57:17 +02:00
|
|
|
const formNoteRef = useRef(formNote);
|
|
|
|
formNoteRef.current = formNote;
|
|
|
|
|
2024-11-08 17:32:05 +02:00
|
|
|
const initNoteState: InitNoteStateCallback = useCallback(async (n, isNewNote) => {
|
2020-05-02 17:41:07 +02:00
|
|
|
let originalCss = '';
|
|
|
|
|
|
|
|
if (n.markup_language === MarkupToHtml.MARKUP_LANGUAGE_HTML) {
|
2023-07-26 18:36:21 +02:00
|
|
|
const splitted = splitHtml(n.body);
|
2020-05-02 17:41:07 +02:00
|
|
|
originalCss = splitted.css;
|
|
|
|
}
|
|
|
|
|
2023-09-25 17:16:07 +02:00
|
|
|
const newFormNote = {
|
2020-05-02 17:41:07 +02:00
|
|
|
id: n.id,
|
|
|
|
title: n.title,
|
|
|
|
body: n.body,
|
|
|
|
is_todo: n.is_todo,
|
|
|
|
parent_id: n.parent_id,
|
2024-03-02 16:25:27 +02:00
|
|
|
deleted_time: n.deleted_time,
|
2024-08-22 22:53:39 +02:00
|
|
|
is_conflict: n.is_conflict,
|
2020-05-02 17:41:07 +02:00
|
|
|
bodyWillChangeId: 0,
|
|
|
|
bodyChangeId: 0,
|
|
|
|
markup_language: n.markup_language,
|
|
|
|
saveActionQueue: new AsyncActionQueue(300),
|
|
|
|
originalCss: originalCss,
|
|
|
|
hasChanged: false,
|
|
|
|
user_updated_time: n.user_updated_time,
|
|
|
|
encryption_applied: n.encryption_applied,
|
|
|
|
};
|
|
|
|
|
2024-05-22 15:57:17 +02:00
|
|
|
logger.debug('Initializing note state');
|
|
|
|
|
2020-05-02 17:41:07 +02:00
|
|
|
// Note that for performance reason,the call to setResourceInfos should
|
|
|
|
// be first because it loads the resource infos in an async way. If we
|
|
|
|
// swap them, the formNote will be updated first and rendered, then the
|
|
|
|
// the resources will load, and the note will be re-rendered.
|
2024-05-22 15:57:17 +02:00
|
|
|
const resources = await attachedResources(n.body);
|
|
|
|
|
|
|
|
// If the user changes the note while resources are loading, this can lead to
|
|
|
|
// a note being incorrectly marked as "unchanged".
|
|
|
|
if (!isNewNote && formNoteRef.current?.hasChanged) {
|
|
|
|
logger.info('Cancelled note refresh -- form note changed while loading attached resources.');
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
setResourceInfos(resources);
|
2020-05-02 17:41:07 +02:00
|
|
|
setFormNote(newFormNote);
|
2024-11-08 17:32:05 +02:00
|
|
|
formNoteRef.current = newFormNote;
|
2020-05-02 17:41:07 +02:00
|
|
|
|
2024-05-22 15:57:17 +02:00
|
|
|
logger.debug('Resource info and form note set.');
|
|
|
|
|
2020-05-02 17:41:07 +02:00
|
|
|
await handleResourceDownloadMode(n.body);
|
|
|
|
|
|
|
|
return newFormNote;
|
2024-05-22 15:57:17 +02:00
|
|
|
}, []);
|
2020-05-02 17:41:07 +02:00
|
|
|
|
2024-11-10 16:04:46 +02:00
|
|
|
useRefreshFormNoteOnChange(formNoteRef, editorId, noteId, initNoteState, builtInEditorVisible);
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
useEffect(() => {
|
2020-11-16 19:11:31 +02:00
|
|
|
if (!noteId) {
|
|
|
|
if (formNote.id) setFormNote(defaultFormNote());
|
|
|
|
return () => {};
|
|
|
|
}
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
if (formNote.id === noteId) return () => {};
|
|
|
|
|
|
|
|
let cancelled = false;
|
|
|
|
|
2024-05-22 15:57:17 +02:00
|
|
|
logger.debug('Loading existing note', noteId);
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
function handleAutoFocus(noteIsTodo: boolean) {
|
|
|
|
if (!isProvisional) return;
|
|
|
|
|
|
|
|
const focusSettingName = noteIsTodo ? 'newTodoFocus' : 'newNoteFocus';
|
|
|
|
|
|
|
|
requestAnimationFrame(() => {
|
|
|
|
if (Setting.value(focusSettingName) === 'title') {
|
2024-04-01 16:34:22 +02:00
|
|
|
if (titleInputRef.current) focus('useFormNote::handleAutoFocus', titleInputRef.current);
|
2020-05-02 17:41:07 +02:00
|
|
|
} else {
|
2020-12-02 12:36:00 +02:00
|
|
|
if (editorRef.current) editorRef.current.execCommand({ name: 'editor.focus' });
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async function loadNote() {
|
|
|
|
const n = await Note.load(noteId);
|
|
|
|
if (cancelled) return;
|
|
|
|
if (!n) throw new Error(`Cannot find note with ID: ${noteId}`);
|
2024-05-22 15:57:17 +02:00
|
|
|
logger.debug('Loaded note:', n);
|
2020-05-02 17:41:07 +02:00
|
|
|
|
2023-09-25 17:16:07 +02:00
|
|
|
await onBeforeLoad({ formNote });
|
2020-05-02 17:41:07 +02:00
|
|
|
|
2024-05-22 15:57:17 +02:00
|
|
|
const newFormNote = await initNoteState(n, true);
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
setIsNewNote(isProvisional);
|
|
|
|
|
2023-09-25 17:16:07 +02:00
|
|
|
await onAfterLoad({ formNote: newFormNote });
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
handleAutoFocus(!!n.is_todo);
|
|
|
|
}
|
|
|
|
|
2020-11-25 16:40:25 +02:00
|
|
|
void loadNote();
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
cancelled = true;
|
|
|
|
};
|
2022-08-19 13:10:04 +02:00
|
|
|
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
|
2020-05-02 17:41:07 +02:00
|
|
|
}, [noteId, isProvisional, formNote]);
|
|
|
|
|
2024-04-05 13:16:49 +02:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
|
2023-02-20 17:02:29 +02:00
|
|
|
const onResourceChange = useCallback(async (event: any = null) => {
|
2020-05-02 17:41:07 +02:00
|
|
|
const resourceIds = await Note.linkedResourceIds(formNote.body);
|
|
|
|
if (!event || resourceIds.indexOf(event.id) >= 0) {
|
|
|
|
clearResourceCache();
|
2024-05-28 12:30:56 +02:00
|
|
|
const newResourceInfos = await attachedResources(formNote.body);
|
|
|
|
setResourceInfos(newResourceInfos);
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
}, [formNote.body]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
installResourceChangeHandler(onResourceChange);
|
|
|
|
return () => {
|
|
|
|
uninstallResourceChangeHandler(onResourceChange);
|
|
|
|
};
|
|
|
|
}, [onResourceChange]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (previousNoteId !== formNote.id) {
|
2020-11-25 16:40:25 +02:00
|
|
|
void onResourceChange();
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
}, [previousNoteId, formNote.id, onResourceChange]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
let cancelled = false;
|
|
|
|
|
|
|
|
async function runEffect() {
|
|
|
|
const r = await attachedResources(formNote.body);
|
|
|
|
if (cancelled) return;
|
2020-11-12 21:13:28 +02:00
|
|
|
setResourceInfos((previous: ResourceInfos) => {
|
2020-06-07 12:01:33 +02:00
|
|
|
return resourceInfosChanged(previous, r) ? r : previous;
|
|
|
|
});
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|
|
|
|
|
2020-11-25 16:40:25 +02:00
|
|
|
void runEffect();
|
2020-05-02 17:41:07 +02:00
|
|
|
|
|
|
|
return () => {
|
|
|
|
cancelled = true;
|
|
|
|
};
|
|
|
|
}, [formNote.body]);
|
|
|
|
|
2024-05-22 15:57:17 +02:00
|
|
|
// Currently, useFormNote relies on formNoteRef being up-to-date immediately after the editor
|
|
|
|
// changes, with no delay during which async code can run. Even a small delay (e.g. that introduced
|
|
|
|
// by a setState -> useEffect) can lead to a race condition. See https://github.com/laurent22/joplin/issues/8960.
|
|
|
|
const onSetFormNote: OnSetFormNote = useCallback(newFormNote => {
|
2024-11-08 17:32:05 +02:00
|
|
|
let newNote;
|
2024-05-22 15:57:17 +02:00
|
|
|
if (typeof newFormNote === 'function') {
|
2024-11-08 17:32:05 +02:00
|
|
|
newNote = newFormNote(formNoteRef.current);
|
2024-05-22 15:57:17 +02:00
|
|
|
} else {
|
2024-11-08 17:32:05 +02:00
|
|
|
newNote = newFormNote;
|
2024-05-22 15:57:17 +02:00
|
|
|
}
|
2024-11-08 17:32:05 +02:00
|
|
|
formNoteRef.current = newNote;
|
|
|
|
setFormNote(newNote);
|
2024-05-22 15:57:17 +02:00
|
|
|
}, [setFormNote]);
|
|
|
|
|
|
|
|
return {
|
|
|
|
isNewNote,
|
|
|
|
formNote,
|
|
|
|
setFormNote: onSetFormNote,
|
|
|
|
resourceInfos,
|
|
|
|
};
|
2020-05-02 17:41:07 +02:00
|
|
|
}
|