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
fix share extension
Ammar Ahmed9f04e484f2a9
diff --git a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainActivity.java b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainActivity.javaindex b05d27520..1cf620f91 100644--- a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainActivity.java+++ b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/MainActivity.java@@ -49,7 +49,6 @@ public class MainActivity extends ReactActivity {ReactRootView reactRootView = new ReactRootView(getContext());// If you opted-in for the New Architecture, we enable the Fabric Renderer.reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);-return reactRootView;}diff --git a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareActivity.java b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareActivity.javaindex 06a130fa1..c8bab9946 100644--- a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareActivity.java+++ b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareActivity.java@@ -1,7 +1,45 @@package com.streetwriters.notesnook;+import android.os.Bundle;import com.facebook.react.ReactActivity;+import com.facebook.react.ReactActivityDelegate;+import com.facebook.react.ReactRootView;public class ShareActivity extends ReactActivity {++ public static class ShareActivityDelegate extends ReactActivityDelegate {+ public ShareActivityDelegate(ReactActivity activity, String mainComponentName) {+ super(activity, mainComponentName);+ }+ @Override+ protected ReactRootView createRootView() {+ ReactRootView reactRootView = new ReactRootView(getContext());+ // If you opted-in for the New Architecture, we enable the Fabric Renderer.+ reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);+ return reactRootView;+ }++ @Override+ protected boolean isConcurrentRootEnabled() {+ // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18).+ // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html+ return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;+ }+ }++ /**+ * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and+ * you can specify the rendered you wish to use (Fabric or the older renderer).+ */+ @Override+ protected ReactActivityDelegate createReactActivityDelegate() {+ return new ShareActivity.ShareActivityDelegate(this, getMainComponentName());+ }++ @Override+ protected void onCreate(Bundle savedInstanceState) {+ super.onCreate(null);+ }+@Overrideprotected String getMainComponentName() {return "NotesnookShare";diff --git a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareApplication.java b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareApplication.javaindex c3036281d..3f935d49b 100644--- a/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareApplication.java+++ b/apps/mobile/android/app/src/main/java/com/streetwriters/notesnook/ShareApplication.java@@ -1,17 +1,20 @@package com.streetwriters.notesnook;-import com.streetwriters.notesnook.BuildConfig;-import com.facebook.react.PackageList;import com.facebook.react.ReactApplication;import com.facebook.react.ReactNativeHost;import com.facebook.react.ReactPackage;-import com.facebook.soloader.SoLoader;import java.util.List;-import androidx.multidex.MultiDexApplication;+import com.facebook.react.bridge.JavaScriptExecutorFactory;+import com.facebook.react.config.ReactFeatureFlags;+import com.facebook.react.modules.systeminfo.AndroidInfoHelpers;+import com.facebook.soloader.SoLoader;++import io.csie.kudo.reactnative.v8.executor.V8ExecutorFactory;+import androidx.annotation.Nullable;public class ShareApplication extends MultiDexApplication implements ReactApplication {private final ReactNativeHost mReactNativeHost =@@ -21,6 +24,25 @@ public class ShareApplication extends MultiDexApplication implements ReactApplicreturn BuildConfig.DEBUG;}+ @Nullable+ @Override+ protected String getBundleAssetName() {+ final String v8BundleAssetName = V8ExecutorFactory.getBundleAssetName(getApplicationContext(), getUseDeveloperSupport());+ if (v8BundleAssetName != null) {+ return v8BundleAssetName;+ }+ return super.getBundleAssetName();+ }++ @Override+ protected JavaScriptExecutorFactory getJavaScriptExecutorFactory() {+ return new V8ExecutorFactory(+ getApplicationContext(),+ getPackageName(),+ AndroidInfoHelpers.getFriendlyDeviceName(),+ getUseDeveloperSupport());+ }+@Overrideprotected List<ReactPackage> getPackages() {@SuppressWarnings("UnnecessaryLocalVariable")@@ -42,4 +64,11 @@ public class ShareApplication extends MultiDexApplication implements ReactApplicreturn mReactNativeHost;}+ @Override+ public void onCreate() {+ super.onCreate();+ ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;+ SoLoader.init(this, /* native exopackage */ false);+ }+}\ No newline at end of filediff --git a/apps/mobile/share/index.js b/apps/mobile/share/index.jsindex deba2e777..4a9b5fc22 100644--- a/apps/mobile/share/index.js+++ b/apps/mobile/share/index.js@@ -1,868 +1,20 @@-import Clipboard from '@react-native-clipboard/clipboard';-//import { getLinkPreview } from 'link-preview-js';-import { parseHTML } from 'notes-core/utils/htmlparser';-import React, { Fragment, useEffect, useRef, useState } from 'react';-import {- ActivityIndicator,- Alert,- Keyboard,- Modal,- Platform,- SafeAreaView,- ScrollView,- StatusBar,- Text,- TouchableOpacity,- useWindowDimensions,- View-} from 'react-native';-import { useSafeAreaInsets } from 'react-native-safe-area-context';-import Icon from 'react-native-vector-icons/MaterialCommunityIcons';-import WebView from 'react-native-webview';-import ShareExtension from 'rn-extensions-share';-import isURL from 'validator/lib/isURL';-import { eSendEvent, eSubscribeEvent, eUnSubscribeEvent } from '../src/services/event-manager';-import { getElevation } from '../src/utils';-import { db } from '../src/utils/database';-import Storage from '../src/utils/database/storage';-import { sleep } from '../src/utils/time';-import { Search } from './search';-import { useShareStore } from './store';-const getLinkPreview = () => {};-async function sanitizeHtml(site) {- try {- let html = await fetch(site);- html = await html.text();- return sanitize(html, site);- } catch (e) {- return '';- }-}--function makeHtmlFromUrl(url) {- return `<a style="overflow-wrap:anywhere;white-space:pre-wrap" href='${url}' target='_blank'>${url}</a>`;-}--function makeHtmlFromPlainText(text) {- if (!text) return '';-- return `<p style="overflow-wrap:anywhere;white-space:pre-wrap" >${text.replace(- /(?:\r\n|\r|\n)/g,- '<br>'- )}</p>`;-}--function getBaseUrl(site) {- var url = site.split('/').slice(0, 3).join('/');- return url;-}--function wrapTablesWithDiv(document) {- const tables = document.getElementsByTagName('table');- for (let table of tables) {- table.setAttribute('contenteditable', 'true');- const div = document.createElement('div');- div.setAttribute('contenteditable', 'false');- div.innerHTML = table.outerHTML;- div.classList.add('table-container');- table.replaceWith(div);- }- return document;-}--let elementBlacklist = [- 'script',- 'button',- 'input',- 'textarea',- 'style',- 'form',- 'link',- 'head',- 'nav',- 'iframe',- 'canvas',- 'select',- 'dialog',- 'footer'-];--function removeInvalidElements(document) {- let elements = document.querySelectorAll(elementBlacklist.join(','));- for (let element of elements) {- element.remove();- }- return document;-}--function replaceSrcWithAbsoluteUrls(document, baseUrl) {- let images = document.querySelectorAll('img');- console.log(images.length);- for (var i = 0; i < images.length; i++) {- let img = images[i];- let url = getBaseUrl(baseUrl);- let src = img.getAttribute('src');- if (src.startsWith('/')) {- if (src.startsWith('//')) {- src = src.replace('//', 'https://');- } else {- src = url + src;+import React, { Fragment } from 'react';+import { Modal, Platform } from 'react-native';+import ShareView from './share';+const Wrapper = Platform.OS === 'android' ? Modal : Fragment;+const outerProps =+ Platform.OS === 'android'+ ? {+ animationType: 'fade',+ transparent: true,+ visible: true}- }- if (src.startsWith('data:')) {- img.remove();- } else {- img.setAttribute('src', src);- }- }- console.log('end');- return document;-}--function fixCodeBlocks(document) {- let elements = document.querySelectorAll('code,pre');-- for (let element of elements) {- element.classList.add('.hljs');- }- return document;-}--function sanitize(html, baseUrl) {- let parser = parseHTML(html);- parser = wrapTablesWithDiv(parser);- parser = removeInvalidElements(parser);- parser = replaceSrcWithAbsoluteUrls(parser, baseUrl);- parser = fixCodeBlocks(parser);- let htmlString = parser.outerHTML;-- htmlString = htmlString + `<hr>${makeHtmlFromUrl(baseUrl)}`;-- return htmlString;-}--let defaultNote = {- title: null,- id: null,- content: {- type: 'tiny',- data: null- }-};--const modes = {- 1: {- type: 'text',- title: 'Plain text',- icon: 'card-text-outline'- },- 2: {- type: 'clip',- title: 'Web clip',- icon: 'web'- },- 3: {- type: 'link',- title: 'Link',- icon: 'link'- }-};-+ : {};const NotesnookShare = ({ quicknote = false }) => {- const colors = useShareStore(state => state.colors);- const accent = useShareStore(state => state.accent);-- const appendNote = useShareStore(state => state.appendNote);- const [note, setNote] = useState({ ...defaultNote });- const [loadingIntent, setLoadingIntent] = useState(true);- const [loading, setLoading] = useState(false);- const [floating, setFloating] = useState(false);- const [rawData, setRawData] = useState({- type: null,- value: null- });- const [mode, setMode] = useState(1);- const keyboardHeight = useRef(0);- const { width, height } = useWindowDimensions();- const webviewRef = useRef();- const insets = Platform.OS === 'android' ? { top: StatusBar.currentHeight } : useSafeAreaInsets();- const [showSearch, setShowSearch] = useState(false);- const [kh, setKh] = useState(0);-- const onKeyboardDidShow = event => {- let kHeight = event.endCoordinates.height;- keyboardHeight.current = kHeight;- setKh(kHeight);- console.log('keyboard show/hide');- };-- const onKeyboardDidHide = () => {- keyboardHeight.current = 0;- setKh(0);- console.log('keyboard hide');- };-- useEffect(() => {- useShareStore.getState().setAccent();- let keyboardWillChangeFrame = Keyboard.addListener(- 'keyboardWillChangeFrame',- onKeyboardWillChangeFrame- );- let keyboardDidShow = Keyboard.addListener('keyboardDidShow', onKeyboardDidShow);- let keyboardDidHide = Keyboard.addListener('keyboardDidHide', onKeyboardDidHide);- return () => {- keyboardWillChangeFrame?.remove();- keyboardDidShow?.remove();- keyboardDidHide?.remove();- };- }, []);-- const onKeyboardWillChangeFrame = event => {- setFloating(event.endCoordinates.width !== width);- };-- const showLinkPreview = async (note, link) => {- let _note = note;- _note.content.data = makeHtmlFromUrl(link);- try {- let preview = await getLinkPreview(link);- _note.title = preview.title;- } catch (e) {- console.log(e);- }- return note;- };-- const loadData = async () => {- try {- defaultNote.content.data = null;- setNote({ ...defaultNote });- const data = await ShareExtension.data();- if (!data || data.length === 0) {- setRawData({- value: ''- });- setLoadingIntent(false);- return;- }- let note = { ...defaultNote };- for (let item of data) {- if (item.type === 'text') {- setRawData(item);- if (isURL(item.value)) {- note = await showLinkPreview(note, item.value);- } else {- note.content.data = makeHtmlFromPlainText(item.value);- }- }- }- setNote({ ...note });- } catch (e) {}- setLoadingIntent(false);- };-- useEffect(() => {- console.log('setting value in storage');- loadData();- useShareStore.getState().restoreAppendNote();- sleep(50).then(() => {- sleep(500).then(r => {- Storage.write('shareExtensionOpened', 'opened');- });- });- }, []);-- const close = async () => {- setNote({ ...defaultNote });- setLoadingIntent(true);- if (quicknote) {- ShareExtension.openURL('ShareMedia://MainApp');- } else {- ShareExtension.close();- }- };-- const onLoad = () => {- postMessage(webviewRef, 'htmldiff', note.content?.data || '');- console.log('on load');- setTimeout(() => {- let theme = { ...colors };- theme.factor = 1;-- webviewRef.current?.injectJavaScript(`- document.querySelector('.htmldiff_div').setAttribute('contenteditable', 'true');`);-- webviewRef.current?.injectJavaScript(`(function() {- try {- pageTheme.colors = ${JSON.stringify(theme)};- setTheme();- } catch(e) {- console.log(e);- }- })();-- `);- }, 300);- };-- function postMessage(webview, type, value = null) {- let message = {- type: type,- value- };- webview.current?.postMessage(JSON.stringify(message));- }-- const onPress = async () => {- let content = await getContent();- if (!content || content === '' || typeof content !== 'string') {- return;- }- setLoading(true);- await db.init();- await db.notes.init();-- if (appendNote && !db.notes.note(appendNote.id)) {- useShareStore.getState().setAppendNote(null);- Alert.alert('The note you are trying to append to has been deleted.');- return;- }-- let _note;- if (appendNote && db.notes.note(appendNote.id)) {- let raw = await db.content.raw(appendNote.contentId);- _note = {- content: {- data: raw.data + '\n' + content,- type: 'tiny'- },- id: appendNote.id,- sessionId: Date.now()- };- } else {- _note = { ...note };- _note.content.data = content;- _note.sessionId = Date.now();- }- await db.notes.add(_note);- await Storage.write('notesAddedFromIntent', 'added');- close();- setLoading(false);- };-- const sourceUri = 'Web.bundle/site/plaineditor.html';-- const onShouldStartLoadWithRequest = request => {- if (request.url.includes('/site/plaineditor.html')) {- return true;- } else {- return false;- }- };-- const getContent = () => {- return new Promise(resolve => {- let oncontent = value => {- eUnSubscribeEvent('share_content_event', oncontent);- resolve(value);- };- eSubscribeEvent('share_content_event', oncontent);- webviewRef.current?.injectJavaScript(`(function() {- let html = document.querySelector(".htmldiff_div").innerHTML;- if (!html) {- html = '';- }- reactNativeEventHandler('tiny', html);- })();`);- });- };-- const onMessage = event => {- if (!event) return;- let data = JSON.parse(event.nativeEvent.data);- if (data.type === 'tiny') {- eSendEvent('share_content_event', data.value);- }- };-- useEffect(() => {- useShareStore.getState().setColors();- onLoad();- }, [note]);-- const changeMode = async m => {- setMode(m);-- setLoading(true);- try {- if (m === 2) {- let html = await sanitizeHtml(rawData.value);- setNote(note => {- note.content.data = html;- return { ...note };- });- } else {- let html = isURL(rawData.value)- ? makeHtmlFromUrl(rawData.value)- : makeHtmlFromPlainText(rawData.value);- setNote(note => {- note.content.data = html;- return { ...note };- });- }- } catch (e) {- } finally {- setLoading(false);- }- };-- const onPaste = async () => {- let text = await Clipboard.getString();- if (text) {- let content = await getContent();- setNote(note => {- note.content.data = content + '\n' + makeHtmlFromPlainText(text);- return { ...note };- });- }- };-- const Outer = Platform.OS === 'android' ? Modal : Fragment;-- const outerProps =- Platform.OS === 'android'- ? {- animationType: 'fade',- transparent: true,- visible: true- }- : {};-return (- <Outer {...outerProps}>- <SafeAreaView- style={{- width: width > 500 ? 500 : width,- height: height - kh,- alignSelf: 'center',- justifyContent: 'flex-end'- }}- >- {quicknote && !showSearch ? (- <View- style={{- width: '100%',- backgroundColor: colors.bg,- height: 50 + insets.top,- paddingTop: insets.top,- ...getElevation(1),- marginTop: -insets.top,- flexDirection: 'row',- alignItems: 'center',- justifyContent: 'space-between'- }}- >- <Button- type="action"- icon="close"- iconColor={colors.pri}- onPress={() => {- if (showSearch) {- console.log('hide search');- setShowSearch(false);- } else {- close();- }- }}- style={{- width: 50,- height: 50,- marginBottom: 0- }}- iconSize={25}- />-- <Text- style={{- color: colors.pri,- fontSize: 17,- fontFamily: 'OpenSans-Regular'- }}- >- Quick note- </Text>-- <Button- type="action"- icon="check"- iconColor={accent.color}- onPress={onPress}- style={{- width: 50,- height: 50,- marginBottom: 0- }}- iconSize={25}- />- </View>- ) : (- <TouchableOpacity- activeOpacity={1}- onPress={() => {- if (showSearch) {- console.log('hide search');- setShowSearch(false);- } else {- close();- }- }}- style={{- width: '100%',- height: '100%',- position: 'absolute'- }}- >- <View- style={{- width: '100%',- height: '100%',- backgroundColor: 'white',- opacity: 0.01- }}- />- <View />- </TouchableOpacity>- )}-- {showSearch ? (- <Search- quicknote={quicknote}- getKeyboardHeight={() => keyboardHeight.current}- close={() => {- setShowSearch(false);- }}- />- ) : null}-- <View- style={{- paddingVertical: 25,- backgroundColor: 'transparent',- marginBottom: insets.top,- display: showSearch ? 'none' : 'flex'- }}- >- <View- style={{- maxHeight: '100%',- paddingHorizontal: 12- }}- >- <ScrollView- horizontal- contentContainerStyle={{- alignItems: 'center',- height: 50- }}- style={{- width: '100%',- height: 50,- borderRadius: 10,- flexDirection: 'row',- bottom: -10- }}- >- <Button- color={colors.nav}- onPress={() => {- useShareStore.getState().setAppendNote(null);- }}- icon="plus"- iconSize={18}- iconColor={!appendNote ? accent.color : colors.icon}- title="New note"- textColor={!appendNote ? accent.color : colors.icon}- type="rounded"- textStyle={{- fontSize: 13- }}- style={{- paddingHorizontal: 12,- ...getElevation(1),- height: 35- }}- />-- <Button- color={colors.nav}- onPress={() => {- setShowSearch(true);- }}- icon="text-short"- iconSize={18}- iconColor={appendNote ? accent.color : colors.icon}- title={`${appendNote ? appendNote.title.slice(0, 25) : 'Append to note'}`}- textColor={appendNote ? accent.color : colors.icon}- type="rounded"- textStyle={{- fontSize: 13- }}- style={{- paddingHorizontal: 12,- ...getElevation(1),- height: 35- }}- />- </ScrollView>-- <View- style={{- width: '100%'- }}- >- <View- style={{- marginTop: 10,- minHeight: 100,- borderRadius: 10,- ...getElevation(quicknote ? 1 : 5),- backgroundColor: colors.bg,- overflow: 'hidden'- }}- >- <View- style={{- width: '100%',- height: height * 0.3,- paddingBottom: 15,- borderRadius: 10- }}- >- <WebView- onLoad={onLoad}- ref={webviewRef}- style={{- width: '100%',- height: '100%',- borderRadius: 10,- backgroundColor: 'transparent'- }}- cacheMode="LOAD_DEFAULT"- domStorageEnabled={true}- scrollEnabled={true}- bounces={false}- allowFileAccess={true}- scalesPageToFit={true}- allowingReadAccessToURL={Platform.OS === 'android' ? true : null}- onMessage={onMessage}- onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}- allowFileAccessFromFileURLs={true}- allowUniversalAccessFromFileURLs={true}- originWhitelist={['*']}- javaScriptEnabled={true}- cacheEnabled={true}- source={- Platform.OS === 'ios'- ? { uri: sourceUri }- : {- uri: 'file:///android_asset/plaineditor.html',- baseUrl: 'file:///android_asset/'- }- }- />- </View>-- {appendNote ? (- <Text- style={{- fontSize: 12,- color: colors.icon,- fontFamily: 'OpenSans-Regular',- paddingHorizontal: 12,- marginBottom: 10,- flexWrap: 'wrap'- }}- >- Above content will append to{' '}- <Text- style={{- color: accent.color,- fontFamily: 'OpenSans-SemiBold'- }}- >- "{appendNote.title}"- </Text>{' '}- . Click on "New note" to create a new note.- </Text>- ) : null}-- <View- style={{- flexDirection: 'row',- paddingHorizontal: 12,- alignItems: 'flex-end',- justifyContent: 'space-between',- width: '100%'- }}- >- <View- style={{- flexDirection: 'row'- }}- >- {rawData.value && isURL(rawData.value) ? (- <Button- color={mode == 2 ? colors.shade : colors.nav}- icon={modes[2].icon}- onPress={() => changeMode(2)}- title={modes[2].title}- iconSize={18}- iconColor={mode == 2 ? accent.color : colors.icon}- textColor={mode == 2 ? accent.color : colors.icon}- type="rounded"- style={{ paddingHorizontal: 12 }}- />- ) : null}- <Button- color={mode == 1 ? colors.shade : colors.nav}- icon={modes[1].icon}- onPress={() => changeMode(1)}- title={modes[1].title}- iconSize={18}- iconColor={mode == 1 ? accent.color : colors.icon}- textColor={mode == 1 ? accent.color : colors.icon}- type="rounded"- style={{ paddingHorizontal: 12 }}- />- </View>-- {!quicknote ? (- <Button- color={accent.color}- onPress={onPress}- loading={loading || loadingIntent}- icon="check"- iconSize={20}- iconColor={colors.light}- style={{- paddingHorizontal: 0,- height: 40,- width: 40,- borderRadius: 100,- minWidth: 0- }}- />- ) : null}- </View>- </View>- </View>-- <View- style={{- height: Platform.isPad ? 150 : Platform.OS === 'ios' ? 110 : 0- }}- />- </View>- </View>- </SafeAreaView>- </Outer>- );-};--const Button = ({- title,- onPress,- color,- loading,- style,- textStyle,- icon,- iconSize = 22,- type = 'button',- iconColor = 'gray',- textColor = 'white',- fontSize = 18-}) => {- const types = {- action: {- style: {- width: 60,- height: 60,- borderRadius: 100,- minWidth: 0,- paddingHorizontal: 0- },- textStyle: {}- },- button: {- style: {- height: 50,- borderRadius: 5,- justifyContent: 'center',- alignItems: 'center',- flexDirection: 'row',- marginBottom: 10,- minWidth: 80,- paddingHorizontal: 20- },- textStyle: {}- },- rounded: {- style: {- marginRight: 15,- height: 30,- borderRadius: 100,- paddingHorizontal: 6,- marginTop: -2.5- },- textStyle: {- fontSize: 12,- marginLeft: 5- }- }- };-- return (- <TouchableOpacity- onPress={onPress}- activeOpacity={0.8}- style={[- {- backgroundColor: color,- height: 50,- borderRadius: 5,- justifyContent: 'center',- alignItems: 'center',- flexDirection: 'row',- marginBottom: 10,- minWidth: 80,- paddingHorizontal: 20- },- types[type].style,- style- ]}- >- {loading ? <ActivityIndicator color={iconColor} /> : null}-- {icon && !loading ? <Icon name={icon} size={iconSize} color={iconColor || 'white'} /> : null}-- {title ? (- <Text- style={[- {- fontSize: fontSize || 18,- fontFamily: 'OpenSans-Regular',- color: textColor,- marginLeft: loading ? 10 : 0- },- types[type].textStyle,- textStyle- ]}- >- {title}- </Text>- ) : null}- </TouchableOpacity>+ <Wrapper {...outerProps}>+ <ShareView quicknote={quicknote} />+ </Wrapper>);};diff --git a/apps/mobile/share/share.js b/apps/mobile/share/share.jsnew file mode 100644index 000000000..9c157077a--- /dev/null+++ b/apps/mobile/share/share.js@@ -0,0 +1,791 @@+/* eslint-disable @typescript-eslint/no-var-requires */+import Clipboard from '@react-native-clipboard/clipboard';+//import { getLinkPreview } from 'link-preview-js';+import { getPreviewData } from '@flyerhq/react-native-link-preview';+import { parseHTML } from 'notes-core/utils/htmlparser';+import React, { Fragment, useEffect, useRef, useState } from 'react';+import {+ ActivityIndicator,+ Alert,+ Keyboard,+ Modal,+ Platform,+ SafeAreaView,+ ScrollView,+ StatusBar,+ Text,+ TouchableOpacity,+ useWindowDimensions,+ View+} from 'react-native';+import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';+import Icon from 'react-native-vector-icons/MaterialCommunityIcons';+import ShareExtension from 'rn-extensions-share';+import isURL from 'validator/lib/isURL';+import { getElevation } from '../src/utils';+import { db, loadDatabase } from '../src/utils/database';+import Storage from '../src/utils/database/storage';+import { sleep } from '../src/utils/time';+import { Search } from './search';+import { useShareStore } from './store';+import { eSendEvent } from '../src/services/event-manager';+import { eOnLoadNote } from '../src/utils/events';+let Editor = null;+const getLinkPreview = url => {+ return getPreviewData(url, 5000);+};+async function sanitizeHtml(site) {+ try {+ let html = await fetch(site);+ html = await html.text();+ return sanitize(html, site);+ } catch (e) {+ return '';+ }+}++function makeHtmlFromUrl(url) {+ return `<a style="overflow-wrap:anywhere;white-space:pre-wrap" href='${url}' target='_blank'>${url}</a>`;+}++function makeHtmlFromPlainText(text) {+ if (!text) return '';++ return `<p style="overflow-wrap:anywhere;white-space:pre-wrap" >${text.replace(+ /(?:\r\n|\r|\n)/g,+ '<br>'+ )}</p>`;+}++function getBaseUrl(site) {+ var url = site.split('/').slice(0, 3).join('/');+ return url;+}++function wrapTablesWithDiv(document) {+ const tables = document.getElementsByTagName('table');+ for (let table of tables) {+ table.setAttribute('contenteditable', 'true');+ const div = document.createElement('div');+ div.setAttribute('contenteditable', 'false');+ div.innerHTML = table.outerHTML;+ div.classList.add('table-container');+ table.replaceWith(div);+ }+ return document;+}++let elementBlacklist = [+ 'script',+ 'button',+ 'input',+ 'textarea',+ 'style',+ 'form',+ 'link',+ 'head',+ 'nav',+ 'iframe',+ 'canvas',+ 'select',+ 'dialog',+ 'footer'+];++function removeInvalidElements(document) {+ let elements = document.querySelectorAll(elementBlacklist.join(','));+ for (let element of elements) {+ element.remove();+ }+ return document;+}++function replaceSrcWithAbsoluteUrls(document, baseUrl) {+ let images = document.querySelectorAll('img');+ console.log(images.length);+ for (var i = 0; i < images.length; i++) {+ let img = images[i];+ let url = getBaseUrl(baseUrl);+ let src = img.getAttribute('src');+ if (src.startsWith('/')) {+ if (src.startsWith('//')) {+ src = src.replace('//', 'https://');+ } else {+ src = url + src;+ }+ }+ if (src.startsWith('data:')) {+ img.remove();+ } else {+ img.setAttribute('src', src);+ }+ }+ console.log('end');+ return document;+}++function fixCodeBlocks(document) {+ let elements = document.querySelectorAll('code,pre');++ for (let element of elements) {+ element.classList.add('.hljs');+ }+ return document;+}++function sanitize(html, baseUrl) {+ let parser = parseHTML(html);+ parser = wrapTablesWithDiv(parser);+ parser = removeInvalidElements(parser);+ parser = replaceSrcWithAbsoluteUrls(parser, baseUrl);+ parser = fixCodeBlocks(parser);+ let htmlString = parser.outerHTML;++ htmlString = htmlString + `<hr>${makeHtmlFromUrl(baseUrl)}`;++ return htmlString;+}++let defaultNote = {+ title: null,+ id: null,+ content: {+ type: 'tiny',+ data: null+ }+};++const modes = {+ 1: {+ type: 'text',+ title: 'Plain text',+ icon: 'card-text-outline'+ },+ 2: {+ type: 'clip',+ title: 'Web clip',+ icon: 'web'+ },+ 3: {+ type: 'link',+ title: 'Link',+ icon: 'link'+ }+};++const ShareView = ({ quicknote = false }) => {+ const colors = useShareStore(state => state.colors);+ const accent = useShareStore(state => state.accent);+ const appendNote = useShareStore(state => state.appendNote);+ const [note, setNote] = useState({ ...defaultNote });+ const noteContent = useRef();+ const [loadingIntent, setLoadingIntent] = useState(true);+ const [loading, setLoading] = useState(false);+ const [loadingExtension, setLoadingExtension] = useState(true);+ const [floating, setFloating] = useState(false);+ const [rawData, setRawData] = useState({+ type: null,+ value: null+ });+ const [mode, setMode] = useState(1);+ const keyboardHeight = useRef(0);+ const { width, height } = useWindowDimensions();+ const insets = Platform.OS === 'android' ? { top: StatusBar.currentHeight } : useSafeAreaInsets();+ const [showSearch, setShowSearch] = useState(false);+ const [kh, setKh] = useState(0);+ const editorRef = useRef();++ const onKeyboardDidShow = event => {+ let kHeight = event.endCoordinates.height;+ keyboardHeight.current = kHeight;+ setKh(kHeight);+ console.log('keyboard show/hide');+ };++ const onKeyboardDidHide = () => {+ keyboardHeight.current = 0;+ setKh(0);+ console.log('keyboard hide');+ };++ useEffect(() => {+ useShareStore.getState().setAccent();+ let keyboardWillChangeFrame = Keyboard.addListener(+ 'keyboardWillChangeFrame',+ onKeyboardWillChangeFrame+ );+ let keyboardDidShow = Keyboard.addListener('keyboardDidShow', onKeyboardDidShow);+ let keyboardDidHide = Keyboard.addListener('keyboardDidHide', onKeyboardDidHide);+ return () => {+ keyboardWillChangeFrame?.remove();+ keyboardDidShow?.remove();+ keyboardDidHide?.remove();+ };+ }, []);++ const onKeyboardWillChangeFrame = event => {+ setFloating(event.endCoordinates.width !== width);+ };++ const showLinkPreview = async (note, link) => {+ let _note = note;+ _note.content.data = makeHtmlFromUrl(link);+ try {+ let preview = await getLinkPreview(link);+ _note.title = preview.title;+ } catch (e) {+ console.log(e);+ }+ return note;+ };++ const loadData = async () => {+ try {+ defaultNote.content.data = null;+ setNote({ ...defaultNote });+ const data = await ShareExtension.data();+ if (!data || data.length === 0) {+ setRawData({+ value: ''+ });+ setLoadingIntent(false);+ return;+ }+ let note = { ...defaultNote };+ for (let item of data) {+ if (item.type === 'text') {+ setRawData(item);+ if (isURL(item.value)) {+ note = await showLinkPreview(note, item.value);+ } else {+ note.content.data = makeHtmlFromPlainText(item.value);+ }+ noteContent.current = note.content.data;+ }+ }+ setNote({ ...note });+ onLoad();+ } catch (e) {}+ setLoadingIntent(false);+ };++ useEffect(() => {+ console.log('setting value in storage');+ (async () => {+ await loadDatabase();+ Editor = require('../src/screens/editor/index').default;+ setLoadingExtension(false);+ loadData();+ useShareStore.getState().restoreAppendNote();+ sleep(50).then(() => {+ sleep(500).then(r => {+ Storage.write('shareExtensionOpened', 'opened');+ });+ });+ })();+ }, []);++ const close = async () => {+ setNote({ ...defaultNote });+ setLoadingIntent(true);+ setLoadingExtension(true);+ if (quicknote) {+ ShareExtension.openURL('ShareMedia://MainApp');+ } else {+ ShareExtension.close();+ }+ };++ const onLoad = () => {+ eSendEvent(eOnLoadNote + 'shareEditor', {+ id: null,+ content: {+ type: 'tiny',+ data: noteContent.current+ }+ });+ };++ const onPress = async () => {+ setLoading(true);+ await db.init();+ await db.notes.init();++ if (appendNote && !db.notes.note(appendNote.id)) {+ useShareStore.getState().setAppendNote(null);+ Alert.alert('The note you are trying to append to has been deleted.');+ return;+ }++ let _note;+ if (appendNote && db.notes.note(appendNote.id)) {+ let raw = await db.content.raw(appendNote.contentId);+ _note = {+ content: {+ data: raw.data + '\n' + noteContent.current,+ type: 'tiny'+ },+ id: appendNote.id,+ sessionId: Date.now()+ };+ } else {+ _note = { ...note };+ _note.content.data = noteContent.current;+ _note.sessionId = Date.now();+ }+ await db.notes.add(_note);+ await Storage.write('notesAddedFromIntent', 'added');+ close();+ setLoading(false);+ };++ useEffect(() => {+ useShareStore.getState().setColors();+ }, [note]);++ const changeMode = async m => {+ setMode(m);++ setLoading(true);+ try {+ if (m === 2) {+ let html = await sanitizeHtml(rawData.value);+ setNote(note => {+ note.content.data = html;+ return { ...note };+ });+ } else {+ let html = isURL(rawData.value)+ ? makeHtmlFromUrl(rawData.value)+ : makeHtmlFromPlainText(rawData.value);+ setNote(note => {+ note.content.data = html;+ noteContent.current = html;+ onLoad();+ return { ...note };+ });+ }+ } catch (e) {+ } finally {+ setLoading(false);+ }+ };++ return loadingExtension ? null : (+ <SafeAreaView+ style={{+ width: width > 500 ? 500 : width,+ height: height - kh,+ alignSelf: 'center',+ justifyContent: 'flex-end'+ }}+ >+ {quicknote && !showSearch ? (+ <View+ style={{+ width: '100%',+ backgroundColor: colors.bg,+ height: 50 + insets.top,+ paddingTop: insets.top,+ ...getElevation(1),+ marginTop: -insets.top,+ flexDirection: 'row',+ alignItems: 'center',+ justifyContent: 'space-between'+ }}+ >+ <Button+ type="action"+ icon="close"+ iconColor={colors.pri}+ onPress={() => {+ if (showSearch) {+ console.log('hide search');+ setShowSearch(false);+ } else {+ close();+ }+ }}+ style={{+ width: 50,+ height: 50,+ marginBottom: 0+ }}+ iconSize={25}+ />++ <Text+ style={{+ color: colors.pri,+ fontSize: 17,+ fontFamily: 'OpenSans-Regular'+ }}+ >+ Quick note+ </Text>++ <Button+ type="action"+ icon="check"+ iconColor={accent.color}+ onPress={onPress}+ style={{+ width: 50,+ height: 50,+ marginBottom: 0+ }}+ iconSize={25}+ />+ </View>+ ) : (+ <TouchableOpacity+ activeOpacity={1}+ onPress={() => {+ if (showSearch) {+ console.log('hide search');+ setShowSearch(false);+ } else {+ close();+ }+ }}+ style={{+ width: '100%',+ height: '100%',+ position: 'absolute'+ }}+ >+ <View+ style={{+ width: '100%',+ height: '100%',+ backgroundColor: 'white',+ opacity: 0.01+ }}+ />+ <View />+ </TouchableOpacity>+ )}++ {showSearch ? (+ <Search+ quicknote={quicknote}+ getKeyboardHeight={() => keyboardHeight.current}+ close={() => {+ setShowSearch(false);+ }}+ />+ ) : null}++ <View+ style={{+ paddingVertical: 25,+ backgroundColor: 'transparent',+ marginBottom: insets.top,+ display: showSearch ? 'none' : 'flex'+ }}+ >+ <View+ style={{+ maxHeight: '100%',+ paddingHorizontal: 12+ }}+ >+ <ScrollView+ horizontal+ contentContainerStyle={{+ alignItems: 'center',+ height: 50+ }}+ style={{+ width: '100%',+ height: 50,+ borderRadius: 10,+ flexDirection: 'row',+ bottom: -10+ }}+ >+ <Button+ color={colors.nav}+ onPress={() => {+ useShareStore.getState().setAppendNote(null);+ }}+ icon="plus"+ iconSize={18}+ iconColor={!appendNote ? accent.color : colors.icon}+ title="New note"+ textColor={!appendNote ? accent.color : colors.icon}+ type="rounded"+ textStyle={{+ fontSize: 13+ }}+ style={{+ paddingHorizontal: 12,+ ...getElevation(1),+ height: 35+ }}+ />++ <Button+ color={colors.nav}+ onPress={() => {+ setShowSearch(true);+ }}+ icon="text-short"+ iconSize={18}+ iconColor={appendNote ? accent.color : colors.icon}+ title={`${appendNote ? appendNote.title.slice(0, 25) : 'Append to note'}`}+ textColor={appendNote ? accent.color : colors.icon}+ type="rounded"+ textStyle={{+ fontSize: 13+ }}+ style={{+ paddingHorizontal: 12,+ ...getElevation(1),+ height: 35+ }}+ />+ </ScrollView>++ <View+ style={{+ width: '100%'+ }}+ >+ <View+ style={{+ marginTop: 10,+ minHeight: 100,+ borderRadius: 10,+ ...getElevation(quicknote ? 1 : 5),+ backgroundColor: colors.bg,+ overflow: 'hidden'+ }}+ >+ <View+ style={{+ width: '100%',+ height: height * 0.3,+ paddingBottom: 15,+ borderRadius: 10+ }}+ >+ <SafeAreaProvider+ style={{+ flex: 1+ }}+ >+ {Editor && (+ <Editor+ ref={editorRef}+ theme={{+ ...colors,+ accent+ }}+ editorId="shareEditor"+ noHeader={true}+ noToolbar={true}+ readonly={false}+ onLoad={onLoad}+ onChange={html => {+ noteContent.current = html;+ }}+ />+ )}+ </SafeAreaProvider>+ </View>++ {appendNote ? (+ <Text+ style={{+ fontSize: 12,+ color: colors.icon,+ fontFamily: 'OpenSans-Regular',+ paddingHorizontal: 12,+ marginBottom: 10,+ flexWrap: 'wrap'+ }}+ >+ Above content will append to{' '}+ <Text+ style={{+ color: accent.color,+ fontFamily: 'OpenSans-SemiBold'+ }}+ >+ "{appendNote.title}"+ </Text>{' '}+ . Click on "New note" to create a new note.+ </Text>+ ) : null}++ <View+ style={{+ flexDirection: 'row',+ paddingHorizontal: 12,+ alignItems: 'flex-end',+ justifyContent: 'space-between',+ width: '100%'+ }}+ >+ <View+ style={{+ flexDirection: 'row'+ }}+ >+ {rawData.value && isURL(rawData.value) ? (+ <Button+ color={mode == 2 ? colors.shade : colors.nav}+ icon={modes[2].icon}+ onPress={() => changeMode(2)}+ title={modes[2].title}+ iconSize={18}+ iconColor={mode == 2 ? accent.color : colors.icon}+ textColor={mode == 2 ? accent.color : colors.icon}+ type="rounded"+ style={{ paddingHorizontal: 12 }}+ />+ ) : null}+ <Button+ color={mode == 1 ? colors.shade : colors.nav}+ icon={modes[1].icon}+ onPress={() => changeMode(1)}+ title={modes[1].title}+ iconSize={18}+ iconColor={mode == 1 ? accent.color : colors.icon}+ textColor={mode == 1 ? accent.color : colors.icon}+ type="rounded"+ style={{ paddingHorizontal: 12 }}+ />+ </View>++ {!quicknote ? (+ <Button+ color={accent.color}+ onPress={onPress}+ loading={loading || loadingIntent}+ icon="check"+ iconSize={20}+ iconColor={colors.light}+ style={{+ paddingHorizontal: 0,+ height: 40,+ width: 40,+ borderRadius: 100,+ minWidth: 0+ }}+ />+ ) : null}+ </View>+ </View>+ </View>++ <View+ style={{+ height: Platform.isPad ? 150 : Platform.OS === 'ios' ? 110 : 0+ }}+ />+ </View>+ </View>+ </SafeAreaView>+ );+};++const Button = ({+ title,+ onPress,+ color,+ loading,+ style,+ textStyle,+ icon,+ iconSize = 22,+ type = 'button',+ iconColor = 'gray',+ textColor = 'white',+ fontSize = 18+}) => {+ const types = {+ action: {+ style: {+ width: 60,+ height: 60,+ borderRadius: 100,+ minWidth: 0,+ paddingHorizontal: 0+ },+ textStyle: {}+ },+ button: {+ style: {+ height: 50,+ borderRadius: 5,+ justifyContent: 'center',+ alignItems: 'center',+ flexDirection: 'row',+ marginBottom: 10,+ minWidth: 80,+ paddingHorizontal: 20+ },+ textStyle: {}+ },+ rounded: {+ style: {+ marginRight: 15,+ height: 30,+ borderRadius: 100,+ paddingHorizontal: 6,+ marginTop: -2.5+ },+ textStyle: {+ fontSize: 12,+ marginLeft: 5+ }+ }+ };++ return (+ <TouchableOpacity+ onPress={onPress}+ activeOpacity={0.8}+ style={[+ {+ backgroundColor: color,+ height: 50,+ borderRadius: 5,+ justifyContent: 'center',+ alignItems: 'center',+ flexDirection: 'row',+ marginBottom: 10,+ minWidth: 80,+ paddingHorizontal: 20+ },+ types[type].style,+ style+ ]}+ >+ {loading ? <ActivityIndicator color={iconColor} /> : null}++ {icon && !loading ? <Icon name={icon} size={iconSize} color={iconColor || 'white'} /> : null}++ {title ? (+ <Text+ style={[+ {+ fontSize: fontSize || 18,+ fontFamily: 'OpenSans-Regular',+ color: textColor,+ marginLeft: loading ? 10 : 0+ },+ types[type].textStyle,+ textStyle+ ]}+ >+ {title}+ </Text>+ ) : null}+ </TouchableOpacity>+ );+};++export default ShareView;diff --git a/apps/mobile/src/components/auth/authmodal.js b/apps/mobile/src/components/auth/authmodal.jsindex 9e6b59ab1..886901105 100644--- a/apps/mobile/src/components/auth/authmodal.js+++ b/apps/mobile/src/components/auth/authmodal.js@@ -1,6 +1,4 @@import React, { useEffect, useRef, useState } from 'react';-import { Platform } from 'react-native';-import { useSafeAreaInsets } from 'react-native-safe-area-context';import { eSubscribeEvent, eUnSubscribeEvent } from '../../services/event-manager';import { useThemeStore } from '../../stores/use-theme-store';import { eCloseLoginDialog, eOpenLoginDialog } from '../../utils/events';@@ -24,7 +22,6 @@ const AuthModal = () => {const [visible, setVisible] = useState(false);const [currentAuthMode, setCurrentAuthMode] = useState(AuthMode.login);const actionSheetRef = useRef();- const insets = useSafeAreaInsets();useEffect(() => {eSubscribeEvent(eOpenLoginDialog, open);@@ -85,8 +82,7 @@ const AuthModal = () => {customStyle={{position: 'absolute',zIndex: 999,- left: 12,- top: Platform.OS === 'ios' ? 12 + insets.top : insets.top+ left: 12}}/>)}diff --git a/apps/mobile/src/components/delaylayout/index.tsx b/apps/mobile/src/components/delaylayout/index.tsxindex 2357eeb3c..0b4e4c881 100644--- a/apps/mobile/src/components/delaylayout/index.tsx+++ b/apps/mobile/src/components/delaylayout/index.tsx@@ -1,6 +1,5 @@import React from 'react';-import { ViewProps } from 'react-native';-import Animated, { FadeOut } from 'react-native-reanimated';+import { View, ViewProps } from 'react-native';import { useThemeStore } from '../../stores/use-theme-store';import { useDelayLayout } from '../../utils/hooks/use-delay-layout';import { DefaultPlaceholder } from './default-placeholder';@@ -24,8 +23,7 @@ export default function DelayLayout(props: IDelayLayoutProps) {const Placeholder = placeholder[props.type || 'default'];return loading || props.wait ? (- <Animated.View- exiting={FadeOut}+ <Viewstyle={{backgroundColor: colors.bg,flex: 1,@@ -33,7 +31,7 @@ export default function DelayLayout(props: IDelayLayoutProps) {}}><Placeholder />- </Animated.View>+ </View>) : (<>{props.children}</>);diff --git a/apps/mobile/src/screens/editor/index.tsx b/apps/mobile/src/screens/editor/index.tsxindex 52cb71419..cf0d16ceb 100755--- a/apps/mobile/src/screens/editor/index.tsx+++ b/apps/mobile/src/screens/editor/index.tsx@@ -1,5 +1,5 @@import { EV, EVENTS } from 'notes-core/common';-import React, { useEffect } from 'react';+import React, { forwardRef, RefObject, useEffect, useImperativeHandle } from 'react';import { Linking, ViewStyle } from 'react-native';import WebView from 'react-native-webview';import { ShouldStartLoadRequest } from 'react-native-webview/lib/WebViewTypes';@@ -29,102 +29,118 @@ const onShouldStartLoadWithRequest = (request: ShouldStartLoadRequest) => {};const Editor = React.memo(- ({- readonly = false,- noToolbar = false,- noHeader = false,- withController = true,- editorId = '',- onLoad- }: EditorProps) => {- const editor = useEditor(editorId || '', readonly);- const onMessage = useEditorEvents(editor, {- readonly,- noToolbar,- noHeader- });-- const onMediaDownloaded = ({- hash,- groupId,- src- }: {- hash: string;- groupId: string;- src: string;- }) => {- console.log('onMediaDownoaded', groupId);- if (groupId !== editor.note.current?.id) return;- editor.commands.updateImage({- hash: hash,- src: src+ forwardRef<+ {+ get: () => useEditorType;+ },+ EditorProps+ >(+ (+ {+ readonly = false,+ noToolbar = false,+ noHeader = false,+ withController = true,+ editorId = '',+ onLoad,+ onChange,+ theme+ },+ ref+ ) => {+ const editor = useEditor(editorId || '', readonly, onChange, theme);+ const onMessage = useEditorEvents(editor, {+ readonly,+ noToolbar,+ noHeader});- };- useEffect(() => {- onLoad && onLoad();- EV.subscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded);- return () => {- EV.unsubscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded);+ useImperativeHandle(ref, () => ({+ get: () => editor+ }));++ const onMediaDownloaded = ({+ hash,+ groupId,+ src+ }: {+ hash: string;+ groupId: string;+ src: string;+ }) => {+ console.log('onMediaDownoaded', groupId);++ if (groupId !== editor.note.current?.id) return;+ editor.commands.updateImage({+ hash: hash,+ src: src+ });};- }, []);- if (withController) {- //@ts-ignore- editorController.current = editor;- }+ useEffect(() => {+ onLoad && onLoad();+ EV.subscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded);+ return () => {+ EV.unsubscribe(EVENTS.mediaAttachmentDownloaded, onMediaDownloaded);+ };+ }, []);- const onError = () => {- editor.setLoading(true);- setTimeout(() => editor.setLoading(false), 10);- };+ if (withController) {+ //@ts-ignore+ editorController.current = editor;+ }- return editor.loading ? null : (- <>- <WebView- testID={notesnook.editor.id}- ref={editor.ref}- onLoad={editor.onLoad}- onRenderProcessGone={onError}- nestedScrollEnabled- onError={onError}- injectedJavaScriptBeforeContentLoaded={`+ const onError = () => {+ editor.setLoading(true);+ setTimeout(() => editor.setLoading(false), 10);+ };++ return editor.loading ? null : (+ <>+ <WebView+ testID={notesnook.editor.id}+ ref={editor.ref}+ onLoad={editor.onLoad}+ onRenderProcessGone={onError}+ nestedScrollEnabled+ onError={onError}+ injectedJavaScriptBeforeContentLoaded={`globalThis.readonly=${readonly};globalThis.noToolbar=${noToolbar};globalThis.noHeader=${noHeader};`}- injectedJavaScript={`- globalThis.sessionId="${editor.sessionId}";`}- javaScriptEnabled={true}- focusable={true}- setSupportMultipleWindows={false}- overScrollMode="never"- keyboardDisplayRequiresUserAction={false}- onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}- cacheMode="LOAD_DEFAULT"- cacheEnabled={true}- domStorageEnabled={true}- bounces={false}- setBuiltInZoomControls={false}- setDisplayZoomControls={false}- allowFileAccess={true}- scalesPageToFit={true}- hideKeyboardAccessoryView={true}- allowFileAccessFromFileURLs={true}- allowUniversalAccessFromFileURLs={true}- originWhitelist={['*']}- source={{- uri: __DEV__ ? 'http://localhost:3000' : EDITOR_URI- }}- style={style}- autoManageStatusBarEnabled={false}- onMessage={onMessage || undefined}- />- <EditorOverlay editorId={editorId || ''} editor={editor} />- <ReadonlyButton editor={editor} />- </>- );- },+ injectedJavaScript={`globalThis.sessionId="${editor.sessionId}";`}+ javaScriptEnabled={true}+ focusable={true}+ setSupportMultipleWindows={false}+ overScrollMode="never"+ keyboardDisplayRequiresUserAction={false}+ onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}+ cacheMode="LOAD_DEFAULT"+ cacheEnabled={true}+ domStorageEnabled={true}+ bounces={false}+ setBuiltInZoomControls={false}+ setDisplayZoomControls={false}+ allowFileAccess={true}+ scalesPageToFit={true}+ hideKeyboardAccessoryView={true}+ allowFileAccessFromFileURLs={true}+ allowUniversalAccessFromFileURLs={true}+ originWhitelist={['*']}+ source={{+ uri: __DEV__ ? 'http://localhost:3000' : EDITOR_URI+ }}+ style={style}+ autoManageStatusBarEnabled={false}+ onMessage={onMessage || undefined}+ />+ {theme ? null : <EditorOverlay editorId={editorId || ''} editor={editor} />}+ <ReadonlyButton editor={editor} />+ </>+ );+ }+ ),() => true);diff --git a/apps/mobile/src/screens/editor/tiptap/commands.ts b/apps/mobile/src/screens/editor/tiptap/commands.tsindex ece7e4116..82f8958d2 100644--- a/apps/mobile/src/screens/editor/tiptap/commands.ts+++ b/apps/mobile/src/screens/editor/tiptap/commands.ts@@ -114,6 +114,7 @@ typeof globalThis.statusBar !== "undefined" && statusBar.current.set({date:"",sa};setSettings = async (settings: Partial<Settings>) => {+ console.log('setSettings', JSON.stringify(settings));await this.doAsync(`if (typeof globalThis.settingsController !== "undefined") {globalThis.settingsController.update(${JSON.stringify(settings)})@@ -123,11 +124,13 @@ typeof globalThis.statusBar !== "undefined" && statusBar.current.set({date:"",sasetTags = async (note: NoteType | null | undefined) => {if (!note) return;- let tags = note.tags- .map((t: any) =>- db.tags?.tag(t) ? { title: db.tags.tag(t).title, alias: db.tags.tag(t).alias } : null- )- .filter((t: any) => t !== null);+ let tags = !note.tags+ ? []+ : note.tags+ .map((t: any) =>+ db.tags?.tag(t) ? { title: db.tags.tag(t).title, alias: db.tags.tag(t).alias } : null+ )+ .filter((t: any) => t !== null);await this.doAsync(`if (typeof editorTags !== "undefined" && editorTags.current) {editorTags.current.setTags(${JSON.stringify(tags)});diff --git a/apps/mobile/src/screens/editor/tiptap/types.ts b/apps/mobile/src/screens/editor/tiptap/types.tsindex d7cbd21fd..8e034fbb3 100644--- a/apps/mobile/src/screens/editor/tiptap/types.ts+++ b/apps/mobile/src/screens/editor/tiptap/types.ts@@ -1,5 +1,6 @@import { useEditor } from './use-editor';-import { ToolbarGroupDefinition } from 'notesnook-editor/dist/toolbar/types';+import { ToolbarGroupDefinition } from 'notesnook-editor/dist/es/toolbar/types';+import { ThemeStore } from '../../../stores/use-theme-store';export type useEditorType = ReturnType<typeof useEditor>;export type EditorState = {@@ -33,6 +34,8 @@ export type EditorProps = {withController: boolean;editorId?: string;onLoad?: () => void;+ onChange?: (html: string) => void;+ theme?: ThemeStore['colors'];};export type EditorMessage = {diff --git a/apps/mobile/src/screens/editor/tiptap/useEditor.ts b/apps/mobile/src/screens/editor/tiptap/useEditor.tsindex 9873373c3..2dd05f6a1 100644--- a/apps/mobile/src/screens/editor/tiptap/useEditor.ts+++ b/apps/mobile/src/screens/editor/tiptap/useEditor.ts@@ -7,7 +7,7 @@ import Navigation from '../../../services/navigation';import { TipManager } from '../../../services/tip-manager';import { useEditorStore } from '../../../stores/use-editor-store';import { useTagStore } from '../../../stores/use-tag-store';-import { useThemeStore } from '../../../stores/use-theme-store';+import { ThemeStore, useThemeStore } from '../../../stores/use-theme-store';import { db } from '../../../utils/database';import { MMKV } from '../../../utils/database/mmkv';import { eOnLoadNote } from '../../../utils/events';@@ -25,7 +25,12 @@ import {post} from './utils';-export const useEditor = (editorId = '', readonly?: boolean) => {+export const useEditor = (+ editorId = '',+ readonly?: boolean,+ onChange?: (html: string) => void,+ theme?: ThemeStore['colors']+) => {const [loading, setLoading] = useState(false);const [sessionId, setSessionId] = useState<string>(makeSessionId());const sessionIdRef = useRef(sessionId);@@ -33,7 +38,7 @@ export const useEditor = (editorId = '', readonly?: boolean) => {const currentNote = useRef<NoteType | null>();const currentContent = useRef<Content | null>();const timers = useRef<{ [name: string]: NodeJS.Timeout }>({});- const commands = useMemo(() => new Commands(editorRef), []);+ const commands = useMemo(() => new Commands(editorRef), [editorRef]);const sessionHistoryId = useRef<number>();const state = useRef<Partial<EditorState>>(defaultState);const placeholderTip = useRef(TipManager.placeholderTip());@@ -60,6 +65,7 @@ export const useEditor = (editorId = '', readonly?: boolean) => {}, [tags]);useEffect(() => {+ if (theme) return;let unsub = useThemeStore.subscribe(state => {postMessage(EditorEvents.theme, state.colors);});@@ -300,6 +306,10 @@ export const useEditor = (editorId = '', readonly?: boolean) => {if (currentNote.current && !params.id && params.sessionId === sessionId) {params.id = currentNote.current?.id;}+ if (onChange && params.data) {+ onChange(params.data);+ return;+ }saveNote(params);},500@@ -312,7 +322,7 @@ export const useEditor = (editorId = '', readonly?: boolean) => {console.log('on editor load');state.current.ready = true;onReady();- postMessage(EditorEvents.theme, useThemeStore.getState().colors);+ postMessage(EditorEvents.theme, theme || useThemeStore.getState().colors);commands.setInsets(isDefaultEditor ? insets : { top: 0, left: 0, right: 0, bottom: 0 });if (currentNote.current) {console.log('force reload note');diff --git a/apps/mobile/src/screens/editor/tiptap/useEditorEvents.ts b/apps/mobile/src/screens/editor/tiptap/useEditorEvents.tsindex e245a2af2..396cb2e7d 100644--- a/apps/mobile/src/screens/editor/tiptap/useEditorEvents.ts+++ b/apps/mobile/src/screens/editor/tiptap/useEditorEvents.ts@@ -134,7 +134,7 @@ export const useEditorEvents = (noHeader: noHeader,noToolbar: readonly || editorPropReadonly || noToolbar});- }, [fullscreen, isPremium, readonly, editor.sessionId, editor.loading, tools]);+ }, [fullscreen, isPremium, readonly, editor.sessionId, editor.loading, tools, editor.commands]);const onBackPress = useCallback(async () => {const editorHandledBack = await editor.commands.handleBack();diff --git a/apps/mobile/src/screens/home/index.tsx b/apps/mobile/src/screens/home/index.tsxindex 1b5dc4a7b..08c9b3aa0 100755--- a/apps/mobile/src/screens/home/index.tsx+++ b/apps/mobile/src/screens/home/index.tsx@@ -11,7 +11,6 @@ import { useNoteStore } from '../../stores/use-notes-store';import { db } from '../../utils/database';import { useNavigationFocus } from '../../utils/hooks/use-navigation-focus';import { openEditor } from '../notes/common';-const prepareSearch = () => {SearchService.update({placeholder: 'Type a keyword to search in notes',