1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-11-24 08:12:24 +02:00
joplin/ReactNativeClient/root.js

540 lines
14 KiB
JavaScript
Raw Normal View History

2017-05-09 21:59:14 +02:00
import React, { Component } from 'react';
2017-07-10 23:44:55 +02:00
import { BackHandler, Keyboard } from 'react-native';
2017-07-10 23:00:41 +02:00
import { connect, Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux';
2017-07-10 20:09:58 +02:00
import { shimInit } from 'lib/shim-init-react.js';
2017-06-24 20:06:28 +02:00
import { Log } from 'lib/log.js'
2017-07-14 20:49:14 +02:00
import { AppNav } from 'lib/components/app-nav.js'
2017-07-07 19:19:24 +02:00
import { Logger } from 'lib/logger.js'
2017-06-24 20:06:28 +02:00
import { Note } from 'lib/models/note.js'
import { Folder } from 'lib/models/folder.js'
2017-07-15 17:54:19 +02:00
import { FoldersScreenUtils } from 'lib/components/screens/folders-utils.js';
2017-07-06 21:48:17 +02:00
import { Resource } from 'lib/models/resource.js'
import { Tag } from 'lib/models/tag.js'
import { NoteTag } from 'lib/models/note-tag.js'
import { BaseItem } from 'lib/models/base-item.js'
2017-06-24 20:06:28 +02:00
import { BaseModel } from 'lib/base-model.js'
2017-07-06 21:48:17 +02:00
import { JoplinDatabase } from 'lib/joplin-database.js'
2017-07-07 19:19:24 +02:00
import { Database } from 'lib/database.js'
2017-07-05 22:34:25 +02:00
import { NotesScreen } from 'lib/components/screens/notes.js'
import { NoteScreen } from 'lib/components/screens/note.js'
2017-07-23 20:26:50 +02:00
import { ConfigScreen } from 'lib/components/screens/config.js'
2017-07-05 22:34:25 +02:00
import { FolderScreen } from 'lib/components/screens/folder.js'
2017-07-07 19:19:24 +02:00
import { LogScreen } from 'lib/components/screens/log.js'
2017-07-10 21:16:59 +02:00
import { StatusScreen } from 'lib/components/screens/status.js'
import { WelcomeScreen } from 'lib/components/screens/welcome.js'
2017-07-23 00:52:24 +02:00
import { SearchScreen } from 'lib/components/screens/search.js'
2017-07-06 21:29:09 +02:00
import { OneDriveLoginScreen } from 'lib/components/screens/onedrive-login.js'
2017-06-24 20:06:28 +02:00
import { Setting } from 'lib/models/setting.js'
2017-05-16 22:25:19 +02:00
import { MenuContext } from 'react-native-popup-menu';
2017-07-05 22:34:25 +02:00
import { SideMenu } from 'lib/components/side-menu.js';
import { SideMenuContent } from 'lib/components/side-menu-content.js';
2017-06-24 20:06:28 +02:00
import { DatabaseDriverReactNative } from 'lib/database-driver-react-native';
2017-07-06 21:48:17 +02:00
import { reg } from 'lib/registry.js';
2017-07-19 23:26:30 +02:00
import { _, setLocale } from 'lib/locale.js';
2017-07-06 21:48:17 +02:00
import RNFetchBlob from 'react-native-fetch-blob';
2017-07-22 19:35:39 +02:00
import { PoorManIntervals } from 'lib/poor-man-intervals.js';
2017-05-16 22:25:19 +02:00
2017-05-09 22:46:54 +02:00
let defaultState = {
2017-05-12 21:54:06 +02:00
notes: [],
2017-07-25 20:09:01 +02:00
notesSource: '',
2017-05-15 22:50:14 +02:00
folders: [],
2017-05-09 22:46:54 +02:00
selectedNoteId: null,
2017-05-24 22:51:50 +02:00
selectedItemType: 'note',
2017-05-15 21:10:00 +02:00
selectedFolderId: null,
2017-05-24 21:27:13 +02:00
showSideMenu: false,
2017-07-09 00:57:09 +02:00
screens: {},
loading: true,
2017-07-09 01:46:25 +02:00
historyCanGoBack: false,
2017-07-15 20:13:31 +02:00
notesOrder: {
orderBy: 'updated_time',
orderByDir: 'DESC',
},
syncStarted: false,
syncReport: {},
2017-07-23 00:52:24 +02:00
searchQuery: '',
2017-05-09 22:46:54 +02:00
};
2017-07-13 23:50:21 +02:00
const initialRoute = {
type: 'NAV_GO',
2017-07-13 23:50:21 +02:00
routeName: 'Welcome',
params: {}
};
2017-07-14 20:49:14 +02:00
defaultState.route = initialRoute;
2017-07-09 01:46:25 +02:00
let navHistory = [];
2017-07-15 19:08:54 +02:00
function historyCanGoBackTo(route) {
2017-07-20 23:20:56 +02:00
if (route.routeName == 'Note') return false;
if (route.routeName == 'Folder') return false;
2017-07-15 19:08:54 +02:00
return true;
}
2017-07-16 18:06:05 +02:00
function reducerActionsAreSame(a1, a2) {
if (Object.getOwnPropertyNames(a1).length !== Object.getOwnPropertyNames(a2).length) return false;
for (let n in a1) {
if (!a1.hasOwnProperty(n)) continue;
if (a1[n] !== a2[n]) return false;
}
return true;
}
2017-05-09 22:46:54 +02:00
const reducer = (state = defaultState, action) => {
2017-05-10 21:21:09 +02:00
let newState = state;
2017-07-20 23:20:56 +02:00
let historyGoingBack = false;
2017-05-10 21:21:09 +02:00
2017-07-15 01:12:32 +02:00
try {
switch (action.type) {
2017-05-09 22:46:54 +02:00
case 'NAV_BACK':
2017-07-09 01:57:30 +02:00
2017-07-20 23:20:56 +02:00
if (!navHistory.length) break;
2017-07-09 01:46:25 +02:00
2017-07-20 23:20:56 +02:00
let newAction = null;
while (navHistory.length) {
newAction = navHistory.pop();
if (newAction.routeName != state.route.routeName) break;
2017-07-15 19:08:54 +02:00
}
2017-07-20 23:20:56 +02:00
action = newAction ? newAction : navHistory.pop();
historyGoingBack = true;
2017-07-15 19:08:54 +02:00
2017-07-15 01:12:32 +02:00
// Fall throught
2017-07-09 01:46:25 +02:00
case 'NAV_GO':
2017-07-09 01:46:25 +02:00
2017-07-15 01:12:32 +02:00
const currentRoute = state.route;
const currentRouteName = currentRoute ? currentRoute.routeName : '';
2017-05-12 21:54:06 +02:00
2017-07-20 23:20:56 +02:00
if (!historyGoingBack && historyCanGoBackTo(currentRoute)) {
// If the route *name* is the same (even if the other parameters are different), we
// overwrite the last route in the history with the current one. If the route name
// is different, we push a new history entry.
if (currentRoute.routeName == action.routeName) {
// nothing
} else {
navHistory.push(currentRoute);
}
}
// HACK: whenever a new screen is loaded, all the previous screens of that type
// are overwritten with the new screen parameters. This is because the way notes
// are currently loaded is not optimal (doesn't retain history properly) so
// this is a simple fix without doing a big refactoring to change the way notes
// are loaded. Might be good enough since going back to different folders
// is probably not a common workflow.
for (let i = 0; i < navHistory.length; i++) {
let n = navHistory[i];
if (n.routeName == action.routeName) {
navHistory[i] = Object.assign({}, action);
}
}
if (action.routeName == 'Welcome') navHistory = [];
2017-07-15 01:12:32 +02:00
reg.logger().info('Route: ' + currentRouteName + ' => ' + action.routeName);
2017-05-15 22:50:14 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
2017-05-10 21:21:09 +02:00
2017-07-15 01:12:32 +02:00
if ('noteId' in action) {
newState.selectedNoteId = action.noteId;
}
2017-05-15 21:46:34 +02:00
2017-07-15 01:12:32 +02:00
if ('folderId' in action) {
newState.selectedFolderId = action.folderId;
}
if ('itemType' in action) {
newState.selectedItemType = action.itemType;
}
2017-05-10 21:21:09 +02:00
2017-07-16 18:06:05 +02:00
newState.route = action;
2017-07-20 23:20:56 +02:00
newState.historyCanGoBack = !!navHistory.length;
2017-05-24 22:11:37 +02:00
2017-07-15 01:12:32 +02:00
if (newState.route.routeName == 'Notes') {
Setting.setValue('activeFolderId', newState.selectedFolderId);
}
2017-07-10 23:44:55 +02:00
2017-07-15 01:12:32 +02:00
break;
2017-05-09 22:46:54 +02:00
2017-07-15 01:12:32 +02:00
// Replace all the notes with the provided array
case 'APPLICATION_LOADING_DONE':
2017-07-09 00:57:09 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.loading = false;
break;
2017-07-09 00:57:09 +02:00
2017-07-15 01:12:32 +02:00
// Replace all the notes with the provided array
case 'NOTES_UPDATE_ALL':
2017-05-09 22:46:54 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.notes = action.notes;
2017-07-25 20:09:01 +02:00
newState.notesSource = action.notesSource;
2017-07-15 01:12:32 +02:00
break;
2017-05-11 22:14:01 +02:00
2017-07-15 01:12:32 +02:00
// Insert the note into the note list if it's new, or
// update it within the note array if it already exists.
case 'NOTES_UPDATE_ONE':
2017-07-16 18:06:05 +02:00
const modNote = action.note;
2017-07-08 00:25:03 +02:00
2017-07-15 01:12:32 +02:00
let newNotes = state.notes.splice(0);
var found = false;
for (let i = 0; i < newNotes.length; i++) {
let n = newNotes[i];
2017-07-16 18:06:05 +02:00
if (n.id == modNote.id) {
if (!('parent_id' in modNote) || modNote.parent_id == n.parent_id) {
// Merge the properties that have changed (in modNote) into
// the object we already have.
newNotes[i] = Object.assign(newNotes[i], action.note);
} else {
newNotes.splice(i, 1);
}
2017-07-15 01:12:32 +02:00
found = true;
break;
}
}
2017-05-10 21:21:09 +02:00
2017-07-16 18:06:05 +02:00
if (!found && ('parent_id' in modNote) && modNote.parent_id == state.selectedFolderId) newNotes.push(modNote);
2017-07-15 01:12:32 +02:00
2017-07-15 20:13:31 +02:00
newNotes = Note.sortNotes(newNotes, state.notesOrder);
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.notes = newNotes;
break;
case 'NOTES_DELETE':
var newNotes = [];
for (let i = 0; i < state.notes.length; i++) {
let f = state.notes[i];
if (f.id == action.noteId) continue;
newNotes.push(f);
}
2017-05-11 22:14:01 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.notes = newNotes;
break;
2017-05-09 22:46:54 +02:00
2017-07-15 01:12:32 +02:00
case 'FOLDERS_UPDATE_ALL':
2017-05-15 21:46:34 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.folders = action.folders;
break;
2017-05-15 21:46:34 +02:00
2017-07-15 01:12:32 +02:00
case 'FOLDERS_UPDATE_ONE':
2017-05-15 21:10:00 +02:00
2017-07-15 01:12:32 +02:00
var newFolders = state.folders.splice(0);
var found = false;
for (let i = 0; i < newFolders.length; i++) {
let n = newFolders[i];
if (n.id == action.folder.id) {
newFolders[i] = Object.assign(newFolders[i], action.folder);
2017-07-15 01:12:32 +02:00
found = true;
break;
}
2017-05-15 21:10:00 +02:00
}
2017-07-15 01:12:32 +02:00
if (!found) newFolders.push(action.folder);
2017-05-15 21:10:00 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.folders = newFolders;
break;
2017-05-15 21:10:00 +02:00
2017-07-15 01:12:32 +02:00
case 'FOLDER_DELETE':
2017-05-16 22:25:19 +02:00
2017-07-15 01:12:32 +02:00
var newFolders = [];
for (let i = 0; i < state.folders.length; i++) {
let f = state.folders[i];
if (f.id == action.folderId) continue;
newFolders.push(f);
}
2017-05-16 22:25:19 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.folders = newFolders;
break;
2017-05-16 22:25:19 +02:00
2017-07-15 01:12:32 +02:00
case 'SIDE_MENU_TOGGLE':
2017-05-24 21:27:13 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.showSideMenu = !newState.showSideMenu
break;
2017-05-24 21:27:13 +02:00
2017-07-15 01:12:32 +02:00
case 'SIDE_MENU_OPEN':
2017-05-24 21:27:13 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.showSideMenu = true
break;
2017-05-24 21:27:13 +02:00
2017-07-15 01:12:32 +02:00
case 'SIDE_MENU_CLOSE':
2017-05-24 21:27:13 +02:00
2017-07-15 01:12:32 +02:00
newState = Object.assign({}, state);
newState.showSideMenu = false
break;
2017-05-24 21:27:13 +02:00
case 'SYNC_STARTED':
newState = Object.assign({}, state);
newState.syncStarted = true;
break;
case 'SYNC_COMPLETED':
newState = Object.assign({}, state);
newState.syncStarted = false;
break;
case 'SYNC_REPORT_UPDATE':
newState = Object.assign({}, state);
newState.syncReport = action.report;
break;
2017-07-23 00:52:24 +02:00
case 'SEARCH_QUERY':
newState = Object.assign({}, state);
newState.searchQuery = action.query.trim();
2017-07-15 01:12:32 +02:00
}
} catch (error) {
error.message = 'In reducer: ' + error.message;
throw error;
2017-05-09 22:46:54 +02:00
}
2017-05-10 21:21:09 +02:00
return newState;
2017-05-09 22:46:54 +02:00
}
const generalMiddleware = store => next => action => {
reg.logger().info('Reducer action', action.type);
PoorManIntervals.update(); // This function needs to be called regularly so put it here
const result = next(action);
if (action.type == 'NAV_GO') Keyboard.dismiss();
if (['NOTES_UPDATE_ONE', 'NOTES_DELETE', 'FOLDERS_UPDATE_ONE', 'FOLDER_DELETE'].indexOf(action.type) >= 0) {
reg.scheduleSync();
}
return result;
}
let store = createStore(reducer, applyMiddleware(generalMiddleware));
2017-05-09 22:46:54 +02:00
2017-07-10 00:57:15 +02:00
let initializationState_ = 'waiting';
2017-07-06 23:30:45 +02:00
2017-07-10 23:00:41 +02:00
async function initialize(dispatch, backButtonHandler) {
2017-07-10 00:57:15 +02:00
if (initializationState_ != 'waiting') return;
2017-07-07 19:19:24 +02:00
2017-07-10 20:09:58 +02:00
shimInit();
2017-07-07 19:19:24 +02:00
2017-07-10 20:09:58 +02:00
initializationState_ = 'in_progress';
2017-07-06 23:30:45 +02:00
2017-07-10 00:57:15 +02:00
Setting.setConstant('env', __DEV__ ? 'dev' : 'prod');
Setting.setConstant('appId', 'net.cozic.joplin');
Setting.setConstant('appType', 'mobile');
Setting.setConstant('resourceDir', RNFetchBlob.fs.dirs.DocumentDir);
const logDatabase = new Database(new DatabaseDriverReactNative());
await logDatabase.open({ name: 'log.sqlite' });
await logDatabase.exec(Logger.databaseCreateTableSql());
2017-07-15 01:12:32 +02:00
const mainLogger = new Logger();
mainLogger.addTarget('database', { database: logDatabase, source: 'm' });
2017-07-15 19:08:54 +02:00
if (Setting.value('env') == 'dev') mainLogger.addTarget('console');
2017-07-15 01:12:32 +02:00
mainLogger.setLevel(Logger.LEVEL_DEBUG);
reg.setLogger(mainLogger);
2017-07-10 00:57:15 +02:00
reg.logger().info('====================================');
reg.logger().info('Starting application ' + Setting.value('appId') + ' (' + Setting.value('env') + ')');
2017-07-15 01:12:32 +02:00
const dbLogger = new Logger();
2017-07-17 22:22:05 +02:00
dbLogger.addTarget('database', { database: logDatabase, source: 'm' });
2017-07-15 19:08:54 +02:00
if (Setting.value('env') == 'dev') {
2017-07-17 22:22:05 +02:00
dbLogger.addTarget('console');
dbLogger.setLevel(Logger.LEVEL_INFO); // Set to LEVEL_DEBUG for full SQL queries
2017-07-15 19:08:54 +02:00
} else {
dbLogger.setLevel(Logger.LEVEL_INFO);
}
2017-07-15 01:12:32 +02:00
2017-07-10 00:57:15 +02:00
let db = new JoplinDatabase(new DatabaseDriverReactNative());
2017-07-15 01:12:32 +02:00
db.setLogger(dbLogger);
2017-07-10 00:57:15 +02:00
reg.setDb(db);
reg.dispatch = dispatch;
2017-07-10 00:57:15 +02:00
BaseModel.dispatch = dispatch;
2017-07-15 17:54:19 +02:00
FoldersScreenUtils.dispatch = dispatch;
2017-07-10 00:57:15 +02:00
BaseModel.db_ = db;
BaseItem.loadClass('Note', Note);
BaseItem.loadClass('Folder', Folder);
BaseItem.loadClass('Resource', Resource);
BaseItem.loadClass('Tag', Tag);
BaseItem.loadClass('NoteTag', NoteTag);
try {
if (Setting.value('env') == 'prod') {
await db.open({ name: 'joplin.sqlite' })
} else {
//await db.open({ name: 'joplin-56.sqlite' })
await db.open({ name: 'joplin-56.sqlite' })
2017-07-10 00:57:15 +02:00
2017-07-10 22:48:17 +02:00
// await db.exec('DELETE FROM notes');
// await db.exec('DELETE FROM folders');
// await db.exec('DELETE FROM tags');
// await db.exec('DELETE FROM note_tags');
// await db.exec('DELETE FROM resources');
// await db.exec('DELETE FROM deleted_items');
2017-07-15 17:54:19 +02:00
// await db.exec('UPDATE notes SET is_conflict = 1 where id like "546f%"');
2017-07-10 00:57:15 +02:00
}
2017-05-16 23:46:21 +02:00
2017-07-10 00:57:15 +02:00
reg.logger().info('Database is ready.');
reg.logger().info('Loading settings...');
await Setting.load();
2017-07-24 23:29:40 +02:00
setLocale(Setting.value('locale'));
2017-07-19 23:26:30 +02:00
2017-07-10 00:57:15 +02:00
reg.logger().info('Loading folders...');
2017-07-06 23:30:45 +02:00
2017-07-15 17:54:19 +02:00
await FoldersScreenUtils.refreshFolders();
2017-07-09 00:57:09 +02:00
2017-07-10 00:57:15 +02:00
dispatch({
type: 'APPLICATION_LOADING_DONE',
});
2017-07-15 01:12:32 +02:00
let folderId = Setting.value('activeFolderId');
let folder = await Folder.load(folderId);
2017-07-25 20:09:01 +02:00
if (!folder) folder = await Folder.defaultFolder();
2017-07-23 20:26:50 +02:00
2017-07-25 20:09:01 +02:00
if (!folder) {
dispatch({
type: 'NAV_GO',
2017-07-25 20:09:01 +02:00
routeName: 'Welcome',
});
2017-07-24 23:52:30 +02:00
} else {
2017-07-25 20:09:01 +02:00
dispatch({
type: 'NAV_GO',
2017-07-25 20:09:01 +02:00
routeName: 'Notes',
folderId: folder.id,
});
2017-07-24 23:52:30 +02:00
}
2017-07-10 00:57:15 +02:00
} catch (error) {
reg.logger().error('Initialization error:', error);
}
2017-07-10 23:00:41 +02:00
BackHandler.addEventListener('hardwareBackPress', () => {
return backButtonHandler();
});
2017-07-22 19:35:39 +02:00
PoorManIntervals.setInterval(() => {
reg.logger().info('Running background sync on timer...');
2017-07-24 23:52:30 +02:00
reg.scheduleSync(0);
2017-07-22 19:35:39 +02:00
}, 1000 * 60 * 5);
2017-07-23 00:52:24 +02:00
if (Setting.value('env') == 'dev') {
} else {
reg.scheduleSync();
}
2017-07-10 00:57:15 +02:00
initializationState_ = 'done';
reg.logger().info('Application initialized');
}
class AppComponent extends React.Component {
constructor() {
super();
this.lastSyncStarted_ = defaultState.syncStarted;
}
2017-07-10 00:57:15 +02:00
async componentDidMount() {
2017-07-10 23:00:41 +02:00
await initialize(this.props.dispatch, this.backButtonHandler.bind(this));
}
backButtonHandler() {
if (this.props.showSideMenu) {
this.props.dispatch({ type: 'SIDE_MENU_CLOSE' });
return true;
}
if (this.props.historyCanGoBack) {
this.props.dispatch({ type: 'NAV_BACK' });
2017-07-10 23:00:41 +02:00
return true;
}
return false;
2017-05-11 22:14:01 +02:00
}
componentWillReceiveProps(newProps) {
if (newProps.syncStarted != this.lastSyncStarted_) {
if (!newProps.syncStarted) FoldersScreenUtils.refreshFolders();
this.lastSyncStarted_ = newProps.syncStarted;
}
}
sideMenu_change(isOpen) {
2017-05-24 21:27:13 +02:00
// Make sure showSideMenu property of state is updated
// when the menu is open/closed.
this.props.dispatch({
type: isOpen ? 'SIDE_MENU_OPEN' : 'SIDE_MENU_CLOSE',
});
}
2017-05-11 22:14:01 +02:00
render() {
2017-05-24 21:27:13 +02:00
const sideMenuContent = <SideMenuContent/>;
2017-05-24 21:09:46 +02:00
2017-07-14 20:49:14 +02:00
const appNavInit = {
Welcome: { screen: WelcomeScreen },
Notes: { screen: NotesScreen },
Note: { screen: NoteScreen },
Folder: { screen: FolderScreen },
OneDriveLogin: { screen: OneDriveLoginScreen },
Log: { screen: LogScreen },
Status: { screen: StatusScreen },
2017-07-23 00:52:24 +02:00
Search: { screen: SearchScreen },
2017-07-23 20:26:50 +02:00
Config: { screen: ConfigScreen },
2017-07-14 20:49:14 +02:00
};
2017-05-11 22:14:01 +02:00
return (
<SideMenu menu={sideMenuContent} onChange={(isOpen) => this.sideMenu_change(isOpen)}>
2017-05-24 21:09:46 +02:00
<MenuContext style={{ flex: 1 }}>
2017-07-14 20:49:14 +02:00
<AppNav screens={appNavInit} />
2017-05-24 21:09:46 +02:00
</MenuContext>
</SideMenu>
2017-05-11 22:14:01 +02:00
);
}
2017-05-10 20:58:02 +02:00
}
const mapStateToProps = (state) => {
return {
2017-07-10 23:00:41 +02:00
historyCanGoBack: state.historyCanGoBack,
showSideMenu: state.showSideMenu,
syncStarted: state.syncStarted,
2017-05-10 20:58:02 +02:00
};
};
const App = connect(mapStateToProps)(AppComponent);
2017-05-09 22:46:54 +02:00
class Root extends React.Component {
render() {
return (
<Provider store={store}>
2017-07-14 20:49:14 +02:00
<App/>
2017-05-09 22:46:54 +02:00
</Provider>
);
}
2017-05-09 21:59:14 +02:00
}
export { Root };