Skip to content

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

improve editor performance

ammarahm-edb5c73c79fac4
diff --git a/apps/mobile/html/Web.bundle/site/init.js b/apps/mobile/html/Web.bundle/site/init.js
index 2bfc958a9..4ce49e4c7 100755
--- a/apps/mobile/html/Web.bundle/site/init.js
+++ b/apps/mobile/html/Web.bundle/site/init.js
@@ -107,12 +107,15 @@ function collapseElement(target) {
sibling = sibling.nextSibling;
}
}
-
+let undoTimer = null;
function onUndoChange() {
- reactNativeEventHandler('history', {
- undo: editor.undoManager.hasUndo(),
- redo: editor.undoManager.hasRedo()
- });
+ clearTimeout(undoTimer);
+ undoTimer = setTimeout(function () {
+ reactNativeEventHandler('history', {
+ undo: editor.undoManager.hasUndo(),
+ redo: editor.undoManager.hasRedo()
+ });
+ }, 1000);
}
function init_tiny(size) {
@@ -235,7 +238,8 @@ function init_tiny(size) {
autoresize_bottom_margin: 120,
table_toolbar:
'tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol',
- imagetools_toolbar: 'imagedownload | rotateleft rotateright flipv fliph | imageopts ',
+ imagetools_toolbar:
+ 'imagedownload | rotateleft rotateright flipv fliph | imageopts ',
placeholder: 'Start writing your note here',
object_resizing: true,
resize: true,
@@ -377,6 +381,8 @@ function init_tiny(size) {
editor.on('TypingUndos', onUndoChange);
editor.on('BeforeAddUndo', onUndoChange);
editor.on('AddUndo', onUndoChange);
+ editor.on('cut', onUndoChange);
+ editor.on('copy', onUndoChange);
editor.on('tap', e => {
if (e.target.classList.contains('mce-content-body')) {
e.preventDefault();
@@ -432,8 +438,7 @@ function init_tiny(size) {
target.classList.add(COLLAPSED_KEY);
}
collapseElement(target);
- console.log('element has collapsed');
- reactNativeEventHandler('tiny', editor.getContent());
+ reactNativeEventHandler('tiny', editor.dom.doc.body.innerHTML);
});
}
});
@@ -451,26 +456,55 @@ function init_tiny(size) {
}
});
}
-window.prevContent = '';
+
+let prevCount = 0;
+
+function delay(base = 0) {
+ if (prevCount < 20000) return base + 200;
+ if (prevCount > 20000 && prevCount < 40000) return base + 400;
+ if (prevCount > 40000 && prevCount < 70000) return base + 600;
+ if (prevCount > 70000) return base + 1000;
+}
+
+
const onChange = function (event) {
- console.log(event.type, event.selectionChange);
- onUndoChange();
if (event.type === 'nodechange' && !event.selectionChange) return;
-
if (isLoading) {
isLoading = false;
return;
}
- if (editor.plugins.wordcount.getCount() === 0) return;
- console.log('saving now doc');
+
+ if (prevCount === 0) {
+ updateCount(0);
+ }
+
+ if (prevCount === 0) return;
+
clearTimeout(changeTimer);
changeTimer = null;
+
changeTimer = setTimeout(function () {
+ let now2 = performance.now();
+ reactNativeEventHandler('tiny', editor.dom.doc.body.innerHTML);
+ console.log('save:', performance.now() - now2);
+ onUndoChange();
+ let now3 = performance.now();
selectchange();
- reactNativeEventHandler('tiny', editor.getContent());
- }, 10);
+ console.log('select:', performance.now() - now3);
+ }, delay());
};
+let countTimer;
+function updateCount(timer=1000) {
+ countTimer = null;
+ countTimer = setTimeout(function() {
+ let count = countWords(tinymce.activeEditor.dom.doc.body.innerText);
+ info = document.querySelector('.info-bar');
+ info.querySelector('#infowords').innerText = count + ' words';
+ prevCount = count;
+ }, delay(timer));
+}
+
function getNodeColor(element) {
if (element.style.color && element.style.color !== '') {
return element.style.color;
@@ -485,83 +519,86 @@ function getNodeBg(element) {
return null;
}
+let selectionTimer = null;
function selectchange() {
- info = document.querySelector('.info-bar');
- info.querySelector('#infowords').innerText =
- editor.plugins.wordcount.getCount() + ' words';
-
- let formats = Object.keys(editor.formatter.get());
- let currentFormats = {};
- editor.formatter.matchAll(formats).forEach(function (format) {
- currentFormats[format] = true;
- });
-
- let node = editor.selection.getNode();
- currentFormats.hilitecolor = getNodeBg(node);
- currentFormats.forecolor = getNodeColor(node);
-
- if (!currentFormats.hilitecolor || !currentFormats.forecolor) {
- for (var i = 0; i < node.children.length; i++) {
- let item = editor.selection.getNode().children.item(i);
- currentFormats.hilitecolor = getNodeBg(item);
- currentFormats.forecolor = getNodeColor(item);
+ clearTimeout(selectionTimer);
+ selectionTimer = null;
+ selectionTimer = setTimeout(function () {
+ console.log('selection change called');
+ updateCount();
+ let formats = Object.keys(editor.formatter.get());
+ let currentFormats = {};
+ editor.formatter.matchAll(formats).forEach(function (format) {
+ currentFormats[format] = true;
+ });
+
+ let node = editor.selection.getNode();
+ currentFormats.hilitecolor = getNodeBg(node);
+ currentFormats.forecolor = getNodeColor(node);
+
+ if (!currentFormats.hilitecolor || !currentFormats.forecolor) {
+ for (var i = 0; i < node.children.length; i++) {
+ let item = editor.selection.getNode().children.item(i);
+ currentFormats.hilitecolor = getNodeBg(item);
+ currentFormats.forecolor = getNodeColor(item);
+ }
}
- }
- let range = editor.selection.getRng();
+ let range = editor.selection.getRng();
- currentFormats.current = {
- index: range.startOffset,
- length: range.endOffset - range.startOffset
- };
+ currentFormats.current = {
+ index: range.startOffset,
+ length: range.endOffset - range.startOffset
+ };
- currentFormats.fontsize = editor.selection.getNode().style.fontSize;
+ currentFormats.fontsize = editor.selection.getNode().style.fontSize;
- if (currentFormats.fontsize === '') {
- currentFormats.fontsize = DEFAULT_FONT_SIZE;
+ if (currentFormats.fontsize === '') {
+ currentFormats.fontsize = DEFAULT_FONT_SIZE;
- if (currentFormats.h2) {
- currentFormats.fontsize = '18pt';
- }
- if (currentFormats.h3) {
- currentFormats.fontsize = '14pt';
- }
- if (currentFormats.h4) {
- currentFormats.fontsize = '12pt';
- }
- if (currentFormats.h5) {
- currentFormats.fontsize = '10pt';
+ if (currentFormats.h2) {
+ currentFormats.fontsize = '18pt';
+ }
+ if (currentFormats.h3) {
+ currentFormats.fontsize = '14pt';
+ }
+ if (currentFormats.h4) {
+ currentFormats.fontsize = '12pt';
+ }
+ if (currentFormats.h5) {
+ currentFormats.fontsize = '10pt';
+ }
+ if (currentFormats.h6) {
+ currentFormats.fontsize = '8pt';
+ }
}
- if (currentFormats.h6) {
- currentFormats.fontsize = '8pt';
+ if (node.nodeName === 'A') {
+ currentFormats.link = node.getAttribute('href');
}
- }
- if (node.nodeName === 'A') {
- currentFormats.link = node.getAttribute('href');
- }
- currentFormats.fontname = editor.selection.getNode().style.fontFamily;
+ currentFormats.fontname = editor.selection.getNode().style.fontFamily;
- if (/^(LI|UL|OL|DL)$/.test(node.nodeName)) {
- let listElm = editor.selection.getNode();
- if (listElm.nodeName === 'LI') {
- listElm = editor.dom.getParent(listElm, 'ol,ul');
- }
+ if (/^(LI|UL|OL|DL)$/.test(node.nodeName)) {
+ let listElm = editor.selection.getNode();
+ if (listElm.nodeName === 'LI') {
+ listElm = editor.dom.getParent(listElm, 'ol,ul');
+ }
- let style = editor.dom.getStyle(listElm, 'listStyleType');
- if (style === '') {
- style = 'default';
- }
- if (listElm.nodeName === 'OL') {
- currentFormats.ol = style;
- } else {
- if (!listElm) return;
- if (listElm.className === 'tox-checklist') {
- currentFormats.cl = true;
+ let style = editor.dom.getStyle(listElm, 'listStyleType');
+ if (style === '') {
+ style = 'default';
+ }
+ if (listElm.nodeName === 'OL') {
+ currentFormats.ol = style;
} else {
- currentFormats.ul = style;
+ if (!listElm) return;
+ if (listElm.className === 'tox-checklist') {
+ currentFormats.cl = true;
+ } else {
+ currentFormats.ul = style;
+ }
}
}
- }
- currentFormats.node = editor.selection.getNode().nodeName;
- reactNativeEventHandler('selectionchange', currentFormats);
+ currentFormats.node = editor.selection.getNode().nodeName;
+ reactNativeEventHandler('selectionchange', currentFormats);
+ }, 300);
}
diff --git a/apps/mobile/html/Web.bundle/site/listeners.js b/apps/mobile/html/Web.bundle/site/listeners.js
index bfa3e58fe..6e64c5014 100755
--- a/apps/mobile/html/Web.bundle/site/listeners.js
+++ b/apps/mobile/html/Web.bundle/site/listeners.js
@@ -1,3 +1,24 @@
+function countWords(str) {
+ let count = 0;
+ let shouldCount = false;
+
+ for (var i = 0; i < str.length; ++i) {
+ const s = str[i];
+
+ if (s === " " || s === "\r" || s === "\n" || s === "*") {
+ if (!shouldCount) continue;
+ ++count;
+ shouldCount = false;
+ } else {
+ shouldCount = true;
+ }
+ }
+
+ if (shouldCount) ++count;
+ return count;
+}
+
+
let titleInput = document.getElementById('titleInput');
let infoBar = '.info-bar';
let info = null;
@@ -84,7 +105,7 @@ function onTitleChange() {
info = document.querySelector(infoBar);
if (tinymce.activeEditor) {
info.querySelector('#infowords').innerText =
- tinymce.activeEditor.plugins.wordcount.getCount() + ' words';
+ countWords(tinymce.activeEditor.dom.doc.body.innerText) + ' words';
}
if (titleMessage && typeof titleMessage.value === 'string') {
@@ -140,7 +161,7 @@ function attachMessageListener() {
window.blur();
}, 300);
info.querySelector('#infowords').innerText =
- tinymce.activeEditor.plugins.wordcount.getCount() + ' words';
+ countWords(tinymce.activeEditor.dom.doc.body.innerText) + ' words';
break;
case 'htmldiff':
document.getElementsByClassName('htmldiff_div')[0].innerHTML = value;
diff --git a/apps/mobile/src/views/Editor/Functions.js b/apps/mobile/src/views/Editor/Functions.js
index b3361f5ed..7288b9110 100644
--- a/apps/mobile/src/views/Editor/Functions.js
+++ b/apps/mobile/src/views/Editor/Functions.js
@@ -10,7 +10,7 @@ import {
} from '../../services/EventManager';
import Navigation from '../../services/Navigation';
import PremiumService from '../../services/PremiumService';
-import {editing, InteractionManager} from '../../utils';
+import {editing} from '../../utils';
import {COLORS_NOTE, COLOR_SCHEME} from '../../utils/Colors';
import {hexToRGBA} from '../../utils/ColorUtils';
import {db} from '../../utils/database';
@@ -26,6 +26,7 @@ import {tabBarRef} from '../../utils/Refs';
import {normalize} from '../../utils/SizeUtils';
import {sleep, timeConverter} from '../../utils/TimeUtils';
import tiny from './tiny/tiny';
+import {IMAGE_TOOLTIP_CONFIG} from './tiny/toolbar/config';
export let EditorWebView = createRef();
export const editorTitleInput = createRef();
@@ -46,9 +47,16 @@ let title = '';
let saveCounter = 0;
let timer = null;
let webviewInit = false;
-let intent = false;
let appColors = COLOR_SCHEME;
+let currentEditingTimer = null;
+let webviewTimer = null;
+let requestedReload = false;
+let cTimeout = null;
+let disableSaving = false;
+let isSaving = false;
+let waitForContent = false;
+
export function setWebviewInit(init) {
webviewInit = init;
}
@@ -57,14 +65,6 @@ export function getWebviewInit() {
return webviewInit;
}
-export function setIntent() {
- intent = true;
-}
-
-export function getIntent() {
- return intent;
-}
-
export function setColors(colors) {
if (colors) {
appColors = colors;
@@ -81,20 +81,42 @@ export function isNotedEdited() {
return noteEdited;
}
+async function waitForEvent(event, caller) {
+ return new Promise((resolve, reject) => {
+ let resolved;
+ let event_callback = () => {
+ eUnSubscribeEvent(event, event_callback);
+ resolved = true;
+ clearTimeout(resolved);
+ waitForContent = false;
+ resolve(true);
+ };
+ eSubscribeEvent(event, event_callback);
+ caller();
+ resolved = setTimeout(() => {
+ resolve(true);
+ }, 2000);
+ });
+}
+
export async function clearTimer(clear) {
- if (timer) {
- clearTimeout(timer);
- timer = null;
- if (clear) {
- if (!id) return;
- if (
- (content?.data &&
- typeof content.data === 'string' &&
- content.data?.trim().length > 0) ||
- (title && title?.trim().length > 0)
- ) {
- await saveNote(true);
- }
+ clearTimeout(timer);
+ timer = null;
+ if (waitForContent) {
+ await waitForEvent('content_event', () => {
+ tiny.call(EditorWebView, request_content);
+ });
+ }
+ if (clear) {
+ if (!id) return;
+ if (
+ (content?.data &&
+ typeof content.data === 'string' &&
+ content.data?.trim().length > 0) ||
+ (title && title?.trim().length > 0)
+ ) {
+ console.log('saving note');
+ await saveNote(true);
}
}
if (currentEditingTimer) {
@@ -114,6 +136,17 @@ export const CHECK_STATUS = `(function() {
},${Platform.OS === 'ios' ? '300' : '1'})
})();`;
+const request_content = `(function() {
+ if (window.ReactNativeWebView) {
+ window.ReactNativeWebView.postMessage(
+ JSON.stringify({
+ type: 'tiny',
+ value: tinymce.activeEditor.dom.doc.body.innerHTML
+ })
+ );
+ }
+})();`;
+
export function getNote() {
return note;
}
@@ -183,10 +216,6 @@ function clearNote() {
};
}
-let currentEditingTimer = null;
-
-let webviewTimer = null;
-let requestedReload = false;
export const loadNote = async item => {
console.log('.....OPEN NOTE.....');
editing.currentlyEditing = true;
@@ -204,7 +233,6 @@ export const loadNote = async item => {
lastEditTime = 0;
clearNote();
noteEdited = false;
- isFirstLoad = false;
if (Platform.OS === 'android') {
await sleep(100);
textInput.current?.focus();
@@ -236,7 +264,6 @@ export const loadNote = async item => {
if (getNote()) {
await clearEditor(true, false, true);
}
- isFirstLoad = true;
disableSaving = false;
noteEdited = false;
await setNote(item);
@@ -292,11 +319,11 @@ export const _onMessage = async evt => {
}
switch (message.type) {
case 'history':
+ console.log('history', message.value);
eSendEvent('historyEvent', message.value);
break;
case 'tiny':
if (message.value !== content.data) {
- console.log('content changed');
noteEdited = true;
lastEditTime = Date.now();
content = {
@@ -305,6 +332,9 @@ export const _onMessage = async evt => {
};
onNoteChange();
}
+ if (waitForContent) {
+ eSendEvent('content_event');
+ }
break;
case 'title':
if (message.value !== title) {
@@ -326,7 +356,6 @@ export const _onMessage = async evt => {
case 'noteLoaded':
tiny.call(EditorWebView, tiny.notLoading);
eSendEvent('loadingNote');
-
break;
case 'premium':
let user = await db.user.getUser();
@@ -385,90 +414,33 @@ export const _onMessage = async evt => {
function showImageOptionsTooltip() {
editing.tooltip = 'imageoptions';
- eSendEvent('showTooltip', {
- data: [
- {
- format: 'imagepreview',
- type: 'format',
- fullname: 'Image preview'
- },
- {
- format: 'imageResize25',
- text: '25%',
- type: 'format',
- showTitle: false,
- fullname: 'Resize to 25%'
- },
- {
- format: 'imageResize50',
- text: '50%',
- type: 'format',
- showTitle: false,
- fullname: 'Resize to 25%'
- },
- {
- format: 'imageResize100',
- text: '100%',
- type: 'format',
- showTitle: false,
- fullname: 'Resize to 25%'
- },
- {
- format: 'imagefloatleft',
- type: 'format',
- fullname: 'Remove image'
- },
- {
- format: 'imagefloatright',
- type: 'format',
- fullname: 'Image preview'
- },
- {
- format: 'imagefloatnone',
- type: 'format',
- fullname: 'Image preview'
- },
- {
- format: 'removeimage',
- type: 'format',
- fullname: 'Remove image'
- }
- ],
- title: 'imageoptions',
- default: null,
- type: 'imageoptions',
- pageX: 0
- });
+ eSendEvent('showTooltip', IMAGE_TOOLTIP_CONFIG);
}
-let isFirstLoad = true;
-
function onNoteChange() {
clearTimeout(timer);
timer = null;
- if (isFirstLoad) {
- isFirstLoad = false;
- noteEdited = false;
- return;
- }
noteEdited = true;
timer = setTimeout(() => {
if (noteEdited) {
saveNote();
}
- }, 250);
+ }, 150);
}
-let cTimeout = null;
-let disableSaving = false;
export async function clearEditor(
clear = true,
reset = true,
immediate = false
) {
tiny.call(EditorWebView, tiny.isLoading);
- clear && (await clearTimer(true));
- isFirstLoad = true;
+ if (clear) {
+ console.log('clearing content start');
+ waitForContent = true;
+
+ await clearTimer(true);
+ console.log('clearing content end');
+ }
disableSaving = true;
db.fs.cancel(getNote()?.id);
clearNote();
@@ -479,6 +451,7 @@ export async function clearEditor(
let func = async () => {
try {
reset && EditorWebView.current?.reload();
+
editing.focusType = null;
eSendEvent('historyEvent', {
undo: 0,
@@ -559,14 +532,10 @@ async function addToCollection(id) {
}
}
}
-let isSaving = false;
+
export async function saveNote(preventUpdate) {
- if (disableSaving) {
- return;
- }
+ if (disableSaving || !noteEdited || (isSaving && !id)) return;
- if (!noteEdited) return;
- if (isSaving && !id) return;
isSaving = true;
try {
if (id && !db.notes.note(id)) {
@@ -682,38 +651,6 @@ export const presentResolveConflictDialog = _note => {
});
};
-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;
-
- console.log('injecting note in editor', lastEditTime, _note.dateEdited);
- 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);
-}
-
const loadNoteInEditor = async (keepHistory = true) => {
if (!webviewInit) return;
saveCounter = 0;
@@ -753,3 +690,35 @@ const loadNoteInEditor = async (keepHistory = true) => {
tiny.call(EditorWebView, tiny.clearHistory);
}
};
+
+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;
+
+ console.log('injecting note in editor', lastEditTime, _note.dateEdited);
+ 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/views/Editor/tiny/tiny.js b/apps/mobile/src/views/Editor/tiny/tiny.js
index a482acc26..30ff7471a 100644
--- a/apps/mobile/src/views/Editor/tiny/tiny.js
+++ b/apps/mobile/src/views/Editor/tiny/tiny.js
@@ -72,9 +72,6 @@ const updateDateEdited = value => `
(function() {
info = document.querySelector(infoBar);
info.querySelector('#infodate').innerText = "${value}";
- info.querySelector('#infowords').innerText =
- editor.plugins.wordcount.getCount() + " words";
-
})();
`;
diff --git a/apps/mobile/src/views/Editor/tiny/toolbar/config.js b/apps/mobile/src/views/Editor/tiny/toolbar/config.js
index ca04a9473..943de8b77 100644
--- a/apps/mobile/src/views/Editor/tiny/toolbar/config.js
+++ b/apps/mobile/src/views/Editor/tiny/toolbar/config.js
@@ -6,6 +6,61 @@ import {
editor_colors
} from './constants';
+export const IMAGE_TOOLTIP_CONFIG = {
+ data: [
+ {
+ format: 'imagepreview',
+ type: 'format',
+ fullname: 'Image preview'
+ },
+ {
+ format: 'imageResize25',
+ text: '25%',
+ type: 'format',
+ showTitle: false,
+ fullname: 'Resize to 25%'
+ },
+ {
+ format: 'imageResize50',
+ text: '50%',
+ type: 'format',
+ showTitle: false,
+ fullname: 'Resize to 25%'
+ },
+ {
+ format: 'imageResize100',
+ text: '100%',
+ type: 'format',
+ showTitle: false,
+ fullname: 'Resize to 25%'
+ },
+ {
+ format: 'imagefloatleft',
+ type: 'format',
+ fullname: 'Remove image'
+ },
+ {
+ format: 'imagefloatright',
+ type: 'format',
+ fullname: 'Image preview'
+ },
+ {
+ format: 'imagefloatnone',
+ type: 'format',
+ fullname: 'Image preview'
+ },
+ {
+ format: 'removeimage',
+ type: 'format',
+ fullname: 'Remove image'
+ }
+ ],
+ title: 'imageoptions',
+ default: null,
+ type: 'imageoptions',
+ pageX: 0
+}
+
export const TOOLBAR_CONFIG = [
[
{