Files
notesnook/apps/mobile/share/index.js

712 lines
18 KiB
JavaScript
Raw Normal View History

import Clipboard from '@react-native-clipboard/clipboard';
2021-07-07 11:13:43 +05:00
import absolutify from 'absolutify';
2021-10-11 11:25:22 +05:00
import { getLinkPreview } from 'link-preview-js';
import React, { useEffect, useRef, useState } from 'react';
2021-01-08 12:30:20 +05:00
import {
ActivityIndicator,
2021-10-11 11:25:22 +05:00
Alert, Keyboard,
2021-01-08 12:30:20 +05:00
KeyboardAvoidingView,
Platform,
2021-07-08 09:34:21 +05:00
SafeAreaView,
2021-10-11 11:25:22 +05:00
Text, TouchableOpacity,
2021-07-07 11:13:43 +05:00
useWindowDimensions,
2021-07-30 10:18:14 +05:00
View
2021-01-08 12:30:20 +05:00
} from 'react-native';
2021-10-11 11:25:22 +05:00
import Animated, { Easing, timing, useValue } from 'react-native-reanimated';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
2021-07-07 11:13:43 +05:00
import WebView from 'react-native-webview';
import ShareExtension from 'rn-extensions-share';
import validator from 'validator';
import {
eSendEvent,
eSubscribeEvent,
eUnSubscribeEvent
} from '../src/services/EventManager';
2021-10-11 11:25:22 +05:00
import { getElevation } from '../src/utils';
import { db } from '../src/utils/database';
2021-10-02 10:09:12 +05:00
import Storage from '../src/utils/storage';
2021-10-11 11:25:22 +05:00
import { sleep } from '../src/utils/TimeUtils';
import { Search } from './search';
import { useShareStore } from './store';
2021-07-06 15:01:52 +05:00
2021-07-07 11:44:15 +05:00
const AnimatedKAV = Animated.createAnimatedComponent(KeyboardAvoidingView);
2021-07-08 09:34:21 +05:00
const AnimatedSAV = Animated.createAnimatedComponent(SafeAreaView);
2021-07-06 15:01:52 +05:00
async function sanitizeHtml(site) {
try {
let html = await fetch(site);
html = await html.text();
let siteHtml = html.replace(
2021-10-09 16:44:44 +05:00
/(?:<(script|button|input|textarea|style|link|head)(?:\s[^>]*)?>)\s*((?:(?!<\1)[\s\S])*)\s*(?:<\/\1>)/g,
''
);
2021-07-06 15:01:52 +05:00
return absolutify(siteHtml, site);
} catch (e) {
return '';
}
}
function makeHtmlFromUrl(url) {
2021-07-07 11:13:43 +05:00
return `<a style="overflow-wrap:anywhere;white-space:pre-wrap" href='${url}' target='_blank'>${url}</a>`;
2021-07-06 15:01:52 +05:00
}
function makeHtmlFromPlainText(text) {
2021-07-07 11:13:43 +05:00
if (!text) return '';
return `<p style="overflow-wrap:anywhere;white-space:pre-wrap" >${text}</p>`;
2021-07-06 15:01:52 +05:00
}
function getBaseUrl(site) {
var url = site.split('/').slice(0, 3).join('/');
return url;
}
async function absolutifyImgs(html, site) {
let parser = global.HTMLParser;
global.HTMLParser.body.innerHTML = html;
let images = parser.querySelectorAll('img');
for (var i = 0; i < images.length; i++) {
let img = images[i];
let url = getBaseUrl(site);
2021-10-09 16:44:44 +05:00
if (img.src.startsWith('/')) {
if (img.src.startsWith('//')) {
img.src = img.src.replace('//', 'https://');
} else {
img.src = url + img.src;
}
}
2021-10-09 16:44:44 +05:00
if (img.src.startsWith('data:')) {
img.src = '';
}
}
return parser.body.innerHTML;
}
2021-07-07 08:46:29 +05:00
let defaultNote = {
title: null,
id: null,
content: {
type: 'tiny',
2021-07-30 10:18:14 +05:00
data: null
}
2021-07-07 08:46:29 +05:00
};
2021-10-08 12:22:47 +05:00
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'
}
};
2021-07-07 08:46:29 +05:00
const NotesnookShare = () => {
2021-10-11 11:25:22 +05:00
const colors = useShareStore(state => state.colors);
const appendNote = useShareStore(state => state.appendNote);
2021-10-09 16:44:44 +05:00
const [note, setNote] = useState({...defaultNote});
2021-07-06 15:01:52 +05:00
const [loadingIntent, setLoadingIntent] = useState(true);
2021-07-07 08:46:29 +05:00
const [loading, setLoading] = useState(false);
2021-07-06 15:01:52 +05:00
const [floating, setFloating] = useState(false);
const [rawData, setRawData] = useState({
type: null,
2021-07-30 10:18:14 +05:00
value: null
2021-07-06 15:01:52 +05:00
});
2021-10-11 11:25:22 +05:00
const [mode, setMode] = useState(1);
const keyboardHeight = useRef(0);
2021-07-07 08:46:29 +05:00
const {width, height} = useWindowDimensions();
const webviewRef = useRef();
2021-07-07 11:44:15 +05:00
const opacity = useValue(0);
const translate = useValue(1000);
2021-07-08 09:34:21 +05:00
const insets = {
2021-07-30 10:18:14 +05:00
top: Platform.OS === 'ios' ? 30 : 0
2021-07-08 09:34:21 +05:00
};
2021-10-08 12:22:47 +05:00
const prevAnimation = useRef(null);
2021-10-11 11:25:22 +05:00
const [showSearch, setShowSearch] = useState(false);
2021-07-07 11:44:15 +05:00
const animate = (opacityV, translateV) => {
2021-10-08 12:22:47 +05:00
prevAnimation.current = translateV;
2021-07-08 09:34:21 +05:00
if (Platform.OS === 'ios') return;
2021-07-07 11:44:15 +05:00
timing(opacity, {
toValue: opacityV,
duration: 300,
2021-07-30 10:18:14 +05:00
easing: Easing.in(Easing.ease)
2021-07-07 11:44:15 +05:00
}).start();
timing(translate, {
toValue: translateV,
duration: 300,
2021-07-30 10:18:14 +05:00
easing: Easing.in(Easing.ease)
2021-07-07 11:44:15 +05:00
}).start();
};
2021-07-06 15:01:52 +05:00
const onKeyboardDidShow = event => {
2021-10-08 12:22:47 +05:00
let kHeight = event.endCoordinates.height;
2021-10-09 16:44:44 +05:00
keyboardHeight.current = kHeight;
};
2021-10-08 12:22:47 +05:00
const onKeyboardDidHide = () => {
2021-10-09 16:44:44 +05:00
keyboardHeight.current = 0;
};
2021-10-08 12:22:47 +05:00
2021-07-06 15:01:52 +05:00
useEffect(() => {
let keyboardWillChangeFrame = Keyboard.addListener(
'keyboardWillChangeFrame',
onKeyboardWillChangeFrame
);
let keyboardDidShow = Keyboard.addListener(
'keyboardDidShow',
onKeyboardDidShow
);
let keyboardDidHide = Keyboard.addListener(
'keyboardDidHide',
onKeyboardDidHide
);
2021-07-06 15:01:52 +05:00
return () => {
2021-10-08 12:22:47 +05:00
keyboardWillChangeFrame?.remove();
keyboardDidShow?.remove();
keyboardDidHide?.remove();
2021-07-06 15:01:52 +05:00
};
}, []);
2021-07-06 15:01:52 +05:00
const onKeyboardWillChangeFrame = event => {
2021-07-08 09:34:21 +05:00
setFloating(event.endCoordinates.width !== width);
2021-07-06 15:01:52 +05:00
};
const showLinkPreview = async (note, link) => {
let _note = note;
_note.content.data = makeHtmlFromUrl(link);
2021-07-06 15:01:52 +05:00
try {
2021-07-07 08:46:29 +05:00
let preview = await getLinkPreview(link);
_note.title = preview.siteName || preview.title;
} catch (e) {
console.log(e);
}
return note;
2021-07-06 15:01:52 +05:00
};
const loadData = async () => {
2021-01-08 12:30:20 +05:00
try {
2021-10-09 16:44:44 +05:00
defaultNote.content.data = null;
setNote({...defaultNote});
2021-01-08 12:30:20 +05:00
const data = await ShareExtension.data();
2021-10-08 12:22:47 +05:00
if (!data || data.length === 0) {
setRawData({
value: ''
});
setLoadingIntent(false);
return;
}
2021-10-09 16:44:44 +05:00
let note = {...defaultNote};
2021-07-07 08:46:29 +05:00
for (item of data) {
if (item.type === 'text') {
setRawData(item);
if (validator.isURL(item.value)) {
note = await showLinkPreview(note, item.value);
2021-07-07 08:46:29 +05:00
} else {
note.content.data = makeHtmlFromPlainText(item.value);
2021-07-07 08:46:29 +05:00
}
}
2021-02-09 16:32:27 +05:00
}
setNote({...note});
2021-07-07 08:46:29 +05:00
} catch (e) {}
setLoadingIntent(false);
};
2021-02-09 16:32:27 +05:00
2021-07-07 08:46:29 +05:00
useEffect(() => {
loadData();
2021-10-11 11:25:22 +05:00
useShareStore.getState().restoreAppendNote();
2021-10-08 12:22:47 +05:00
sleep(50).then(() => {
2021-07-07 11:44:15 +05:00
animate(1, 0);
});
2021-07-07 08:46:29 +05:00
}, []);
2021-07-07 11:44:15 +05:00
const close = async () => {
animate(0, 1000);
await sleep(300);
2021-10-09 16:44:44 +05:00
setNote({...defaultNote});
2021-07-30 10:18:14 +05:00
setLoadingIntent(true);
2021-01-08 12:30:20 +05:00
ShareExtension.close();
};
2021-07-07 08:46:29 +05:00
const onLoad = () => {
2021-10-09 16:44:44 +05:00
postMessage(webviewRef, 'htmldiff', note.content?.data || '');
2021-07-07 08:46:29 +05:00
let theme = {...colors};
theme.factor = 1;
postMessage(webviewRef, 'theme', JSON.stringify(theme));
};
function postMessage(webview, type, value = null) {
let message = {
type: type,
2021-07-30 10:18:14 +05:00
value
2021-07-07 08:46:29 +05:00
};
webview.current?.postMessage(JSON.stringify(message));
}
const onPress = async () => {
content = await getContent();
if (!content || content === '') {
return;
}
2021-07-07 08:46:29 +05:00
setLoading(true);
2021-10-11 11:25:22 +05:00
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: {
2021-10-11 11:25:22 +05:00
data: raw.data + '\n' + content,
type: 'tiny'
2021-10-11 11:25:22 +05:00
},
id: appendNote.id
};
2021-01-08 12:30:20 +05:00
} else {
2021-10-11 11:25:22 +05:00
_note = {...note};
_note.content.data = content;
2021-01-08 12:30:20 +05:00
}
2021-10-11 11:25:22 +05:00
await db.notes.add(_note);
2021-01-08 12:30:20 +05:00
await Storage.write('notesAddedFromIntent', 'added');
2021-07-07 11:13:43 +05:00
close();
2021-10-11 11:25:22 +05:00
setLoading(false);
2021-01-08 12:30:20 +05:00
};
2021-10-09 16:44:44 +05:00
const sourceUri = 'Web.bundle/site/plaineditor.html';
2021-07-08 09:34:21 +05:00
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(() => {
onLoad();
}, [note]);
2021-10-11 11:25:22 +05:00
const changeMode = async () => {
let _mode = modes[mode];
if (_mode.type === 'text' && validator.isURL(rawData.value)) {
let html = await sanitizeHtml(rawData.value);
html = await absolutifyImgs(html, rawData.value);
setNote(note => {
note.content.data = html;
return {...note};
});
setMode(2);
return;
}
2021-10-09 16:44:44 +05:00
2021-10-11 11:25:22 +05:00
if (_mode.type === 'clip') {
let html = validator.isURL(rawData.value)
? makeHtmlFromUrl(rawData.value)
: makeHtmlFromPlainText(rawData.value);
setNote(note => {
note.content.data = html;
return {...note};
});
setMode(1);
return;
}
};
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};
});
}
};
2021-10-09 16:44:44 +05:00
2021-07-07 08:46:29 +05:00
return (
2021-07-08 09:34:21 +05:00
<AnimatedSAV
2021-07-07 08:46:29 +05:00
style={{
width: width > 500 ? 500 : width,
height: height,
justifyContent: 'flex-end',
2021-07-30 10:18:14 +05:00
opacity: Platform.OS !== 'ios' ? opacity : 1
2021-07-07 08:46:29 +05:00
}}>
<TouchableOpacity
activeOpacity={1}
onPress={() => {
2021-10-11 11:25:22 +05:00
if (showSearch) {
setShowSearch(false);
animate(1, 0);
} else {
close();
}
2021-07-07 08:46:29 +05:00
}}
2021-01-08 12:30:20 +05:00
style={{
2021-07-07 08:46:29 +05:00
width: '100%',
height: '100%',
2021-07-30 10:18:14 +05:00
position: 'absolute'
2021-01-08 12:30:20 +05:00
}}>
2021-07-07 08:46:29 +05:00
<View
2021-01-08 12:30:20 +05:00
style={{
width: '100%',
height: '100%',
2021-10-08 12:22:47 +05:00
backgroundColor: 'rgba(0,0,0,0)'
2021-07-07 08:46:29 +05:00
}}
/>
</TouchableOpacity>
2021-10-11 11:25:22 +05:00
{showSearch && (
<Search
getKeyboardHeight={() => keyboardHeight.current}
close={() => {
setShowSearch(false);
animate(1, 0);
2021-10-09 16:44:44 +05:00
}}
/>
2021-10-11 11:25:22 +05:00
)}
2021-10-09 16:44:44 +05:00
2021-07-07 11:44:15 +05:00
<AnimatedKAV
2021-07-07 08:46:29 +05:00
enabled={!floating && Platform.OS === 'ios'}
2021-10-08 12:22:47 +05:00
onLayout={event => {
if (prevAnimation.current === 0) return;
translate.setValue(event.nativeEvent.layout.height + 30);
}}
2021-07-07 08:46:29 +05:00
style={{
paddingVertical: 25,
2021-10-08 12:22:47 +05:00
backgroundColor: 'transparent',
2021-07-08 09:34:21 +05:00
marginBottom: insets.top,
2021-07-07 11:44:15 +05:00
transform: [
{
2021-07-30 10:18:14 +05:00
translateY: Platform.OS !== 'ios' ? translate : 0
}
]
2021-07-07 08:46:29 +05:00
}}
behavior="padding">
<View
style={{
maxHeight: '100%',
paddingHorizontal: 12
}}>
2021-10-09 16:44:44 +05:00
<View
style={{
width: '100%',
height: 30,
borderRadius: 10,
flexDirection: 'row',
alignItems: 'center'
}}>
<Button
color={appendNote ? colors.nav : colors.accent}
2021-10-11 11:25:22 +05:00
onPress={() => {
useShareStore.getState().setAppendNote(null);
}}
2021-10-09 16:44:44 +05:00
icon="plus"
iconSize={18}
iconColor={!appendNote ? colors.light : colors.icon}
2021-10-11 11:25:22 +05:00
title="Create new note"
textColor={!appendNote ? colors.light : colors.icon}
type="rounded"
2021-10-09 16:44:44 +05:00
style={{
paddingHorizontal: 12
}}
/>
<Button
color={!appendNote ? colors.nav : colors.accent}
2021-10-11 11:25:22 +05:00
onPress={() => {
setShowSearch(true);
animate(1, 1000);
}}
2021-10-09 16:44:44 +05:00
icon="text-short"
iconSize={18}
iconColor={appendNote ? colors.light : colors.icon}
2021-10-11 11:25:22 +05:00
title={`Append to ${
appendNote ? appendNote.title.slice(0, 15) : 'note'
}`}
textColor={appendNote ? colors.light : colors.icon}
type="rounded"
2021-10-09 16:44:44 +05:00
style={{
paddingHorizontal: 12
}}
/>
</View>
2021-01-08 12:30:20 +05:00
<View
style={{
width: '100%'
2021-07-07 08:46:29 +05:00
}}>
<Button
color={colors.accent}
onPress={onPress}
loading={loading || loadingIntent}
icon="check"
iconSize={25}
type="action"
loading={loading}
2021-10-11 11:25:22 +05:00
iconColor={colors.light}
2021-07-07 08:46:29 +05:00
style={{
position: 'absolute',
zIndex: 999,
...getElevation(10),
right: 24,
bottom: -35
}}
/>
2021-01-08 12:30:20 +05:00
<View
style={{
marginTop: 10,
minHeight: 100,
borderRadius: 10,
...getElevation(5),
backgroundColor: colors.bg
2021-01-08 12:30:20 +05:00
}}>
<View
style={{
width: '100%',
height: height * 0.25,
paddingBottom: 15
}}>
<WebView
onLoad={onLoad}
ref={webviewRef}
2021-10-08 12:22:47 +05:00
style={{
width: '100%',
height: '100%',
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>
2021-10-08 12:22:47 +05:00
2021-10-11 11:25:22 +05:00
{appendNote ? (
<Text
style={{
fontSize: 11,
color: colors.gray,
fontFamily: 'OpenSans-Regular',
paddingHorizontal: 12,
marginBottom: 10,
flexWrap: 'wrap'
}}>
This shared note will be appended to{' '}
<Text
style={{
color: colors.accent,
fontFamily: 'OpenSans-SemiBold'
}}>
"{appendNote.title}"
</Text>{' '}
. Click on "Create new note" to add to a new note instead.
</Text>
) : null}
2021-07-07 08:46:29 +05:00
<View
2021-01-08 12:30:20 +05:00
style={{
flexDirection: 'row',
paddingHorizontal: 12,
paddingRight: 80,
alignItems: 'center'
2021-02-09 16:32:27 +05:00
}}>
2021-10-08 12:22:47 +05:00
<Button
color={colors.shade}
2021-10-08 12:22:47 +05:00
onPress={onPress}
icon={modes[mode].icon}
2021-10-11 11:25:22 +05:00
onPress={changeMode}
title={modes[mode].title}
iconSize={18}
iconColor={colors.accent}
2021-10-11 11:25:22 +05:00
textColor={colors.accent}
type="rounded"
style={{paddingHorizontal: 12}}
2021-07-07 08:46:29 +05:00
/>
2021-07-30 10:18:14 +05:00
{Clipboard.hasString() ? (
<Button
color={colors.nav}
onPress={onPress}
icon="clipboard"
2021-10-11 11:25:22 +05:00
onPress={onPaste}
iconSize={18}
iconColor={colors.icon}
2021-10-11 11:25:22 +05:00
textColor={colors.icon}
title="Paste"
2021-10-11 11:25:22 +05:00
type="rounded"
2021-10-08 12:22:47 +05:00
/>
) : null}
2021-02-09 16:32:27 +05:00
</View>
2021-07-07 08:46:29 +05:00
</View>
</View>
<View
style={{
height: 40
}}
/>
</View>
2021-07-07 11:44:15 +05:00
</AnimatedKAV>
2021-07-08 09:34:21 +05:00
</AnimatedSAV>
2021-07-07 08:46:29 +05:00
);
};
2021-10-08 12:22:47 +05:00
const Button = ({
title,
onPress,
color,
loading,
style,
textStyle,
icon,
iconSize = 1,
type = 'button',
2021-10-11 11:25:22 +05:00
iconColor = 'gray',
textColor = 'white'
2021-10-08 12:22:47 +05:00
}) => {
const types = {
action: {
2021-10-11 11:25:22 +05:00
style: {
width: 60,
height: 60,
borderRadius: 100,
minWidth: 0,
paddingHorizontal: 0
},
textStyle: {}
2021-10-08 12:22:47 +05:00
},
button: {
2021-10-11 11:25:22 +05:00
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
}
2021-10-08 12:22:47 +05:00
}
};
2021-07-07 08:46:29 +05:00
return (
<TouchableOpacity
onPress={onPress}
activeOpacity={0.8}
style={[
{
backgroundColor: color,
height: 50,
borderRadius: 5,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
marginBottom: 10,
2021-07-08 09:34:21 +05:00
minWidth: 80,
2021-07-30 10:18:14 +05:00
paddingHorizontal: 20
2021-07-07 08:46:29 +05:00
},
2021-10-11 11:25:22 +05:00
types[type].style,
2021-07-30 10:18:14 +05:00
style
2021-07-07 08:46:29 +05:00
]}>
2021-10-11 11:25:22 +05:00
{loading && <ActivityIndicator color={iconColor} />}
2021-07-07 08:46:29 +05:00
{icon && !loading && (
2021-10-08 12:22:47 +05:00
<Icon name={icon} size={iconSize} color={iconColor || 'white'} />
)}
{title && (
<Text
style={[
{
fontSize: 18,
fontFamily: Platform.OS === 'android' ? 'Roboto-Medium' : null,
fontWeight: Platform.OS === 'ios' ? '600' : null,
2021-10-11 11:25:22 +05:00
color: textColor,
2021-10-08 12:22:47 +05:00
marginLeft: loading ? 10 : 0
},
2021-10-11 11:25:22 +05:00
textStyle,
types[type].textStyle
2021-10-08 12:22:47 +05:00
]}>
{title}
</Text>
)}
2021-07-07 08:46:29 +05:00
</TouchableOpacity>
);
};
export default NotesnookShare;