A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
refactor editor
ammarahm-edd1250e293d69
diff --git a/apps/mobile/src/views/Editor/InfoBar.js b/apps/mobile/src/views/Editor/InfoBar.jsdeleted file mode 100644index bdf2a411a..000000000--- a/apps/mobile/src/views/Editor/InfoBar.js+++ /dev/null@@ -1,123 +0,0 @@-import React from 'react';-import {View, StatusBar, Text, ActivityIndicator} from 'react-native';-import {db, timeConverter} from '../../utils/utils';-import {simpleDialogEvent} from '../../components/DialogManager/recievers';-import {TEMPLATE_INFO} from '../../components/DialogManager/templates';-import {SIZE, WEIGHT} from '../../common/common';--export default class InfoBar extends React.Component {- constructor(props) {- super(props);- this.state = {- dateEdited: null,- saving: false,- length: 0,- };- this.dateCreated = null;- }-- setSaving() {- this.setState(- {- saving: true,- },- () => {- setTimeout(() => {- this.setState({- saving: false,- });- }, 500);- },- );- }-- setDateEdited(id, length) {- this.setState({- dateEdited: id,- length: length,- });- }- setDateCreated(dateCreated) {- this.dateCreated = dateCreated;- }- clear() {- this.dateCreated = null;- this.setState({- saving: false,- dateEdited: null,- length: 0,- });- }-- render() {- return (- <View- style={{- paddingHorizontal: 12,- marginTop: Platform.OS === 'ios' ? 45 : StatusBar.currentHeight + 45,- width: '100%',- backgroundColor: this.props.colors.bg,- position: 'absolute',- justifyContent: 'flex-start',- flexDirection: 'row',- alignItems: 'center',- paddingLeft: this.props.noMenu ? 12 : 12 + 50,- zIndex: 999,- }}>- {this.state.length ? (- <Text- style={{- color: this.props.colors.icon,- fontSize: SIZE.xxs,- textAlignVertical: 'center',- fontFamily: WEIGHT.regular,- marginRight: 5,- }}>- {this.state.length + ' words •'}- </Text>- ) : null}-- {this.state.dateEdited ? (- <Text- onPress={() => {- simpleDialogEvent(TEMPLATE_INFO(this.dateCreated));- }}- style={{- color: this.props.colors.icon,- fontSize: SIZE.xxs,- textAlignVertical: 'center',- fontFamily: WEIGHT.regular,- }}>- {timeConverter(this.state.dateEdited)} •- </Text>- ) : null}-- <View- style={{- justifyContent: 'center',- alignItems: 'center',- flexDirection: 'row',- }}>- {this.state.saving ? (- <ActivityIndicator- style={{width: 14, height: 14, marginLeft: 10}}- color={this.props.colors.accent}- size={14}- />- ) : null}- <Text- style={{- color: this.props.colors.icon,- fontSize: SIZE.xxs,- textAlignVertical: 'center',- fontFamily: WEIGHT.regular,- marginLeft: 10,- }}>- {this.state.saving ? 'Saving' : ''}- {this.state.dateEdited && !this.state.saving ? 'Saved' : ''}- </Text>- </View>- </View>- );- }-}diff --git a/apps/mobile/src/views/Editor/func.js b/apps/mobile/src/views/Editor/func.jsnew file mode 100644index 000000000..39736308b--- /dev/null+++ b/apps/mobile/src/views/Editor/func.js@@ -0,0 +1,291 @@+import { createRef } from 'react';+import { Linking, Platform } from 'react-native';+import { normalize } from '../../common/common';+import { updateEvent } from '../../components/DialogManager/recievers';+import { ACTIONS } from '../../provider/actions';+import { eSendEvent } from '../../services/eventManager';+import { refreshNotesPage } from '../../services/events';+import { db, editing, timeConverter } from '../../utils/utils';+++export const EditorWebView = createRef();++export const params = 'platform=' + Platform.OS;+export const sourceUri =+ (Platform.OS === 'android' ? 'file:///android_asset/' : '') ++ 'Web.bundle/loader.html';+export const injectedJS = `if (!window.location.search) {+ var link = document.getElementById('progress-bar');+ link.href = './site/index.html?${params}';+ link.click();+ }+ `;++export const INJECTED_JAVASCRIPT = premium => `(function() {+ setTimeout(() => {+ loadAction(${premium});+ },100)+ })();`;++var note = {};+var id = null;+var content = null;+var title = null;+var saveCounter = 0;++var canSave = false;+var timer = null;+export function post(type, value = null) {+ let message = {+ type,+ value,+ };+ EditorWebView.current?.postMessage(JSON.stringify(message));+}++export const _onShouldStartLoadWithRequest = (request) => {+ if (request.url.includes('https')) {+ Linking.openURL(request.url);+ return false;+ } else {+ return true;+ }+}++export function checkNote() {+ return note && note.id;+}++export async function loadNote(item) {+ //EditorWebView.current?.requestFocus();+ editing.currentlyEditing = true;++ updateEvent({type: ACTIONS.NOTES});+ if (item && item.type === 'new') {+ await clearEditor();+ post('focusTitle');+ canSave = true;+ } else {+ note = item;+ canSave = false;+ updateEvent({+ type: ACTIONS.CURRENT_EDITING_NOTE,+ id: item.id,+ });+ updateEditor();+ }+}++const onChange = data => {+ if (data !== '') {+ let rawData = JSON.parse(data);++ if (rawData.type === 'content') {+ content = rawData;+ } else {+ title = rawData.value;+ }+ }+};++export const _onMessage = evt => {+ if (evt.nativeEvent.data === 'loaded') {+ } else if (evt.nativeEvent.data !== '' && evt.nativeEvent.data !== 'loaded') {++ clearTimeout(timer);++ timer = null;+ if (!canSave) {+ setTimeout(() => {+ canSave = true;+ }, 2000);+ }+ onChange(evt.nativeEvent.data);+ timer = setTimeout(() => {+ saveNote(true);+ }, 500);+ }+};++export async function clearEditor() {+ await saveNote(true);+ title = null;+ content = null;+ note = null;+ id = null;+ tapCount = 0;+ saveCounter = 0;+ canSave = false;+ post('clearEditor');+ post('clearTitle');+ post('blur');+}++function checkIfContentIsSavable() {+ if (!canSave) return false;+ if (!title && !content) return false;+ if (content && content.text.length < 2 && title && title?.length < 2)+ return false;+ if (!content && title && title.length < 2) return false;+ if (!title && content.text.length < 2) return false;+ if (title && !content) {+ content = {+ text: '',+ delta: {ops: []},+ };+ }++ return true;+}++async function setNoteInEditorAferSaving(oldId, currentId) {+ if (oldId !== currentId) {+ id = currentId;+ note = db.notes.note(id);+ if (note) {+ note = note.data;+ } else {+ setTimeout(() => {+ note = db.notes.note(id);+ if (note) {+ note = note.data;+ }+ }, 500);+ }+ }+}++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,+ };++ break;+ }+ case 'tag': {+ await db.notes.note(note.id).tag(editing.actionAfterFirstSave.id);+ editing.actionAfterFirstSave = {+ type: null,+ };++ break;+ }+ case 'color': {+ await db.notes.note(id).color(editing.actionAfterFirstSave.id);++ editing.actionAfterFirstSave = {+ type: null,+ };++ break;+ }+ default: {+ break;+ }+ }+}++export async function saveNote(lockNote = true) {+ if (!checkIfContentIsSavable()) return;+ let lockedNote = id ? db.notes.note(id).data.locked : null;+ post('saving', 'Saving');++ if (!lockedNote) {+ let rId = await db.notes.add({+ title,+ content: {+ text: content.text,+ delta: content.delta,+ },+ id: id,+ });+ setNoteInEditorAferSaving(id, rId);+ if (content.text.length < 200 || saveCounter < 2) {+ updateEvent({+ type: ACTIONS.NOTES,+ });+ eSendEvent(refreshNotesPage);+ }++ if (id) {+ await addToCollection(id);+ updateEvent({+ type: ACTIONS.CURRENT_EDITING_NOTE,+ id: id,+ });+ }+ saveCounter++;+ } else {+ await db.vault.save({+ title,+ content: {+ text: content.text,+ delta: content.delta,+ },+ id: id,+ });+ }+ let n = db.notes.note(id).data.dateEdited;+ post('dateEdited', timeConverter(n));+ post('saving', 'Saved');+}++export function onWebViewLoad(noMenu,premium,colors) {+ EditorWebView.current?.injectJavaScript(INJECTED_JAVASCRIPT(premium));++ if (noMenu) {+ post('nomenu', true);+ } else {+ post('nomenu', false);+ }++ if (note && note.id) {+ updateEditor();+ } else {+ post('focusTitle');+ }+ let c = {...colors};+ c.factor = normalize(1);+ post('theme', c);+}++const updateEditor = async () => {+ title = note.title;+ id = note.id;+ saveCounter = 0;+ content = {};+ content.text = '';+ try {+ content.text = await db.notes.note(id).text();+ post('dateEdited', timeConverter(note.dateEdited));+ } catch (e) {}++ if (title !== null || title === '') {+ post('title', note.title);+ } else {+ post('clearTitle');+ post('clearEditor');+ post('focusTitle');+ }+ if (content.text === '' && note.content.delta === null) {+ post('clearEditor');+ } else if (note.content.delta) {+ if (typeof note.content.delta !== 'string') {+ content.delta = note.content.delta;+ } else {+ content.delta = await db.notes.note(id).delta();+ }+ post('delta', content.delta);+ } else {+ post('text', content.text);+ }+};diff --git a/apps/mobile/src/views/Editor/index.js b/apps/mobile/src/views/Editor/index.jsindex 69712381f..adff6a07b 100755--- a/apps/mobile/src/views/Editor/index.js+++ b/apps/mobile/src/views/Editor/index.js@@ -1,8 +1,7 @@-import React, {createRef, useEffect, useState} from 'react';+import React, {useEffect, useState} from 'react';import {BackHandler,KeyboardAvoidingView,- Linking,Platform,SafeAreaView,StatusBar,@@ -18,7 +17,6 @@ import {} from '../../components/DialogManager/recievers';import {TEMPLATE_EXIT_FULLSCREEN} from '../../components/DialogManager/templates';import {useTracked} from '../../provider';-import {ACTIONS} from '../../provider/actions';import {eSendEvent,eSubscribeEvent,@@ -29,426 +27,98 @@ import {eCloseFullscreenEditor,eOnLoadNote,eOpenFullscreenEditor,- refreshNotesPage,} from '../../services/events';-import {exitEditorAnimation, EditorScale} from '../../utils/animations';-import {db, DDS, editing, timeConverter, ToastEvent} from '../../utils/utils';--const InfoBarRef = createRef();-const EditorWebView = createRef();-let note = {};-let id = null;-var content = null;-var title = null;-let timer = null;-let saveCounter = 0;-let tapCount = 0;-let canSave = false;-let handleBack;-+import {exitEditorAnimation} from '../../utils/animations';+import {DDS, editing, ToastEvent} from '../../utils/utils';+import {+ clearEditor,+ EditorWebView,+ injectedJS,+ loadNote,+ onWebViewLoad,+ post,+ sourceUri,+ _onMessage,+ _onShouldStartLoadWithRequest,+ checkNote,+} from './func';++var handleBack;+var tapCount = 0;const Editor = ({noMenu}) => {// Global Stateconst [state, dispatch] = useTracked();- const {colors, currentEditingNote,premium} = state;+ const {colors, premium} = state;const [fullscreen, setFullscreen] = useState(false);- const [dateEdited, setDateEdited] = useState(0);// FUNCTIONS- const post = message =>- EditorWebView.current?.postMessage(JSON.stringify(message));-useEffect(() => {let c = {...colors};c.factor = normalize(1);- post({- type: 'theme',- value: colors,- });+ post('theme', colors);}, [colors.bg]);useEffect(() => {- eSubscribeEvent(eOnLoadNote, loadNote);-- return () => {- eUnSubscribeEvent(eOnLoadNote, loadNote);- };- }, []);-- const loadNote = async item => {- //EditorWebView.current?.requestFocus();- editing.currentlyEditing = true;- if (!DDS.isTab) {- handleBack = BackHandler.addEventListener(- 'hardwareBackPress',- _onHardwareBackPress,- );- }- if (note && note.id) {- dispatch({type: ACTIONS.NOTES});- if (item && item.type === 'new') {- await clearEditor();- post({- type: 'focusTitle',- });- canSave = true;- } else {- note = item;- canSave = false;- dispatch({- type: ACTIONS.CURRENT_EDITING_NOTE,- id: item.id,- });- updateEditor();- }+ if (noMenu) {+ post('nomenu', true);} else {- dispatch({type: ACTIONS.NOTES});- if (item && item.type === 'new') {- await clearEditor();- post({- type: 'focusTitle',- });- canSave = true;- } else {- note = item;- canSave = false;- dispatch({- type: ACTIONS.CURRENT_EDITING_NOTE,- id: item.id,- });- updateEditor();- }+ post('nomenu', false);}- };-- const clearEditor = async () => {- await saveNote(true);- setDateEdited(0);- InfoBarRef.current?.clear();- title = null;- content = null;- note = null;- id = null;- tapCount = 0;- saveCounter = 0;- canSave = false;-- post({- type: 'clearEditor',- });- post({- type: 'clearTitle',- });- post({- type: 'blur',- });- };-- const onCallClear = () => {- canSave = false;- if (editing.currentlyEditing) {- exitEditorAnimation();- }- clearEditor();- };+ }, [noMenu]);useEffect(() => {+ eSubscribeEvent(eOnLoadNote, load);+ eSubscribeEvent(eCloseFullscreenEditor, closeFullscreen);eSubscribeEvent(eClearEditor, onCallClear);-return () => {eUnSubscribeEvent(eClearEditor, onCallClear);+ eUnSubscribeEvent(eCloseFullscreenEditor, closeFullscreen);+ eUnSubscribeEvent(eOnLoadNote, load);};}, []);- const onChange = data => {- if (data !== '') {- let rawData = JSON.parse(data);-- if (rawData.type === 'content') {- content = rawData;- } else {- title = rawData.value;- }- }- };-- const _onMessage = evt => {- if (evt.nativeEvent.data === 'loaded') {- } else if (- evt.nativeEvent.data !== '' &&- evt.nativeEvent.data !== 'loaded'- ) {- clearTimeout(timer);- timer = null;- if (!canSave) {- setTimeout(() => {- canSave = true;- }, 2000);- }- onChange(evt.nativeEvent.data);- timer = setTimeout(() => {- saveNote.call(this, true);- }, 500);- }- };-- const _onShouldStartLoadWithRequest = request => {- if (request.url.includes('https')) {- Linking.openURL(request.url);- return false;- } else {- return true;- }- };-- const addToCollection = async id => {- switch (editing.actionAfterFirstSave.type) {- case 'topic': {- await db.notes.move(- {- topic: editing.actionAfterFirstSave.id,- id: editing.actionAfterFirstSave.notebook,- },- id,- );- editing.actionAfterFirstSave = {- type: null,- };-- break;- }- case 'tag': {- await db.notes.note(note.id).tag(editing.actionAfterFirstSave.id);- editing.actionAfterFirstSave = {- type: null,- };-- break;- }- case 'color': {- await db.notes.note(id).color(editing.actionAfterFirstSave.id);-- editing.actionAfterFirstSave = {- type: null,- };-- break;- }- default: {- break;- }- }- };-useEffect(() => {- EditorWebView.current?.reload();- },[premium])-- const checkIfContentIsSavable = () => {- if (!canSave) return false;- if (!title && !content) return false;- if (content && content.text.length < 2 && title && title?.length < 2)- return false;- if (!content && title && title.length < 2) return false;- if (!title && content.text.length < 2) return false;- if (title && !content) {- content = {- text: '',- delta: {ops: []},- };- }-- return true;- };-- const setNoteInEditorAferSaving = (oldId, currentId) => {- if (oldId !== currentId) {- id = currentId;- note = db.notes.note(id);- if (note) {- note = note.data;- } else {- setTimeout(() => {- note = db.notes.note(id);- if (note) {- note = note.data;- }- }, 500);- }- }- };-- const saveNote = async (lockNote = true) => {- if (!checkIfContentIsSavable()) return;- let lockedNote = id ? db.notes.note(id).data.locked : null;- post({- type: 'saving',- value: 'Saving',- });- if (!lockedNote) {- let rId = await db.notes.add({- title,- content: {- text: content.text,- delta: content.delta,- },- id: id,- });- setNoteInEditorAferSaving(id, rId);- if (content.text.length < 200 || saveCounter < 2) {- dispatch({- type: ACTIONS.NOTES,- });- eSendEvent(refreshNotesPage);- }- InfoBarRef.current?.setSaving();- if (id) {- await addToCollection(id);- if (currentEditingNote !== id) {- dispatch({- type: ACTIONS.CURRENT_EDITING_NOTE,- id: id,- });- }- }- saveCounter++;- } else {- await db.vault.save({- title,- content: {- text: content.text,- delta: content.delta,- },- id: id,+ if (!noMenu && DDS.isTab) {+ handleBack = BackHandler.addEventListener('hardwareBackPress', () => {+ simpleDialogEvent(TEMPLATE_EXIT_FULLSCREEN());+ editing.isFullscreen = false;+ return true;});}- let n = db.notes.note(id).data.dateEdited;- post({- type: 'dateEdited',- value: timeConverter(n),- });- post({- type: 'saving',- value: 'Saved',- });- };-- useEffect(() => {- if (noMenu) {- post({- type: 'nomenu',- value: true,- });- } else {- post({- type: 'nomenu',- value: false,- });- }+ return () => {+ if (handleBack) {+ handleBack.remove();+ handleBack = null;+ }+ };}, [noMenu]);- const onWebViewLoad = () => {- EditorWebView.current?.injectJavaScript(INJECTED_JAVASCRIPT);- if (noMenu) {- post({- type: 'nomenu',- value: true,- });- } else {- post({- type: 'nomenu',- value: false,- });- }-- if (note && note.id) {- updateEditor();- } else {- post({- type: 'focusTitle',- });+ const load = item => {+ loadNote(item);+ if (!DDS.isTab) {+ handleBack = BackHandler.addEventListener(+ 'hardwareBackPress',+ _onHardwareBackPress,+ );}- let c = {...colors};- c.factor = normalize(1);- post({- type: 'theme',- value: c,- });};- const updateEditor = async () => {- title = note.title;- id = note.id;- saveCounter = 0;- content = {};- content.text = '';- try {- content.text = await db.notes.note(id).text();- post({- type: 'dateEdited',- value: timeConverter(note.dateEdited),- });- } catch (e) {}-- if (title !== null || title === '') {- post({- type: 'title',- value: note.title,- });- } else {- post({- type: 'clearTitle',- });- post({- type: 'clearEditor',- });- post({- type: 'focusTitle',- });- }- if (content.text === '' && note.content.delta === null) {- post({- type: 'clearEditor',- });- } else if (note.content.delta) {- if (typeof note.content.delta !== 'string') {- content.delta = note.content.delta;- } else {- content.delta = await db.notes.note(id).delta();- }- post({- type: 'delta',- value: content.delta,- });- } else {- post({type: 'text', value: content.text});+ const onCallClear = () => {+ canSave = false;+ if (editing.currentlyEditing) {+ exitEditorAnimation();}+ clearEditor();};-- const params = 'platform=' + Platform.OS;- const sourceUri =- (Platform.OS === 'android' ? 'file:///android_asset/' : '') +- 'Web.bundle/loader.html';- const injectedJS = `if (!window.location.search) {- var link = document.getElementById('progress-bar');- link.href = './site/index.html?${params}';- link.click();- }`;-const closeFullscreen = () => {setFullscreen(false);};- // EFFECTS-useEffect(() => {- eSubscribeEvent(eCloseFullscreenEditor, closeFullscreen);-- return () => {- eUnSubscribeEvent(eCloseFullscreenEditor, closeFullscreen);- };- }, []);+ EditorWebView.current?.reload();+ }, [premium]);const _onHardwareBackPress = async () => {if (editing.currentlyEditing) {@@ -466,30 +136,13 @@ const Editor = ({noMenu}) => {}};- useEffect(() => {- if (!noMenu && DDS.isTab) {- handleBack = BackHandler.addEventListener('hardwareBackPress', () => {- simpleDialogEvent(TEMPLATE_EXIT_FULLSCREEN());- editing.isFullscreen = false;- return true;- });- }-- return () => {- if (handleBack) {- handleBack.remove();- handleBack = null;- }- };- }, [noMenu]);-const _onBackPress = async () => {editing.currentlyEditing = true;if (DDS.isTab) {simpleDialogEvent(TEMPLATE_EXIT_FULLSCREEN());} else {exitEditorAnimation();- if (note && note.id) {+ if (checkNote()) {ToastEvent.show('Note Saved!', 'success');}await clearEditor();@@ -500,11 +153,6 @@ const Editor = ({noMenu}) => {}};- const INJECTED_JAVASCRIPT = `(function() {-- loadAction(${premium});-})();`;-return (<SafeAreaViewstyle={{@@ -612,11 +260,9 @@ const Editor = ({noMenu}) => {<WebViewref={EditorWebView}onError={error => console.log(error)}- onLoad={onWebViewLoad}+ onLoad={() => onWebViewLoad(noMenu, premium, colors)}javaScriptEnabled={true}- injectedJavaScript={- Platform.OS === 'ios' ? injectedJS : null- }+ injectedJavaScript={Platform.OS === 'ios' ? injectedJS : null}onShouldStartLoadWithRequest={_onShouldStartLoadWithRequest}renderLoading={() => (<View@@ -627,7 +273,6 @@ const Editor = ({noMenu}) => {}}/>)}-cacheMode="LOAD_DEFAULT"cacheEnabled={false}domStorageEnabled={true}