Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: make all commands async

ammarahm-ed9c0ffd486e2f
diff --git a/apps/mobile/src/screens/editor/EditorHeader.js b/apps/mobile/src/screens/editor/EditorHeader.js
index 1eab58a32..181e75063 100644
--- a/apps/mobile/src/screens/editor/EditorHeader.js
+++ b/apps/mobile/src/screens/editor/EditorHeader.js
@@ -85,6 +85,12 @@ const EditorHeader = ({ editor }) => {
editorState().currentlyEditing = false;
keyboardListener.current?.remove();
editor?.reset();
+ Navigation.setRoutesToUpdate([
+ Navigation.routeNames.NotesPage,
+ Navigation.routeNames.Favorites,
+ Navigation.routeNames.Notes,
+ Navigation.routeNames.Notebook
+ ]);
}
}, 1);
};
diff --git a/apps/mobile/src/screens/editor/tiptap/commands.ts b/apps/mobile/src/screens/editor/tiptap/commands.ts
index 0a23cef45..eb82fdf9c 100644
--- a/apps/mobile/src/screens/editor/tiptap/commands.ts
+++ b/apps/mobile/src/screens/editor/tiptap/commands.ts
@@ -2,16 +2,36 @@ import { createRef, MutableRefObject, RefObject } from 'react';
import { Platform } from 'react-native';
import WebView from 'react-native-webview';
import { sleep } from '../../../utils/time';
-import { textInput } from './utils';
+import { getResponse, randId, textInput } from './utils';
-function call(webview: RefObject<WebView | undefined>, func?: string) {
- if (!webview || !func) return;
- webview.current?.injectJavaScript(func);
+type Action = { job: string; id: string };
+
+async function call(webview: RefObject<WebView | undefined>, action?: Action) {
+ if (!webview || !action) return;
+ setImmediate(() => webview.current?.injectJavaScript(action.job));
+ let response = await getResponse(action.id);
+ console.log('webview job: ', action.id, response ? response.value : response);
+ if (!response) {
+ console.warn('webview job failed', action.id, action.job);
+ }
+ return response ? response.value : response;
}
-const fn = (fn: string) => `(() => {
- ${fn}
-})();`;
+const fn = (fn: string) => {
+ let id = randId('fn_');
+ return {
+ job: `(async () => {
+ try {
+ let response = true;
+ ${fn}
+ post("${id}",response);
+ } catch(e) {
+ logger('error', "webview: ", e.message, e.stack);
+ }
+ })();`,
+ id: id
+ };
+};
class Commands {
ref = createRef<WebView | undefined>();
@@ -23,26 +43,28 @@ class Commands {
if (!this.ref) return;
if (Platform.OS === 'android') {
this.ref.current?.requestFocus();
- setTimeout(() => {
+ setTimeout(async () => {
if (!this.ref) return;
textInput.current?.focus();
this.ref?.current?.requestFocus();
- call(this.ref, fn(`editor.commands.focus()`));
+ await call(this.ref, fn(`editor.commands.focus()`));
}, 1);
} else {
await sleep(200);
- call(this.ref, fn(`editor.commands.focus()`));
+ await call(this.ref, fn(`editor.commands.focus()`));
}
};
- blur = () => call(this.ref, fn(`editor.commands.blur();editorTitle.current?.blur()`));
+ blur = async () => await call(this.ref, fn(`editor.commands.blur();editorTitle.current?.blur()`));
- clearContent = () => {
- this.blur();
- call(
+ clearContent = async () => {
+ await call(
this.ref,
fn(
- `editor?.commands.clearContent(false);
+ `
+editor.commands.blur();
+editorTitle.current?.blur();
+editor?.commands.clearContent(false);
editorController.setTitle(null);
statusBar.current.set({date:"",saved:""});
`
@@ -50,13 +72,14 @@ statusBar.current.set({date:"",saved:""});
);
};
- setSessionId = (id: string | null) => call(this.ref, fn(`globalThis.sessionId = "${id}"`));
+ setSessionId = async (id: string | null) =>
+ await call(this.ref, fn(`globalThis.sessionId = "${id}"`));
- setStatus = (date: string | undefined, saved: string) =>
- call(this.ref, fn(`statusBar.current.set({date:"${date}",saved:"${saved}"})`));
+ setStatus = async (date: string | undefined, saved: string) =>
+ await call(this.ref, fn(`statusBar.current.set({date:"${date}",saved:"${saved}"})`));
- setPlaceholder = (placeholder: string) => {
- call(
+ setPlaceholder = async (placeholder: string) => {
+ await call(
this.ref,
fn(`
const element = document.querySelector(".is-editor-empty");
diff --git a/apps/mobile/src/screens/editor/tiptap/types.ts b/apps/mobile/src/screens/editor/tiptap/types.ts
index ec43afa07..4c87558e6 100644
--- a/apps/mobile/src/screens/editor/tiptap/types.ts
+++ b/apps/mobile/src/screens/editor/tiptap/types.ts
@@ -13,4 +13,37 @@ export type EditorState = {
isRestoringState: boolean;
keyboardState: boolean;
ready: boolean;
+ saveCount: 0;
+};
+
+export type Note = {
+ [name: string]: any;
+ id: string | null;
+ type: string;
+ contentId: string;
+ title: string;
+ locked: boolean;
+ conflicted: boolean;
+ dateEdited: number;
+ headline: string;
+};
+
+export type Content = {
+ data?: string;
+ type: string;
+};
+
+export type SavePayload = {
+ title?: string;
+ id?: string | null;
+ data?: Content['data'];
+ type?: Content['type'];
+ sessionId?: string | null;
+};
+
+export type AppState = {
+ note?: Note;
+ editing: boolean;
+ movedAway: boolean;
+ timestamp: number;
};
diff --git a/apps/mobile/src/screens/editor/tiptap/useEditor.ts b/apps/mobile/src/screens/editor/tiptap/useEditor.ts
index d359a3edb..a9b905b0c 100644
--- a/apps/mobile/src/screens/editor/tiptap/useEditor.ts
+++ b/apps/mobile/src/screens/editor/tiptap/useEditor.ts
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import WebView from 'react-native-webview';
import { DDS } from '../../../services/device-detection';
import { eSendEvent, eSubscribeEvent, eUnSubscribeEvent } from '../../../services/event-manager';
+import Navigation from '../../../services/navigation';
import { TipManager } from '../../../services/tip-manager';
import { useEditorStore } from '../../../stores/stores';
import { useThemeStore } from '../../../stores/theme';
@@ -11,33 +12,9 @@ import { eOnLoadNote } from '../../../utils/events';
import { tabBarRef } from '../../../utils/global-refs';
import { timeConverter } from '../../../utils/time';
import Commands from './commands';
-import { EditorState } from './types';
+import { EditorState, Note, Content, AppState, SavePayload } from './types';
import { defaultState, EditorEvents, isEditorLoaded, makeSessionId, post } from './utils';
-type Note = {
- [name: string]: any;
- id: string | null;
- type: string;
- contentId: string;
- title: string;
- locked: boolean;
- conflicted: boolean;
- dateEdited: number;
-};
-
-type Content = {
- data?: string;
- type: string;
-};
-
-type SavePayload = {
- title?: string;
- id?: string | null;
- data?: Content['data'];
- type?: Content['type'];
- sessionId?: string | null;
-};
-
export const useEditor = () => {
const [loading, setLoading] = useState(false);
const [sessionId, setSessionId] = useState<string>(makeSessionId());
@@ -48,7 +25,6 @@ export const useEditor = () => {
const commands = useMemo(() => new Commands(editorRef), []);
const sessionHistoryId = useRef<number>();
const state = useRef<Partial<EditorState>>(defaultState);
- console.log('state: ', defaultState);
const placeholderTip = useRef(TipManager.placeholderTip());
const postMessage = useCallback(
@@ -68,13 +44,16 @@ export const useEditor = () => {
useEffect(() => {
console.log('sessionId:', sessionId);
- commands.setSessionId(sessionId);
- if (sessionId) {
- (async () => {
+ async () => {
+ await commands.setSessionId(sessionId);
+ if (sessionId) {
if (!state.current?.ready) return;
- onReady();
- })();
- }
+ await onReady();
+ }
+ };
+ return () => {
+ state.current.saveCount = 0;
+ };
}, [sessionId, loading]);
const overlay = (show: boolean, data = { type: 'new' }) => {
@@ -100,13 +79,13 @@ export const useEditor = () => {
timers.current[id] = setTimeout(fn, duration);
}, []);
- const reset = useCallback(() => {
+ const reset = useCallback(async () => {
currentNote.current = null;
currentContent.current = null;
useEditorStore.getState().setCurrentlyEditingNote(null);
- commands.clearContent();
+ await commands.clearContent();
placeholderTip.current = TipManager.placeholderTip();
- commands.setPlaceholder(placeholderTip.current);
+ await commands.setPlaceholder(placeholderTip.current);
}, []);
const saveNote = useCallback(
@@ -115,7 +94,7 @@ export const useEditor = () => {
try {
if (id && !db.notes?.note(id)) {
useEditorStore.getState().setCurrentlyEditingNote(null);
- reset();
+ await reset();
return;
}
let note = id ? (db.notes?.note(id)?.data as Note) : null;
@@ -166,7 +145,19 @@ export const useEditor = () => {
}
if (id && sessionId === currentSessionId) {
note = db.notes?.note(id)?.data as Note;
- commands.setStatus(timeConverter(note.dateEdited), 'Saved');
+ await commands.setStatus(timeConverter(note.dateEdited), 'Saved');
+
+ if (
+ currentNote.current?.title !== note.title ||
+ currentNote.current?.headline !== note.headline
+ ) {
+ Navigation.setRoutesToUpdate([
+ Navigation.routeNames.NotesPage,
+ Navigation.routeNames.Favorites,
+ Navigation.routeNames.Notes,
+ Navigation.routeNames.Notebook
+ ]);
+ }
}
return id;
@@ -203,18 +194,22 @@ export const useEditor = () => {
const editorState = useEditorStore.getState();
if (item && item.type === 'new') {
- currentNote.current && reset();
- setSessionId(makeSessionId());
- commands.focus();
+ currentNote.current && (await reset());
+ let nextSessionId = makeSessionId(item);
+ setSessionId(nextSessionId);
+ await commands.setSessionId(nextSessionId);
+ await commands.focus();
} else {
if (!item.forced && currentNote.current?.id === item.id) return;
overlay(true, item);
- currentNote.current && reset();
+ currentNote.current && (await reset());
await loadContent(item);
- setSessionId(makeSessionId(item));
+ let nextSessionId = makeSessionId(item);
+ setSessionId(nextSessionId);
+ await commands.setSessionId(nextSessionId);
editorState.setCurrentlyEditingNote(item.id);
currentNote.current = item;
- commands.setStatus(timeConverter(item.dateEdited), 'Saved');
+ await commands.setStatus(timeConverter(item.dateEdited), 'Saved');
await postMessage(EditorEvents.title, item.title);
await postMessage(EditorEvents.html, currentContent.current?.data);
overlay(false);
@@ -265,9 +260,7 @@ export const useEditor = () => {
});
break;
}
- if (message.type.startsWith('native:')) {
- eSendEvent(message.type, message);
- }
+ eSendEvent(message.type, message);
},
[sessionId]
);
@@ -283,7 +276,7 @@ export const useEditor = () => {
let params = {
title,
data: content,
- type: 'tiptap',
+ type: 'tiny',
sessionId,
id: currentNote.current?.id
};
@@ -291,18 +284,18 @@ export const useEditor = () => {
withTimer(
currentNote.current?.id || 'newnote',
() => {
- if (currentNote.current && !params.id) {
+ if (currentNote.current && !params.id && params.sessionId === sessionId) {
params.id = currentNote.current?.id;
}
saveNote(params);
},
- 300
+ 500
);
},
[]
);
- const onLoad = useCallback(() => {
+ const onLoad = useCallback(async () => {
console.log('on editor load');
state.current.ready = true;
onReady();
@@ -311,38 +304,31 @@ export const useEditor = () => {
console.log('force reload note');
loadNote({ ...currentNote.current, forced: true });
} else {
- commands.setPlaceholder(placeholderTip.current);
+ await commands.setPlaceholder(placeholderTip.current);
restoreEditorState();
}
}, [state, currentNote, loadNote]);
async function restoreEditorState() {
- let appState = await MMKV.getItem('appState');
- if (appState) {
- appState = JSON.parse(appState);
-
+ let json = await MMKV.getItem('appState');
+ if (json) {
+ let appState = JSON.parse(json) as AppState;
if (
- //@ts-ignore
appState.editing &&
- //@ts-ignore
- appState.note &&
- //@ts-ignore
- !appState.note.locked &&
- //@ts-ignore
- appState.note.id &&
- //@ts-ignore
+ !appState.note?.locked &&
+ appState.note?.id &&
Date.now() < appState.timestamp + 3600000
) {
state.current.isRestoringState = true;
- //@ts-ignore
overlay(true, appState.note);
state.current.currentlyEditing = true;
if (!DDS.isTab) {
tabBarRef.current?.goToPage(1);
}
setTimeout(() => {
- //@ts-ignore
- loadNote(appState.note);
+ if (appState.note) {
+ loadNote(appState.note);
+ }
}, 1);
MMKV.removeItem('appState');
state.current.movedAway = false;
diff --git a/apps/mobile/src/screens/editor/tiptap/utils.ts b/apps/mobile/src/screens/editor/tiptap/utils.ts
index 3fd140752..d41a6a24a 100644
--- a/apps/mobile/src/screens/editor/tiptap/utils.ts
+++ b/apps/mobile/src/screens/editor/tiptap/utils.ts
@@ -26,7 +26,7 @@ export const EditorEvents: { [name: string]: string } = {
status: 'native:status'
};
-function randId(prefix: string) {
+export function randId(prefix: string) {
return Math.random()
.toString(36)
.replace('0.', prefix || '');
@@ -51,7 +51,7 @@ export async function post(ref: MutableRefObject<WebView | undefined>, type: str
value,
sessionId: sessionId
};
- ref.current?.postMessage(JSON.stringify(message));
+ setImmediate(() => ref.current?.postMessage(JSON.stringify(message)));
let response = await getResponse(type);
console.log('post: ', type, sessionId, 'result:', !!response);
return response;
@@ -64,7 +64,7 @@ type WebviewResponseData = {
value: any;
};
-const getResponse = async (type: string): Promise<WebviewResponseData | false> => {
+export const getResponse = async (type: string): Promise<WebviewResponseData | false> => {
return new Promise(resolve => {
let callback = (data: WebviewResponseData) => {
eUnSubscribeEvent(type, callback);