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

619 lines
16 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';
import { getLinkPreview } from 'link-preview-js';
import React, { useEffect, useRef, useState } from 'react';
2021-01-08 12:30:20 +05:00
import {
ActivityIndicator,
Appearance,
2021-07-07 11:13:43 +05:00
Keyboard,
2021-01-08 12:30:20 +05:00
KeyboardAvoidingView,
Platform,
2021-07-08 09:34:21 +05:00
SafeAreaView,
2021-01-08 12:30:20 +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';
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';
import { getElevation } from '../src/utils';
import { COLOR_SCHEME_DARK, COLOR_SCHEME_LIGHT } from '../src/utils/Colors';
import { db } from '../src/utils/database';
2021-10-02 10:09:12 +05:00
import Storage from '../src/utils/storage';
import { sleep } from '../src/utils/TimeUtils';
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(
/(?:<(script|button|input|textarea|style|link)(?:\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);
if (!img.src.startsWith('http')) {
if (img.src.startsWith('//')) {
img.src = img.src.replace('//', 'https://');
} else {
img.src = url + 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-07-06 15:01:52 +05:00
const [colors, setColors] = useState(
Appearance.getColorScheme() === 'dark'
? COLOR_SCHEME_DARK
2021-07-30 10:18:14 +05:00
: COLOR_SCHEME_LIGHT
2021-07-06 15:01:52 +05:00
);
2021-07-07 08:46:29 +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-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);
const [mode, setMode] = useState(1);
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;
//translate.setValue(-150);
};
2021-10-08 12:22:47 +05:00
const onKeyboardDidHide = () => {
translate.setValue(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 {
const data = await ShareExtension.data();
2021-10-08 12:22:47 +05:00
if (!data || data.length === 0) {
setRawData({
value: ''
});
setNote({...defaultNote});
2021-10-08 12:22:47 +05:00
setLoadingIntent(false);
return;
}
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-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-07-30 10:18:14 +05:00
setNote(defaultNote);
setLoadingIntent(true);
2021-01-08 12:30:20 +05:00
ShareExtension.close();
};
2021-07-07 08:46:29 +05:00
const onLoad = () => {
postMessage(webviewRef, 'htmldiff', note.content?.data);
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-02-04 14:37:04 +05:00
let add = async () => {
let _note = {
...note,
content: {
data: content,
type: 'tiny'
}
};
await db.notes.add(_note);
2021-02-04 14:37:04 +05:00
};
if (db && db.notes) {
await add();
2021-01-08 12:30:20 +05:00
} else {
await db.init();
2021-02-04 14:37:04 +05:00
await add();
2021-01-08 12:30:20 +05:00
}
await Storage.write('notesAddedFromIntent', 'added');
2021-07-07 11:13:43 +05:00
setLoading(false);
2021-07-08 09:34:21 +05:00
await sleep(300);
2021-07-07 11:13:43 +05:00
close();
2021-01-08 12:30:20 +05:00
};
2021-07-08 09:34:21 +05:00
const sourceUri = 'Plain.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(() => {
onLoad();
}, [note]);
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={() => {
close();
}}
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-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-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-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-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}
onPress={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;
}
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;
}
}}
title={modes[mode].title}
iconSize={18}
iconColor={colors.accent}
textStyle={{
fontSize: 12,
color: colors.accent,
marginLeft: 5
}}
2021-07-07 08:46:29 +05:00
style={{
marginRight: 10,
height: 30,
borderRadius: 100,
paddingHorizontal: 12,
marginTop: -2.5
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"
onPress={async () => {
let text = await Clipboard.getString();
if (text) {
let content = await getContent();
setNote(note => {
note.content.data =
content + '\n' + makeHtmlFromPlainText(text);
return {...note};
});
}
}}
iconSize={18}
iconColor={colors.icon}
title="Paste"
textStyle={{
fontSize: 12,
color: colors.icon,
marginLeft: 5
}}
2021-10-08 12:22:47 +05:00
style={{
marginRight: 15,
height: 30,
borderRadius: 100,
paddingHorizontal: 6,
marginTop: -2.5
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',
iconColor
}) => {
const types = {
action: {
width: 60,
height: 60,
borderRadius: 100,
minWidth: 0,
paddingHorizontal: 0
},
button: {
backgroundColor: color,
height: 50,
borderRadius: 5,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
marginBottom: 10,
minWidth: 80,
paddingHorizontal: 20
}
};
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-08 12:22:47 +05:00
types[type],
2021-07-30 10:18:14 +05:00
style
2021-07-07 08:46:29 +05:00
]}>
{loading && <ActivityIndicator color="white" />}
{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,
color: 'white',
marginLeft: loading ? 10 : 0
},
textStyle
]}>
{title}
</Text>
)}
2021-07-07 08:46:29 +05:00
</TouchableOpacity>
);
};
export default NotesnookShare;