Skip to content

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

implement basic tiptap editor

ammarahm-edbce5e7ea2d86
diff --git a/apps/mobile/src/navigation/tabsholder.js b/apps/mobile/src/navigation/tabsholder.js
index d41a767b9..9f9ac572c 100644
--- a/apps/mobile/src/navigation/tabsholder.js
+++ b/apps/mobile/src/navigation/tabsholder.js
@@ -7,15 +7,13 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { notesnook } from '../../e2e/test.ids';
import { SideMenu } from '../components/side-menu';
import Tabs from '../components/tabs';
-import { useThemeStore } from '../stores/theme';
-import { useEditorStore, useSettingStore } from '../stores/stores';
import { EditorWrapper } from '../screens/editor/EditorWrapper';
-import { checkStatus, EditorWebView, getNote } from '../screens/editor/Functions';
-import tiny from '../screens/editor/tiny/tiny';
import { DDS } from '../services/device-detection';
import { eSendEvent, eSubscribeEvent, eUnSubscribeEvent } from '../services/event-manager';
+import { useEditorStore, useSettingStore } from '../stores/stores';
+import { useThemeStore } from '../stores/theme';
import { editing, setWidthHeight } from '../utils';
-import { updateStatusBarColor } from '../utils/color-scheme';
+import { db } from '../utils/database';
import {
eClearEditor,
eCloseFullscreenEditor,
@@ -24,50 +22,8 @@ import {
} from '../utils/events';
import { editorRef, tabBarRef } from '../utils/global-refs';
import { hideAllTooltips } from '../utils/hooks/use-tooltip';
-import { sleep } from '../utils/time';
import { NavigationStack } from './navigation-stack';
-let layoutTimer = null;
-
-const onChangeTab = async obj => {
- if (obj.i === 1) {
- editing.movedAway = false;
- activateKeepAwake();
- eSendEvent('navigate');
- eSendEvent(eClearEditor, 'addHandler');
- if (!editing.isRestoringState && (!editing.currentlyEditing || !getNote())) {
- if (editing.overlay) {
- editing.overlay = false;
- return;
- }
- eSendEvent(eOnLoadNote, { type: 'new' });
- editing.currentlyEditing = true;
- }
- if (getNote()) {
- await checkStatus();
- }
- sleep(1000).then(() => {
- updateStatusBarColor();
- });
- } else {
- if (obj.from === 1) {
- updateStatusBarColor();
- deactivateKeepAwake();
- eSendEvent(eClearEditor, 'removeHandler');
- setTimeout(() => useEditorStore.getState().setSearchReplace(false), 1);
- if (getNote()?.locked) {
- eSendEvent(eClearEditor);
- }
- eSendEvent('showTooltip');
- editing.movedAway = true;
- if (editing.currentlyEditing) {
- tiny.call(EditorWebView, tiny.blur);
- }
- }
- editing.isFocused = false;
- }
-};
-
export const TabsHolder = React.memo(
() => {
const colors = useThemeStore(state => state.colors);
@@ -355,3 +311,29 @@ export const TabsHolder = React.memo(
},
() => true
);
+
+let layoutTimer = null;
+
+const onChangeTab = async obj => {
+ if (obj.i === 1) {
+ editing.movedAway = false;
+ editing.isFocused = true;
+ activateKeepAwake();
+ if (!editing.currentlyEditing) {
+ eSendEvent(eOnLoadNote, { type: 'new' });
+ }
+ } else {
+ if (obj.from === 1) {
+ deactivateKeepAwake();
+ editing.movedAway = true;
+ editing.isFocused = false;
+ eSendEvent(eClearEditor, 'removeHandler');
+ setTimeout(() => useEditorStore.getState().setSearchReplace(false), 1);
+ let id = useEditorStore.getState().currentEditingNote;
+ let note = db.notes.note(id);
+ if (note?.locked) {
+ eSendEvent(eClearEditor);
+ }
+ }
+ }
+};
diff --git a/apps/mobile/src/screens/editor/EditorHeader.js b/apps/mobile/src/screens/editor/EditorHeader.js
index 254f4706b..33de2008c 100644
--- a/apps/mobile/src/screens/editor/EditorHeader.js
+++ b/apps/mobile/src/screens/editor/EditorHeader.js
@@ -3,10 +3,8 @@ import React, { useEffect, useRef } from 'react';
import { BackHandler, InteractionManager, Keyboard, Platform, Vibration, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { notesnook } from '../../../e2e/test.ids';
-import { IconButton } from '../../components/ui/icon-button';
import { Properties } from '../../components/properties';
-import { useThemeStore } from '../../stores/theme';
-import { useEditorStore, useSettingStore, useUserStore } from '../../stores/stores';
+import { IconButton } from '../../components/ui/icon-button';
import { DDS } from '../../services/device-detection';
import {
eSendEvent,
@@ -15,7 +13,10 @@ import {
ToastEvent
} from '../../services/event-manager';
import Navigation from '../../services/navigation';
+import { useEditorStore, useSettingStore, useUserStore } from '../../stores/stores';
+import { useThemeStore } from '../../stores/theme';
import { editing } from '../../utils';
+import umami from '../../utils/analytics';
import { SUBSCRIPTION_STATUS } from '../../utils/constants';
import { db } from '../../utils/database';
import {
@@ -27,18 +28,16 @@ import {
eOpenPremiumDialog,
eOpenPublishNoteDialog
} from '../../utils/events';
-import useEditorTags from '../../utils/hooks/useEditorTags';
import { tabBarRef } from '../../utils/global-refs';
-import umami from '../../utils/analytics';
import { EditorTitle } from './EditorTitle';
-import { clearEditor, getNote, loadNote, setColors, startClosingSession } from './Functions';
+import { clearEditor, getNote, setColors, startClosingSession } from './Functions';
import { ProgressCircle } from './ProgressCircle';
import tiny, { safeKeyboardDismiss } from './tiny/tiny';
import { endSearch } from './tiny/toolbar/commands';
import { toolbarRef } from './tiny/toolbar/constants';
import picker from './tiny/toolbar/picker';
-const EditorHeader = () => {
+const EditorHeader = ({ editor }) => {
const colors = useThemeStore(state => state.colors);
const deviceMode = useSettingStore(state => state.deviceMode);
const currentlyEditingNote = useEditorStore(state => state.currentEditingNote);
@@ -48,19 +47,11 @@ const EditorHeader = () => {
const handleBack = useRef();
const keyboardListener = useRef();
const closing = useRef(false);
- const editorTags = useEditorTags();
+ //const editorTags = useEditorTags();
const searchReplace = useEditorStore(state => state.searchReplace);
const readonly = useEditorStore(state => state.readonly);
- useEffect(() => {
- setColors(colors);
- }, [colors]);
-
const _onBackPress = async () => {
- editing.lastClosedTime = Date.now();
- if (deviceMode === 'mobile') {
- startClosingSession();
- }
setTimeout(async () => {
closing.current = true;
if (deviceMode !== 'mobile' && fullscreen) {
@@ -76,16 +67,12 @@ const EditorHeader = () => {
y: 0,
animated: false
});
- editing.isFocused = false;
- editing.currentlyEditing = false;
- editing.focusType = null;
- safeKeyboardDismiss();
+
if (deviceMode !== 'mobile') {
if (fullscreen) {
eSendEvent(eCloseFullscreenEditor);
}
} else {
- startClosingSession();
if (deviceMode === 'mobile') {
tabBarRef.current?.goToPage(0);
}
@@ -96,10 +83,10 @@ const EditorHeader = () => {
setTimeout(() => {
useEditorStore.getState().setCurrentlyEditingNote(null);
}, 1);
+ editing.currentlyEditing = false;
keyboardListener.current?.remove();
- await clearEditor();
+ editor?.reset();
}
- closing.current = false;
}, 1);
};
@@ -174,21 +161,7 @@ const EditorHeader = () => {
};
}, []);
- const onNoteRemoved = async id => {
- // try {
- // return;
- // // console.log('NOTE REMOVED', id);
- // // await db.notes.remove(id);
- // // if (id !== getNote().id) return;
- // // Navigation.setRoutesToUpdate([
- // // Navigation.routeNames.Favorites,
- // // Navigation.routeNames.Notes,
- // // Navigation.routeNames.NotesPage,
- // // Navigation.routeNames.Trash,
- // // Navigation.routeNames.Notebook
- // // ]);
- // } catch (e) {}
- };
+ const onNoteRemoved = async id => {};
useEffect(() => {
if (fullscreen && DDS.isTab) {
@@ -204,10 +177,11 @@ const EditorHeader = () => {
}, [fullscreen]);
const load = async item => {
- console.log(item.id);
- await loadNote(item);
+ //console.log(item.id);
+ // await loadNote(item);
+ console.log('load called');
InteractionManager.runAfterInteractions(() => {
- keyboardListener.current = Keyboard.addListener('keyboardDidShow', tiny.onKeyboardShow);
+ //keyboardListener.current = Keyboard.addListener('keyboardDidShow', tiny.onKeyboardShow);
if (!DDS.isTab) {
handleBack.current = BackHandler.addEventListener(
'hardwareBackPress',
diff --git a/apps/mobile/src/screens/editor/EditorWrapper.js b/apps/mobile/src/screens/editor/EditorWrapper.js
index f24f7fdb2..6f4621f5d 100644
--- a/apps/mobile/src/screens/editor/EditorWrapper.js
+++ b/apps/mobile/src/screens/editor/EditorWrapper.js
@@ -13,11 +13,10 @@ import { PremiumToast } from '../../components/premium/premium-toast';
import { DDS } from '../../services/device-detection';
import { useNoteStore, useSettingStore } from '../../stores/stores';
import { useThemeStore } from '../../stores/theme';
-import { editing } from '../../utils';
import { editorRef } from '../../utils/global-refs';
import useIsFloatingKeyboard from '../../utils/hooks/use-is-floating-keyboard';
import EditorOverlay from './EditorOverlay';
-import { checkStatus, textInput } from './Functions';
+import { textInput } from './tiptap/utils';
export const EditorWrapper = ({ width }) => {
const colors = useThemeStore(state => state.colors);
@@ -28,9 +27,9 @@ export const EditorWrapper = ({ width }) => {
const onAppStateChanged = async state => {
if (state === 'active') {
- if (!editing.movedAway) {
- await checkStatus(false);
- }
+ // if (!editing.movedAway) {
+ // await checkStatus(false);
+ // }
}
};
diff --git a/apps/mobile/src/screens/editor/Functions.js b/apps/mobile/src/screens/editor/Functions.js
index 85e23c40f..d96fe2fb8 100644
--- a/apps/mobile/src/screens/editor/Functions.js
+++ b/apps/mobile/src/screens/editor/Functions.js
@@ -1,1045 +1,1045 @@
-import { createRef } from 'react';
-import { Platform } from 'react-native';
-import { presentDialog } from '../../components/dialog/functions';
-import { useEditorStore, useMenuStore, useTagStore } from '../../stores/stores';
-import { DDS } from '../../services/device-detection';
-import {
- eSendEvent,
- eSubscribeEvent,
- eUnSubscribeEvent,
- ToastEvent
-} from '../../services/event-manager';
-import Navigation from '../../services/navigation';
-import PremiumService from '../../services/premium';
-import { TipManager } from '../../services/tip-manager';
-import { editing } from '../../utils';
-import { COLORS_NOTE, COLOR_SCHEME } from '../../utils/color-scheme';
-import { hexToRGBA } from '../../utils/color-scheme/utils';
-import { db } from '../../utils/database';
-import {
- eClearEditor,
- eOnLoadNote,
- eOpenTagsDialog,
- eShowGetPremium,
- eShowMergeDialog
-} from '../../utils/events';
-import filesystem from '../../utils/filesystem';
-import { openLinkInBrowser } from '../../utils/functions';
-import { MMKV } from '../../utils/database/mmkv';
-import { tabBarRef } from '../../utils/global-refs';
-import { normalize } from '../../utils/size';
-import { sleep, timeConverter } from '../../utils/time';
-import umami from '../../utils/analytics';
-import { TableCellProperties } from './TableCellProperties';
-import { TableRowProperties } from './TableRowProperties';
-import tiny from './tiny/tiny';
-import { IMAGE_TOOLTIP_CONFIG, TABLE_TOOLTIP_CONFIG } from './tiny/toolbar/config';
-
-export let EditorWebView = createRef();
-export const editorTitleInput = createRef();
-export const sourceUri = Platform.OS === 'android' ? 'file:///android_asset/' : 'Web.bundle/site/';
-
-let lastEditTime = 0;
-let EDITOR_SETTINGS = null;
-let webviewOK = true;
-let noteEdited = false;
-let note = null;
-let id = null;
-let content = {
- data: '',
- type: 'tiny'
-};
-let title = '';
-let saveCounter = 0;
-let timer = null;
-let webviewInit = false;
-let appColors = COLOR_SCHEME;
-
-let closingSession = false;
-let webviewTimer = null;
-let requestedReload = false;
-let disableSaving = false;
-let isSaving = false;
-let waitForContent = false;
-let prevNoteContent = null;
-let sessionId = null;
-let historySessionId = null;
-let placeholderTip = TipManager.placeholderTip();
-
-export function startClosingSession() {
- closingSession = true;
-}
-
-export function setWebviewInit(init) {
- webviewInit = init;
-}
-
-export function getWebviewInit() {
- return webviewInit;
-}
-
-export function setColors(colors) {
- if (colors) {
- appColors = colors;
- }
- let theme = { ...appColors, factor: normalize(1) };
-
- if (note && note.color && !DDS.isLargeTablet()) {
- theme.shade = hexToRGBA(COLORS_NOTE[note.color?.toLowerCase()], 0.15);
- }
- tiny.call(EditorWebView, tiny.updateTheme(JSON.stringify(theme)));
-}
-
-export function isNotedEdited() {
- return noteEdited;
-}
-
-async function waitForEvent(event, caller, onend) {
- return new Promise(resolve => {
- let resolved;
- let event_callback = () => {
- eUnSubscribeEvent(event, event_callback);
- resolved = true;
- clearTimeout(resolved);
- onend && onend();
- resolve();
- };
- eSubscribeEvent(event, event_callback);
- caller && caller();
- resolved = setTimeout(() => {
- resolve(true);
- }, 2000);
- });
-}
-
-export async function clearTimer() {
- if (waitForContent && noteEdited) {
- await waitForEvent('content_event', () => {
- console.log('requested content from edtior');
- tiny.call(EditorWebView, request_content);
- });
- }
- waitForContent = false;
-}
-
-export const CHECK_STATUS = `(function() {
- let msg = JSON.stringify({
- data: true,
- type: 'running',
- sessionId:sessionId
- });
- window.ReactNativeWebView.postMessage(msg)
-
-})();`;
-
-const request_content = `(function() {
- if (window.ReactNativeWebView) {
- if (!editor) return;
- editor.getHTML().then(function(html) {
- window.ReactNativeWebView.postMessage(
- JSON.stringify({
- type: 'tiny',
- value:html,
- caller:"request_content",
- sessionId:sessionId
- })
- );
- }).catch(console.log)
- }
-})();`;
-
-export function getNote() {
- return note;
-}
-
-export function setReadOnly(readonly) {
- note.readonly = readonly;
-}
-
-export function setNoteOnly(n) {
- note = n;
-}
-
-export function disableEditing() {
- noteEdited = false;
- disableSaving = true;
-}
-
-export const textInput = createRef();
-
-export function post(type, value = null) {
- let message = {
- type,
- value,
- sessionId: sessionId
- };
- if (type === 'html') {
- }
-
- EditorWebView.current?.postMessage(JSON.stringify(message));
-}
-
-export const _onShouldStartLoadWithRequest = async request => {
- if (request.url.includes('https')) {
- if (Platform.OS === 'ios' && !request.isTopFrame) return;
- openLinkInBrowser(request.url, appColors).catch(console.log).then(console.log);
-
- return false;
- } else {
- return true;
- }
-};
-
-export function checkNote() {
- return note && note.id;
-}
-
-async function setNote(item) {
- note = item;
- saveCounter = 0;
- title = note.title;
- id = note.id;
- noteEdited = false;
- lastEditTime = item.dateEdited;
- if (note.locked) {
- content.data = note.content.data;
- content.type = note.content.type;
- } else {
- let data = await db.content.raw(note.contentId);
- if (!data) {
- content.data = '';
- content.type = 'tiny';
- } else {
- data = await db.content.insertPlaceholders(data, 'placeholder.svg');
- content.data = data.data;
- content.type = data.type;
- }
- }
-}
-
-function clearNote() {
- note = null;
- title = '';
- noteEdited = false;
- historySessionId = null;
- prevNoteContent = content.data;
- isSaving = false;
- id = null;
- content = {
- data: '',
- type: 'tiny'
- };
-}
-
-function randId(prefix) {
- return Math.random()
- .toString(36)
- .replace('0.', prefix || '');
-}
-
-function makeSessionId(item) {
- sessionId = item?.id ? item.id + randId('_session_') : randId('session_');
-}
-let loading_queue;
-let loading_note = false;
-export const loadNote = async item => {
- if (loading_note && id) {
- loading_queue = item;
- check_session_status();
- return;
- } else {
- loading_queue = null;
- }
-
- loading_note = true;
- editing.currentlyEditing = true;
- editing.movedAway = false;
-
- if (closingSession) {
- console.log('open note:', 'closing: ', closingSession);
- eSendEvent('loadingNote', item);
- await waitForEvent('session_ended');
- }
-
- closingSession = true;
- if (editing.isFocused) {
- tiny.call(EditorWebView, tiny.blur);
- }
- if (item && item.type === 'new') {
- if (getNote()) {
- eSendEvent('loadingNote', item);
- await clearEditor();
- }
- umami.pageView('/first-note', '/welcome/home');
- clearNote();
- eSendEvent('loadingNote');
- eSendEvent('updateTags');
- useEditorStore.getState().setReadonly(false);
- closingSession = false;
- disableSaving = false;
- lastEditTime = 0;
- noteEdited = false;
- loading_queue = null;
- makeSessionId(item);
- useEditorStore.getState().setSessionId(sessionId);
- await checkStatus(false);
- tiny.call(
- EditorWebView,
- `
- toggleNode(".tag-bar-parent","hide");
- clearNode(".tag-bar")`
- );
-
- if (Platform.OS === 'android') {
- EditorWebView.current?.requestFocus();
- setTimeout(() => {
- textInput.current?.focus();
- EditorWebView.current?.requestFocus();
- tiny.call(EditorWebView, tiny.focusEditor);
- }, 200);
- } else {
- await sleep(200);
- tiny.call(EditorWebView, tiny.focusEditor);
- }
-
- if (EDITOR_SETTINGS) {
- console.log('settings are present');
- tiny.call(
- EditorWebView,
- EDITOR_SETTINGS.directionality === 'rtl'
- ? `tinymce.activeEditor.execCommand('mceDirectionRTL');`
- : `tinymce.activeEditor.execCommand('mceDirectionLTR');`
- );
- }
- requestedReload = true;
- updateSessionStatus();
- tiny.call(EditorWebView, tiny.notLoading + tiny.toogleReadMode('design'));
- } else {
- if (id === item.id && !item.forced) {
- console.log('note is already opened in editor');
- closingSession = false;
- loading_note = false;
- eSendEvent('loadingNote');
- await checkStatus();
- return;
- }
- eSendEvent('loadingNote', item);
- if (getNote()) {
- await clearEditor();
- }
-
- closingSession = false;
- disableSaving = false;
- noteEdited = false;
- webviewInit = false;
- editing.isFocused = false;
- useEditorStore.getState().setReadonly(item.readonly);
- await setNote(item);
- if (loading_queue && (loading_queue?.id !== item?.id || loading_queue?.type === 'new')) {
- clearNote();
- loading_note = false;
- loadNote(loading_queue);
-
- return;
- }
- // tiny.call(
- // EditorWebView,
- // `toggleNode(".tag-bar-parent","show");
- // clearNode(".tag-bar")`
- // );
- makeSessionId(item);
- useEditorStore.getState().setSessionId(sessionId);
- webviewInit = true;
- await loadNoteInEditor();
- requestedReload = true;
- if (await checkStatus(false)) {
- updateSessionStatus();
- }
- setTimeout(() => {
- useEditorStore.getState().setCurrentlyEditingNote(item.id);
- }, 1);
- }
-
- loading_note = false;
-};
-
-export const checkStatus = async noreset => {
- return new Promise(resolve => {
- webviewOK = false;
- console.log('checking status of webview');
- clearTimeout(webviewTimer);
- webviewTimer = null;
- const onWebviewOk = () => {
- webviewOK = true;
- webviewInit = true;
- clearTimeout(webviewTimer);
- webviewTimer = null;
- console.log('webviewOk:', webviewOK);
- resolve(true);
- eUnSubscribeEvent('webviewOk', onWebviewOk);
- };
- eSubscribeEvent('webviewOk', onWebviewOk);
- setTimeout(
- () => {
- EditorWebView.current?.injectJavaScript(CHECK_STATUS);
- },
- Platform.OS === 'ios' ? 300 : 1
- );
-
- webviewTimer = setTimeout(() => {
- console.log('webviewOK:', webviewOK, 'Reset blocked:', noreset);
- if (!webviewOK && !noreset) {
- webviewInit = false;
- console.log('full reset');
- EditorWebView = createRef();
- eSendEvent('webviewreset');
- resolve(true);
- }
- }, 1000);
- });
-};
-
-function updateSessionStatus() {
- tiny.call(
- EditorWebView,
- `(function () {
- sessionId = '${sessionId}';
- reactNativeEventHandler('status', true);
- })();`
- );
-}
-
-function isContentInvalid(content) {
- return (
- !content ||
- content === '' ||
- content.trim() === '' ||
- content === '<p></p>' ||
- content === '<p><br></p>' ||
- content === '<p>&nbsp;</p>' ||
- content === `<p><br data-mce-bogus="1"></p>`
- );
-}
-
-function check_session_status() {
- tiny.call(
- EditorWebView,
- `(function () {
- if (window.ReactNativeWebView) {
- if (!editor) return;
-
- editor.getHTML().then(function (value) {
- let status =
- !value ||
- value === '' ||
- value.trim() === '' ||
- value === '<p></p>' ||
- value === '<p><br></p>' ||
- value === '<p>&nbsp;</p>' ||
- value === '<p><br data-mce-bogus="1"></p>';
-
- window.ReactNativeWebView.postMessage(
- JSON.stringify({
- type: 'content_not_loaded',
- value: status,
- sessionId: sessionId
- })
- );
- }).catch(console.log)
- }
- })();`
- );
-}
-
-export const _onMessage = async evt => {
- if (!evt || !evt.nativeEvent || !evt.nativeEvent.data) return;
- let message = evt.nativeEvent.data;
- let user;
- try {
- message = JSON.parse(message);
- } catch (e) {
- return;
- }
- switch (message.type) {
- case 'tinyerror':
- console.log('tinyerror', message.value);
- ToastEvent.error(message.value, 'Error saving note', 'global');
- break;
- case 'tableconfig':
- showTableOptionsTooltip();
- break;
- case 'tablecelloptions':
- TableCellProperties.present(message.value);
- break;
- case 'tablerowoptions':
- TableRowProperties.present(message.value);
- break;
- case 'selectionvalue':
- eSendEvent('selectionvalue', message.value);
- break;
- case 'history':
- eSendEvent('historyEvent', message.value);
- break;
- case 'noteedited':
- if (message.sessionId !== sessionId) return;
- console.log('noteedited');
- noteEdited = true;
- break;
- case 'tiny':
- if (message.sessionId !== sessionId) return;
- if (prevNoteContent && message.value === prevNoteContent) {
- prevNoteContent = null;
- noteEdited = false;
- return;
- }
- prevNoteContent = null;
- console.log('tiny content recieved', message.caller);
- noteEdited = true;
- lastEditTime = Date.now();
- content = {
- type: message.type,
- data: message.value
- };
- onNoteChange(message.caller ? 0 : 300);
- if (waitForContent) {
- eSendEvent('content_event');
- }
- break;
- case 'title':
- if (message.sessionId !== sessionId) return;
- if (message.value !== title) {
- noteEdited = true;
- lastEditTime = Date.now();
- title = message.value;
- eSendEvent('editorScroll', {
- title: message.value
- });
- onNoteChange();
- }
- break;
- case 'scroll':
- eSendEvent('editorScroll', message);
- break;
- case 'attachment_download':
- filesystem.downloadAttachment(message.value, true);
- break;
- case 'noteLoaded':
- tiny.call(EditorWebView, tiny.notLoading);
- eSendEvent('loadingNote');
- break;
- case 'premium':
- user = await db.user.getUser();
- if (user && !user.isEmailConfirmed) {
- await sleep(500);
- PremiumService.showVerifyEmailDialog();
- } else {
- eSendEvent(eShowGetPremium, {
- context: 'editor',
- title: 'Get Notesnook Pro',
- desc: 'Enjoy Full Rich Text Editor with Markdown Support!'
- });
- }
- break;
- case 'status':
- if (sessionId !== message.sessionId) {
- if (!sessionId) makeSessionId({ id });
- updateSessionStatus();
- return;
- }
-
- if (!requestedReload && getNote()) {
- check_session_status();
- return;
- }
- requestedReload = false;
- setColors(COLOR_SCHEME);
- eSendEvent('webviewOk');
- loading_note = false;
- webviewInit = true;
- webviewOK = true;
- setTimeout(() => {
- if (PremiumService.get()) {
- tiny.call(EditorWebView, tiny.setMarkdown, true);
- } else {
- tiny.call(EditorWebView, tiny.removeMarkdown, true);
- }
- }, 300);
- setTimeout(() => {
- check_session_status();
- }, 1500);
- break;
- case 'content_not_loaded':
- loading_note = false;
- if (isContentInvalid(content.data)) return;
- if (message.sessionId !== sessionId) {
- requestedReload = true;
- updateSessionStatus();
- return;
- }
- if (!id) return;
-
- if (message.value) {
- console.log('content not loaded', content.data);
- await checkStatus();
- console.log('reloading');
- await loadNoteInEditor();
- setTimeout(() => {
- check_session_status();
- }, 1500);
- }
- break;
- case 'running':
- eSendEvent('webviewOk');
- webviewOK = true;
- break;
- case 'resetcomplete':
- console.log('reset event recieved');
- eSendEvent('resetcomplete');
- break;
- case 'editorSettings':
- EDITOR_SETTINGS = message.value;
- eSendEvent('editorSettingsEvent', message.value);
- break;
- case 'imagepreview':
- eSendEvent('ImagePreview', message.value);
- break;
- case 'imageoptions':
- if (editing.tooltip === 'imageoptions') {
- eSendEvent('showTooltip');
- break;
- }
- showImageOptionsTooltip();
- break;
- case 'focus':
- editing.focusType = message.value;
- break;
- case 'selectionchange':
- eSendEvent('onSelectionChange', message.value);
- break;
- case 'notetag':
- if (message.value) {
- let _tag = JSON.parse(message.value);
- console.log(_tag.title);
- await db.notes.note(note.id).untag(_tag.title);
- useTagStore.getState().setTags();
- Navigation.setRoutesToUpdate([
- Navigation.routeNames.Notes,
- Navigation.routeNames.NotesPage,
- Navigation.routeNames.Tags
- ]);
- }
- break;
- case 'newtag':
- if (!getNote()) {
- ToastEvent.show({
- heading: 'Create a note first'
- });
- return;
- }
- eSendEvent(eOpenTagsDialog, note);
- break;
- default:
- break;
- }
-};
-
-function showImageOptionsTooltip() {
- editing.tooltip = 'imageoptions';
- eSendEvent('showTooltip', IMAGE_TOOLTIP_CONFIG);
-}
-
-function showTableOptionsTooltip() {
- editing.tooltip = 'tableconfig';
- console.log('showTooltip');
- eSendEvent('showTooltip', TABLE_TOOLTIP_CONFIG);
-}
-
-function onNoteChange(wait = 300) {
- clearTimeout(timer);
- timer = null;
- noteEdited = false;
- let params = [title, id, content.data, content.type, sessionId, historySessionId];
- timer = setTimeout(() => {
- if (!params[1]) {
- params[1] = id;
- }
- saveNote(...params);
- }, wait);
-}
-
-export async function clearEditor() {
- try {
- console.log('closing session: ', closingSession);
- closingSession = true;
- await sleep(100);
- console.log('note edited: ', noteEdited);
- if (noteEdited) {
- console.log('note is edited');
- disableSaving = false;
- waitForContent = true;
- await clearTimer(true);
- await sleep(100);
- }
-
- disableSaving = true;
- sessionId = null;
- noteEdited = false;
- db.fs.cancel(getNote()?.id);
- clearNote();
- placeholderTip = TipManager.placeholderTip();
- tiny.call(EditorWebView, tiny.reset(placeholderTip));
- //EditorWebView.current?.reload();
- await waitForEvent('resetcomplete');
- editing.focusType = null;
- eSendEvent('historyEvent', {
- undo: 0,
- redo: 0
- });
- saveCounter = 0;
- useEditorStore.getState().setCurrentlyEditingNote(null);
- } catch (e) {}
-
- disableSaving = false;
- eSendEvent('session_ended');
- closingSession = false;
-}
-
-async function setNoteInEditorAfterSaving(oldId, currentId) {
- if (oldId !== currentId) {
- id = currentId;
- note = db.notes.note(id);
- if (note) {
- note = note.data;
- } else {
- await sleep(500);
- note = db.notes.note(id);
- if (note) {
- note = note.data;
- }
- }
- }
-}
-
-async function addToCollection(id) {
- switch (editing.actionAfterFirstSave.type) {
- case 'topic': {
- await db.notes.move(
- {
- topic: editing.actionAfterFirstSave.id,
- id: editing.actionAfterFirstSave.notebook
- },
- id
- );
- editing.actionAfterFirstSave = {
- type: null
- };
- Navigation.setRoutesToUpdate([
- Navigation.routeNames.Notebooks,
- Navigation.routeNames.NotesPage,
- Navigation.routeNames.Notebook
- ]);
- break;
- }
- case 'tag': {
- await db.notes.note(id).tag(editing.actionAfterFirstSave.id);
- editing.actionAfterFirstSave = {
- type: null
- };
- Navigation.setRoutesToUpdate([Navigation.routeNames.Tags, Navigation.routeNames.NotesPage]);
- break;
- }
- case 'color': {
- await db.notes.note(id).color(editing.actionAfterFirstSave.id);
- editing.actionAfterFirstSave = {
- type: null
- };
- Navigation.setRoutesToUpdate([Navigation.routeNames.NotesPage]);
- useMenuStore.getState().setColorNotes();
- break;
- }
- default: {
- break;
- }
- }
-}
-
-export async function saveNote(title, _id, data, type, _sessionId, _historySessionId) {
- console.log('saving note:', disableSaving, isSaving, _id, id);
- if (typeof data !== 'string') return;
- if (disableSaving || (isSaving && !id)) return;
- if (_sessionId !== sessionId) {
- noteEdited = false;
- }
- isSaving = true;
- try {
- if (_id && !db.notes.note(_id)) {
- clearNote();
- useEditorStore.getState().setCurrentlyEditingNote(null);
- return;
- }
- let locked = false;
- if (_id) {
- let _note = db.notes.note(_id).data;
- if (_note.readonly) return;
- if (_note.conflicted) {
- presentResolveConflictDialog(_note);
- return;
- }
- locked = _note.locked;
- }
-
- if (isContentInvalid(data) || !_historySessionId) {
- _historySessionId = note?.dateEdited || Date.now();
- historySessionId = _historySessionId;
- console.log('new session begins');
- }
-
- console.log('compare ids:', _sessionId === sessionId, _historySessionId === historySessionId);
- console.log(sessionId, historySessionId);
- let noteData = {
- title,
- content: {
- data: data,
- type: type
- },
- id: _id,
- sessionId: isContentInvalid(data) ? null : _historySessionId
- };
-
- console.log(
- 'Note Saved:::',
- 'historySessionId:',
- _historySessionId,
- 'preventUpdate: ',
- sessionId === _sessionId
- );
-
- if (!locked) {
- let noteId = await db.notes.add(noteData);
- if (!_id || saveCounter < 3) {
- Navigation.setRoutesToUpdate([
- Navigation.routeNames.Notes,
- Navigation.routeNames.Favorites,
- Navigation.routeNames.NotesPage,
- Navigation.routeNames.Notebook
- ]);
- }
- if (!_id) {
- id = noteId;
- await addToCollection(noteId);
- }
-
- if (!_id && sessionId === _sessionId) {
- if (!title || title === '') {
- console.log('posting title now');
- post('titleplaceholder', db.notes.note(noteId)?.data?.title || '');
- }
-
- await setNoteInEditorAfterSaving(_id, noteId);
- saveCounter++;
- setTimeout(() => {
- useEditorStore.getState().setCurrentlyEditingNote(noteId);
- });
- }
- _id = noteId;
- } else {
- noteData.contentId = note.contentId;
- await db.vault.save(noteData);
- }
- if (sessionId === _sessionId) {
- Navigation.setRoutesToUpdate([
- Navigation.routeNames.NotesPage,
- Navigation.routeNames.Favorites,
- Navigation.routeNames.Notes
- ]);
-
- lastEditTime = n + 10;
- let n = db.notes.note(_id)?.data?.dateEdited;
- tiny.call(
- EditorWebView,
- tiny.updateDateEdited(n ? timeConverter(n) : '') + tiny.updateSavingState(!n ? '' : 'Saved')
- );
- }
- } catch (e) {
- if (e.message === 'ERR_VAULT_LOCKED') {
- console.log(e);
- presentDialog({
- input: true,
- inputPlaceholder: 'Enter vault password',
- title: 'Unlock note',
- paragraph: 'To save note, unlock it',
- positiveText: 'Unlock',
- positivePress: async password => {
- if (password && password.trim()) {
- try {
- await db.vault.unlock(password);
- noteEdited = true;
- onNoteChange(0);
- } catch (e) {
- console.log(e);
- return false;
- }
- } else {
- return false;
- }
- },
- negativeText: 'Cancel',
- onClose: () => {
- noteEdited = false;
- eSendEvent(eClearEditor);
- }
- });
- }
- console.log(e);
- ToastEvent.show({
- heading: 'Error saving note',
- message: e.message,
- type: 'error'
- });
- }
- isSaving = false;
-}
-let isInitalLaunch = true;
-export async function onWebViewLoad(premium, colors) {
- eSendEvent('resetcomplete');
- setTimeout(() => {
- if (PremiumService.get()) {
- tiny.call(EditorWebView, tiny.setMarkdown, true);
- } else {
- tiny.call(EditorWebView, tiny.removeMarkdown, true);
- }
- }, 300);
- setColors(colors);
-
- if (isInitalLaunch) {
- tiny.call(EditorWebView, tiny.setPlaceholder(placeholderTip));
- isInitalLaunch = false;
- }
-}
-
-async function restoreEditorState() {
- let appState = await MMKV.getItem('appState');
- if (appState) {
- appState = JSON.parse(appState);
- if (
- appState.editing &&
- appState.note &&
- !appState.note.locked &&
- appState.note.id &&
- Date.now() < appState.timestamp + 3600000
- ) {
- editing.isRestoringState = true;
- eSendEvent('loadingNote', appState.note);
- editing.currentlyEditing = true;
- if (!DDS.isTab) {
- tabBarRef.current?.goToPage(1);
- }
- setTimeout(() => {
- eSendEvent(eOnLoadNote, appState.note);
- }, 100);
- MMKV.removeItem('appState');
- editing.movedAway = false;
- eSendEvent('load_overlay', 'hide_editor');
- editing.isRestoringState = false;
- return;
- }
- editing.isRestoringState = false;
- return;
- }
- editing.isRestoringState = false;
-}
-
-export const presentResolveConflictDialog = _note => {
- presentDialog({
- title: 'Changes not saved',
- paragraph: 'Please resolve conflicts to save changes',
- positiveText: 'Resolve',
- positivePress: () => {
- eSendEvent(eShowMergeDialog, _note);
- }
- });
-};
-
-const loadNoteInEditor = async (keepHistory = true) => {
- console.log(webviewInit, 'ready?');
- if (!webviewInit) return;
- try {
- if (note?.id) {
- eSendEvent('updateTags');
- post('title', title);
-
- if (!content || !content.data || content?.data?.length === 0) {
- tiny.call(
- EditorWebView,
- `
- sessionId = "${sessionId}"
- globalThis.isClearingNoteData = false;
- window.ReactNativeWebView.postMessage(
- JSON.stringify({
- type: 'noteLoaded',
- value: true,
- sessionId:sessionId
- }),
- );
- `
- );
- } else {
- console.log('posting html');
- post('html', {
- data: content.data,
- readOnly: note.readonly
- });
- }
- if (id) {
- db.attachments.downloadImages(id);
- }
-
- setColors();
- tiny.call(
- EditorWebView,
- tiny.updateDateEdited(timeConverter(note.dateEdited)) + tiny.updateSavingState('Saved')
- );
- } else {
- tiny.call(EditorWebView, tiny.toogleReadMode('design'));
- await restoreEditorState();
- }
-
- if (keepHistory) {
- tiny.call(EditorWebView, tiny.clearHistory);
- }
- } catch (e) {}
-
- disableSaving = false;
- check_session_status();
-};
-
-export async function updateNoteInEditor() {
- return;
- // let _note = db.notes.note(id).data;
- // if (_note.conflicted) {
- // presentResolveConflictDialog(_note);
- // return;
- // }
- // let data = await db.content.raw(_note.contentId);
- // if (lastEditTime > _note.dateEdited) return;
- // if (data.data === content.data) return;
- // if (content.data.indexOf(data.data) !== -1) return;
- // if (note.dateEdited === _note.dateEdited) return;
-
- // title = note.title;
- // content.data = data.data;
- // note = _note;
- // lastEditTime = _note.dateEdited + 10;
- // tiny.call(EditorWebView, tiny.isLoading);
- // await setNote(_note);
- // tiny.call(EditorWebView, tiny.isLoading);
- // post('title', title);
- // post('inject', content.data);
- // setTimeout(() => {
- // tiny.call(EditorWebView, tiny.notLoading);
- // }, 50);
- // if (id) {
- // db.attachments.downloadImages(id);
- // }
- // tiny.call(EditorWebView, tiny.notLoading);
-}
+// import { createRef } from 'react';
+// import { Platform } from 'react-native';
+// import { presentDialog } from '../../components/dialog/functions';
+// import { useEditorStore, useMenuStore, useTagStore } from '../../stores/stores';
+// import { DDS } from '../../services/device-detection';
+// import {
+// eSendEvent,
+// eSubscribeEvent,
+// eUnSubscribeEvent,
+// ToastEvent
+// } from '../../services/event-manager';
+// import Navigation from '../../services/navigation';
+// import PremiumService from '../../services/premium';
+// import { TipManager } from '../../services/tip-manager';
+// import { editing } from '../../utils';
+// import { COLORS_NOTE, COLOR_SCHEME } from '../../utils/color-scheme';
+// import { hexToRGBA } from '../../utils/color-scheme/utils';
+// import { db } from '../../utils/database';
+// import {
+// eClearEditor,
+// eOnLoadNote,
+// eOpenTagsDialog,
+// eShowGetPremium,
+// eShowMergeDialog
+// } from '../../utils/events';
+// import filesystem from '../../utils/filesystem';
+// import { openLinkInBrowser } from '../../utils/functions';
+// import { MMKV } from '../../utils/database/mmkv';
+// import { tabBarRef } from '../../utils/global-refs';
+// import { normalize } from '../../utils/size';
+// import { sleep, timeConverter } from '../../utils/time';
+// import umami from '../../utils/analytics';
+// import { TableCellProperties } from './TableCellProperties';
+// import { TableRowProperties } from './TableRowProperties';
+// import tiny from './tiny/tiny';
+// import { IMAGE_TOOLTIP_CONFIG, TABLE_TOOLTIP_CONFIG } from './tiny/toolbar/config';
+
+// export let EditorWebView = createRef();
+// export const editorTitleInput = createRef();
+// export const sourceUri = Platform.OS === 'android' ? 'file:///android_asset/' : 'Web.bundle/site/';
+
+// let lastEditTime = 0;
+// let EDITOR_SETTINGS = null;
+// let webviewOK = true;
+// let noteEdited = false;
+// let note = null;
+// let id = null;
+// let content = {
+// data: '',
+// type: 'tiny'
+// };
+// let title = '';
+// let saveCounter = 0;
+// let timer = null;
+// let webviewInit = false;
+// let appColors = COLOR_SCHEME;
+
+// let closingSession = false;
+// let webviewTimer = null;
+// let requestedReload = false;
+// let disableSaving = false;
+// let isSaving = false;
+// let waitForContent = false;
+// let prevNoteContent = null;
+// let sessionId = null;
+// let historySessionId = null;
+// let placeholderTip = TipManager.placeholderTip();
+
+// export function startClosingSession() {
+// closingSession = true;
+// }
+
+// export function setWebviewInit(init) {
+// webviewInit = init;
+// }
+
+// export function getWebviewInit() {
+// return webviewInit;
+// }
+
+// export function setColors(colors) {
+// if (colors) {
+// appColors = colors;
+// }
+// let theme = { ...appColors, factor: normalize(1) };
+
+// if (note && note.color && !DDS.isLargeTablet()) {
+// theme.shade = hexToRGBA(COLORS_NOTE[note.color?.toLowerCase()], 0.15);
+// }
+// tiny.call(EditorWebView, tiny.updateTheme(JSON.stringify(theme)));
+// }
+
+// export function isNotedEdited() {
+// return noteEdited;
+// }
+
+// async function waitForEvent(event, caller, onend) {
+// return new Promise(resolve => {
+// let resolved;
+// let event_callback = () => {
+// eUnSubscribeEvent(event, event_callback);
+// resolved = true;
+// clearTimeout(resolved);
+// onend && onend();
+// resolve();
+// };
+// eSubscribeEvent(event, event_callback);
+// caller && caller();
+// resolved = setTimeout(() => {
+// resolve(true);
+// }, 2000);
+// });
+// }
+
+// export async function clearTimer() {
+// if (waitForContent && noteEdited) {
+// await waitForEvent('content_event', () => {
+// console.log('requested content from edtior');
+// tiny.call(EditorWebView, request_content);
+// });
+// }
+// waitForContent = false;
+// }
+
+// export const CHECK_STATUS = `(function() {
+// let msg = JSON.stringify({
+// data: true,
+// type: 'running',
+// sessionId:sessionId
+// });
+// window.ReactNativeWebView.postMessage(msg)
+
+// })();`;
+
+// const request_content = `(function() {
+// if (window.ReactNativeWebView) {
+// if (!editor) return;
+// editor.getHTML().then(function(html) {
+// window.ReactNativeWebView.postMessage(
+// JSON.stringify({
+// type: 'tiny',
+// value:html,
+// caller:"request_content",
+// sessionId:sessionId
+// })
+// );
+// }).catch(console.log)
+// }
+// })();`;
+
+// export function getNote() {
+// return note;
+// }
+
+// export function setReadOnly(readonly) {
+// note.readonly = readonly;
+// }
+
+// export function setNoteOnly(n) {
+// note = n;
+// }
+
+// export function disableEditing() {
+// noteEdited = false;
+// disableSaving = true;
+// }
+
+// export const textInput = createRef();
+
+// export function post(type, value = null) {
+// let message = {
+// type,
+// value,
+// sessionId: sessionId
+// };
+// if (type === 'html') {
+// }
+
+// EditorWebView.current?.postMessage(JSON.stringify(message));
+// }
+
+// export const _onShouldStartLoadWithRequest = async request => {
+// if (request.url.includes('https')) {
+// if (Platform.OS === 'ios' && !request.isTopFrame) return;
+// openLinkInBrowser(request.url, appColors).catch(console.log).then(console.log);
+
+// return false;
+// } else {
+// return true;
+// }
+// };
+
+// export function checkNote() {
+// return note && note.id;
+// }
+
+// async function setNote(item) {
+// note = item;
+// saveCounter = 0;
+// title = note.title;
+// id = note.id;
+// noteEdited = false;
+// lastEditTime = item.dateEdited;
+// if (note.locked) {
+// content.data = note.content.data;
+// content.type = note.content.type;
+// } else {
+// let data = await db.content.raw(note.contentId);
+// if (!data) {
+// content.data = '';
+// content.type = 'tiny';
+// } else {
+// data = await db.content.insertPlaceholders(data, 'placeholder.svg');
+// content.data = data.data;
+// content.type = data.type;
+// }
+// }
+// }
+
+// function clearNote() {
+// note = null;
+// title = '';
+// noteEdited = false;
+// historySessionId = null;
+// prevNoteContent = content.data;
+// isSaving = false;
+// id = null;
+// content = {
+// data: '',
+// type: 'tiny'
+// };
+// }
+
+// function randId(prefix) {
+// return Math.random()
+// .toString(36)
+// .replace('0.', prefix || '');
+// }
+
+// function makeSessionId(item) {
+// sessionId = item?.id ? item.id + randId('_session_') : randId('session_');
+// }
+// let loading_queue;
+// let loading_note = false;
+// export const loadNote = async item => {
+// if (loading_note && id) {
+// loading_queue = item;
+// check_session_status();
+// return;
+// } else {
+// loading_queue = null;
+// }
+
+// loading_note = true;
+// editing.currentlyEditing = true;
+// editing.movedAway = false;
+
+// if (closingSession) {
+// console.log('open note:', 'closing: ', closingSession);
+// eSendEvent('loadingNote', item);
+// await waitForEvent('session_ended');
+// }
+
+// closingSession = true;
+// if (editing.isFocused) {
+// tiny.call(EditorWebView, tiny.blur);
+// }
+// if (item && item.type === 'new') {
+// if (getNote()) {
+// eSendEvent('loadingNote', item);
+// await clearEditor();
+// }
+// umami.pageView('/first-note', '/welcome/home');
+// clearNote();
+// eSendEvent('loadingNote');
+// eSendEvent('updateTags');
+// useEditorStore.getState().setReadonly(false);
+// closingSession = false;
+// disableSaving = false;
+// lastEditTime = 0;
+// noteEdited = false;
+// loading_queue = null;
+// makeSessionId(item);
+// useEditorStore.getState().setSessionId(sessionId);
+// await checkStatus(false);
+// tiny.call(
+// EditorWebView,
+// `
+// toggleNode(".tag-bar-parent","hide");
+// clearNode(".tag-bar")`
+// );
+
+// if (Platform.OS === 'android') {
+// EditorWebView.current?.requestFocus();
+// setTimeout(() => {
+// textInput.current?.focus();
+// EditorWebView.current?.requestFocus();
+// tiny.call(EditorWebView, tiny.focusEditor);
+// }, 200);
+// } else {
+// await sleep(200);
+// tiny.call(EditorWebView, tiny.focusEditor);
+// }
+
+// if (EDITOR_SETTINGS) {
+// console.log('settings are present');
+// tiny.call(
+// EditorWebView,
+// EDITOR_SETTINGS.directionality === 'rtl'
+// ? `tinymce.activeEditor.execCommand('mceDirectionRTL');`
+// : `tinymce.activeEditor.execCommand('mceDirectionLTR');`
+// );
+// }
+// requestedReload = true;
+// updateSessionStatus();
+// tiny.call(EditorWebView, tiny.notLoading + tiny.toogleReadMode('design'));
+// } else {
+// if (id === item.id && !item.forced) {
+// console.log('note is already opened in editor');
+// closingSession = false;
+// loading_note = false;
+// eSendEvent('loadingNote');
+// await checkStatus();
+// return;
+// }
+// eSendEvent('loadingNote', item);
+// if (getNote()) {
+// await clearEditor();
+// }
+
+// closingSession = false;
+// disableSaving = false;
+// noteEdited = false;
+// webviewInit = false;
+// editing.isFocused = false;
+// useEditorStore.getState().setReadonly(item.readonly);
+// await setNote(item);
+// if (loading_queue && (loading_queue?.id !== item?.id || loading_queue?.type === 'new')) {
+// clearNote();
+// loading_note = false;
+// loadNote(loading_queue);
+
+// return;
+// }
+// // tiny.call(
+// // EditorWebView,
+// // `toggleNode(".tag-bar-parent","show");
+// // clearNode(".tag-bar")`
+// // );
+// makeSessionId(item);
+// useEditorStore.getState().setSessionId(sessionId);
+// webviewInit = true;
+// await loadNoteInEditor();
+// requestedReload = true;
+// if (await checkStatus(false)) {
+// updateSessionStatus();
+// }
+// setTimeout(() => {
+// useEditorStore.getState().setCurrentlyEditingNote(item.id);
+// }, 1);
+// }
+
+// loading_note = false;
+// };
+
+// export const checkStatus = async noreset => {
+// return new Promise(resolve => {
+// webviewOK = false;
+// console.log('checking status of webview');
+// clearTimeout(webviewTimer);
+// webviewTimer = null;
+// const onWebviewOk = () => {
+// webviewOK = true;
+// webviewInit = true;
+// clearTimeout(webviewTimer);
+// webviewTimer = null;
+// console.log('webviewOk:', webviewOK);
+// resolve(true);
+// eUnSubscribeEvent('webviewOk', onWebviewOk);
+// };
+// eSubscribeEvent('webviewOk', onWebviewOk);
+// setTimeout(
+// () => {
+// EditorWebView.current?.injectJavaScript(CHECK_STATUS);
+// },
+// Platform.OS === 'ios' ? 300 : 1
+// );
+
+// webviewTimer = setTimeout(() => {
+// console.log('webviewOK:', webviewOK, 'Reset blocked:', noreset);
+// if (!webviewOK && !noreset) {
+// webviewInit = false;
+// console.log('full reset');
+// EditorWebView = createRef();
+// eSendEvent('webviewreset');
+// resolve(true);
+// }
+// }, 1000);
+// });
+// };
+
+// function updateSessionStatus() {
+// tiny.call(
+// EditorWebView,
+// `(function () {
+// sessionId = '${sessionId}';
+// reactNativeEventHandler('status', true);
+// })();`
+// );
+// }
+
+// function isContentInvalid(content) {
+// return (
+// !content ||
+// content === '' ||
+// content.trim() === '' ||
+// content === '<p></p>' ||
+// content === '<p><br></p>' ||
+// content === '<p>&nbsp;</p>' ||
+// content === `<p><br data-mce-bogus="1"></p>`
+// );
+// }
+
+// function check_session_status() {
+// tiny.call(
+// EditorWebView,
+// `(function () {
+// if (window.ReactNativeWebView) {
+// if (!editor) return;
+
+// editor.getHTML().then(function (value) {
+// let status =
+// !value ||
+// value === '' ||
+// value.trim() === '' ||
+// value === '<p></p>' ||
+// value === '<p><br></p>' ||
+// value === '<p>&nbsp;</p>' ||
+// value === '<p><br data-mce-bogus="1"></p>';
+
+// window.ReactNativeWebView.postMessage(
+// JSON.stringify({
+// type: 'content_not_loaded',
+// value: status,
+// sessionId: sessionId
+// })
+// );
+// }).catch(console.log)
+// }
+// })();`
+// );
+// }
+
+// export const _onMessage = async evt => {
+// if (!evt || !evt.nativeEvent || !evt.nativeEvent.data) return;
+// let message = evt.nativeEvent.data;
+// let user;
+// try {
+// message = JSON.parse(message);
+// } catch (e) {
+// return;
+// }
+// switch (message.type) {
+// case 'tinyerror':
+// console.log('tinyerror', message.value);
+// ToastEvent.error(message.value, 'Error saving note', 'global');
+// break;
+// case 'tableconfig':
+// showTableOptionsTooltip();
+// break;
+// case 'tablecelloptions':
+// TableCellProperties.present(message.value);
+// break;
+// case 'tablerowoptions':
+// TableRowProperties.present(message.value);
+// break;
+// case 'selectionvalue':
+// eSendEvent('selectionvalue', message.value);
+// break;
+// case 'history':
+// eSendEvent('historyEvent', message.value);
+// break;
+// case 'noteedited':
+// if (message.sessionId !== sessionId) return;
+// console.log('noteedited');
+// noteEdited = true;
+// break;
+// case 'tiny':
+// if (message.sessionId !== sessionId) return;
+// if (prevNoteContent && message.value === prevNoteContent) {
+// prevNoteContent = null;
+// noteEdited = false;
+// return;
+// }
+// prevNoteContent = null;
+// console.log('tiny content recieved', message.caller);
+// noteEdited = true;
+// lastEditTime = Date.now();
+// content = {
+// type: message.type,
+// data: message.value
+// };
+// onNoteChange(message.caller ? 0 : 300);
+// if (waitForContent) {
+// eSendEvent('content_event');
+// }
+// break;
+// case 'title':
+// if (message.sessionId !== sessionId) return;
+// if (message.value !== title) {
+// noteEdited = true;
+// lastEditTime = Date.now();
+// title = message.value;
+// eSendEvent('editorScroll', {
+// title: message.value
+// });
+// onNoteChange();
+// }
+// break;
+// case 'scroll':
+// eSendEvent('editorScroll', message);
+// break;
+// case 'attachment_download':
+// filesystem.downloadAttachment(message.value, true);
+// break;
+// case 'noteLoaded':
+// tiny.call(EditorWebView, tiny.notLoading);
+// eSendEvent('loadingNote');
+// break;
+// case 'premium':
+// user = await db.user.getUser();
+// if (user && !user.isEmailConfirmed) {
+// await sleep(500);
+// PremiumService.showVerifyEmailDialog();
+// } else {
+// eSendEvent(eShowGetPremium, {
+// context: 'editor',
+// title: 'Get Notesnook Pro',
+// desc: 'Enjoy Full Rich Text Editor with Markdown Support!'
+// });
+// }
+// break;
+// case 'status':
+// if (sessionId !== message.sessionId) {
+// if (!sessionId) makeSessionId({ id });
+// updateSessionStatus();
+// return;
+// }
+
+// if (!requestedReload && getNote()) {
+// check_session_status();
+// return;
+// }
+// requestedReload = false;
+// setColors(COLOR_SCHEME);
+// eSendEvent('webviewOk');
+// loading_note = false;
+// webviewInit = true;
+// webviewOK = true;
+// setTimeout(() => {
+// if (PremiumService.get()) {
+// tiny.call(EditorWebView, tiny.setMarkdown, true);
+// } else {
+// tiny.call(EditorWebView, tiny.removeMarkdown, true);
+// }
+// }, 300);
+// setTimeout(() => {
+// check_session_status();
+// }, 1500);
+// break;
+// case 'content_not_loaded':
+// loading_note = false;
+// if (isContentInvalid(content.data)) return;
+// if (message.sessionId !== sessionId) {
+// requestedReload = true;
+// updateSessionStatus();
+// return;
+// }
+// if (!id) return;
+
+// if (message.value) {
+// console.log('content not loaded', content.data);
+// await checkStatus();
+// console.log('reloading');
+// await loadNoteInEditor();
+// setTimeout(() => {
+// check_session_status();
+// }, 1500);
+// }
+// break;
+// case 'running':
+// eSendEvent('webviewOk');
+// webviewOK = true;
+// break;
+// case 'resetcomplete':
+// console.log('reset event recieved');
+// eSendEvent('resetcomplete');
+// break;
+// case 'editorSettings':
+// EDITOR_SETTINGS = message.value;
+// eSendEvent('editorSettingsEvent', message.value);
+// break;
+// case 'imagepreview':
+// eSendEvent('ImagePreview', message.value);
+// break;
+// case 'imageoptions':
+// if (editing.tooltip === 'imageoptions') {
+// eSendEvent('showTooltip');
+// break;
+// }
+// showImageOptionsTooltip();
+// break;
+// case 'focus':
+// editing.focusType = message.value;
+// break;
+// case 'selectionchange':
+// eSendEvent('onSelectionChange', message.value);
+// break;
+// case 'notetag':
+// if (message.value) {
+// let _tag = JSON.parse(message.value);
+// console.log(_tag.title);
+// await db.notes.note(note.id).untag(_tag.title);
+// useTagStore.getState().setTags();
+// Navigation.setRoutesToUpdate([
+// Navigation.routeNames.Notes,
+// Navigation.routeNames.NotesPage,
+// Navigation.routeNames.Tags
+// ]);
+// }
+// break;
+// case 'newtag':
+// if (!getNote()) {
+// ToastEvent.show({
+// heading: 'Create a note first'
+// });
+// return;
+// }
+// eSendEvent(eOpenTagsDialog, note);
+// break;
+// default:
+// break;
+// }
+// };
+
+// function showImageOptionsTooltip() {
+// editing.tooltip = 'imageoptions';
+// eSendEvent('showTooltip', IMAGE_TOOLTIP_CONFIG);
+// }
+
+// function showTableOptionsTooltip() {
+// editing.tooltip = 'tableconfig';
+// console.log('showTooltip');
+// eSendEvent('showTooltip', TABLE_TOOLTIP_CONFIG);
+// }
+
+// function onNoteChange(wait = 300) {
+// clearTimeout(timer);
+// timer = null;
+// noteEdited = false;
+// let params = [title, id, content.data, content.type, sessionId, historySessionId];
+// timer = setTimeout(() => {
+// if (!params[1]) {
+// params[1] = id;
+// }
+// saveNote(...params);
+// }, wait);
+// }
+
+// export async function clearEditor() {
+// try {
+// console.log('closing session: ', closingSession);
+// closingSession = true;
+// await sleep(100);
+// console.log('note edited: ', noteEdited);
+// if (noteEdited) {
+// console.log('note is edited');
+// disableSaving = false;
+// waitForContent = true;
+// await clearTimer(true);
+// await sleep(100);
+// }
+
+// disableSaving = true;
+// sessionId = null;
+// noteEdited = false;
+// db.fs.cancel(getNote()?.id);
+// clearNote();
+// placeholderTip = TipManager.placeholderTip();
+// tiny.call(EditorWebView, tiny.reset(placeholderTip));
+// //EditorWebView.current?.reload();
+// await waitForEvent('resetcomplete');
+// editing.focusType = null;
+// eSendEvent('historyEvent', {
+// undo: 0,
+// redo: 0
+// });
+// saveCounter = 0;
+// useEditorStore.getState().setCurrentlyEditingNote(null);
+// } catch (e) {}
+
+// disableSaving = false;
+// eSendEvent('session_ended');
+// closingSession = false;
+// }
+
+// async function setNoteInEditorAfterSaving(oldId, currentId) {
+// if (oldId !== currentId) {
+// id = currentId;
+// note = db.notes.note(id);
+// if (note) {
+// note = note.data;
+// } else {
+// await sleep(500);
+// note = db.notes.note(id);
+// if (note) {
+// note = note.data;
+// }
+// }
+// }
+// }
+
+// async function addToCollection(id) {
+// switch (editing.actionAfterFirstSave.type) {
+// case 'topic': {
+// await db.notes.move(
+// {
+// topic: editing.actionAfterFirstSave.id,
+// id: editing.actionAfterFirstSave.notebook
+// },
+// id
+// );
+// editing.actionAfterFirstSave = {
+// type: null
+// };
+// Navigation.setRoutesToUpdate([
+// Navigation.routeNames.Notebooks,
+// Navigation.routeNames.NotesPage,
+// Navigation.routeNames.Notebook
+// ]);
+// break;
+// }
+// case 'tag': {
+// await db.notes.note(id).tag(editing.actionAfterFirstSave.id);
+// editing.actionAfterFirstSave = {
+// type: null
+// };
+// Navigation.setRoutesToUpdate([Navigation.routeNames.Tags, Navigation.routeNames.NotesPage]);
+// break;
+// }
+// case 'color': {
+// await db.notes.note(id).color(editing.actionAfterFirstSave.id);
+// editing.actionAfterFirstSave = {
+// type: null
+// };
+// Navigation.setRoutesToUpdate([Navigation.routeNames.NotesPage]);
+// useMenuStore.getState().setColorNotes();
+// break;
+// }
+// default: {
+// break;
+// }
+// }
+// }
+
+// export async function saveNote(title, _id, data, type, _sessionId, _historySessionId) {
+// console.log('saving note:', disableSaving, isSaving, _id, id);
+// if (typeof data !== 'string') return;
+// if (disableSaving || (isSaving && !id)) return;
+// if (_sessionId !== sessionId) {
+// noteEdited = false;
+// }
+// isSaving = true;
+// try {
+// if (_id && !db.notes.note(_id)) {
+// clearNote();
+// useEditorStore.getState().setCurrentlyEditingNote(null);
+// return;
+// }
+// let locked = false;
+// if (_id) {
+// let _note = db.notes.note(_id).data;
+// if (_note.readonly) return;
+// if (_note.conflicted) {
+// presentResolveConflictDialog(_note);
+// return;
+// }
+// locked = _note.locked;
+// }
+
+// if (isContentInvalid(data) || !_historySessionId) {
+// _historySessionId = note?.dateEdited || Date.now();
+// historySessionId = _historySessionId;
+// console.log('new session begins');
+// }
+
+// console.log('compare ids:', _sessionId === sessionId, _historySessionId === historySessionId);
+// console.log(sessionId, historySessionId);
+// let noteData = {
+// title,
+// content: {
+// data: data,
+// type: type
+// },
+// id: _id,
+// sessionId: isContentInvalid(data) ? null : _historySessionId
+// };
+
+// console.log(
+// 'Note Saved:::',
+// 'historySessionId:',
+// _historySessionId,
+// 'preventUpdate: ',
+// sessionId === _sessionId
+// );
+
+// if (!locked) {
+// let noteId = await db.notes.add(noteData);
+// if (!_id || saveCounter < 3) {
+// Navigation.setRoutesToUpdate([
+// Navigation.routeNames.Notes,
+// Navigation.routeNames.Favorites,
+// Navigation.routeNames.NotesPage,
+// Navigation.routeNames.Notebook
+// ]);
+// }
+// if (!_id) {
+// id = noteId;
+// await addToCollection(noteId);
+// }
+
+// if (!_id && sessionId === _sessionId) {
+// if (!title || title === '') {
+// console.log('posting title now');
+// post('titleplaceholder', db.notes.note(noteId)?.data?.title || '');
+// }
+
+// await setNoteInEditorAfterSaving(_id, noteId);
+// saveCounter++;
+// setTimeout(() => {
+// useEditorStore.getState().setCurrentlyEditingNote(noteId);
+// });
+// }
+// _id = noteId;
+// } else {
+// noteData.contentId = note.contentId;
+// await db.vault.save(noteData);
+// }
+// if (sessionId === _sessionId) {
+// Navigation.setRoutesToUpdate([
+// Navigation.routeNames.NotesPage,
+// Navigation.routeNames.Favorites,
+// Navigation.routeNames.Notes
+// ]);
+
+// lastEditTime = n + 10;
+// let n = db.notes.note(_id)?.data?.dateEdited;
+// tiny.call(
+// EditorWebView,
+// tiny.updateDateEdited(n ? timeConverter(n) : '') + tiny.updateSavingState(!n ? '' : 'Saved')
+// );
+// }
+// } catch (e) {
+// if (e.message === 'ERR_VAULT_LOCKED') {
+// console.log(e);
+// presentDialog({
+// input: true,
+// inputPlaceholder: 'Enter vault password',
+// title: 'Unlock note',
+// paragraph: 'To save note, unlock it',
+// positiveText: 'Unlock',
+// positivePress: async password => {
+// if (password && password.trim()) {
+// try {
+// await db.vault.unlock(password);
+// noteEdited = true;
+// onNoteChange(0);
+// } catch (e) {
+// console.log(e);
+// return false;
+// }
+// } else {
+// return false;
+// }
+// },
+// negativeText: 'Cancel',
+// onClose: () => {
+// noteEdited = false;
+// eSendEvent(eClearEditor);
+// }
+// });
+// }
+// console.log(e);
+// ToastEvent.show({
+// heading: 'Error saving note',
+// message: e.message,
+// type: 'error'
+// });
+// }
+// isSaving = false;
+// }
+// let isInitalLaunch = true;
+// export async function onWebViewLoad(premium, colors) {
+// eSendEvent('resetcomplete');
+// setTimeout(() => {
+// if (PremiumService.get()) {
+// tiny.call(EditorWebView, tiny.setMarkdown, true);
+// } else {
+// tiny.call(EditorWebView, tiny.removeMarkdown, true);
+// }
+// }, 300);
+// setColors(colors);
+
+// if (isInitalLaunch) {
+// tiny.call(EditorWebView, tiny.setPlaceholder(placeholderTip));
+// isInitalLaunch = false;
+// }
+// }
+
+// async function restoreEditorState() {
+// let appState = await MMKV.getItem('appState');
+// if (appState) {
+// appState = JSON.parse(appState);
+// if (
+// appState.editing &&
+// appState.note &&
+// !appState.note.locked &&
+// appState.note.id &&
+// Date.now() < appState.timestamp + 3600000
+// ) {
+// editing.isRestoringState = true;
+// eSendEvent('loadingNote', appState.note);
+// editing.currentlyEditing = true;
+// if (!DDS.isTab) {
+// tabBarRef.current?.goToPage(1);
+// }
+// setTimeout(() => {
+// eSendEvent(eOnLoadNote, appState.note);
+// }, 100);
+// MMKV.removeItem('appState');
+// editing.movedAway = false;
+// eSendEvent('load_overlay', 'hide_editor');
+// editing.isRestoringState = false;
+// return;
+// }
+// editing.isRestoringState = false;
+// return;
+// }
+// editing.isRestoringState = false;
+// }
+
+// export const presentResolveConflictDialog = _note => {
+// presentDialog({
+// title: 'Changes not saved',
+// paragraph: 'Please resolve conflicts to save changes',
+// positiveText: 'Resolve',
+// positivePress: () => {
+// eSendEvent(eShowMergeDialog, _note);
+// }
+// });
+// };
+
+// const loadNoteInEditor = async (keepHistory = true) => {
+// console.log(webviewInit, 'ready?');
+// if (!webviewInit) return;
+// try {
+// if (note?.id) {
+// eSendEvent('updateTags');
+// post('title', title);
+
+// if (!content || !content.data || content?.data?.length === 0) {
+// tiny.call(
+// EditorWebView,
+// `
+// sessionId = "${sessionId}"
+// globalThis.isClearingNoteData = false;
+// window.ReactNativeWebView.postMessage(
+// JSON.stringify({
+// type: 'noteLoaded',
+// value: true,
+// sessionId:sessionId
+// }),
+// );
+// `
+// );
+// } else {
+// console.log('posting html');
+// post('html', {
+// data: content.data,
+// readOnly: note.readonly
+// });
+// }
+// if (id) {
+// db.attachments.downloadImages(id);
+// }
+
+// setColors();
+// tiny.call(
+// EditorWebView,
+// tiny.updateDateEdited(timeConverter(note.dateEdited)) + tiny.updateSavingState('Saved')
+// );
+// } else {
+// tiny.call(EditorWebView, tiny.toogleReadMode('design'));
+// await restoreEditorState();
+// }
+
+// if (keepHistory) {
+// tiny.call(EditorWebView, tiny.clearHistory);
+// }
+// } catch (e) {}
+
+// disableSaving = false;
+// check_session_status();
+// };
+
+// export async function updateNoteInEditor() {
+// return;
+// // let _note = db.notes.note(id).data;
+// // if (_note.conflicted) {
+// // presentResolveConflictDialog(_note);
+// // return;
+// // }
+// // let data = await db.content.raw(_note.contentId);
+// // if (lastEditTime > _note.dateEdited) return;
+// // if (data.data === content.data) return;
+// // if (content.data.indexOf(data.data) !== -1) return;
+// // if (note.dateEdited === _note.dateEdited) return;
+
+// // title = note.title;
+// // content.data = data.data;
+// // note = _note;
+// // lastEditTime = _note.dateEdited + 10;
+// // tiny.call(EditorWebView, tiny.isLoading);
+// // await setNote(_note);
+// // tiny.call(EditorWebView, tiny.isLoading);
+// // post('title', title);
+// // post('inject', content.data);
+// // setTimeout(() => {
+// // tiny.call(EditorWebView, tiny.notLoading);
+// // }, 50);
+// // if (id) {
+// // db.attachments.downloadImages(id);
+// // }
+// // tiny.call(EditorWebView, tiny.notLoading);
+// }
diff --git a/apps/mobile/src/screens/editor/index.js b/apps/mobile/src/screens/editor/index.js
index 196696972..408ada906 100755
--- a/apps/mobile/src/screens/editor/index.js
+++ b/apps/mobile/src/screens/editor/index.js
@@ -1,27 +1,11 @@
-import React, { useEffect, useRef, useState } from 'react';
+import React from 'react';
import { Platform, View } from 'react-native';
import WebView from 'react-native-webview';
import { notesnook } from '../../../e2e/test.ids';
import { useEditorStore, useUserStore } from '../../stores/stores';
-import { DDS } from '../../services/device-detection';
-import { eSendEvent, eSubscribeEvent, eUnSubscribeEvent } from '../../services/event-manager';
-import { getCurrentColors } from '../../utils/color-scheme';
-import { eOnLoadNote } from '../../utils/events';
-import { tabBarRef } from '../../utils/global-refs';
-import { sleep } from '../../utils/time';
import EditorHeader from './EditorHeader';
-import {
- disableEditing,
- EditorWebView,
- getNote,
- onWebViewLoad,
- sourceUri,
- _onMessage,
- _onShouldStartLoadWithRequest
-} from './Functions';
-import tiny from './tiny/tiny';
-import EditorToolbar from './tiny/toolbar';
-import { useEditor } from './use-editor';
+import { sourceUri, _onShouldStartLoadWithRequest } from './Functions';
+import { useEditor } from './tiptap/use-editor';
const source = { uri: sourceUri + 'index.html' };
@@ -37,49 +21,9 @@ const Editor = React.memo(
() => {
const premiumUser = useUserStore(state => state.premium);
const sessionId = useEditorStore(state => state.sessionId);
- const [resetting, setResetting] = useState(false);
- const editorRef = useRef();
- const editor = useEditor(editorRef);
+ const editor = useEditor();
- const onLoad = async () => {
- await onWebViewLoad(premiumUser, getCurrentColors());
- };
-
- useEffect(() => {
- if (premiumUser) {
- tiny.call(EditorWebView, tiny.setMarkdown, true);
- }
- }, [premiumUser]);
-
- const onResetRequested = async preventSave => {
- if (!getNote()) {
- eSendEvent('loadingNote', null);
- }
- setResetting(true);
- await sleep(10);
- setResetting(false);
- if (!DDS.isTab && tabBarRef.current?.page === 0) {
- console.log('Editor out of bounds');
- return;
- }
- if (preventSave) {
- disableEditing();
- }
-
- if (getNote()) {
- eSendEvent(eOnLoadNote, { ...getNote(), forced: true });
- }
- console.log('resetting editor');
- };
-
- useEffect(() => {
- eSubscribeEvent('webviewreset', onResetRequested);
- return () => {
- eUnSubscribeEvent('webviewreset', onResetRequested);
- };
- }, []);
-
- return resetting ? null : (
+ return editor.loading ? null : (
<>
<View
style={{
@@ -88,17 +32,17 @@ const Editor = React.memo(
flex: 1
}}
>
- <EditorHeader />
+ <EditorHeader editor={editor} />
<WebView
testID={notesnook.editor.id}
- ref={EditorWebView}
- onLoad={onLoad}
- onRenderProcessGone={() => {
- onResetRequested();
- }}
- onError={() => {
- onResetRequested();
- }}
+ ref={editor.ref}
+ onLoad={editor.onLoad}
+ // onRenderProcessGone={() => {
+ // onResetRequested();
+ // }}
+ // onError={() => {
+ // onResetRequested();
+ // }}
injectedJavaScript={`globalThis.sessionId="${sessionId}";`}
javaScriptEnabled={true}
focusable={true}
@@ -118,14 +62,13 @@ const Editor = React.memo(
allowUniversalAccessFromFileURLs={true}
originWhitelist={['*']}
source={{
- uri: 'http://192.168.10.3:3000'
+ uri: 'http://192.168.10.6:3000'
}}
style={style}
autoManageStatusBarEnabled={false}
onMessage={editor.onMessage}
/>
</View>
- <EditorToolbar />
</>
);
},
diff --git a/apps/mobile/src/screens/editor/tiny/tiny.js b/apps/mobile/src/screens/editor/tiny/tiny.js
index 549f8f5dc..092786416 100644
--- a/apps/mobile/src/screens/editor/tiny/tiny.js
+++ b/apps/mobile/src/screens/editor/tiny/tiny.js
@@ -1,6 +1,7 @@
import { Platform } from 'react-native';
import { editing } from '../../../utils';
-import { EditorWebView, getWebviewInit, post, textInput } from '../Functions';
+import { EditorWebView, getWebviewInit, post } from '../Functions';
+import { textInput } from '../tiptap/utils';
/**
*
@@ -211,7 +212,7 @@ export function safeKeyboardDismiss() {
textInput.current?.focus();
textInput.current?.blur();
} else {
- call(EditorWebView, blur);
+ // call(EditorWebView, blur);
}
}
diff --git a/apps/mobile/src/screens/editor/tiptap/commands.ts b/apps/mobile/src/screens/editor/tiptap/commands.ts
new file mode 100644
index 000000000..3a9fea98c
--- /dev/null
+++ b/apps/mobile/src/screens/editor/tiptap/commands.ts
@@ -0,0 +1,59 @@
+import { RefObject } from 'react';
+import { Platform } from 'react-native';
+import WebView from 'react-native-webview';
+import { sleep } from '../../../utils/time';
+import { textInput } from './utils';
+
+function call(webview: RefObject<WebView> | null, func?: string) {
+ if (!webview || !func) return;
+ webview.current?.injectJavaScript(func);
+}
+
+const fn = (fn: string) => `(() => {
+ ${fn}
+})();`;
+
+class Commands {
+ ref: RefObject<WebView> | null = null;
+ constructor(ref: RefObject<WebView>) {
+ this.ref = ref;
+ }
+
+ focus = async () => {
+ if (!this.ref) return;
+ if (Platform.OS === 'android') {
+ this.ref.current?.requestFocus();
+ setTimeout(() => {
+ if (!this.ref) return;
+ textInput.current?.focus();
+ this.ref?.current?.requestFocus();
+ call(this.ref, fn(`editor.commands.focus()`));
+ }, 1);
+ } else {
+ await sleep(200);
+ call(this.ref, fn(`editor.commands.focus()`));
+ }
+ };
+
+ blur = () => call(this.ref, fn(`editor.commands.blur();editorTitle.current?.blur()`));
+
+ clearContent = () => {
+ this.blur();
+ call(
+ this.ref,
+ fn(
+ `editor?.commands.clearContent(false);
+editorController.setTitle(null);
+statusBar.current.set({date:"",saved:""});
+ `
+ )
+ );
+ };
+
+ setSessionId = (id: string) => call(this.ref, fn(`globalThis.sessionId = "${id}"`));
+
+ setStatus = (date: string, saved: string) =>
+ call(this.ref, fn(`statusBar.current.set({date:"${date}",saved:"${saved}"})`));
+}
+
+export default Commands;
diff --git a/apps/mobile/src/screens/editor/tiptap/useEditor.js b/apps/mobile/src/screens/editor/tiptap/useEditor.js
new file mode 100644
index 000000000..92967cd9f
--- /dev/null
+++ b/apps/mobile/src/screens/editor/tiptap/useEditor.js
@@ -0,0 +1,216 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { eSendEvent, eSubscribeEvent, eUnSubscribeEvent } from '../../../services/event-manager';
+import { useEditorStore } from '../../../stores/stores';
+import { editing } from '../../../utils';
+import { db } from '../../../utils/database';
+import { eOnLoadNote } from '../../../utils/events';
+import { timeConverter } from '../../../utils/time';
+import Commands from './commands';
+import { EditorEvents, isEditorLoaded, makeSessionId, post } from './utils';
+
+export const useEditor = () => {
+ const [loading, setLoading] = useState(false);
+ const sessionId = useEditorStore(state => state.sessionId);
+ const editorRef = useRef();
+ const currentNote = useRef();
+ const currentContent = useRef();
+ const postMessage = async (type, data) => await post(editorRef, type, data);
+ const timers = useRef({});
+ const commands = new Commands(editorRef);
+ const sessionHistoryId = useRef();
+
+ useEffect(() => {
+ console.log('sessionId:', sessionId);
+ commands.setSessionId(sessionId);
+ if (sessionId) {
+ (async () => {
+ if (!(await isEditorLoaded(editorRef))) {
+ console.log('should reload');
+ setLoading(true);
+ }
+ })();
+ }
+ }, [sessionId, loading]);
+
+ useEffect(() => {
+ if (loading) {
+ setLoading(false);
+ }
+ }, [loading]);
+
+ const withTimer = (id, fn, duration) => {
+ clearTimeout(id);
+ timers.current[id] = setTimeout(fn, duration);
+ };
+
+ const reset = () => {
+ currentNote.current = null;
+ currentContent.current = null;
+ useEditorStore.getState().setCurrentlyEditingNote(null);
+ commands.clearContent();
+ };
+
+ async function saveNote(title, id, data, type, sessionId) {
+ console.log('saving note', id);
+ try {
+ if (id && !db.notes.note(id)) {
+ useEditorStore.getState().setCurrentlyEditingNote(null);
+ return;
+ }
+ let note = id && db.notes.note(id)?.data;
+ let locked = note?.locked;
+ if (note?.conflicted) return;
+
+ if (!sessionHistoryId.current) {
+ if (note) {
+ sessionHistoryId.current = note.dateEdited;
+ } else {
+ sessionHistoryId.current = Date.now();
+ }
+ }
+
+ let noteData = {
+ id,
+ sessionId: sessionHistoryId.current
+ };
+
+ if (title) {
+ noteData.title = title;
+ }
+
+ if (data) {
+ noteData.content = {
+ data: data,
+ type: type
+ };
+ }
+
+ if (!locked) {
+ id = await db.notes.add(noteData);
+ if (!note) currentNote.current = db.notes.note(id).data;
+
+ if (useEditorStore.getState().currentEditingNote !== id) {
+ setTimeout(() => {
+ useEditorStore.getState().setCurrentlyEditingNote(id);
+ });
+ }
+ } else {
+ noteData.contentId = note.contentId;
+ await db.vault.save(noteData);
+ }
+
+ commands.setStatus(timeConverter(db.notes.note(id)?.data?.dateEdited), 'Saved');
+
+ return id;
+
+ //let n = db.notes.note(id)?.data?.dateEdited;
+ // tiny.call(EditorWebView, tiny.updateDateEdited(n ? timeConverter(n) : ''));
+ // tiny.call(EditorWebView, tiny.updateSavingState(!n ? '' : 'Saved'));
+ } catch (e) {
+ console.log('error saving: ', e);
+ }
+ }
+
+ const loadContent = async note => {
+ currentNote.current = note;
+ if (note.locked) {
+ currentContent.current = {
+ data: note.content.data,
+ type: note.content.type
+ };
+ } else {
+ let data = await db.content.raw(note.contentId);
+ if (data) {
+ data = await db.content.insertPlaceholders(data, 'placeholder.svg');
+ currentContent.current = {
+ data: data.data,
+ type: data.type
+ };
+ }
+ }
+ };
+
+ const loadNote = async item => {
+ console.log('loading note', item.type);
+ editing.currentlyEditing = true;
+ const editorState = useEditorStore.getState();
+
+ if (item && item.type === 'new') {
+ currentNote.current && reset();
+ editorState.setSessionId(makeSessionId());
+ commands.focus();
+ } else {
+ if (!item.forced && currentNote.current?.id === item.id) return;
+ currentNote.current && reset();
+ await loadContent(item);
+ editorState.setSessionId(makeSessionId(item));
+ editorState.setCurrentlyEditingNote(item.id);
+ currentNote.current = item;
+ commands.setStatus(timeConverter(item.dateEdited), 'Saved');
+ await postMessage(EditorEvents.title, item.title);
+ await postMessage(EditorEvents.html, currentContent.current?.data);
+ }
+ };
+
+ useEffect(() => {
+ eSubscribeEvent(eOnLoadNote, loadNote);
+ return () => {
+ eUnSubscribeEvent(eOnLoadNote, loadNote);
+ };
+ }, []);
+
+ const onMessage = useCallback(
+ event => {
+ let message = event.nativeEvent.data;
+ message = JSON.parse(message);
+
+ console.log(message.type);
+
+ if (message.sessionId !== sessionId && message.type !== EditorEvents.status) {
+ console.log(
+ 'useEditor: message recieved from invalid session',
+ message.type,
+ sessionId,
+ message.sessionId
+ );
+ return;
+ }
+ switch (message.type) {
+ case EditorEvents.logger:
+ console.log(message.type, message.value);
+ break;
+ case 'editor-event:content':
+ saveContent(null, message.value);
+ break;
+ case 'editor-event:selection':
+ break;
+ case 'editor-event:title':
+ saveContent(message.value);
+ break;
+ }
+ if (message.type.startsWith('native:')) {
+ eSendEvent(message.type, message);
+ }
+ },
+ [sessionId]
+ );
+
+ const saveContent = (title, content) => {
+ currentContent.current = {
+ data: content,
+ type: 'tiny'
+ };
+ let params = [title, currentNote.current?.id, content, 'tiny', sessionId];
+ withTimer(currentNote.current?.id, () => saveNote(...params));
+ };
+
+ const onLoad = () => {
+ console.log('on editor load');
+ if (currentNote.current) {
+ console.log('force reload note');
+ loadNote({ ...currentNote.current, forced: true });
+ }
+ };
+
+ return { onMessage, ref: editorRef, onLoad, commands, reset, loading, setLoading };
+};
diff --git a/apps/mobile/src/screens/editor/tiptap/utils.js b/apps/mobile/src/screens/editor/tiptap/utils.js
new file mode 100644
index 000000000..abe5a6247
--- /dev/null
+++ b/apps/mobile/src/screens/editor/tiptap/utils.js
@@ -0,0 +1,60 @@
+import { createRef } from 'react';
+import { Platform } from 'react-native';
+import { eSubscribeEvent, eUnSubscribeEvent } from '../../../services/event-manager';
+import { useEditorStore } from '../../../stores/stores';
+import { sleep } from '../../../utils/time';
+import commands from './commands';
+export const textInput = createRef();
+
+export const EditorEvents = {
+ html: 'native:html',
+ title: 'native:title',
+ theme: 'native:theme',
+ titleplaceholder: 'native:titleplaceholder',
+ logger: 'native:logger',
+ status: 'native:status'
+};
+
+function randId(prefix) {
+ return Math.random()
+ .toString(36)
+ .replace('0.', prefix || '');
+}
+
+export function makeSessionId(item) {
+ return item?.id ? item.id + randId('_session_') : randId('session_');
+}
+
+export async function isEditorLoaded(ref) {
+ return await post(ref, EditorEvents.status);
+}
+
+export async function post(ref, type, value = null) {
+ let sessionId = useEditorStore.getState().sessionId;
+ if (!sessionId) {
+ console.warn('post called without sessionId of type:', type);
+ return;
+ }
+ let message = {
+ type,
+ value,
+ sessionId: sessionId
+ };
+ ref.current?.postMessage(JSON.stringify(message));
+ let response = await getResponse(type);
+ console.log('post: ', type, 'result:', response);
+ return response;
+}
+
+const getResponse = async type => {
+ return new Promise(resolve => {
+ let callback = data => {
+ eUnSubscribeEvent(type, callback);
+ resolve(data);
+ };
+ eSubscribeEvent(type, callback);
+ setTimeout(() => {
+ resolve(false);
+ }, 5000);
+ });
+};
diff --git a/apps/mobile/src/screens/editor/useEditor.js b/apps/mobile/src/screens/editor/useEditor.js
deleted file mode 100644
index 3e6a4d5da..000000000
--- a/apps/mobile/src/screens/editor/useEditor.js
+++ /dev/null
@@ -1,43 +0,0 @@
-import { db } from '../../utils/database';
-import { useEditorStore } from '../../provider/stores';
-
-async function save(id, data, sessionId) {
- let note = id ? db.notes.note(id).data : null;
-
- let noteId = await db.notes.add({
- id,
- ...data,
- sessionId
- });
-
- return noteId || id;
-}
-
-export const useEditor = ref => {
- const sessionId = useEditorStore(state => state.sessionId);
-
- const onMessage = event => {
- let message = event.nativeEvent.data;
- message = JSON.parse(message);
-
- console.log(message.type, message.value);
-
- if (message.sessionId !== sessionId) {
- console.log('useEditor: message recieved from invalid session', sessionId, message.sessionId);
- return;
- }
- switch (message.type) {
- case 'native:logger':
- console.log(message.type, message.value);
- return;
- case 'editor-event:content':
- return;
- case 'editor-event:selection':
- return;
- case 'editor-event:title':
- return;
- }
- };
-
- return { onMessage };
-};
diff --git a/apps/mobile/src/stores/stores.ts b/apps/mobile/src/stores/stores.ts
index 5d29d216c..46648fbd0 100644
--- a/apps/mobile/src/stores/stores.ts
+++ b/apps/mobile/src/stores/stores.ts
@@ -298,8 +298,6 @@ export const useEditorStore = create<EditorStore>((set, get) => ({
setCurrentlyEditingNote: note => set({ currentEditingNote: note }),
sessionId: null,
setSessionId: sessionId => {
- console.log(sessionId, 'session id');
- tiny.call(EditorWebView, `sessionId="${sessionId}";`);
set({ sessionId });
},
searchReplace: false,