1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-27 10:32:58 +02:00
joplin/ReactNativeClient/root.js

523 lines
16 KiB
JavaScript
Raw Normal View History

const React = require('react'); const Component = React.Component;
const { Keyboard, NativeModules, BackHandler } = require('react-native');
const { SafeAreaView } = require('react-navigation');
const { connect, Provider } = require('react-redux');
const { BackButtonService } = require('lib/services/back-button.js');
const AlarmService = require('lib/services/AlarmService.js');
const AlarmServiceDriver = require('lib/services/AlarmServiceDriver');
2017-11-28 22:17:34 +02:00
const Alarm = require('lib/models/Alarm');
const { createStore, applyMiddleware } = require('redux');
const { shimInit } = require('lib/shim-init-react.js');
const { Log } = require('lib/log.js');
const { time } = require('lib/time-utils.js');
const { AppNav } = require('lib/components/app-nav.js');
const { Logger } = require('lib/logger.js');
2017-12-14 20:12:14 +02:00
const Note = require('lib/models/Note.js');
const Folder = require('lib/models/Folder.js');
const BaseSyncTarget = require('lib/BaseSyncTarget.js');
const { FoldersScreenUtils } = require('lib/folders-screen-utils.js');
2017-12-14 20:12:14 +02:00
const Resource = require('lib/models/Resource.js');
const Tag = require('lib/models/Tag.js');
const NoteTag = require('lib/models/NoteTag.js');
const BaseItem = require('lib/models/BaseItem.js');
const BaseModel = require('lib/BaseModel.js');
const { JoplinDatabase } = require('lib/joplin-database.js');
const { Database } = require('lib/database.js');
const { NotesScreen } = require('lib/components/screens/notes.js');
const { NoteScreen } = require('lib/components/screens/note.js');
const { ConfigScreen } = require('lib/components/screens/config.js');
const { FolderScreen } = require('lib/components/screens/folder.js');
const { LogScreen } = require('lib/components/screens/log.js');
const { StatusScreen } = require('lib/components/screens/status.js');
const { WelcomeScreen } = require('lib/components/screens/welcome.js');
const { SearchScreen } = require('lib/components/screens/search.js');
const { OneDriveLoginScreen } = require('lib/components/screens/onedrive-login.js');
2017-12-14 20:12:14 +02:00
const Setting = require('lib/models/Setting.js');
const { MenuContext } = require('react-native-popup-menu');
const { SideMenu } = require('lib/components/side-menu.js');
const { SideMenuContent } = require('lib/components/side-menu-content.js');
const { DatabaseDriverReactNative } = require('lib/database-driver-react-native');
const { reg } = require('lib/registry.js');
const { _, setLocale, closestSupportedLocale, defaultLocale } = require('lib/locale.js');
const RNFetchBlob = require('react-native-fetch-blob').default;
const { PoorManIntervals } = require('lib/poor-man-intervals.js');
const { reducer, defaultState } = require('lib/reducer.js');
2017-11-28 22:17:34 +02:00
const DropdownAlert = require('react-native-dropdownalert').default;
2017-11-24 22:14:56 +02:00
const SyncTargetRegistry = require('lib/SyncTargetRegistry.js');
2017-11-24 21:09:15 +02:00
const SyncTargetOneDrive = require('lib/SyncTargetOneDrive.js');
const SyncTargetOneDriveDev = require('lib/SyncTargetOneDriveDev.js');
SyncTargetRegistry.addClass(SyncTargetOneDrive);
SyncTargetRegistry.addClass(SyncTargetOneDriveDev);
const generalMiddleware = store => next => async (action) => {
if (action.type !== 'SIDE_MENU_OPEN_PERCENT') reg.logger().info('Reducer action', action.type);
PoorManIntervals.update(); // This function needs to be called regularly so put it here
const result = next(action);
const newState = store.getState();
if (action.type == 'NAV_GO') Keyboard.dismiss();
2017-11-08 23:22:24 +02:00
if (['NOTE_UPDATE_ONE', 'NOTE_DELETE', 'FOLDER_UPDATE_ONE', 'FOLDER_DELETE'].indexOf(action.type) >= 0) {
if (!await reg.syncTarget().syncStarted()) reg.scheduleSync();
}
2017-11-28 20:58:04 +02:00
if (['EVENT_NOTE_ALARM_FIELD_CHANGE', 'NOTE_DELETE'].indexOf(action.type) >= 0) {
await AlarmService.updateNoteNotification(action.id, action.type === 'NOTE_DELETE');
}
2017-11-08 23:22:24 +02:00
if (action.type == 'SETTING_UPDATE_ONE' && action.key == 'sync.interval' || action.type == 'SETTING_UPDATE_ALL') {
reg.setupRecurrentSync();
}
if ((action.type == 'SETTING_UPDATE_ONE' && (action.key == 'dateFormat' || action.key == 'timeFormat')) || (action.type == 'SETTING_UPDATE_ALL')) {
time.setDateFormat(Setting.value('dateFormat'));
time.setTimeFormat(Setting.value('timeFormat'));
}
2017-11-08 23:22:24 +02:00
if (action.type == 'SETTING_UPDATE_ONE' && action.key == 'locale' || action.type == 'SETTING_UPDATE_ALL') {
2017-11-03 20:51:13 +02:00
setLocale(Setting.value('locale'));
}
if (action.type == 'NAV_GO' && action.routeName == 'Notes') {
Setting.setValue('activeFolderId', newState.selectedFolderId);
}
return result;
}
let navHistory = [];
function historyCanGoBackTo(route) {
if (route.routeName == 'Note') return false;
if (route.routeName == 'Folder') return false;
return true;
}
const appDefaultState = Object.assign({}, defaultState, {
sideMenuOpenPercent: 0,
route: {
type: 'NAV_GO',
routeName: 'Welcome',
params: {},
},
noteSelectionEnabled: false,
});
const appReducer = (state = appDefaultState, action) => {
let newState = state;
let historyGoingBack = false;
try {
switch (action.type) {
case 'NAV_BACK':
if (!navHistory.length) break;
let newAction = null;
while (navHistory.length) {
newAction = navHistory.pop();
if (newAction.routeName != state.route.routeName) break;
}
action = newAction ? newAction : navHistory.pop();
historyGoingBack = true;
// Fall throught
case 'NAV_GO':
const currentRoute = state.route;
const currentRouteName = currentRoute ? currentRoute.routeName : '';
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 = [];
//reg.logger().info('Route: ' + currentRouteName + ' => ' + action.routeName);
newState = Object.assign({}, state);
if ('noteId' in action) {
2017-11-22 20:35:31 +02:00
newState.selectedNoteIds = action.noteId ? [action.noteId] : [];
}
if ('folderId' in action) {
newState.selectedFolderId = action.folderId;
newState.notesParentType = 'Folder';
}
if ('tagId' in action) {
newState.selectedTagId = action.tagId;
newState.notesParentType = 'Tag';
}
if ('itemType' in action) {
newState.selectedItemType = action.itemType;
}
newState.route = action;
newState.historyCanGoBack = !!navHistory.length;
break;
case 'SIDE_MENU_TOGGLE':
newState = Object.assign({}, state);
newState.showSideMenu = !newState.showSideMenu
break;
case 'SIDE_MENU_OPEN':
newState = Object.assign({}, state);
newState.showSideMenu = true
break;
case 'SIDE_MENU_CLOSE':
newState = Object.assign({}, state);
newState.showSideMenu = false
break;
case 'SIDE_MENU_OPEN_PERCENT':
newState = Object.assign({}, state);
newState.sideMenuOpenPercent = action.value;
break;
case 'NOTE_SELECTION_TOGGLE':
newState = Object.assign({}, state);
const noteId = action.id;
const newSelectedNoteIds = state.selectedNoteIds.slice();
const existingIndex = state.selectedNoteIds.indexOf(noteId);
if (existingIndex >= 0) {
newSelectedNoteIds.splice(existingIndex, 1);
} else {
newSelectedNoteIds.push(noteId);
}
newState.selectedNoteIds = newSelectedNoteIds;
newState.noteSelectionEnabled = !!newSelectedNoteIds.length;
break;
case 'NOTE_SELECTION_START':
if (!state.noteSelectionEnabled) {
newState = Object.assign({}, state);
newState.noteSelectionEnabled = true;
newState.selectedNoteIds = [action.id];
}
break;
case 'NOTE_SELECTION_END':
newState = Object.assign({}, state);
newState.noteSelectionEnabled = false;
newState.selectedNoteIds = [];
break;
}
} catch (error) {
error.message = 'In reducer: ' + error.message + ' Action: ' + JSON.stringify(action);
throw error;
}
return reducer(newState, action);
}
let store = createStore(appReducer, applyMiddleware(generalMiddleware));
2017-05-09 22:46:54 +02:00
async function initialize(dispatch) {
2017-07-10 20:09:58 +02:00
shimInit();
2017-07-07 19:19:24 +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');
2017-11-20 00:08:58 +02:00
//Setting.setConstant('resourceDir', () => { return RNFetchBlob.fs.dirs.DocumentDir; });
2017-07-10 00:57:15 +02:00
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);
reg.setShowErrorMessageBoxHandler((message) => { alert(message) });
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;
BaseSyncTarget.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);
AlarmService.setDriver(new AlarmServiceDriver());
AlarmService.setLogger(mainLogger);
2017-07-10 00:57:15 +02:00
try {
if (Setting.value('env') == 'prod') {
await db.open({ name: 'joplin.sqlite' })
} else {
await db.open({ name: 'joplin-68.sqlite' })
2017-07-26 22:00:16 +02:00
//await db.open({ name: 'joplin-67.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-25 20:57:06 +02:00
if (Setting.value('firstStart')) {
const locale = NativeModules.I18nManager.localeIdentifier
if (!locale) locale = defaultLocale();
Setting.setValue('locale', closestSupportedLocale(locale));
if (Setting.value('env') === 'dev') Setting.setValue('sync.target', SyncTargetRegistry.nameToId('onedrive_dev'));
2017-07-25 20:57:06 +02:00
Setting.setValue('firstStart', 0)
}
reg.logger().info('Sync target: ' + Setting.value('sync.target'));
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-25 20:36:52 +02:00
const tags = await Tag.all();
dispatch({
2017-11-08 23:22:24 +02:00
type: 'TAG_UPDATE_ALL',
items: tags,
2017-07-25 20:36:52 +02:00
});
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);
}
reg.setupRecurrentSync();
2017-07-22 19:35:39 +02:00
2017-11-28 20:58:04 +02:00
PoorManIntervals.setTimeout(() => {
AlarmService.garbageCollect();
}, 1000 * 60 * 60);
2017-11-24 20:06:45 +02:00
2017-11-28 20:58:04 +02:00
reg.scheduleSync().then(() => {
// Wait for the first sync before updating the notifications, since synchronisation
// might change the notifications.
AlarmService.updateAllNotifications();
});
2017-11-24 20:06:45 +02:00
2017-07-10 00:57:15 +02:00
reg.logger().info('Application initialized');
}
class AppComponent extends React.Component {
constructor() {
super();
this.lastSyncStarted_ = defaultState.syncStarted;
this.backButtonHandler_ = () => {
return this.backButtonHandler();
}
}
2017-07-10 00:57:15 +02:00
async componentDidMount() {
2017-08-01 19:41:58 +02:00
if (this.props.appState == 'starting') {
this.props.dispatch({
2017-11-08 23:22:24 +02:00
type: 'APP_STATE_SET',
2017-08-01 19:41:58 +02:00
state: 'initializing',
});
await initialize(this.props.dispatch);
2017-08-01 19:41:58 +02:00
this.props.dispatch({
2017-11-08 23:22:24 +02:00
type: 'APP_STATE_SET',
2017-08-01 19:41:58 +02:00
state: 'ready',
});
}
2017-11-28 22:17:34 +02:00
BackButtonService.initialize(this.backButtonHandler_);
2017-11-28 22:17:34 +02:00
AlarmService.setInAppNotificationHandler(async (alarmId) => {
const alarm = await Alarm.load(alarmId);
const notification = await Alarm.makeNotification(alarm);
this.dropdownAlert_.alertWithType('info', notification.title, notification.body ? notification.body : '');
});
2017-07-10 23:00:41 +02:00
}
async backButtonHandler() {
if (this.props.noteSelectionEnabled) {
this.props.dispatch({ type: 'NOTE_SELECTION_END' });
return true;
}
2017-07-10 23:00:41 +02:00
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;
}
BackHandler.exitApp();
2017-07-10 23:00:41 +02:00
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-08-01 19:41:58 +02:00
if (this.props.appState != 'ready') return null;
const sideMenuContent = <SafeAreaView style={{flex:1}}><SideMenuContent/></SafeAreaView>;
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)}
onSliding={(percent) => {
this.props.dispatch({
type: 'SIDE_MENU_OPEN_PERCENT',
value: percent,
});
}}
>
2017-05-24 21:09:46 +02:00
<MenuContext style={{ flex: 1 }}>
<SafeAreaView style={{flex:1}}>
<AppNav screens={appNavInit} />
</SafeAreaView>
2017-11-28 22:17:34 +02:00
<DropdownAlert ref={ref => this.dropdownAlert_ = ref} tapToCloseEnabled={true} />
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-11-04 18:40:34 +02:00
historyCanGoBack: state.historyCanGoBack,
showSideMenu: state.showSideMenu,
syncStarted: state.syncStarted,
appState: state.appState,
noteSelectionEnabled: state.noteSelectionEnabled,
2017-11-04 18:40:34 +02:00
};
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
}
2017-11-03 02:13:17 +02:00
module.exports = { Root };