1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-12 08:54:00 +02:00
joplin/ReactNativeClient/lib/components/screens/note.js

521 lines
14 KiB
JavaScript
Raw Normal View History

2017-05-12 22:23:54 +02:00
import React, { Component } from 'react';
2017-07-22 19:21:39 +02:00
import { BackHandler, View, Button, TextInput, WebView, Text, StyleSheet, Linking } from 'react-native';
2017-05-12 22:23:54 +02:00
import { connect } from 'react-redux'
2017-06-24 20:06:28 +02:00
import { Log } from 'lib/log.js'
import { Note } from 'lib/models/note.js'
2017-07-13 23:50:21 +02:00
import { Folder } from 'lib/models/folder.js'
2017-07-15 01:12:32 +02:00
import { BaseModel } from 'lib/base-model.js'
2017-07-14 01:35:37 +02:00
import { ActionButton } from 'lib/components/action-button.js';
import Icon from 'react-native-vector-icons/Ionicons';
2017-06-24 20:06:28 +02:00
import { ScreenHeader } from 'lib/components/screen-header.js';
2017-07-15 19:08:54 +02:00
import { time } from 'lib/time-utils.js';
2017-06-24 20:06:28 +02:00
import { Checkbox } from 'lib/components/checkbox.js'
import { _ } from 'lib/locale.js';
2017-07-10 23:34:26 +02:00
import marked from 'lib/marked.js';
2017-07-16 23:17:22 +02:00
import { reg } from 'lib/registry.js';
2017-07-14 20:49:14 +02:00
import { BaseScreenComponent } from 'lib/components/base-screen.js';
2017-07-15 01:12:32 +02:00
import { dialogs } from 'lib/dialogs.js';
2017-07-21 23:40:02 +02:00
import { globalStyle } from 'lib/components/global-style.js';
2017-07-15 01:12:32 +02:00
import DialogBox from 'react-native-dialogbox';
2017-05-12 22:23:54 +02:00
2017-07-22 18:36:55 +02:00
const styleObject = {
2017-07-21 23:40:02 +02:00
titleTextInput: {
flex: 1,
2017-07-22 18:36:55 +02:00
paddingLeft: 0,
2017-07-21 23:40:02 +02:00
color: globalStyle.color,
backgroundColor: globalStyle.backgroundColor,
},
bodyTextInput: {
flex: 1,
2017-07-22 18:36:55 +02:00
paddingLeft: globalStyle.marginLeft,
paddingRight: globalStyle.marginRight,
2017-07-21 23:40:02 +02:00
textAlignVertical: 'top',
color: globalStyle.color,
backgroundColor: globalStyle.backgroundColor,
2017-07-14 00:20:08 +02:00
},
2017-07-22 18:36:55 +02:00
bodyViewContainer: {
flex: 1,
paddingLeft: globalStyle.marginLeft,
paddingRight: globalStyle.marginRight,
paddingTop: globalStyle.marginTop,
paddingBottom: globalStyle.marginBottom,
},
};
styleObject.titleContainer = {
flexDirection: 'row',
paddingLeft: globalStyle.marginLeft,
paddingRight: globalStyle.marginRight,
height: 40,
borderBottomColor: globalStyle.dividerColor,
borderBottomWidth: 1,
};
styleObject.titleContainerTodo = Object.assign({}, styleObject.titleContainer);
const styles = StyleSheet.create(styleObject);
2017-07-14 00:20:08 +02:00
2017-07-14 20:49:14 +02:00
class NoteScreenComponent extends BaseScreenComponent {
2017-05-12 22:23:54 +02:00
2017-06-06 22:01:43 +02:00
static navigationOptions(options) {
2017-05-16 21:57:09 +02:00
return { header: null };
}
2017-05-12 22:23:54 +02:00
constructor() {
super();
2017-07-10 23:34:26 +02:00
this.state = {
note: Note.new(),
mode: 'view',
noteMetadata: '',
showNoteMetadata: false,
2017-07-13 23:50:21 +02:00
folder: null,
2017-07-15 01:12:32 +02:00
lastSavedNote: null,
2017-07-24 23:52:30 +02:00
isLoading: true,
2017-07-16 23:17:22 +02:00
};
2017-07-25 22:24:30 +02:00
this.bodyScrollTop_ = 0;
2017-07-16 23:17:22 +02:00
this.saveButtonHasBeenShown_ = false;
2017-07-15 01:12:32 +02:00
this.backHandler = () => {
if (!this.state.note.id) {
return false;
}
if (this.state.mode == 'edit') {
2017-07-15 20:21:39 +02:00
this.setState({
note: Object.assign({}, this.state.lastSavedNote),
mode: 'view',
});
2017-07-15 01:12:32 +02:00
return true;
}
return false;
};
}
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;
2017-05-12 22:23:54 +02:00
}
2017-07-23 16:11:44 +02:00
async componentWillMount() {
2017-07-15 01:12:32 +02:00
BackHandler.addEventListener('hardwareBackPress', this.backHandler);
2017-07-23 16:11:44 +02:00
let note = null;
let mode = 'view';
2017-05-22 22:22:50 +02:00
if (!this.props.noteId) {
2017-07-23 16:11:44 +02:00
note = this.props.itemType == 'todo' ? Note.newTodo(this.props.folderId) : Note.new(this.props.folderId);
mode = 'edit';
2017-05-22 22:22:50 +02:00
} else {
2017-07-23 16:11:44 +02:00
note = await Note.load(this.props.noteId);
2017-05-22 22:22:50 +02:00
}
2017-07-13 23:50:21 +02:00
2017-07-25 19:49:31 +02:00
const folder = Folder.byId(this.props.folders, note.parent_id);
2017-07-23 16:11:44 +02:00
this.setState({
lastSavedNote: Object.assign({}, note),
note: note,
mode: mode,
2017-07-25 19:49:31 +02:00
folder: folder,
2017-07-24 23:52:30 +02:00
isLoading: false,
2017-07-23 16:11:44 +02:00
});
this.refreshNoteMetadata();
2017-07-13 23:50:21 +02:00
}
2017-07-15 01:12:32 +02:00
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
}
2017-06-06 22:01:43 +02:00
noteComponent_change(propName, propValue) {
2017-07-16 23:17:22 +02:00
let note = Object.assign({}, this.state.note);
note[propName] = propValue;
this.setState({ note: note });
2017-05-12 22:23:54 +02:00
}
async refreshNoteMetadata(force = null) {
if (force !== true && !this.state.showNoteMetadata) return;
let noteMetadata = await Note.serializeAllProps(this.state.note);
this.setState({ noteMetadata: noteMetadata });
}
2017-06-06 22:01:43 +02:00
title_changeText(text) {
2017-05-12 22:23:54 +02:00
this.noteComponent_change('title', text);
}
2017-06-06 22:01:43 +02:00
body_changeText(text) {
2017-05-12 22:23:54 +02:00
this.noteComponent_change('body', text);
}
async noteExists(noteId) {
const existingNote = await Note.load(noteId);
return !!existingNote;
}
2017-07-05 23:29:00 +02:00
async saveNoteButton_press() {
2017-07-13 23:50:21 +02:00
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;
2017-07-17 22:22:05 +02:00
reg.logger().info('Saving note: ', note);
2017-07-15 01:12:32 +02:00
if (!note.parent_id) {
2017-07-13 23:50:21 +02:00
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;
2017-07-15 01:12:32 +02:00
if (!note.title) note.title = _('Untitled');
2017-07-13 23:50:21 +02:00
note = await Note.save(note);
2017-07-15 01:12:32 +02:00
this.setState({
lastSavedNote: Object.assign({}, note),
note: note,
});
2017-07-05 23:29:00 +02:00
if (isNew) Note.updateGeolocation(note.id);
this.refreshNoteMetadata();
2017-05-12 22:23:54 +02:00
}
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 });
}
}
2017-07-15 01:12:32 +02:00
async deleteNote_onPress() {
let note = this.state.note;
if (!note.id) return;
let ok = await dialogs.confirm(this, _('Delete note?'));
if (!ok) return;
let folderId = note.parent_id;
await Note.delete(note.id);
2017-07-16 23:17:22 +02:00
2017-07-25 20:09:01 +02:00
this.props.dispatch({
type: 'NAV_GO',
2017-07-25 20:09:01 +02:00
routeName: 'Notes',
folderId: folderId,
});
2017-06-04 17:01:52 +02:00
}
2017-07-15 01:12:32 +02:00
attachFile_onPress() {
}
2017-07-17 22:22:05 +02:00
async toggleIsTodo_onPress() {
let note = await Note.toggleIsTodo(this.state.note.id);
let newState = { note: note };
if (!note.id) newState.lastSavedNote = Object.assign({}, note);
this.setState(newState);
}
showMetadata_onPress() {
this.setState({ showNoteMetadata: !this.state.showNoteMetadata });
this.refreshNoteMetadata(true);
2017-06-04 17:01:52 +02:00
}
async showOnMap_onPress() {
if (!this.state.note.id) return;
let note = await Note.load(this.state.note.id);
try {
const url = Note.geolocationUrl(note);
Linking.openURL(url);
} catch (error) {
await dialogs.error(this, error.message);
}
}
2017-06-06 22:01:43 +02:00
menuOptions() {
2017-07-17 22:22:05 +02:00
const note = this.state.note;
2017-06-04 17:01:52 +02:00
return [
2017-07-15 01:12:32 +02:00
{ title: _('Attach file'), onPress: () => { this.attachFile_onPress(); } },
{ title: _('Delete note'), onPress: () => { this.deleteNote_onPress(); } },
2017-07-17 22:22:05 +02:00
{ title: note && !!note.is_todo ? _('Convert to regular note') : _('Convert to todo'), onPress: () => { this.toggleIsTodo_onPress(); } },
2017-07-22 18:36:55 +02:00
{ title: this.state.showNoteMetadata ? _('Hide metadata') : _('Show metadata'), onPress: () => { this.showMetadata_onPress(); } },
{ title: _('View location on map'), onPress: () => { this.showOnMap_onPress(); } },
2017-06-04 17:01:52 +02:00
];
}
2017-07-16 18:06:05 +02:00
async todoCheckbox_change(checked) {
2017-07-16 23:17:22 +02:00
await this.saveOneProperty('todo_completed', checked ? time.unixMs() : 0);
2017-07-15 01:12:32 +02:00
}
2017-05-12 22:23:54 +02:00
render() {
2017-07-24 23:52:30 +02:00
if (this.state.isLoading) {
return (
<View style={this.styles().screen}>
2017-07-24 23:58:14 +02:00
<ScreenHeader/>
2017-07-24 23:52:30 +02:00
</View>
);
}
2017-05-24 22:51:50 +02:00
const note = this.state.note;
const isTodo = !!Number(note.is_todo);
2017-07-13 23:50:21 +02:00
const folder = this.state.folder;
2017-07-24 23:52:30 +02:00
const isNew = !note.id;
2017-05-24 22:51:50 +02:00
2017-07-10 23:34:26 +02:00
let bodyComponent = null;
if (this.state.mode == 'view') {
2017-07-17 23:34:08 +02:00
function 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 + '°°';
});
2017-07-14 00:20:08 +02:00
}
2017-07-17 23:34:08 +02:00
body = body.replace(/°°JOP°CHECKBOX°NOTICK°°/g, '- [ ]');
body = body.replace(/°°JOP°CHECKBOX°TICK°°/g, '- [X]');
return body;
}
2017-07-25 22:24:30 +02:00
const markdownToHtml = (body, style) => {
2017-07-17 23:34:08 +02:00
// 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}
`;
2017-07-21 23:40:02 +02:00
2017-07-17 23:34:08 +02:00
const css = `
body {
2017-07-21 23:40:02 +02:00
font-size: ` + style.htmlFontSize + `;
color: ` + style.htmlColor + `;
2017-07-17 23:34:08 +02:00
}
h1 {
font-size: 1.2em;
font-weight: bold;
}
h2 {
font-size: 1em;
font-weight: bold;
}
li {
}
ul {
padding-left: 1em;
}
a.checkbox {
font-size: 1.4em;
position: relative;
top: 0.1em;
text-decoration: none;
2017-07-21 23:40:02 +02:00
color: ` + style.htmlColor + `;
2017-07-17 23:34:08 +02:00
}
2017-07-19 00:57:22 +02:00
table {
border-collapse: collapse;
}
td, th {
border: 1px solid silver;
padding: .5em 1em .5em 1em;
}
2017-07-22 19:21:39 +02:00
hr {
border: 1px solid ` + style.htmlDividerColor + `;
}
2017-07-17 23:34:08 +02:00
`;
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 + '°°';
});
2017-07-14 00:20:08 +02:00
}
2017-07-22 19:21:39 +02:00
const renderer = new marked.Renderer();
renderer.link = function (href, title, text) {
const js = "postMessage(" + JSON.stringify(href) + "); return false;";
let output = "<a href='#' onclick='" + js + "'>" + text + '</a>';
return output;
}
let html = note ? '<style>' + normalizeCss + "\n" + css + '</style>' + marked(body, { gfm: true, breaks: true, renderer: renderer }) : '';
2017-07-14 00:20:08 +02:00
2017-07-17 23:34:08 +02:00
let elementId = 1;
while (html.indexOf('°°JOP°') >= 0) {
html = html.replace(/°°JOP°CHECKBOX°([A-Z]+)°(\d+)°°/, function(v, type, index) {
2017-07-25 22:24:30 +02:00
const js = "postMessage('checkboxclick:" + type + '_' + index + "'); this.textContent = this.textContent == '☐' ? '☑' : '☐'; return false;";
2017-07-17 23:34:08 +02:00
return '<a href="#" onclick="' + js + '" class="checkbox">' + (type == 'NOTICK' ? '☐' : '☑') + '</a>';
});
}
2017-07-10 23:34:26 +02:00
2017-07-25 22:24:30 +02:00
let scriptHtml = '<script>document.body.scrollTop = ' + this.bodyScrollTop_ + ';</script>';
html = '<body onscroll="postMessage(\'bodyscroll:\' + document.body.scrollTop);">' + html + scriptHtml + '</body>';
2017-07-17 23:34:08 +02:00
return html;
}
2017-07-14 00:20:08 +02:00
2017-07-10 23:34:26 +02:00
bodyComponent = (
2017-07-22 18:36:55 +02:00
<View style={styles.bodyViewContainer}>
2017-07-17 23:34:08 +02:00
<WebView
2017-07-21 23:40:02 +02:00
source={{ html: markdownToHtml(note.body, globalStyle) }}
2017-07-17 23:34:08 +02:00
onMessage={(event) => {
let msg = event.nativeEvent.data;
2017-07-22 19:21:39 +02:00
reg.logger().info('postMessage received: ' + msg);
2017-07-25 22:24:30 +02:00
if (msg.indexOf('checkboxclick:') === 0) {
msg = msg.split(':');
2017-07-17 23:34:08 +02:00
let index = Number(msg[msg.length - 1]);
let currentState = msg[msg.length - 2]; // Not really needed but keep it anyway
const newBody = toggleTickAt(note.body, index);
this.saveOneProperty('body', newBody);
2017-07-25 22:24:30 +02:00
} else if (msg.indexOf('bodyscroll:') === 0) {
msg = msg.split(':');
this.bodyScrollTop_ = Number(msg[1]);
2017-07-22 19:21:39 +02:00
} else {
Linking.openURL(msg);
2017-07-17 23:34:08 +02:00
}
}}
/>
2017-07-10 23:34:26 +02:00
</View>
);
} else {
2017-07-24 23:52:30 +02:00
const focusBody = !isNew && !!note.title;
2017-07-15 01:12:32 +02:00
bodyComponent = (
<TextInput
2017-07-16 18:31:42 +02:00
autoCapitalize="sentences"
2017-07-24 23:52:30 +02:00
autoFocus={focusBody}
2017-07-21 23:40:02 +02:00
style={styles.bodyTextInput}
2017-07-15 01:12:32 +02:00
multiline={true}
value={note.body}
onChangeText={(text) => this.body_changeText(text)}
/>
);
2017-07-10 23:34:26 +02:00
}
2017-07-14 01:35:37 +02:00
const renderActionButton = () => {
let buttons = [];
buttons.push({
title: _('Edit'),
icon: 'md-create',
onPress: () => {
this.setState({ mode: 'edit' });
},
});
if (this.state.mode == 'edit') return <ActionButton style={{display:'none'}}/>;
2017-07-15 01:12:32 +02:00
return <ActionButton multiStates={true} buttons={buttons} buttonIndex={0} />
2017-07-14 01:35:37 +02:00
}
2017-07-16 18:06:05 +02:00
const titlePickerItems = () => {
let output = [];
for (let i = 0; i < this.props.folders.length; i++) {
let f = this.props.folders[i];
2017-07-25 19:49:31 +02:00
output.push({ label: f.title, value: f.id });
2017-07-16 18:06:05 +02:00
}
return output;
}
2017-07-14 01:35:37 +02:00
const actionButtonComp = renderActionButton();
2017-07-16 23:17:22 +02:00
let showSaveButton = this.state.mode == 'edit' || this.isModified() || this.saveButtonHasBeenShown_;
let saveButtonDisabled = !this.isModified();
2017-07-16 23:17:22 +02:00
if (showSaveButton) this.saveButtonHasBeenShown_ = true;
2017-07-22 18:36:55 +02:00
const titleContainerStyle = isTodo ? styles.titleContainerTodo : styles.titleContainer;
2017-07-21 23:40:02 +02:00
2017-05-12 22:23:54 +02:00
return (
2017-07-14 20:49:14 +02:00
<View style={this.styles().screen}>
<ScreenHeader
2017-07-16 18:06:05 +02:00
titlePicker={{
items: titlePickerItems(),
selectedValue: folder ? folder.id : null,
onValueChange: async (itemValue, itemIndex) => {
let note = Object.assign({}, this.state.note);
2017-07-17 22:22:05 +02:00
// 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);
2017-07-16 18:06:05 +02:00
if (note.id) await Note.moveToFolder(note.id, itemValue);
note.parent_id = itemValue;
const folder = await Folder.load(note.parent_id);
this.setState({
lastSavedNote: Object.assign({}, note),
note: note,
folder: folder,
});
}
}}
menuOptions={this.menuOptions()}
showSaveButton={showSaveButton}
saveButtonDisabled={saveButtonDisabled}
onSaveButtonPress={() => this.saveNoteButton_press()}
/>
2017-07-21 23:40:02 +02:00
<View style={titleContainerStyle}>
2017-07-24 23:52:30 +02:00
{ isTodo && <Checkbox checked={!!Number(note.todo_completed)} onChange={(checked) => { this.todoCheckbox_change(checked) }} /> }<TextInput autoFocus={isNew} underlineColorAndroid="#ffffff00" autoCapitalize="sentences" style={styles.titleTextInput} value={note.title} onChangeText={(text) => this.title_changeText(text)} />
2017-05-24 22:51:50 +02:00
</View>
{ bodyComponent }
2017-07-14 01:35:37 +02:00
{ actionButtonComp }
2017-07-22 18:36:55 +02:00
{ this.state.showNoteMetadata && <Text style={{ paddingLeft: globalStyle.marginLeft, paddingRight: globalStyle.marginRight, }}>{this.state.noteMetadata}</Text> }
2017-07-15 01:12:32 +02:00
<DialogBox ref={dialogbox => { this.dialogbox = dialogbox }}/>
2017-05-12 22:23:54 +02:00
</View>
);
}
}
const NoteScreen = connect(
(state) => {
return {
2017-05-22 22:22:50 +02:00
noteId: state.selectedNoteId,
folderId: state.selectedFolderId,
2017-05-24 22:51:50 +02:00
itemType: state.selectedItemType,
2017-07-16 18:06:05 +02:00
folders: state.folders,
2017-05-12 22:23:54 +02:00
};
}
)(NoteScreenComponent)
export { NoteScreen };