1
0
mirror of https://github.com/laurent22/joplin.git synced 2025-11-26 22:41:17 +02:00

Merge branch 'master' into alarm-support

This commit is contained in:
Laurent Cozic
2017-11-24 17:09:24 +00:00
379 changed files with 30742 additions and 10859 deletions

View File

@@ -0,0 +1,133 @@
const React = require('react');
const { TouchableOpacity, TouchableWithoutFeedback , Dimensions, Text, Modal, View } = require('react-native');
const { ItemList } = require('lib/components/ItemList.js');
class Dropdown extends React.Component {
constructor() {
super();
this.headerRef_ = null;
}
componentWillMount() {
this.setState({
headerSize: { x: 0, y: 0, width: 0, height: 0 },
listVisible: false,
});
}
componentDidMount() {
// https://stackoverflow.com/questions/30096038/react-native-getting-the-position-of-an-element
setTimeout(() => {
this.headerRef_.measure((fx, fy, width, height, px, py) => {
this.setState({
headerSize: { x: px, y: py, width: width, height: height }
});
});
}, 100);
}
render() {
const items = this.props.items;
const itemHeight = 60;
const windowHeight = Dimensions.get('window').height - 50;
// Dimensions doesn't return quite the right dimensions so leave an extra gap to make
// sure nothing is off screen.
const listMaxHeight = windowHeight;
const listHeight = Math.min(items.length * itemHeight, listMaxHeight); //Dimensions.get('window').height - this.state.headerSize.y - this.state.headerSize.height - 50;
const maxListTop = windowHeight - listHeight;
const listTop = Math.min(maxListTop, this.state.headerSize.y + this.state.headerSize.height);
const wrapperStyle = {
width: this.state.headerSize.width,
height: listHeight + 2, // +2 for the border (otherwise it makes the scrollbar appear)
marginTop: listTop,
marginLeft: this.state.headerSize.x,
};
const itemListStyle = Object.assign({}, this.props.itemListStyle ? this.props.itemListStyle : {}, {
borderWidth: 1,
borderColor: '#ccc',
});
const itemWrapperStyle = Object.assign({}, this.props.itemWrapperStyle ? this.props.itemWrapperStyle : {}, {
flex:1,
justifyContent: 'center',
height: itemHeight,
paddingLeft: 20,
paddingRight: 10,
});
const headerWrapperStyle = Object.assign({}, this.props.headerWrapperStyle ? this.props.headerWrapperStyle : {}, {
height: 35,
// borderWidth: 1,
// borderColor: '#ccc',
//paddingLeft: 20,
//paddingRight: 20,
flex: 1,
flexDirection: 'row',
alignItems: 'center',
});
const headerStyle = Object.assign({}, this.props.headerStyle ? this.props.headerStyle : {}, {
flex: 1,
});
const headerArrowStyle = Object.assign({}, this.props.headerStyle ? this.props.headerStyle : {}, {
flex: 0,
marginRight: 10,
});
const itemStyle = Object.assign({}, this.props.itemStyle ? this.props.itemStyle : {}, {
});
let headerLabel = '...';
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.value === this.props.selectedValue) {
headerLabel = item.label;
break;
}
}
const closeList = () => {
this.setState({ listVisible: false });
}
const itemRenderer= (item) => {
return (
<TouchableOpacity style={itemWrapperStyle} key={item.value} onPress={() => { closeList(); if (this.props.onValueChange) this.props.onValueChange(item.value); }}>
<Text ellipsizeMode="tail" numberOfLines={1} style={itemStyle} key={item.value}>{item.label}</Text>
</TouchableOpacity>
);
}
return (
<View style={{flex: 1, flexDirection: 'column' }}>
<TouchableOpacity style={headerWrapperStyle} ref={(ref) => this.headerRef_ = ref} onPress={() => { this.setState({ listVisible: true }) }}>
<Text ellipsizeMode="tail" numberOfLines={1} style={headerStyle}>{headerLabel}</Text>
<Text style={headerArrowStyle}>{'▼'}</Text>
</TouchableOpacity>
<Modal transparent={true} visible={this.state.listVisible} onRequestClose={() => { closeList(); }} >
<TouchableWithoutFeedback onPressOut={() => { closeList() }}>
<View style={{flex:1}}>
<View style={wrapperStyle}>
<ItemList
style={itemListStyle}
items={this.props.items}
itemHeight={itemHeight}
itemRenderer={(item) => { return itemRenderer(item) }}
/>
</View>
</View>
</TouchableWithoutFeedback>
</Modal>
</View>
);
}
}
module.exports = { Dropdown };

View File

@@ -0,0 +1,103 @@
const React = require('react');
const { Text, TouchableHighlight, View, StyleSheet, ScrollView } = require('react-native');
class ItemList extends React.Component {
constructor() {
super();
this.scrollTop_ = 0;
}
itemCount(props = null) {
if (props === null) props = this.props;
return this.props.items ? this.props.items.length : this.props.itemComponents.length;
}
updateStateItemIndexes(props = null, height = null) {
if (props === null) props = this.props;
if (height === null) {
if (!this.state) return;
height = this.state.height;
}
const topItemIndex = Math.max(0, Math.floor(this.scrollTop_ / props.itemHeight));
const visibleItemCount = Math.ceil(height / props.itemHeight);
let bottomItemIndex = topItemIndex + visibleItemCount - 1;
if (bottomItemIndex >= this.itemCount(props)) bottomItemIndex = this.itemCount(props) - 1;
this.setState({
topItemIndex: topItemIndex,
bottomItemIndex: bottomItemIndex,
});
}
componentWillMount() {
this.setState({
topItemIndex: 0,
bottomItemIndex: 0,
height: 0,
itemHeight: this.props.itemHeight ? this.props.itemHeight : 0,
});
this.updateStateItemIndexes();
}
componentWillReceiveProps(newProps) {
if (newProps.itemHeight) {
this.setState({
itemHeight: newProps.itemHeight,
});
}
this.updateStateItemIndexes(newProps);
}
onScroll(event) {
this.scrollTop_ = Math.floor(event.nativeEvent.contentOffset.y);
this.updateStateItemIndexes();
}
onLayout(event) {
this.setState({ height: event.nativeEvent.layout.height });
this.updateStateItemIndexes(null, event.nativeEvent.layout.height);
}
render() {
const style = this.props.style ? this.props.style : {};
const itemHeight = this.state.itemHeight;
//if (!this.props.itemHeight) throw new Error('itemHeight is required');
let itemComps = [];
if (this.props.items) {
const items = this.props.items;
const blankItem = function(key, height) {
return <View key={key} style={{height:height}}></View>
}
itemComps = [blankItem('top', this.state.topItemIndex * this.props.itemHeight)];
for (let i = this.state.topItemIndex; i <= this.state.bottomItemIndex; i++) {
const itemComp = this.props.itemRenderer(items[i]);
itemComps.push(itemComp);
}
itemComps.push(blankItem('bottom', (items.length - this.state.bottomItemIndex - 1) * this.props.itemHeight));
} else {
itemComps = this.props.itemComponents;
}
return (
<ScrollView scrollEventThrottle={500} onLayout={(event) => { this.onLayout(event); }} style={style} onScroll={ (event) => { this.onScroll(event) }}>
{ itemComps }
</ScrollView>
);
}
}
module.exports = { ItemList };

View File

@@ -1,11 +1,11 @@
import React, { Component } from 'react';
import { StyleSheet, Text } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import ReactNativeActionButton from 'react-native-action-button';
import { connect } from 'react-redux'
import { globalStyle } from 'lib/components/global-style.js'
import { Log } from 'lib/log.js'
import { _ } from 'lib/locale.js'
const React = require('react'); const Component = React.Component;
const { StyleSheet, Text } = require('react-native');
const Icon = require('react-native-vector-icons/Ionicons').default;
const ReactNativeActionButton = require('react-native-action-button').default;
const { connect } = require('react-redux');
const { globalStyle } = require('lib/components/global-style.js');
const { Log } = require('lib/log.js');
const { _ } = require('lib/locale.js');
const styles = StyleSheet.create({
actionButtonIcon: {
@@ -67,7 +67,7 @@ class ActionButtonComponent extends React.Component {
if (this.props.addFolderNoteButtons) {
if (this.props.folders.length) {
buttons.push({
title: _('New todo'),
title: _('New to-do'),
onPress: () => { this.newTodo_press() },
color: '#9b59b6',
icon: 'md-checkbox-outline',
@@ -134,8 +134,9 @@ const ActionButton = connect(
(state) => {
return {
folders: state.folders,
locale: state.settings.locale,
};
}
)(ActionButtonComponent)
export { ActionButton };
module.exports = { ActionButton };

View File

@@ -1,9 +1,10 @@
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { NotesScreen } from 'lib/components/screens/notes.js';
import { SearchScreen } from 'lib/components/screens/search.js';
import { View } from 'react-native';
import { _ } from 'lib/locale.js';
const React = require('react'); const Component = React.Component;
const { connect } = require('react-redux');
const { NotesScreen } = require('lib/components/screens/notes.js');
const { SearchScreen } = require('lib/components/screens/search.js');
const { View } = require('react-native');
const { _ } = require('lib/locale.js');
const { themeStyle } = require('lib/components/global-style.js');
class AppNavComponent extends Component {
@@ -38,8 +39,12 @@ class AppNavComponent extends Component {
this.previousRouteName_ = route.routeName;
const theme = themeStyle(this.props.theme);
const style = { flex: 1, backgroundColor: theme.backgroundColor }
return (
<View style={{ flex: 1 }}>
<View style={style}>
<NotesScreen visible={notesScreenVisible} navigation={{ state: route }} />
{ searchScreenLoaded && <SearchScreen visible={searchScreenVisible} navigation={{ state: route }} /> }
{ (!notesScreenVisible && !searchScreenVisible) && <Screen navigation={{ state: route }} /> }
@@ -53,8 +58,9 @@ const AppNav = connect(
(state) => {
return {
route: state.route,
theme: state.settings.theme,
};
}
)(AppNavComponent)
export { AppNav };
module.exports = { AppNav };

View File

@@ -1,6 +1,6 @@
import React, { Component } from 'react';
import { StyleSheet } from 'react-native';
import { globalStyle, themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { StyleSheet } = require('react-native');
const { globalStyle, themeStyle } = require('lib/components/global-style.js');
const styleObject_ = {
screen: {
@@ -37,4 +37,4 @@ class BaseScreenComponent extends React.Component {
}
export { BaseScreenComponent };
module.exports = { BaseScreenComponent };

View File

@@ -1,6 +1,6 @@
import React, { Component } from 'react';
import { StyleSheet, TouchableHighlight } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
const React = require('react'); const Component = React.Component;
const { StyleSheet, View, TouchableHighlight } = require('react-native');
const Icon = require('react-native-vector-icons/Ionicons').default;
const styles = {
checkboxIcon: {
@@ -20,7 +20,7 @@ class Checkbox extends Component {
}
componentWillMount() {
this.state = { checked: this.props.checked };
this.setState({ checked: this.props.checked });
}
componentWillReceiveProps(newProps) {
@@ -55,7 +55,9 @@ class Checkbox extends Component {
alignItems: 'center',
};
if (style.display) thStyle.display = style.display;
if (style && style.display === 'none') return <View/>
//if (style.display) thStyle.display = style.display;
return (
<TouchableHighlight onPress={() => this.onPress()} style={thStyle}>
@@ -66,4 +68,4 @@ class Checkbox extends Component {
}
export { Checkbox };
module.exports = { Checkbox };

View File

@@ -1,4 +1,4 @@
import { Setting } from 'lib/models/setting.js';
const { Setting } = require('lib/models/setting.js');
const globalStyle = {
fontSize: 16,
@@ -20,11 +20,12 @@ const globalStyle = {
raisedHighlightedColor: "#ffffff",
// For WebView - must correspond to the properties above
htmlFontSize: '20x',
htmlFontSize: '16px',
htmlColor: 'black', // Note: CSS in WebView component only supports named colors or rgb() notation
htmlBackgroundColor: 'white',
htmlDividerColor: 'Gainsboro',
htmlLinkColor: 'blue',
htmlLineHeight: '20px',
};
globalStyle.marginRight = globalStyle.margin;
@@ -69,4 +70,4 @@ function themeStyle(theme) {
return themeCache_[theme];
}
export { globalStyle, themeStyle }
module.exports = { globalStyle, themeStyle };

View File

@@ -1,11 +1,10 @@
import React, { Component } from 'react';
import { WebView, View, Linking } from 'react-native';
import { globalStyle } from 'lib/components/global-style.js';
import { Resource } from 'lib/models/resource.js';
import { shim } from 'lib/shim.js';
import marked from 'lib/marked.js';
const Entities = require('html-entities').AllHtmlEntities;
const htmlentities = (new Entities()).encode;
const React = require('react'); const Component = React.Component;
const { Platform, WebView, View, Linking } = require('react-native');
const { globalStyle } = require('lib/components/global-style.js');
const { Resource } = require('lib/models/resource.js');
const { Setting } = require('lib/models/setting.js');
const { reg } = require('lib/registry.js');
const MdToHtml = require('lib/MdToHtml.js');
class NoteBodyViewer extends Component {
@@ -19,160 +18,16 @@ class NoteBodyViewer extends Component {
this.isMounted_ = false;
}
async loadResource(id) {
const resource = await Resource.load(id);
resource.base64 = await shim.readLocalFileBase64(Resource.fullPath(resource));
let newResources = Object.assign({}, this.state.resources);
newResources[id] = resource;
this.setState({ resources: newResources });
}
componentWillMount() {
this.mdToHtml_ = new MdToHtml({ supportsResourceLinks: false });
this.isMounted_ = true;
}
componentWillUnmount() {
this.mdToHtml_ = null;
this.isMounted_ = false;
}
toggleTickAt(body, index) {
let counter = -1;
while (body.indexOf('- [ ]') >= 0 || body.indexOf('- [X]') >= 0) {
counter++;
body = body.replace(/- \[(X| )\]/, function(v, p1) {
let s = p1 == ' ' ? 'NOTICK' : 'TICK';
if (index == counter) {
s = s == 'NOTICK' ? 'TICK' : 'NOTICK';
}
return '°°JOP°CHECKBOX°' + s + '°°';
});
}
body = body.replace(/°°JOP°CHECKBOX°NOTICK°°/g, '- [ ]');
body = body.replace(/°°JOP°CHECKBOX°TICK°°/g, '- [X]');
return body;
}
markdownToHtml(body, style) {
// https://necolas.github.io/normalize.css/
const normalizeCss = `
html{line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}
article,aside,footer,header,nav,section{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}
pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent;-webkit-text-decoration-skip:objects}
b,strong{font-weight:bolder}small{font-size:80%}img{border-style:none}
`;
const css = `
body {
font-size: ` + style.htmlFontSize + `;
color: ` + style.htmlColor + `;
line-height: 1.5em;
background-color: ` + style.htmlBackgroundColor + `;
}
h1 {
font-size: 1.2em;
font-weight: bold;
}
h2 {
font-size: 1em;
font-weight: bold;
}
a {
color: ` + style.htmlLinkColor + `
}
ul {
padding-left: 1em;
}
a.checkbox {
font-size: 1.6em;
position: relative;
top: 0.1em;
text-decoration: none;
color: ` + style.htmlColor + `;
}
table {
border-collapse: collapse;
}
td, th {
border: 1px solid silver;
padding: .5em 1em .5em 1em;
}
hr {
border: 1px solid ` + style.htmlDividerColor + `;
}
img {
width: 100%;
}
`;
let counter = -1;
while (body.indexOf('- [ ]') >= 0 || body.indexOf('- [X]') >= 0) {
body = body.replace(/- \[(X| )\]/, function(v, p1) {
let s = p1 == ' ' ? 'NOTICK' : 'TICK';
counter++;
return '°°JOP°CHECKBOX°' + s + '°' + counter + '°°';
});
}
const renderer = new marked.Renderer();
renderer.link = function (href, title, text) {
if (Resource.isResourceUrl(href)) {
return '[Resource not yet supported: ' + htmlentities(text) + ']';
} else {
const js = "postMessage(" + JSON.stringify(href) + "); return false;";
let output = "<a title='" + htmlentities(title) + "' href='#' onclick='" + js + "'>" + htmlentities(text) + '</a>';
return output;
}
}
renderer.image = (href, title, text) => {
const resourceId = Resource.urlToId(href);
if (!this.state.resources[resourceId]) {
this.loadResource(resourceId);
return '';
}
const r = this.state.resources[resourceId];
const mime = r.mime.toLowerCase();
if (mime == 'image/png' || mime == 'image/jpg' || mime == 'image/jpeg' || mime == 'image/gif') {
const src = 'data:' + r.mime + ';base64,' + r.base64;
let output = '<img title="' + htmlentities(title) + '" src="' + src + '"/>';
return output;
}
return '[Image: ' + htmlentities(r.title) + ' (' + htmlentities(mime) + ')]';
}
let styleHtml = '<style>' + normalizeCss + "\n" + css + '</style>';
let html = body ? styleHtml + marked(body, {
gfm: true,
breaks: true,
renderer: renderer,
sanitize: true,
}) : styleHtml;
let elementId = 1;
while (html.indexOf('°°JOP°') >= 0) {
html = html.replace(/°°JOP°CHECKBOX°([A-Z]+)°(\d+)°°/, function(v, type, index) {
const js = "postMessage('checkboxclick:" + type + ':' + index + "'); this.textContent = this.textContent == '☐' ? '☑' : '☐'; return false;";
return '<a href="#" onclick="' + js + '" class="checkbox">' + (type == 'NOTICK' ? '☐' : '☑') + '</a>';
});
}
let scriptHtml = '<script>document.body.scrollTop = ' + this.bodyScrollTop_ + ';</script>';
html = '<body onscroll="postMessage(\'bodyscroll:\' + document.body.scrollTop);">' + html + scriptHtml + '</body>';
// console.info(html);
return html;
}
onLoadEnd() {
if (this.state.webViewLoaded) return;
@@ -181,36 +36,72 @@ class NoteBodyViewer extends Component {
setTimeout(() => {
if (!this.isMounted_) return;
this.setState({ webViewLoaded: true });
}, 200);
}, 100);
}
render() {
const note = this.props.note;
const style = this.props.style;
const onCheckboxChange = this.props.onCheckboxChange;
const html = this.markdownToHtml(note ? note.body : '', this.props.webViewStyle);
const mdOptions = {
onResourceLoaded: () => {
this.forceUpdate();
},
paddingBottom: '3.8em', // Extra bottom padding to make it possible to scroll past the action button (so that it doesn't overlap the text)
};
const html = this.mdToHtml_.render(note ? note.body : '', this.props.webViewStyle, mdOptions);
let webViewStyle = {}
if (!this.state.webViewLoaded) webViewStyle.display = 'none';
// On iOS, the onLoadEnd() event is never fired so always
// display the webview (don't do the little trick
// to avoid the white flash).
if (Platform.OS !== 'ios') {
webViewStyle.opacity = this.state.webViewLoaded ? 1 : 0.01;
}
// On iOS scalesPageToFit work like this:
//
// Find the widest image, resize it *and everything else* by x% so that
// the image fits within the viewport. The problem is that it means if there's
// a large image, everything is going to be scaled to a very small size, making
// the text unreadable.
//
// On Android:
//
// Find the widest elements and scale them (and them only) to fit within the viewport
// It means it's going to scale large images, but the text will remain at the normal
// size.
//
// That means we can use scalesPageToFix on Android but not on iOS.
// The weird thing is that on iOS, scalesPageToFix=false along with a CSS
// rule "img { max-width: 100% }", works like scalesPageToFix=true on Android.
// So we use scalesPageToFix=false on iOS along with that CSS rule.
// `baseUrl` is where the images will be loaded from. So images must use a path relative to resourceDir.
const source = {
html: html,
baseUrl: 'file://' + Setting.value('resourceDir') + '/',
};
return (
<View style={style}>
<WebView
scalesPageToFit={Platform.OS !== 'ios'}
style={webViewStyle}
source={{ html: html }}
source={source}
onLoadEnd={() => this.onLoadEnd()}
onError={(e) => reg.logger().error('WebView error', e) }
onMessage={(event) => {
let msg = event.nativeEvent.data;
if (msg.indexOf('checkboxclick:') === 0) {
msg = msg.split(':');
let index = Number(msg[msg.length - 1]);
let currentState = msg[msg.length - 2]; // Not really needed but keep it anyway
const newBody = this.toggleTickAt(note.body, index);
const newBody = this.mdToHtml_.handleCheckboxClick(msg, note.body);
if (onCheckboxChange) onCheckboxChange(newBody);
} else if (msg.indexOf('bodyscroll:') === 0) {
msg = msg.split(':');
this.bodyScrollTop_ = Number(msg[1]);
//msg = msg.split(':');
//this.bodyScrollTop_ = Number(msg[1]);
} else {
Linking.openURL(msg);
}
@@ -222,4 +113,4 @@ class NoteBodyViewer extends Component {
}
export { NoteBodyViewer };
module.exports = { NoteBodyViewer };

View File

@@ -1,13 +1,13 @@
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { ListView, Text, TouchableHighlight, View, StyleSheet } from 'react-native';
import { Log } from 'lib/log.js';
import { _ } from 'lib/locale.js';
import { Checkbox } from 'lib/components/checkbox.js';
import { reg } from 'lib/registry.js';
import { Note } from 'lib/models/note.js';
import { time } from 'lib/time-utils.js';
import { globalStyle, themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { connect } = require('react-redux');
const { ListView, Text, TouchableOpacity , View, StyleSheet } = require('react-native');
const { Log } = require('lib/log.js');
const { _ } = require('lib/locale.js');
const { Checkbox } = require('lib/components/checkbox.js');
const { reg } = require('lib/registry.js');
const { Note } = require('lib/models/note.js');
const { time } = require('lib/time-utils.js');
const { globalStyle, themeStyle } = require('lib/components/global-style.js');
class NoteItemComponent extends Component {
@@ -41,13 +41,16 @@ class NoteItemComponent extends Component {
paddingRight: theme.marginRight,
paddingTop: theme.itemMarginTop,
paddingBottom: theme.itemMarginBottom,
backgroundColor: theme.backgroundColor,
//backgroundColor: theme.backgroundColor,
},
listItemText: {
flex: 1,
color: theme.color,
fontSize: theme.fontSize,
},
selectionWrapper: {
backgroundColor: theme.backgroundColor,
},
};
styles.listItemWithCheckbox = Object.assign({}, styles.listItem);
@@ -59,6 +62,9 @@ class NoteItemComponent extends Component {
styles.listItemTextWithCheckbox.marginTop = styles.listItem.paddingTop - 1;
styles.listItemTextWithCheckbox.marginBottom = styles.listItem.paddingBottom;
styles.selectionWrapperSelected = Object.assign({}, styles.selectionWrapper);
styles.selectionWrapperSelected.backgroundColor = theme.selectedColor;
this.styles_[this.props.theme] = StyleSheet.create(styles);
return this.styles_[this.props.theme];
}
@@ -76,10 +82,26 @@ class NoteItemComponent extends Component {
onPress() {
if (!this.props.note) return;
if (this.props.noteSelectionEnabled) {
this.props.dispatch({
type: 'NOTE_SELECTION_TOGGLE',
id: this.props.note.id,
});
} else {
this.props.dispatch({
type: 'NAV_GO',
routeName: 'Note',
noteId: this.props.note.id,
});
}
}
onLongPress() {
if (!this.props.note) return;
this.props.dispatch({
type: 'NAV_GO',
routeName: 'Note',
noteId: this.props.note.id,
type: this.props.noteSelectionEnabled ? 'NOTE_SELECTION_TOGGLE' : 'NOTE_SELECTION_START',
id: this.props.note.id,
});
}
@@ -90,6 +112,7 @@ class NoteItemComponent extends Component {
const onCheckboxChange = this.props.onCheckboxChange;
const theme = themeStyle(this.props.theme);
// IOS: display: none crashes the app
let checkboxStyle = !isTodo ? { display: 'none' } : { color: theme.color };
if (isTodo) {
@@ -103,19 +126,26 @@ class NoteItemComponent extends Component {
const listItemStyle = isTodo ? this.styles().listItemWithCheckbox : this.styles().listItem;
const listItemTextStyle = isTodo ? this.styles().listItemTextWithCheckbox : this.styles().listItemText;
const rootStyle = isTodo && checkboxChecked ? {opacity: 0.4} : {};
const opacityStyle = isTodo && checkboxChecked ? {opacity: 0.4} : {};
const isSelected = this.props.noteSelectionEnabled && this.props.selectedNoteIds.indexOf(note.id) >= 0;
const selectionWrapperStyle = isSelected ? this.styles().selectionWrapperSelected : this.styles().selectionWrapper;
return (
<TouchableHighlight onPress={() => this.onPress()} underlayColor="#0066FF" style={rootStyle}>
<View style={ listItemStyle }>
<Checkbox
style={checkboxStyle}
checked={checkboxChecked}
onChange={(checked) => this.todoCheckbox_change(checked)}
/>
<Text style={listItemTextStyle}>{note.title}</Text>
<TouchableOpacity onPress={() => this.onPress()} onLongPress={() => this.onLongPress() } activeOpacity={0.5}>
<View style={ selectionWrapperStyle }>
<View style={ opacityStyle }>
<View style={ listItemStyle }>
<Checkbox
style={checkboxStyle}
checked={checkboxChecked}
onChange={(checked) => this.todoCheckbox_change(checked)}
/>
<Text style={listItemTextStyle}>{note.title}</Text>
</View>
</View>
</View>
</TouchableHighlight>
</TouchableOpacity>
);
}
@@ -125,8 +155,10 @@ const NoteItem = connect(
(state) => {
return {
theme: state.settings.theme,
noteSelectionEnabled: state.noteSelectionEnabled,
selectedNoteIds: state.selectedNoteIds,
};
}
)(NoteItemComponent)
export { NoteItem }
module.exports = { NoteItem };

View File

@@ -1,15 +1,15 @@
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { ListView, Text, TouchableHighlight, Switch, View, StyleSheet } from 'react-native';
import { Log } from 'lib/log.js';
import { _ } from 'lib/locale.js';
import { Checkbox } from 'lib/components/checkbox.js';
import { NoteItem } from 'lib/components/note-item.js';
import { reg } from 'lib/registry.js';
import { Note } from 'lib/models/note.js';
import { Setting } from 'lib/models/setting.js';
import { time } from 'lib/time-utils.js';
import { themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { connect } = require('react-redux');
const { ListView, Text, TouchableHighlight, Switch, View, StyleSheet } = require('react-native');
const { Log } = require('lib/log.js');
const { _ } = require('lib/locale.js');
const { Checkbox } = require('lib/components/checkbox.js');
const { NoteItem } = require('lib/components/note-item.js');
const { reg } = require('lib/registry.js');
const { Note } = require('lib/models/note.js');
const { Setting } = require('lib/models/setting.js');
const { time } = require('lib/time-utils.js');
const { themeStyle } = require('lib/components/global-style.js');
class NoteListComponent extends Component {
@@ -50,7 +50,7 @@ class NoteListComponent extends Component {
}
filterNotes(notes) {
const todoFilter = Setting.value('todoFilter');
const todoFilter = 'all'; //Setting.value('todoFilter');
if (todoFilter == 'all') return notes;
const now = time.unixMs();
@@ -71,7 +71,7 @@ class NoteListComponent extends Component {
componentWillMount() {
const newDataSource = this.state.dataSource.cloneWithRows(this.filterNotes(this.props.items));
this.state = { dataSource: newDataSource };
this.setState({ dataSource: newDataSource });
}
componentWillReceiveProps(newProps) {
@@ -113,8 +113,9 @@ const NoteList = connect(
items: state.notes,
notesSource: state.notesSource,
theme: state.settings.theme,
noteSelectionEnabled: state.noteSelectionEnabled,
};
}
)(NoteListComponent)
export { NoteList };
module.exports = { NoteList };

View File

@@ -1,16 +1,25 @@
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { View, Text, Button, StyleSheet, TouchableOpacity, Picker, Image } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { Log } from 'lib/log.js';
import { BackButtonService } from 'lib/services/back-button.js';
import { Menu, MenuOptions, MenuOption, MenuTrigger } from 'react-native-popup-menu';
import { _ } from 'lib/locale.js';
import { Setting } from 'lib/models/setting.js';
import { FileApi } from 'lib/file-api.js';
import { FileApiDriverOneDrive } from 'lib/file-api-driver-onedrive.js';
import { reg } from 'lib/registry.js'
import { themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { connect } = require('react-redux');
const { Platform, View, Text, Button, StyleSheet, TouchableOpacity, Image } = require('react-native');
const Icon = require('react-native-vector-icons/Ionicons').default;
const { Log } = require('lib/log.js');
const { BackButtonService } = require('lib/services/back-button.js');
const { ReportService } = require('lib/services/report.js');
const { Menu, MenuOptions, MenuOption, MenuTrigger } = require('react-native-popup-menu');
const { _ } = require('lib/locale.js');
const { Setting } = require('lib/models/setting.js');
const { Note } = require('lib/models/note.js');
const { Folder } = require('lib/models/folder.js');
const { FileApi } = require('lib/file-api.js');
const { FileApiDriverOneDrive } = require('lib/file-api-driver-onedrive.js');
const { reg } = require('lib/registry.js');
const { themeStyle } = require('lib/components/global-style.js');
const { ItemList } = require('lib/components/ItemList.js');
const { Dropdown } = require('lib/components/Dropdown.js');
const { time } = require('lib/time-utils');
const RNFS = require('react-native-fs');
const { dialogs } = require('lib/dialogs.js');
const DialogBox = require('react-native-dialogbox').default;
// Rather than applying a padding to the whole bar, it is applied to each
// individual component (button, picker, etc.) so that the touchable areas
@@ -39,11 +48,7 @@ class ScreenHeaderComponent extends Component {
alignItems: 'center',
shadowColor: '#000000',
elevation: 5,
},
folderPicker: {
flex:1,
color: theme.raisedHighlightedColor,
// Note: cannot set backgroundStyle as that would remove the arrow in the component
paddingTop: Platform.OS === 'ios' ? 15 : 0, // Extra padding for iOS because the top icons are there
},
divider: {
borderBottomWidth: 1,
@@ -146,7 +151,6 @@ class ScreenHeaderComponent extends Component {
async backButton_press() {
await BackButtonService.back();
//this.props.dispatch({ type: 'NAV_BACK' });
}
searchButton_press() {
@@ -156,6 +160,17 @@ class ScreenHeaderComponent extends Component {
});
}
async deleteButton_press() {
// Dialog needs to be displayed as a child of the parent component, otherwise
// it won't be visible within the header component.
const ok = await dialogs.confirm(this.props.parentComponent, _('Delete these notes?'));
if (!ok) return;
const noteIds = this.props.selectedNoteIds;
this.props.dispatch({ type: 'NOTE_SELECTION_END' });
await Note.batchDelete(noteIds);
}
menu_select(value) {
if (typeof(value) == 'function') {
value();
@@ -183,6 +198,32 @@ class ScreenHeaderComponent extends Component {
});
}
async debugReport_press() {
const service = new ReportService();
const logItems = await reg.logger().lastEntries(null);
const logItemRows = [
['Date','Level','Message']
];
for (let i = 0; i < logItems.length; i++) {
const item = logItems[i];
logItemRows.push([
time.formatMsToLocal(item.timestamp, 'MM-DDTHH:mm:ss'),
item.level,
item.message
]);
}
const logItemCsv = service.csvCreate(logItemRows);
const itemListCsv = await service.basicItemList({ format: 'csv' });
const filePath = RNFS.ExternalDirectoryPath + '/syncReport-' + (new Date()).getTime() + '.txt';
const finalText = [logItemCsv, itemListCsv].join("\n--------------------------------------------------------------------------------");
await RNFS.writeFile(filePath, finalText);
alert('Debug report exported to ' + filePath);
}
render() {
function sideMenuButton(styles, onPress) {
@@ -229,53 +270,129 @@ class ScreenHeaderComponent extends Component {
);
}
function deleteButton(styles, onPress) {
return (
<TouchableOpacity onPress={onPress}>
<View style={styles.iconButton}>
<Icon name='md-trash' style={styles.topIcon} />
</View>
</TouchableOpacity>
);
}
let key = 0;
let menuOptionComponents = [];
for (let i = 0; i < this.props.menuOptions.length; i++) {
let o = this.props.menuOptions[i];
if (!this.props.noteSelectionEnabled) {
for (let i = 0; i < this.props.menuOptions.length; i++) {
let o = this.props.menuOptions[i];
menuOptionComponents.push(
<MenuOption value={o.onPress} key={'menuOption_' + key++} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{o.title}</Text>
</MenuOption>);
}
if (this.props.showAdvancedOptions) {
if (menuOptionComponents.length) {
menuOptionComponents.push(<View key={'menuOption_showAdvancedOptions'} style={this.styles().divider}/>);
}
menuOptionComponents.push(
<MenuOption value={() => this.log_press()} key={'menuOption_log'} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Log')}</Text>
</MenuOption>);
menuOptionComponents.push(
<MenuOption value={() => this.status_press()} key={'menuOption_status'} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Status')}</Text>
</MenuOption>);
if (Platform.OS === 'android') {
menuOptionComponents.push(
<MenuOption value={() => this.debugReport_press()} key={'menuOption_debugReport'} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Export Debug Report')}</Text>
</MenuOption>);
}
}
if (menuOptionComponents.length) {
menuOptionComponents.push(<View key={'menuOption_' + key++} style={this.styles().divider}/>);
}
menuOptionComponents.push(
<MenuOption value={o.onPress} key={'menuOption_' + key++} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{o.title}</Text>
<MenuOption value={() => this.config_press()} key={'menuOption_config'} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Configuration')}</Text>
</MenuOption>);
} else {
menuOptionComponents.push(
<MenuOption value={() => this.deleteButton_press()} key={'menuOption_delete'} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Delete')}</Text>
</MenuOption>);
}
if (menuOptionComponents.length) {
menuOptionComponents.push(<View key={'menuOption_' + key++} style={this.styles().divider}/>);
}
menuOptionComponents.push(
<MenuOption value={() => this.log_press()} key={'menuOption_' + key++} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Log')}</Text>
</MenuOption>);
menuOptionComponents.push(
<MenuOption value={() => this.status_press()} key={'menuOption_' + key++} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Status')}</Text>
</MenuOption>);
if (menuOptionComponents.length) {
menuOptionComponents.push(<View key={'menuOption_' + key++} style={this.styles().divider}/>);
}
menuOptionComponents.push(
<MenuOption value={() => this.config_press()} key={'menuOption_' + key++} style={this.styles().contextMenuItem}>
<Text style={this.styles().contextMenuItemText}>{_('Configuration')}</Text>
</MenuOption>);
const createTitleComponent = () => {
const p = this.props.titlePicker;
if (p) {
let items = [];
for (let i = 0; i < p.items.length; i++) {
let item = p.items[i];
items.push(<Picker.Item label={item.label} value={item.value} key={item.value}/>);
const themeId = Setting.value('theme');
const theme = themeStyle(themeId);
const folderPickerOptions = this.props.folderPickerOptions;
if (folderPickerOptions && folderPickerOptions.enabled) {
const titlePickerItems = (mustSelect) => {
let output = [];
if (mustSelect) output.push({ label: _('Move to notebook...'), value: null });
for (let i = 0; i < this.props.folders.length; i++) {
let f = this.props.folders[i];
output.push({ label: f.title, value: f.id });
}
output.sort((a, b) => {
if (a.value === null) return -1;
if (b.value === null) return +1;
return a.label.toLowerCase() < b.label.toLowerCase() ? -1 : +1;
});
return output;
}
return (
<View style={{ flex: 1 }}>
<Picker style={this.styles().folderPicker} selectedValue={p.selectedValue} onValueChange={(itemValue, itemIndex) => { if (p.onValueChange) p.onValueChange(itemValue, itemIndex); }}>
{ items }
</Picker>
</View>
<Dropdown
items={titlePickerItems(!!folderPickerOptions.mustSelect)}
itemHeight={35}
selectedValue={('selectedFolderId' in folderPickerOptions) ? folderPickerOptions.selectedFolderId : null}
itemListStyle={{
backgroundColor: theme.backgroundColor,
}}
headerStyle={{
color: theme.raisedHighlightedColor,
fontSize: theme.fontSize,
}}
itemStyle={{
color: theme.color,
fontSize: theme.fontSize,
}}
onValueChange={async (folderId, itemIndex) => {
// If onValueChange is specified, use this as a callback, otherwise do the default
// which is to take the selectedNoteIds from the state and move them to the
// chosen folder.
if (folderPickerOptions.onValueChange) {
folderPickerOptions.onValueChange(folderId, itemIndex);
return;
}
if (!folderId) return;
const noteIds = this.props.selectedNoteIds;
if (!noteIds.length) return;
const folder = await Folder.load(folderId);
const ok = noteIds.length > 1 ? await dialogs.confirm(this.props.parentComponent, _('Move %d notes to notebook "%s"?', noteIds.length, folder.title)) : true;
if (!ok) return;
this.props.dispatch({ type: 'NOTE_SELECTION_END' });
for (let i = 0; i < noteIds.length; i++) {
await Note.moveToFolder(noteIds[i], folderId);
}
}}
/>
);
} else {
let title = 'title' in this.props && this.props.title !== null ? this.props.title : '';
@@ -284,22 +401,32 @@ class ScreenHeaderComponent extends Component {
}
const titleComp = createTitleComponent();
const sideMenuComp = this.props.noteSelectionEnabled ? null : sideMenuButton(this.styles(), () => this.sideMenuButton_press());
const backButtonComp = backButton(this.styles(), () => this.backButton_press(), !this.props.historyCanGoBack);
const searchButtonComp = this.props.noteSelectionEnabled ? null : searchButton(this.styles(), () => this.searchButton_press());
const deleteButtonComp = this.props.noteSelectionEnabled ? deleteButton(this.styles(), () => this.deleteButton_press()) : null;
const menuComp = (
<Menu onSelect={(value) => this.menu_select(value)} style={this.styles().contextMenu}>
<MenuTrigger style={{ paddingTop: PADDING_V, paddingBottom: PADDING_V }}>
<Text style={this.styles().contextMenuTrigger}> &#8942;</Text>
</MenuTrigger>
<MenuOptions>
{ menuOptionComponents }
</MenuOptions>
</Menu>
);
return (
<View style={this.styles().container} >
{ sideMenuButton(this.styles(), () => this.sideMenuButton_press()) }
{ backButton(this.styles(), () => this.backButton_press(), !this.props.historyCanGoBack) }
{ sideMenuComp }
{ backButtonComp }
{ saveButton(this.styles(), () => { if (this.props.onSaveButtonPress) this.props.onSaveButtonPress() }, this.props.saveButtonDisabled === true, this.props.showSaveButton === true) }
{ titleComp }
{ searchButton(this.styles(), () => this.searchButton_press()) }
<Menu onSelect={(value) => this.menu_select(value)} style={this.styles().contextMenu}>
<MenuTrigger style={{ paddingTop: PADDING_V, paddingBottom: PADDING_V }}>
<Text style={this.styles().contextMenuTrigger}> &#8942;</Text>
</MenuTrigger>
<MenuOptions>
{ menuOptionComponents }
</MenuOptions>
</Menu>
{ searchButtonComp }
{ deleteButtonComp }
{ menuComp }
<DialogBox ref={dialogbox => { this.dialogbox = dialogbox }}/>
</View>
);
}
@@ -315,9 +442,13 @@ const ScreenHeader = connect(
return {
historyCanGoBack: state.historyCanGoBack,
locale: state.settings.locale,
folders: state.folders,
theme: state.settings.theme,
showAdvancedOptions: state.settings.showAdvancedOptions,
noteSelectionEnabled: state.noteSelectionEnabled,
selectedNoteIds: state.selectedNoteIds,
};
}
)(ScreenHeaderComponent)
export { ScreenHeader };
module.exports = { ScreenHeader };

View File

@@ -1,11 +1,12 @@
import React, { Component } from 'react';
import { View, Switch, Slider, StyleSheet, Picker, Text, Button } from 'react-native';
import { connect } from 'react-redux'
import { ScreenHeader } from 'lib/components/screen-header.js';
import { _, setLocale } from 'lib/locale.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { themeStyle } from 'lib/components/global-style.js';
import { Setting } from 'lib/models/setting.js';
const React = require('react'); const Component = React.Component;
const { TouchableOpacity, Linking, View, Switch, Slider, StyleSheet, Text, Button, ScrollView } = require('react-native');
const { connect } = require('react-redux');
const { ScreenHeader } = require('lib/components/screen-header.js');
const { _, setLocale } = require('lib/locale.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { Dropdown } = require('lib/components/Dropdown.js');
const { themeStyle } = require('lib/components/global-style.js');
const { Setting } = require('lib/models/setting.js');
class ConfigScreenComponent extends BaseScreenComponent {
@@ -26,7 +27,15 @@ class ConfigScreenComponent extends BaseScreenComponent {
this.styles_ = {};
let styles = {
body: {
flex: 1,
justifyContent: 'flex-start',
flexDirection: 'column',
},
settingContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: theme.dividerColor,
paddingTop: theme.marginTop,
@@ -38,13 +47,12 @@ class ConfigScreenComponent extends BaseScreenComponent {
fontWeight: 'bold',
color: theme.color,
fontSize: theme.fontSize,
flex: 1,
},
settingControl: {
color: theme.color,
flex: 1,
},
pickerItem: {
fontSize: theme.fontSize,
}
}
styles.switchSettingText = Object.assign({}, styles.settingText);
@@ -54,15 +62,24 @@ class ConfigScreenComponent extends BaseScreenComponent {
styles.switchSettingContainer.flexDirection = 'row';
styles.switchSettingContainer.justifyContent = 'space-between';
styles.linkText = Object.assign({}, styles.settingText);
styles.linkText.borderBottomWidth = 1;
styles.linkText.borderBottomColor = theme.color;
styles.linkText.flex = 0;
styles.linkText.fontWeight = 'normal';
styles.switchSettingControl = Object.assign({}, styles.settingControl);
delete styles.switchSettingControl.color;
styles.switchSettingControl.width = '20%';
//styles.switchSettingControl.width = '20%';
styles.switchSettingControl.flex = 0;
this.styles_[themeId] = StyleSheet.create(styles);
return this.styles_[themeId];
}
settingToComponent(key, value) {
const themeId = this.props.theme;
const theme = themeStyle(themeId);
let output = null;
const updateSettingValue = (key, value) => {
@@ -72,25 +89,36 @@ class ConfigScreenComponent extends BaseScreenComponent {
const md = Setting.settingMetadata(key);
if (md.isEnum) {
// The Picker component doesn't work properly with int values, so
// convert everything to string (Setting.setValue will convert
// back to the correct type.
value = value.toString();
let items = [];
const settingOptions = md.options();
for (let k in settingOptions) {
if (!settingOptions.hasOwnProperty(k)) continue;
items.push(<Picker.Item label={settingOptions[k]} value={k.toString()} key={k}/>);
items.push({ label: settingOptions[k], value: k.toString() });
}
return (
<View key={key} style={this.styles().settingContainer}>
<Text key="label" style={this.styles().settingText}>{md.label()}</Text>
<Picker key="control" style={this.styles().settingControl} selectedValue={value} onValueChange={(itemValue, itemIndex) => updateSettingValue(key, itemValue)} >
{ items }
</Picker>
<Dropdown
key="control"
style={this.styles().settingControl}
items={items}
selectedValue={value}
itemListStyle={{
backgroundColor: theme.backgroundColor,
}}
headerStyle={{
color: theme.color,
fontSize: theme.fontSize,
}}
itemStyle={{
color: theme.color,
fontSize: theme.fontSize,
}}
onValueChange={(itemValue, itemIndex) => { updateSettingValue(key, itemValue); }}
/>
</View>
);
} else if (md.type == Setting.TYPE_BOOL) {
@@ -117,23 +145,42 @@ class ConfigScreenComponent extends BaseScreenComponent {
render() {
const settings = this.props.settings;
const keys = Setting.keys(true, 'mobile');
let settingComps = [];
for (let key in settings) {
if (key == 'sync.target') continue;
if (!settings.hasOwnProperty(key)) continue;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key == 'sync.target' && !settings.showAdvancedOptions) continue;
if (!Setting.isPublic(key)) continue;
const comp = this.settingToComponent(key, settings[key]);
if (!comp) continue;
settingComps.push(comp);
}
settingComps.push(
<View key="website_link" style={this.styles().settingContainer}>
<TouchableOpacity onPress={() => { Linking.openURL('http://joplin.cozic.net/') }}>
<Text key="label" style={this.styles().linkText}>Joplin Website</Text>
</TouchableOpacity>
</View>
);
settingComps.push(
<View key="privacy_link" style={this.styles().settingContainer}>
<TouchableOpacity onPress={() => { Linking.openURL('http://joplin.cozic.net/privacy/') }}>
<Text key="label" style={this.styles().linkText}>Privacy Policy</Text>
</TouchableOpacity>
</View>
);
//style={this.styles().body}
return (
<View style={this.rootStyle(this.props.theme).root}>
<ScreenHeader title={_('Configuration')}/>
<View style={this.styles().body}>
<ScrollView >
{ settingComps }
</View>
</ScrollView>
</View>
);
}
@@ -149,4 +196,4 @@ const ConfigScreen = connect(
}
)(ConfigScreenComponent)
export { ConfigScreen };
module.exports = { ConfigScreen };

View File

@@ -1,16 +1,16 @@
import React, { Component } from 'react';
import { View, Button, TextInput, StyleSheet } from 'react-native';
import { connect } from 'react-redux'
import { Log } from 'lib/log.js'
import { ActionButton } from 'lib/components/action-button.js';
import { Folder } from 'lib/models/folder.js'
import { BaseModel } from 'lib/base-model.js'
import { ScreenHeader } from 'lib/components/screen-header.js';
import { reg } from 'lib/registry.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { dialogs } from 'lib/dialogs.js';
import { themeStyle } from 'lib/components/global-style.js';
import { _ } from 'lib/locale.js';
const React = require('react'); const Component = React.Component;
const { View, Button, TextInput, StyleSheet } = require('react-native');
const { connect } = require('react-redux');
const { Log } = require('lib/log.js');
const { ActionButton } = require('lib/components/action-button.js');
const { Folder } = require('lib/models/folder.js');
const { BaseModel } = require('lib/base-model.js');
const { ScreenHeader } = require('lib/components/screen-header.js');
const { reg } = require('lib/registry.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { dialogs } = require('lib/dialogs.js');
const { themeStyle } = require('lib/components/global-style.js');
const { _ } = require('lib/locale.js');
class FolderScreenComponent extends BaseScreenComponent {
@@ -36,6 +36,7 @@ class FolderScreenComponent extends BaseScreenComponent {
let styles = {
textInput: {
color: theme.color,
paddingLeft: 10,
},
};
@@ -129,4 +130,4 @@ const FolderScreen = connect(
}
)(FolderScreenComponent)
export { FolderScreen };
module.exports = { FolderScreen };

View File

@@ -1,15 +0,0 @@
import { Folder } from 'lib/models/folder.js'
class FoldersScreenUtils {
static async refreshFolders() {
let initialFolders = await Folder.all({ includeConflictFolder: true });
this.dispatch({
type: 'FOLDERS_UPDATE_ALL',
folders: initialFolders,
});
}
}
export { FoldersScreenUtils }

View File

@@ -1,14 +1,14 @@
import React, { Component } from 'react';
import { ListView, View, Text, Button, StyleSheet } from 'react-native';
import { connect } from 'react-redux'
import { Log } from 'lib/log.js'
import { reg } from 'lib/registry.js'
import { ScreenHeader } from 'lib/components/screen-header.js';
import { time } from 'lib/time-utils'
import { themeStyle } from 'lib/components/global-style.js';
import { Logger } from 'lib/logger.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { _ } from 'lib/locale.js';
const React = require('react'); const Component = React.Component;
const { ListView, View, Text, Button, StyleSheet } = require('react-native');
const { connect } = require('react-redux');
const { Log } = require('lib/log.js');
const { reg } = require('lib/registry.js');
const { ScreenHeader } = require('lib/components/screen-header.js');
const { time } = require('lib/time-utils');
const { themeStyle } = require('lib/components/global-style.js');
const { Logger } = require('lib/logger.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { _ } = require('lib/locale.js');
class LogScreenComponent extends BaseScreenComponent {
@@ -106,4 +106,4 @@ const LogScreen = connect(
}
)(LogScreenComponent)
export { LogScreen };
module.exports = { LogScreen };

View File

@@ -1,30 +1,36 @@
import React, { Component } from 'react';
import { Keyboard, BackHandler, View, Button, TextInput, WebView, Text, StyleSheet, Linking, Image } from 'react-native';
import { connect } from 'react-redux'
import { uuid } from 'lib/uuid.js';
import { Log } from 'lib/log.js'
import { Note } from 'lib/models/note.js'
import { Resource } from 'lib/models/resource.js'
import { Folder } from 'lib/models/folder.js'
import { BackButtonService } from 'lib/services/back-button.js';
import { BaseModel } from 'lib/base-model.js'
import { ActionButton } from 'lib/components/action-button.js';
import Icon from 'react-native-vector-icons/Ionicons';
import { ScreenHeader } from 'lib/components/screen-header.js';
import { time } from 'lib/time-utils.js';
import { Checkbox } from 'lib/components/checkbox.js'
import { _ } from 'lib/locale.js';
import { reg } from 'lib/registry.js';
import { shim } from 'lib/shim.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { dialogs } from 'lib/dialogs.js';
import { globalStyle, themeStyle } from 'lib/components/global-style.js';
import DialogBox from 'react-native-dialogbox';
import { NoteBodyViewer } from 'lib/components/note-body-viewer.js';
import RNFetchBlob from 'react-native-fetch-blob';
import { DocumentPicker, DocumentPickerUtil } from 'react-native-document-picker';
import ImageResizer from 'react-native-image-resizer';
import { SelectDateTimeDialog } from 'lib/components/select-date-time-dialog.js';
const React = require('react'); const Component = React.Component;
const { Platform, Keyboard, BackHandler, View, Button, TextInput, WebView, Text, StyleSheet, Linking, Image } = require('react-native');
const { connect } = require('react-redux');
const { uuid } = require('lib/uuid.js');
const { Log } = require('lib/log.js');
const RNFS = require('react-native-fs');
const { Note } = require('lib/models/note.js');
const { Setting } = require('lib/models/setting.js');
const { Resource } = require('lib/models/resource.js');
const { Folder } = require('lib/models/folder.js');
const { BackButtonService } = require('lib/services/back-button.js');
const { BaseModel } = require('lib/base-model.js');
const { ActionButton } = require('lib/components/action-button.js');
const Icon = require('react-native-vector-icons/Ionicons').default;
const { fileExtension, basename } = require('lib/path-utils.js');
const mimeUtils = require('lib/mime-utils.js').mime;
const { ScreenHeader } = require('lib/components/screen-header.js');
const { time } = require('lib/time-utils.js');
const { Checkbox } = require('lib/components/checkbox.js');
const { _ } = require('lib/locale.js');
const { reg } = require('lib/registry.js');
const { shim } = require('lib/shim.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { dialogs } = require('lib/dialogs.js');
const { globalStyle, themeStyle } = require('lib/components/global-style.js');
const DialogBox = require('react-native-dialogbox').default;
const { NoteBodyViewer } = require('lib/components/note-body-viewer.js');
const RNFetchBlob = require('react-native-fetch-blob').default;
const { DocumentPicker, DocumentPickerUtil } = require('react-native-document-picker');
const ImageResizer = require('react-native-image-resizer').default;
const shared = require('lib/components/shared/note-screen-shared.js');
const ImagePicker = require('react-native-image-picker');
const { SelectDateTimeDialog } = require('lib/components/select-date-time-dialog.js');
class NoteScreenComponent extends BaseScreenComponent {
@@ -42,11 +48,13 @@ class NoteScreenComponent extends BaseScreenComponent {
folder: null,
lastSavedNote: null,
isLoading: true,
resources: {},
titleTextInputHeight: 20,
alarmDialogShown: false,
};
// iOS doesn't support multiline text fields properly so disable it
this.enableMultilineTitle_ = Platform.OS !== 'ios';
this.saveButtonHasBeenShown_ = false;
this.styles_ = {};
@@ -130,123 +138,41 @@ class NoteScreenComponent extends BaseScreenComponent {
}
isModified() {
if (!this.state.note || !this.state.lastSavedNote) return false;
let diff = BaseModel.diffObjects(this.state.note, this.state.lastSavedNote);
delete diff.type_;
return !!Object.getOwnPropertyNames(diff).length;
return shared.isModified(this);
}
async componentWillMount() {
BackButtonService.addHandler(this.backHandler);
let note = null;
let mode = 'view';
if (!this.props.noteId) {
note = this.props.itemType == 'todo' ? Note.newTodo(this.props.folderId) : Note.new(this.props.folderId);
mode = 'edit';
} else {
note = await Note.load(this.props.noteId);
}
const folder = Folder.byId(this.props.folders, note.parent_id);
this.setState({
lastSavedNote: Object.assign({}, note),
note: note,
mode: mode,
folder: folder,
isLoading: false,
});
await shared.initState(this);
this.refreshNoteMetadata();
}
refreshNoteMetadata(force = null) {
return shared.refreshNoteMetadata(this, force);
}
componentWillUnmount() {
BackButtonService.removeHandler(this.backHandler);
}
noteComponent_change(propName, propValue) {
let note = Object.assign({}, this.state.note);
note[propName] = propValue;
this.setState({ note: note });
}
async refreshNoteMetadata(force = null) {
if (force !== true && !this.state.showNoteMetadata) return;
let noteMetadata = await Note.serializeAllProps(this.state.note);
this.setState({ noteMetadata: noteMetadata });
}
title_changeText(text) {
this.noteComponent_change('title', text);
shared.noteComponent_change(this, 'title', text);
}
body_changeText(text) {
this.noteComponent_change('body', text);
}
async noteExists(noteId) {
const existingNote = await Note.load(noteId);
return !!existingNote;
shared.noteComponent_change(this, 'body', text);
}
async saveNoteButton_press() {
let note = Object.assign({}, this.state.note);
await shared.saveNoteButton_press(this);
// Note has been deleted while user was modifying it. In that, we
// just save a new note by clearing the note ID.
if (note.id && !(await this.noteExists(note.id))) delete note.id;
reg.logger().info('Saving note: ', note);
if (!note.parent_id) {
let folder = await Folder.defaultFolder();
if (!folder) {
Log.warn('Cannot save note without a notebook');
return;
}
note.parent_id = folder.id;
}
let isNew = !note.id;
if (isNew && !note.title) {
note.title = Note.defaultTitle(note);
}
note = await Note.save(note);
this.setState({
lastSavedNote: Object.assign({}, note),
note: note,
});
if (isNew) Note.updateGeolocation(note.id);
this.refreshNoteMetadata();
Keyboard.dismiss();
}
async saveOneProperty(name, value) {
let note = Object.assign({}, this.state.note);
// Note has been deleted while user was modifying it. In that, we
// just save a new note by clearing the note ID.
if (note.id && !(await this.noteExists(note.id))) delete note.id;
reg.logger().info('Saving note property: ', note.id, name, value);
if (note.id) {
let toSave = { id: note.id };
toSave[name] = value;
toSave = await Note.save(toSave);
note[name] = toSave[name];
this.setState({
lastSavedNote: Object.assign({}, note),
note: note,
});
} else {
note[name] = value;
this.setState({ note: note });
}
await shared.saveOneProperty(this, name, value);
}
async deleteNote_onPress() {
@@ -269,9 +195,12 @@ class NoteScreenComponent extends BaseScreenComponent {
async pickDocument() {
return new Promise((resolve, reject) => {
DocumentPicker.show({ filetype: [DocumentPickerUtil.images()] }, (error,res) => {
DocumentPicker.show({ filetype: [DocumentPickerUtil.allFiles()] }, (error,res) => {
if (error) {
reject(error);
// Also returns an error if the user doesn't pick a file
// so just resolve with null.
console.info('pickDocument error:', error);
resolve(null);
return;
}
@@ -288,51 +217,100 @@ class NoteScreenComponent extends BaseScreenComponent {
});
}
async attachFile_onPress() {
const res = await this.pickDocument();
showImagePicker(options) {
return new Promise((resolve, reject) => {
ImagePicker.showImagePicker(options, (response) => {
resolve(response);
});
});
}
const localFilePath = res.uri;
async resizeImage(localFilePath, targetPath, mimeType) {
const maxSize = Resource.IMAGE_MAX_DIMENSION;
let dimensions = await this.imageDimensions(localFilePath);
reg.logger().info('Original dimensions ', dimensions);
if (dimensions.width > maxSize || dimensions.height > maxSize) {
dimensions.width = maxSize;
dimensions.height = maxSize;
}
reg.logger().info('New dimensions ', dimensions);
const format = mimeType == 'image/png' ? 'PNG' : 'JPEG';
reg.logger().info('Resizing image ' + localFilePath);
const resizedImage = await ImageResizer.createResizedImage(localFilePath, dimensions.width, dimensions.height, format, 85); //, 0, targetPath);
const resizedImagePath = resizedImage.uri;
reg.logger().info('Resized image ', resizedImagePath);
reg.logger().info('Moving ' + resizedImagePath + ' => ' + targetPath);
await RNFS.copyFile(resizedImagePath, targetPath);
try {
await RNFS.unlink(resizedImagePath);
} catch (error) {
reg.logger().warn('Error when unlinking cached file: ', error);
}
}
async attachFile(pickerResponse, fileType) {
if (!pickerResponse) {
reg.logger().warn('Got no response from picker');
return;
}
if (pickerResponse.error) {
reg.logger().warn('Got error from picker', pickerResponse.error);
return;
}
if (pickerResponse.didCancel) {
reg.logger().info('User cancelled picker');
return;
}
const localFilePath = pickerResponse.uri;
let mimeType = pickerResponse.type;
if (!mimeType) {
const ext = fileExtension(localFilePath);
mimeType = mimeUtils.fromFileExtension(ext);
}
if (!mimeType && fileType === 'image') {
// Assume JPEG if we couldn't determine the file type. It seems to happen with the image picker
// when the file path is something like content://media/external/images/media/123456
// If the image is not a JPEG, something will throw an error below, but there's a good chance
// it will work.
reg.logger().info('Missing file type and could not detect it - assuming image/jpg');
mimeType = 'image/jpg';
}
reg.logger().info('Got file: ' + localFilePath);
reg.logger().info('Got type: ' + res.type);
// res.uri,
// res.type, // mime type
// res.fileName,
// res.fileSize
reg.logger().info('Got type: ' + mimeType);
let resource = Resource.new();
resource.id = uuid.create();
resource.mime = res.type;
resource.title = res.fileName ? res.fileName : _('Untitled');
resource.mime = mimeType;
resource.title = pickerResponse.fileName ? pickerResponse.fileName : _('Untitled');
let targetPath = Resource.fullPath(resource);
if (res.type == 'image/jpeg' || res.type == 'image/jpg' || res.type == 'image/png') {
const maxSize = 1920;
let dimensions = await this.imageDimensions(localFilePath);
reg.logger().info('Original dimensions ', dimensions);
if (dimensions.width > maxSize || dimensions.height > maxSize) {
dimensions.width = maxSize;
dimensions.height = maxSize;
try {
if (mimeType == 'image/jpeg' || mimeType == 'image/jpg' || mimeType == 'image/png') {
await this.resizeImage(localFilePath, targetPath, pickerResponse.mime);
} else {
if (fileType === 'image') {
dialogs.error(this, _('Unsupported image type: %s', mimeType));
return;
} else {
await RNFetchBlob.fs.cp(localFilePath, targetPath);
}
}
reg.logger().info('New dimensions ', dimensions);
const format = res.type == 'image/png' ? 'PNG' : 'JPEG';
reg.logger().info('Resizing image ' + localFilePath);
const resizedImagePath = await ImageResizer.createResizedImage(localFilePath, dimensions.width, dimensions.height, format, 85);
reg.logger().info('Resized image ', resizedImagePath);
RNFetchBlob.fs.cp(resizedImagePath, targetPath); // mv doesn't work ("source path does not exist") so need to do cp and unlink
try {
RNFetchBlob.fs.unlink(resizedImagePath);
} catch (error) {
reg.logger().info('Error when unlinking cached file: ', error);
}
} else {
RNFetchBlob.fs.cp(localFilePath, targetPath);
} catch (error) {
reg.logger().warn('Could not attach file:', error);
return;
}
await Resource.save(resource, { isNew: true });
@@ -344,10 +322,21 @@ class NoteScreenComponent extends BaseScreenComponent {
this.setState({ note: newNote });
}
async attachImage_onPress() {
const options = {
mediaType: 'photo',
};
const response = await this.showImagePicker(options);
await this.attachFile(response, 'image');
}
async attachFile_onPress() {
const response = await this.pickDocument();
await this.attachFile(response, 'all');
}
toggleIsTodo_onPress() {
let newNote = Note.toggleIsTodo(this.state.note);
let newState = { note: newNote };
this.setState(newState);
shared.toggleIsTodo_onPress(this);
}
setAlarm_onPress() {
@@ -371,8 +360,7 @@ class NoteScreenComponent extends BaseScreenComponent {
}
showMetadata_onPress() {
this.setState({ showNoteMetadata: !this.state.showNoteMetadata });
this.refreshNoteMetadata(true);
shared.showMetadata_onPress(this);
}
async showOnMap_onPress() {
@@ -389,14 +377,31 @@ class NoteScreenComponent extends BaseScreenComponent {
menuOptions() {
const note = this.state.note;
const isTodo = note && !!note.is_todo;
return [
{ title: _('Attach file'), onPress: () => { this.attachFile_onPress(); } },
{ title: _('Delete note'), onPress: () => { this.deleteNote_onPress(); } },
{ title: note && !!note.is_todo ? _('Convert to regular note') : _('Convert to todo'), onPress: () => { this.toggleIsTodo_onPress(); } },
{ title: this.state.showNoteMetadata ? _('Hide metadata') : _('Show metadata'), onPress: () => { this.showMetadata_onPress(); } },
{ title: _('View location on map'), onPress: () => { this.showOnMap_onPress(); } },
];
let output = [];
// The file attachement modules only work in Android >= 5 (Version 21)
// https://github.com/react-community/react-native-image-picker/issues/606
let canAttachPicture = true;
if (Platform.OS === 'android' && Platform.Version < 21) canAttachPicture = false;
if (canAttachPicture) {
output.push({ title: _('Attach image'), onPress: () => { this.attachImage_onPress(); } });
output.push({ title: _('Attach any other file'), onPress: () => { this.attachFile_onPress(); } });
}
output.push({ title: _('Delete note'), onPress: () => { this.deleteNote_onPress(); } });
output.push({ title: _('Alarm'), onPress: () => { this.setState({ alarmDialogShown: true }) }});;
// if (isTodo) {
// let text = note.todo_due ? _('Edit/Clear alarm') : _('Set an alarm');
// output.push({ title: text, onPress: () => { this.setAlarm_onPress(); } });
// }
output.push({ title: isTodo ? _('Convert to regular note') : _('Convert to todo'), onPress: () => { this.toggleIsTodo_onPress(); } });
if (this.props.showAdvancedOptions) output.push({ title: this.state.showNoteMetadata ? _('Hide metadata') : _('Show metadata'), onPress: () => { this.showMetadata_onPress(); } });
output.push({ title: _('View location on map'), onPress: () => { this.showOnMap_onPress(); } });
return output;
}
async todoCheckbox_change(checked) {
@@ -404,6 +409,8 @@ class NoteScreenComponent extends BaseScreenComponent {
}
titleTextInput_contentSizeChange(event) {
if (!this.enableMultilineTitle_) return;
let height = event.nativeEvent.contentSize.height;
this.setState({ titleTextInputHeight: height });
}
@@ -432,6 +439,9 @@ class NoteScreenComponent extends BaseScreenComponent {
bodyComponent = <NoteBodyViewer style={this.styles().noteBodyViewer} webViewStyle={theme} note={note} onCheckboxChange={(newBody) => { onCheckboxChange(newBody) }}/>
} else {
const focusBody = !isNew && !!note.title;
// Note: blurOnSubmit is necessary to get multiline to work.
// See https://github.com/facebook/react-native/issues/12717#issuecomment-327001997
bodyComponent = (
<TextInput
autoCapitalize="sentences"
@@ -440,6 +450,7 @@ class NoteScreenComponent extends BaseScreenComponent {
multiline={true}
value={note.body}
onChangeText={(text) => this.body_changeText(text)}
blurOnSubmit={false}
/>
);
}
@@ -460,15 +471,6 @@ class NoteScreenComponent extends BaseScreenComponent {
return <ActionButton multiStates={true} buttons={buttons} buttonIndex={0} />
}
const titlePickerItems = () => {
let output = [];
for (let i = 0; i < this.props.folders.length; i++) {
let f = this.props.folders[i];
output.push({ label: f.title, value: f.id });
}
return output;
}
const actionButtonComp = renderActionButton();
let showSaveButton = this.state.mode == 'edit' || this.isModified() || this.saveButtonHasBeenShown_;
@@ -485,14 +487,18 @@ class NoteScreenComponent extends BaseScreenComponent {
backgroundColor: theme.backgroundColor,
fontWeight: 'bold',
fontSize: theme.fontSize,
paddingTop: 10, // Added for iOS (Not needed for Android??)
paddingBottom: 10, // Added for iOS (Not needed for Android??)
};
titleTextInputStyle.height = this.state.titleTextInputHeight;
if (this.enableMultilineTitle_) titleTextInputStyle.height = this.state.titleTextInputHeight;
let checkboxStyle = {
color: theme.color,
paddingRight: 10,
paddingLeft: theme.marginLeft,
paddingTop: 10, // Added for iOS (Not needed for Android??)
paddingBottom: 10, // Added for iOS (Not needed for Android??)
}
const dueDate = isTodo && note.todo_due ? new Date(note.todo_due) : null;
@@ -503,7 +509,7 @@ class NoteScreenComponent extends BaseScreenComponent {
<TextInput
onContentSizeChange={(event) => this.titleTextInput_contentSizeChange(event)}
autoFocus={isNew}
multiline={true}
multiline={this.enableMultilineTitle_}
underlineColorAndroid="#ffffff00"
autoCapitalize="sentences"
style={titleTextInputStyle}
@@ -516,19 +522,10 @@ class NoteScreenComponent extends BaseScreenComponent {
return (
<View style={this.rootStyle(this.props.theme).root}>
<ScreenHeader
titlePicker={{
items: titlePickerItems(),
selectedValue: folder ? folder.id : null,
folderPickerOptions={{
enabled: true,
selectedFolderId: folder ? folder.id : null,
onValueChange: async (itemValue, itemIndex) => {
let note = Object.assign({}, this.state.note);
// RN bug: https://github.com/facebook/react-native/issues/9220
// The Picker fires the onValueChange when the component is initialized
// so we need to check that it has actually changed.
if (note.parent_id == itemValue) return;
reg.logger().info('Moving note: ' + note.parent_id + ' => ' + itemValue);
if (note.id) await Note.moveToFolder(note.id, itemValue);
note.parent_id = itemValue;
@@ -539,7 +536,7 @@ class NoteScreenComponent extends BaseScreenComponent {
note: note,
folder: folder,
});
}
},
}}
menuOptions={this.menuOptions()}
showSaveButton={showSaveButton}
@@ -568,13 +565,14 @@ class NoteScreenComponent extends BaseScreenComponent {
const NoteScreen = connect(
(state) => {
return {
noteId: state.selectedNoteId,
noteId: state.selectedNoteIds.length ? state.selectedNoteIds[0] : null,
folderId: state.selectedFolderId,
itemType: state.selectedItemType,
folders: state.folders,
theme: state.settings.theme,
showAdvancedOptions: state.settings.showAdvancedOptions,
};
}
)(NoteScreenComponent)
export { NoteScreen };
module.exports = { NoteScreen };

View File

@@ -1,21 +1,21 @@
import React, { Component } from 'react';
import { View, Button, Picker } from 'react-native';
import { connect } from 'react-redux'
import { reg } from 'lib/registry.js';
import { Log } from 'lib/log.js'
import { NoteList } from 'lib/components/note-list.js'
import { Folder } from 'lib/models/folder.js'
import { Tag } from 'lib/models/tag.js'
import { Note } from 'lib/models/note.js'
import { Setting } from 'lib/models/setting.js'
import { themeStyle } from 'lib/components/global-style.js';
import { ScreenHeader } from 'lib/components/screen-header.js';
import { MenuOption, Text } from 'react-native-popup-menu';
import { _ } from 'lib/locale.js';
import { ActionButton } from 'lib/components/action-button.js';
import { dialogs } from 'lib/dialogs.js';
import DialogBox from 'react-native-dialogbox';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
const React = require('react'); const Component = React.Component;
const { View, Button } = require('react-native');
const { connect } = require('react-redux');
const { reg } = require('lib/registry.js');
const { Log } = require('lib/log.js');
const { NoteList } = require('lib/components/note-list.js');
const { Folder } = require('lib/models/folder.js');
const { Tag } = require('lib/models/tag.js');
const { Note } = require('lib/models/note.js');
const { Setting } = require('lib/models/setting.js');
const { themeStyle } = require('lib/components/global-style.js');
const { ScreenHeader } = require('lib/components/screen-header.js');
const { MenuOption, Text } = require('react-native-popup-menu');
const { _ } = require('lib/locale.js');
const { ActionButton } = require('lib/components/action-button.js');
const { dialogs } = require('lib/dialogs.js');
const DialogBox = require('react-native-dialogbox').default;
const { BaseScreenComponent } = require('lib/components/base-screen.js');
class NotesScreenComponent extends BaseScreenComponent {
@@ -62,7 +62,7 @@ class NotesScreenComponent extends BaseScreenComponent {
}
this.props.dispatch({
type: 'NOTES_UPDATE_ALL',
type: 'NOTE_UPDATE_ALL',
notes: notes,
notesSource: source,
});
@@ -142,12 +142,22 @@ class NotesScreenComponent extends BaseScreenComponent {
let title = parent ? parent.title : null;
const addFolderNoteButtons = this.props.selectedFolderId && this.props.selectedFolderId != Folder.conflictFolderId();
const thisComp = this;
const actionButtonComp = this.props.noteSelectionEnabled ? null : <ActionButton addFolderNoteButtons={addFolderNoteButtons} parentFolderId={this.props.selectedFolderId}></ActionButton>
return (
<View style={rootStyle}>
<ScreenHeader title={title} menuOptions={this.menuOptions()} />
<ScreenHeader
title={title}
menuOptions={this.menuOptions()}
parentComponent={thisComp}
folderPickerOptions={{
enabled: this.props.noteSelectionEnabled,
mustSelect: true,
}}
/>
<NoteList style={{flex: 1}}/>
<ActionButton addFolderNoteButtons={addFolderNoteButtons} parentFolderId={this.props.selectedFolderId}></ActionButton>
{ actionButtonComp }
<DialogBox ref={dialogbox => { this.dialogbox = dialogbox }}/>
</View>
);
@@ -160,6 +170,7 @@ const NotesScreen = connect(
folders: state.folders,
tags: state.tags,
selectedFolderId: state.selectedFolderId,
selectedNoteIds: state.selectedNoteIds,
selectedTagId: state.selectedTagId,
notesParentType: state.notesParentType,
notes: state.notes,
@@ -167,8 +178,9 @@ const NotesScreen = connect(
notesSource: state.notesSource,
uncompletedTodosOnTop: state.settings.uncompletedTodosOnTop,
theme: state.settings.theme,
noteSelectionEnabled: state.noteSelectionEnabled,
};
}
)(NotesScreenComponent)
export { NotesScreen };
module.exports = { NotesScreen };

View File

@@ -1,13 +1,13 @@
import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView, Button, Text } from 'react-native';
import { connect } from 'react-redux'
import { Log } from 'lib/log.js'
import { Setting } from 'lib/models/setting.js'
import { ScreenHeader } from 'lib/components/screen-header.js';
import { reg } from 'lib/registry.js';
import { _ } from 'lib/locale.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
const React = require('react'); const Component = React.Component;
const { View } = require('react-native');
const { WebView, Button, Text } = require('react-native');
const { connect } = require('react-redux');
const { Log } = require('lib/log.js');
const { Setting } = require('lib/models/setting.js');
const { ScreenHeader } = require('lib/components/screen-header.js');
const { reg } = require('lib/registry.js');
const { _ } = require('lib/locale.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
class OneDriveLoginScreenComponent extends BaseScreenComponent {
@@ -28,11 +28,11 @@ class OneDriveLoginScreenComponent extends BaseScreenComponent {
}
startUrl() {
return reg.oneDriveApi().authCodeUrl(this.redirectUrl());
return reg.syncTarget().api().authCodeUrl(this.redirectUrl());
}
redirectUrl() {
return 'https://login.microsoftonline.com/common/oauth2/nativeclient';
return reg.syncTarget().api().nativeClientRedirectUrl();
}
async webview_load(noIdeaWhatThisIs) {
@@ -48,7 +48,7 @@ class OneDriveLoginScreenComponent extends BaseScreenComponent {
this.authCode_ = code[1];
try {
await reg.oneDriveApi().execTokenRequest(this.authCode_, this.redirectUrl(), true);
await reg.syncTarget().api().execTokenRequest(this.authCode_, this.redirectUrl(), true);
this.props.dispatch({ type: 'NAV_BACK' });
reg.scheduleSync(0);
} catch (error) {
@@ -107,4 +107,4 @@ const OneDriveLoginScreen = connect(
}
)(OneDriveLoginScreenComponent)
export { OneDriveLoginScreen };
module.exports = { OneDriveLoginScreen };

View File

@@ -1,13 +1,15 @@
import React, { Component } from 'react';
import { ListView, StyleSheet, View, TextInput, FlatList, TouchableHighlight } from 'react-native';
import { connect } from 'react-redux'
import { ScreenHeader } from 'lib/components/screen-header.js';
import Icon from 'react-native-vector-icons/Ionicons';
import { _ } from 'lib/locale.js';
import { Note } from 'lib/models/note.js';
import { NoteItem } from 'lib/components/note-item.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { ListView, StyleSheet, View, TextInput, FlatList, TouchableHighlight } = require('react-native');
const { connect } = require('react-redux');
const { ScreenHeader } = require('lib/components/screen-header.js');
const Icon = require('react-native-vector-icons/Ionicons').default;
const { _ } = require('lib/locale.js');
const { Note } = require('lib/models/note.js');
const { NoteItem } = require('lib/components/note-item.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { themeStyle } = require('lib/components/global-style.js');
const { dialogs } = require('lib/dialogs.js');
const DialogBox = require('react-native-dialogbox').default;
class SearchScreenComponent extends BaseScreenComponent {
@@ -139,9 +141,18 @@ class SearchScreenComponent extends BaseScreenComponent {
rootStyle.flex = 0.001; // This is a bit of a hack but it seems to work fine - it makes the component invisible but without unmounting it
}
const thisComponent = this;
return (
<View style={rootStyle}>
<ScreenHeader title={_('Search')}/>
<ScreenHeader
title={_('Search')}
parentComponent={thisComponent}
folderPickerOptions={{
enabled: this.props.noteSelectionEnabled,
mustSelect: true,
}}
/>
<View style={this.styles().body}>
<View style={this.styles().searchContainer}>
<TextInput
@@ -163,6 +174,7 @@ class SearchScreenComponent extends BaseScreenComponent {
renderItem={(event) => <NoteItem note={event.item}/>}
/>
</View>
<DialogBox ref={dialogbox => { this.dialogbox = dialogbox }}/>
</View>
);
}
@@ -174,8 +186,9 @@ const SearchScreen = connect(
return {
query: state.searchQuery,
theme: state.settings.theme,
noteSelectionEnabled: state.noteSelectionEnabled,
};
}
)(SearchScreenComponent)
export { SearchScreen };
module.exports = { SearchScreen };

View File

@@ -1,19 +1,19 @@
import React, { Component } from 'react';
import { ListView, StyleSheet, View, Text, Button, FlatList } from 'react-native';
import { Setting } from 'lib/models/setting.js';
import { connect } from 'react-redux'
import { Log } from 'lib/log.js'
import { reg } from 'lib/registry.js'
import { ScreenHeader } from 'lib/components/screen-header.js';
import { time } from 'lib/time-utils'
import { Logger } from 'lib/logger.js';
import { BaseItem } from 'lib/models/base-item.js';
import { Database } from 'lib/database.js';
import { Folder } from 'lib/models/folder.js';
import { ReportService } from 'lib/services/report.js';
import { _ } from 'lib/locale.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { globalStyle, themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { ListView, StyleSheet, View, Text, Button, FlatList } = require('react-native');
const { Setting } = require('lib/models/setting.js');
const { connect } = require('react-redux');
const { Log } = require('lib/log.js');
const { reg } = require('lib/registry.js');
const { ScreenHeader } = require('lib/components/screen-header.js');
const { time } = require('lib/time-utils');
const { Logger } = require('lib/logger.js');
const { BaseItem } = require('lib/models/base-item.js');
const { Database } = require('lib/database.js');
const { Folder } = require('lib/models/folder.js');
const { ReportService } = require('lib/services/report.js');
const { _ } = require('lib/locale.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { globalStyle, themeStyle } = require('lib/components/global-style.js');
const styles = StyleSheet.create({
body: {
@@ -119,4 +119,4 @@ const StatusScreen = connect(
}
)(StatusScreenComponent)
export { StatusScreen };
module.exports = { StatusScreen };

View File

@@ -1,13 +1,13 @@
import React, { Component } from 'react';
import { ListView, StyleSheet, View, TextInput, FlatList, TouchableHighlight } from 'react-native';
import { connect } from 'react-redux'
import { ScreenHeader } from 'lib/components/screen-header.js';
import Icon from 'react-native-vector-icons/Ionicons';
import { _ } from 'lib/locale.js';
import { Note } from 'lib/models/note.js';
import { NoteItem } from 'lib/components/note-item.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { globalStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { ListView, StyleSheet, View, TextInput, FlatList, TouchableHighlight } = require('react-native');
const { connect } = require('react-redux');
const { ScreenHeader } = require('lib/components/screen-header.js');
const Icon = require('react-native-vector-icons/Ionicons').default;
const { _ } = require('lib/locale.js');
const { Note } = require('lib/models/note.js');
const { NoteItem } = require('lib/components/note-item.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { globalStyle } = require('lib/components/global-style.js');
let styles = {
body: {
@@ -40,7 +40,7 @@ class TagScreenComponent extends BaseScreenComponent {
const notes = await Tag.notes(props.selectedTagId);
this.props.dispatch({
type: 'NOTES_UPDATE_ALL',
type: 'NOTE_UPDATE_ALL',
notes: notes,
notesSource: source,
});
@@ -73,4 +73,4 @@ const TagScreen = connect(
}
)(TagScreenComponent)
export { TagScreen };
module.exports = { TagScreen };

View File

@@ -1,12 +1,12 @@
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { connect } from 'react-redux'
import { Log } from 'lib/log.js'
import { ScreenHeader } from 'lib/components/screen-header.js';
import { ActionButton } from 'lib/components/action-button.js';
import { BaseScreenComponent } from 'lib/components/base-screen.js';
import { _ } from 'lib/locale.js';
import { themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { View, Text, StyleSheet } = require('react-native');
const { connect } = require('react-redux');
const { Log } = require('lib/log.js');
const { ScreenHeader } = require('lib/components/screen-header.js');
const { ActionButton } = require('lib/components/action-button.js');
const { BaseScreenComponent } = require('lib/components/base-screen.js');
const { _ } = require('lib/locale.js');
const { themeStyle } = require('lib/components/global-style.js');
class WelcomeScreenComponent extends BaseScreenComponent {
@@ -61,4 +61,4 @@ const WelcomeScreen = connect(
}
)(WelcomeScreenComponent)
export { WelcomeScreen };
module.exports = { WelcomeScreen };

View File

@@ -0,0 +1,125 @@
const { reg } = require('lib/registry.js');
const { Folder } = require('lib/models/folder.js');
const { BaseModel } = require('lib/base-model.js');
const { Note } = require('lib/models/note.js');
const shared = {};
shared.noteExists = async function(noteId) {
const existingNote = await Note.load(noteId);
return !!existingNote;
}
shared.saveNoteButton_press = async function(comp) {
let note = Object.assign({}, comp.state.note);
// Note has been deleted while user was modifying it. In that, we
// just save a new note by clearing the note ID.
if (note.id && !(await shared.noteExists(note.id))) delete note.id;
reg.logger().info('Saving note: ', note);
if (!note.parent_id) {
let folder = await Folder.defaultFolder();
if (!folder) {
//Log.warn('Cannot save note without a notebook');
return;
}
note.parent_id = folder.id;
}
let isNew = !note.id;
if (isNew && !note.title) {
note.title = Note.defaultTitle(note);
}
note = await Note.save(note);
comp.setState({
lastSavedNote: Object.assign({}, note),
note: note,
});
if (isNew) Note.updateGeolocation(note.id);
comp.refreshNoteMetadata();
}
shared.saveOneProperty = async function(comp, name, value) {
let note = Object.assign({}, comp.state.note);
// Note has been deleted while user was modifying it. In that, we
// just save a new note by clearing the note ID.
if (note.id && !(await shared.noteExists(note.id))) delete note.id;
reg.logger().info('Saving note property: ', note.id, name, value);
if (note.id) {
let toSave = { id: note.id };
toSave[name] = value;
toSave = await Note.save(toSave);
note[name] = toSave[name];
comp.setState({
lastSavedNote: Object.assign({}, note),
note: note,
});
} else {
note[name] = value;
comp.setState({ note: note });
}
}
shared.noteComponent_change = function(comp, propName, propValue) {
let note = Object.assign({}, comp.state.note);
note[propName] = propValue;
comp.setState({ note: note });
}
shared.refreshNoteMetadata = async function(comp, force = null) {
if (force !== true && !comp.state.showNoteMetadata) return;
let noteMetadata = await Note.serializeAllProps(comp.state.note);
comp.setState({ noteMetadata: noteMetadata });
}
shared.isModified = function(comp) {
if (!comp.state.note || !comp.state.lastSavedNote) return false;
let diff = BaseModel.diffObjects(comp.state.note, comp.state.lastSavedNote);
delete diff.type_;
return !!Object.getOwnPropertyNames(diff).length;
}
shared.initState = async function(comp) {
let note = null;
let mode = 'view';
if (!comp.props.noteId) {
note = comp.props.itemType == 'todo' ? Note.newTodo(comp.props.folderId) : Note.new(comp.props.folderId);
mode = 'edit';
} else {
note = await Note.load(comp.props.noteId);
}
const folder = Folder.byId(comp.props.folders, note.parent_id);
comp.setState({
lastSavedNote: Object.assign({}, note),
note: note,
mode: mode,
folder: folder,
isLoading: false,
});
comp.lastLoadedNoteId_ = note ? note.id : null;
}
shared.showMetadata_onPress = function(comp) {
comp.setState({ showNoteMetadata: !comp.state.showNoteMetadata });
comp.refreshNoteMetadata(true);
}
shared.toggleIsTodo_onPress = function(comp) {
let newNote = Note.toggleIsTodo(comp.state.note);
let newState = { note: newNote };
comp.setState(newState);
}
module.exports = shared;

View File

@@ -0,0 +1,65 @@
let shared = {};
shared.renderFolders = function(props, renderItem) {
let items = [];
for (let i = 0; i < props.folders.length; i++) {
let folder = props.folders[i];
items.push(renderItem(folder, props.selectedFolderId == folder.id && props.notesParentType == 'Folder'));
}
return items;
}
shared.renderTags = function(props, renderItem) {
let tags = props.tags.slice();
tags.sort((a, b) => { return a.title < b.title ? -1 : +1; });
let tagItems = [];
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
tagItems.push(renderItem(tag, props.selectedTagId == tag.id && props.notesParentType == 'Tag'));
}
return tagItems;
}
shared.renderSearches = function(props, renderItem) {
let searches = props.searches.slice();
let searchItems = [];
for (let i = 0; i < searches.length; i++) {
const search = searches[i];
searchItems.push(renderItem(search, props.selectedSearchId == search.id && props.notesParentType == 'Search'));
}
return searchItems;
}
shared.synchronize_press = async function(comp) {
const { Setting } = require('lib/models/setting.js');
const { reg } = require('lib/registry.js');
const action = comp.props.syncStarted ? 'cancel' : 'start';
if (!reg.syncTarget().isAuthenticated()) {
comp.props.dispatch({
type: 'NAV_GO',
routeName: 'OneDriveLogin',
});
return 'auth';
}
let sync = null;
try {
sync = await reg.syncTarget().synchronizer();
} catch (error) {
reg.logger().info('Could not acquire synchroniser:');
reg.logger().info(error);
return 'error';
}
if (action == 'cancel') {
sync.cancel();
return 'cancel';
} else {
reg.scheduleSync(0);
return 'sync';
}
}
module.exports = shared;

View File

@@ -1,16 +1,17 @@
import React, { Component } from 'react';
import { TouchableOpacity , Button, Text, Image, StyleSheet, ScrollView, View } from 'react-native';
import { connect } from 'react-redux'
import Icon from 'react-native-vector-icons/Ionicons';
import { Log } from 'lib/log.js';
import { Tag } from 'lib/models/tag.js';
import { Note } from 'lib/models/note.js';
import { Setting } from 'lib/models/setting.js';
import { FoldersScreenUtils } from 'lib/components/screens/folders-utils.js'
import { Synchronizer } from 'lib/synchronizer.js';
import { reg } from 'lib/registry.js';
import { _ } from 'lib/locale.js';
import { globalStyle, themeStyle } from 'lib/components/global-style.js';
const React = require('react'); const Component = React.Component;
const { TouchableOpacity , Button, Text, Image, StyleSheet, ScrollView, View } = require('react-native');
const { connect } = require('react-redux');
const Icon = require('react-native-vector-icons/Ionicons').default;
const { Log } = require('lib/log.js');
const { Tag } = require('lib/models/tag.js');
const { Note } = require('lib/models/note.js');
const { Setting } = require('lib/models/setting.js');
const { FoldersScreenUtils } = require('lib/folders-screen-utils.js');
const { Synchronizer } = require('lib/synchronizer.js');
const { reg } = require('lib/registry.js');
const { _ } = require('lib/locale.js');
const { globalStyle, themeStyle } = require('lib/components/global-style.js');
const shared = require('lib/components/shared/side-menu-shared.js');
class SideMenuContentComponent extends Component {
@@ -104,32 +105,8 @@ class SideMenuContentComponent extends Component {
}
async synchronize_press() {
const action = this.props.syncStarted ? 'cancel' : 'start';
if (Setting.value('sync.target') == Setting.SYNC_TARGET_ONEDRIVE && !reg.oneDriveApi().auth()) {
this.props.dispatch({ type: 'SIDE_MENU_CLOSE' });
this.props.dispatch({
type: 'NAV_GO',
routeName: 'OneDriveLogin',
});
return;
}
let sync = null;
try {
sync = await reg.synchronizer(Setting.value('sync.target'))
} catch (error) {
reg.logger().info('Could not acquire synchroniser:');
reg.logger().info(error);
return;
}
if (action == 'cancel') {
sync.cancel();
} else {
reg.scheduleSync(0);
}
const actionDone = await shared.synchronize_press(this);
if (actionDone === 'auth') this.props.dispatch({ type: 'SIDE_MENU_CLOSE' });
}
folderItem(folder, selected) {
@@ -181,27 +158,20 @@ class SideMenuContentComponent extends Component {
render() {
let items = [];
const theme = themeStyle(this.props.theme);
// HACK: inner height of ScrollView doesn't appear to be calculated correctly when
// using padding. So instead creating blank elements for padding bottom and top.
items.push(<View style={{ height: globalStyle.marginTop }} key='bottom_top_hack'/>);
if (this.props.folders.length) {
for (let i = 0; i < this.props.folders.length; i++) {
let folder = this.props.folders[i];
items.push(this.folderItem(folder, this.props.selectedFolderId == folder.id && this.props.notesParentType == 'Folder'));
}
const folderItems = shared.renderFolders(this.props, this.folderItem.bind(this));
items = items.concat(folderItems);
if (items.length) items.push(this.makeDivider('divider_1'));
}
if (this.props.tags.length) {
let tags = this.props.tags.slice();
tags.sort((a, b) => { return a.title < b.title ? -1 : +1; });
let tagItems = [];
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
tagItems.push(this.tagItem(tag, this.props.selectedTagId == tag.id && this.props.notesParentType == 'Tag'));
}
const tagItems = shared.renderTags(this.props, this.tagItem.bind(this));
items.push(
<View style={this.styles().tagItemList} key="tag_items">
@@ -222,14 +192,23 @@ class SideMenuContentComponent extends Component {
items.push(<View style={{ height: globalStyle.marginBottom }} key='bottom_padding_hack'/>);
let style = {
flex:1,
borderRightWidth: 1,
borderRightColor: globalStyle.dividerColor,
backgroundColor: theme.backgroundColor,
};
return (
<View style={{flex:1, borderRightWidth: 1, borderRightColor: globalStyle.dividerColor }}>
<View style={{flexDirection:'row'}}>
<Image style={{flex:1, height: 100}} source={require('../images/SideMenuHeader.png')} />
<View style={style}>
<View style={{flex:1, opacity: this.props.opacity}}>
<View style={{flexDirection:'row'}}>
<Image style={{flex:1, height: 100}} source={require('../images/SideMenuHeader.png')} />
</View>
<ScrollView scrollsToTop={false} style={this.styles().menu}>
{ items }
</ScrollView>
</View>
<ScrollView scrollsToTop={false} style={this.styles().menu}>
{ items }
</ScrollView>
</View>
);
}
@@ -247,8 +226,9 @@ const SideMenuContent = connect(
notesParentType: state.notesParentType,
locale: state.settings.locale,
theme: state.settings.theme,
opacity: state.sideMenuOpenPercent,
};
}
)(SideMenuContentComponent)
export { SideMenuContent };
module.exports = { SideMenuContent };

View File

@@ -1,11 +1,11 @@
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { Log } from 'lib/log.js';
import SideMenu_ from 'react-native-side-menu';
const React = require('react'); const Component = React.Component;
const { connect } = require('react-redux');
const { Log } = require('lib/log.js');
const SideMenu_ = require('react-native-side-menu').default;
class SideMenuComponent extends SideMenu_ {};
const SideMenu = connect(
const MySideMenu = connect(
(state) => {
return {
isOpen: state.showSideMenu,
@@ -13,4 +13,4 @@ const SideMenu = connect(
}
)(SideMenuComponent)
export { SideMenu };
module.exports = { SideMenu: MySideMenu };