Merge ErrorsStore into UiStore

This commit is contained in:
Tom Moor
2018-05-31 11:42:39 -07:00
parent 55e1451160
commit f633f63a61
18 changed files with 105 additions and 158 deletions

View File

@ -31,7 +31,9 @@ const Auth = observer(({ auth, children }: Props) => {
// Stores for authenticated user // Stores for authenticated user
const cache = new CacheStore(user.id); const cache = new CacheStore(user.id);
authenticatedStores = { authenticatedStores = {
integrations: new IntegrationsStore(), integrations: new IntegrationsStore({
ui: stores.ui,
}),
apiKeys: new ApiKeysStore(), apiKeys: new ApiKeysStore(),
users: new UsersStore(), users: new UsersStore(),
collections: new CollectionsStore({ collections: new CollectionsStore({

View File

@ -8,15 +8,15 @@ import Toast from './components/Toast';
@observer @observer
class Toasts extends React.Component<*> { class Toasts extends React.Component<*> {
handleClose = index => { handleClose = index => {
this.props.errors.remove(index); this.props.ui.remove(index);
}; };
render() { render() {
const { errors } = this.props; const { ui } = this.props;
return ( return (
<List> <List>
{errors.data.map((error, index) => ( {ui.toasts.map((error, index) => (
<Toast <Toast
key={index} key={index}
onRequestClose={this.handleClose.bind(this, index)} onRequestClose={this.handleClose.bind(this, index)}
@ -37,4 +37,4 @@ const List = styled.ol`
padding: 0; padding: 0;
`; `;
export default inject('errors')(Toasts); export default inject('ui')(Toasts);

View File

@ -6,13 +6,13 @@ import BaseModel from 'models/BaseModel';
import Document from 'models/Document'; import Document from 'models/Document';
import { client } from 'utils/ApiClient'; import { client } from 'utils/ApiClient';
import stores from 'stores'; import stores from 'stores';
import ErrorsStore from 'stores/ErrorsStore'; import UiStore from 'stores/UiStore';
import type { NavigationNode } from 'types'; import type { NavigationNode } from 'types';
class Collection extends BaseModel { class Collection extends BaseModel {
isSaving: boolean = false; isSaving: boolean = false;
hasPendingChanges: boolean = false; hasPendingChanges: boolean = false;
errors: ErrorsStore; ui: UiStore;
data: Object; data: Object;
createdAt: string; createdAt: string;
@ -79,7 +79,7 @@ class Collection extends BaseModel {
this.updateData(data); this.updateData(data);
}); });
} catch (e) { } catch (e) {
this.errors.add('Collection failed loading'); this.ui.showToast('Collection failed loading');
} }
return this; return this;
@ -112,7 +112,7 @@ class Collection extends BaseModel {
this.hasPendingChanges = false; this.hasPendingChanges = false;
}); });
} catch (e) { } catch (e) {
this.errors.add('Collection failed saving'); this.ui.showToast('Collection failed saving');
return false; return false;
} finally { } finally {
this.isSaving = false; this.isSaving = false;
@ -128,7 +128,7 @@ class Collection extends BaseModel {
this.emit('collections.delete', { id: this.id }); this.emit('collections.delete', { id: this.id });
return true; return true;
} catch (e) { } catch (e) {
this.errors.add('Collection failed to delete'); this.ui.showToast('Collection failed to delete');
} }
return false; return false;
}; };
@ -143,7 +143,7 @@ class Collection extends BaseModel {
super(); super();
this.updateData(collection); this.updateData(collection);
this.errors = stores.errors; this.ui = stores.ui;
this.on('documents.delete', (data: { collectionId: string }) => { this.on('documents.delete', (data: { collectionId: string }) => {
if (data.collectionId === this.id) this.fetch(); if (data.collectionId === this.id) this.fetch();

View File

@ -28,22 +28,5 @@ describe('Collection model', () => {
expect(client.post).toHaveBeenCalledWith('/collections.info', { id: 123 }); expect(client.post).toHaveBeenCalledWith('/collections.info', { id: 123 });
expect(collection.name).toBe('New collection'); expect(collection.name).toBe('New collection');
}); });
test('should report errors', async () => {
client.post = jest.fn(() => Promise.reject())
const collection = new Collection({
id: 123,
});
collection.errors = {
add: jest.fn(),
};
await collection.fetch();
expect(collection.errors.add).toHaveBeenCalledWith(
'Collection failed loading'
);
});
}); });
}); });

View File

@ -4,7 +4,7 @@ import invariant from 'invariant';
import { client } from 'utils/ApiClient'; import { client } from 'utils/ApiClient';
import stores from 'stores'; import stores from 'stores';
import ErrorsStore from 'stores/ErrorsStore'; import UiStore from 'stores/UiStore';
import parseTitle from '../../shared/utils/parseTitle'; import parseTitle from '../../shared/utils/parseTitle';
import type { User } from 'types'; import type { User } from 'types';
@ -16,7 +16,7 @@ type SaveOptions = { publish?: boolean, done?: boolean, autosave?: boolean };
class Document extends BaseModel { class Document extends BaseModel {
isSaving: boolean = false; isSaving: boolean = false;
hasPendingChanges: boolean = false; hasPendingChanges: boolean = false;
errors: ErrorsStore; ui: UiStore;
collaborators: User[]; collaborators: User[];
collection: $Shape<Collection>; collection: $Shape<Collection>;
@ -107,7 +107,7 @@ class Document extends BaseModel {
this.shareUrl = res.data.url; this.shareUrl = res.data.url;
} catch (e) { } catch (e) {
this.errors.add('Document failed to share'); this.ui.showToast('Document failed to share');
} }
}; };
@ -118,7 +118,7 @@ class Document extends BaseModel {
await client.post('/documents.pin', { id: this.id }); await client.post('/documents.pin', { id: this.id });
} catch (e) { } catch (e) {
this.pinned = false; this.pinned = false;
this.errors.add('Document failed to pin'); this.ui.showToast('Document failed to pin');
} }
}; };
@ -129,7 +129,7 @@ class Document extends BaseModel {
await client.post('/documents.unpin', { id: this.id }); await client.post('/documents.unpin', { id: this.id });
} catch (e) { } catch (e) {
this.pinned = true; this.pinned = true;
this.errors.add('Document failed to unpin'); this.ui.showToast('Document failed to unpin');
} }
}; };
@ -140,7 +140,7 @@ class Document extends BaseModel {
await client.post('/documents.star', { id: this.id }); await client.post('/documents.star', { id: this.id });
} catch (e) { } catch (e) {
this.starred = false; this.starred = false;
this.errors.add('Document failed star'); this.ui.showToast('Document failed star');
} }
}; };
@ -151,7 +151,7 @@ class Document extends BaseModel {
await client.post('/documents.unstar', { id: this.id }); await client.post('/documents.unstar', { id: this.id });
} catch (e) { } catch (e) {
this.starred = false; this.starred = false;
this.errors.add('Document failed unstar'); this.ui.showToast('Document failed unstar');
} }
}; };
@ -161,7 +161,7 @@ class Document extends BaseModel {
try { try {
await client.post('/views.create', { id: this.id }); await client.post('/views.create', { id: this.id });
} catch (e) { } catch (e) {
this.errors.add('Document failed to record view'); this.ui.showToast('Document failed to record view');
} }
}; };
@ -175,7 +175,7 @@ class Document extends BaseModel {
this.updateData(data); this.updateData(data);
}); });
} catch (e) { } catch (e) {
this.errors.add('Document failed loading'); this.ui.showToast('Document failed loading');
} }
}; };
@ -228,7 +228,7 @@ class Document extends BaseModel {
}); });
} }
} catch (e) { } catch (e) {
this.errors.add('Document failed to save'); this.ui.showToast('Document failed to save');
} finally { } finally {
this.isSaving = false; this.isSaving = false;
} }
@ -250,7 +250,7 @@ class Document extends BaseModel {
collectionId: this.collection.id, collectionId: this.collection.id,
}); });
} catch (e) { } catch (e) {
this.errors.add('Error while moving the document'); this.ui.showToast('Error while moving the document');
} }
return; return;
}; };
@ -265,7 +265,7 @@ class Document extends BaseModel {
}); });
return true; return true;
} catch (e) { } catch (e) {
this.errors.add('Error while deleting the document'); this.ui.showToast('Error while deleting the document');
} }
return false; return false;
}; };
@ -294,7 +294,7 @@ class Document extends BaseModel {
super(); super();
this.updateData(data); this.updateData(data);
this.errors = stores.errors; this.ui = stores.ui;
} }
} }

View File

@ -4,7 +4,7 @@ import { extendObservable, action } from 'mobx';
import BaseModel from 'models/BaseModel'; import BaseModel from 'models/BaseModel';
import { client } from 'utils/ApiClient'; import { client } from 'utils/ApiClient';
import stores from 'stores'; import stores from 'stores';
import ErrorsStore from 'stores/ErrorsStore'; import UiStore from 'stores/UiStore';
type Settings = { type Settings = {
url: string, url: string,
@ -15,7 +15,7 @@ type Settings = {
type Events = 'documents.create' | 'collections.create'; type Events = 'documents.create' | 'collections.create';
class Integration extends BaseModel { class Integration extends BaseModel {
errors: ErrorsStore; ui: UiStore;
id: string; id: string;
serviceId: string; serviceId: string;
@ -29,7 +29,7 @@ class Integration extends BaseModel {
await client.post('/integrations.update', { id: this.id, ...data }); await client.post('/integrations.update', { id: this.id, ...data });
extendObservable(this, data); extendObservable(this, data);
} catch (e) { } catch (e) {
this.errors.add('Integration failed to update'); this.ui.showToast('Integration failed to update');
} }
return false; return false;
}; };
@ -41,7 +41,7 @@ class Integration extends BaseModel {
this.emit('integrations.delete', { id: this.id }); this.emit('integrations.delete', { id: this.id });
return true; return true;
} catch (e) { } catch (e) {
this.errors.add('Integration failed to delete'); this.ui.showToast('Integration failed to delete');
} }
return false; return false;
}; };
@ -50,7 +50,7 @@ class Integration extends BaseModel {
super(); super();
extendObservable(this, data); extendObservable(this, data);
this.errors = stores.errors; this.ui = stores.ui;
} }
} }

View File

@ -1,14 +1,11 @@
// @flow // @flow
import * as React from 'react'; import * as React from 'react';
import { observable, runInAction } from 'mobx'; import { observable } from 'mobx';
import { observer, inject } from 'mobx-react'; import { observer, inject } from 'mobx-react';
import invariant from 'invariant';
import styled from 'styled-components'; import styled from 'styled-components';
import { color, size } from 'shared/styles/constants'; import { color, size } from 'shared/styles/constants';
import { client } from 'utils/ApiClient';
import AuthStore from 'stores/AuthStore'; import AuthStore from 'stores/AuthStore';
import ErrorsStore from 'stores/ErrorsStore';
import ImageUpload from './components/ImageUpload'; import ImageUpload from './components/ImageUpload';
import Input, { LabelText } from 'components/Input'; import Input, { LabelText } from 'components/Input';
import Button from 'components/Button'; import Button from 'components/Button';
@ -18,7 +15,6 @@ import Flex from 'shared/components/Flex';
type Props = { type Props = {
auth: AuthStore, auth: AuthStore,
errors: ErrorsStore,
}; };
@observer @observer
@ -27,8 +23,6 @@ class Profile extends React.Component<Props> {
@observable name: string; @observable name: string;
@observable avatarUrl: ?string; @observable avatarUrl: ?string;
@observable isUpdated: boolean;
@observable isSaving: boolean;
componentDidMount() { componentDidMount() {
if (this.props.auth.user) { if (this.props.auth.user) {
@ -42,25 +36,11 @@ class Profile extends React.Component<Props> {
handleSubmit = async (ev: SyntheticEvent<*>) => { handleSubmit = async (ev: SyntheticEvent<*>) => {
ev.preventDefault(); ev.preventDefault();
this.isSaving = true;
try { await this.props.auth.updateUser({
const res = await client.post(`/user.update`, { name: this.name,
name: this.name, avatarUrl: this.avatarUrl,
avatarUrl: this.avatarUrl, });
});
invariant(res && res.data, 'User response not available');
const { data } = res;
runInAction('Settings#handleSubmit', () => {
this.props.auth.user = data;
this.isUpdated = true;
this.timeout = setTimeout(() => (this.isUpdated = false), 2500);
});
} catch (e) {
this.props.errors.add('Failed to update user');
} finally {
this.isSaving = false;
}
}; };
handleNameChange = (ev: SyntheticInputEvent<*>) => { handleNameChange = (ev: SyntheticInputEvent<*>) => {
@ -72,7 +52,7 @@ class Profile extends React.Component<Props> {
}; };
handleAvatarError = (error: ?string) => { handleAvatarError = (error: ?string) => {
this.props.errors.add(error || 'Unable to upload new avatar'); this.props.ui.showToast(error || 'Unable to upload new avatar');
}; };
render() { render() {
@ -85,7 +65,7 @@ class Profile extends React.Component<Props> {
<PageTitle title="Profile" /> <PageTitle title="Profile" />
<h1>Profile</h1> <h1>Profile</h1>
<ProfilePicture column> <ProfilePicture column>
<LabelText>Profile picture</LabelText> <LabelText>Picture</LabelText>
<AvatarContainer> <AvatarContainer>
<ImageUpload <ImageUpload
onSuccess={this.handleAvatarUpload} onSuccess={this.handleAvatarUpload}
@ -108,31 +88,20 @@ class Profile extends React.Component<Props> {
<Button type="submit" disabled={this.isSaving || !this.name}> <Button type="submit" disabled={this.isSaving || !this.name}>
Save Save
</Button> </Button>
<SuccessMessage visible={this.isUpdated}>
Profile updated!
</SuccessMessage>
</form> </form>
</CenteredContent> </CenteredContent>
); );
} }
} }
const SuccessMessage = styled.span`
margin-left: ${size.large};
color: ${color.slate};
opacity: ${props => (props.visible ? 1 : 0)};
transition: opacity 0.25s;
`;
const ProfilePicture = styled(Flex)` const ProfilePicture = styled(Flex)`
margin-bottom: ${size.huge}; margin-bottom: ${size.huge};
`; `;
const avatarStyles = ` const avatarStyles = `
width: 150px; width: 80px;
height: 150px; height: 80px;
border-radius: 50%; border-radius: 10px;
`; `;
const AvatarContainer = styled(Flex)` const AvatarContainer = styled(Flex)`
@ -166,4 +135,4 @@ const StyledInput = styled(Input)`
max-width: 350px; max-width: 350px;
`; `;
export default inject('auth', 'errors')(Profile); export default inject('auth', 'ui')(Profile);

View File

@ -49,6 +49,16 @@ class AuthStore {
} }
}; };
@action
updateUser = async (params: { name: string, avatarUrl?: string }) => {
const res = await client.post(`/user.update`, params);
invariant(res && res.data, 'User response not available');
runInAction('AuthStore#updateUser', () => {
this.user = res.data.user;
});
};
@action @action
logout = async () => { logout = async () => {
this.user = null; this.user = null;

View File

@ -6,7 +6,6 @@ import invariant from 'invariant';
import stores from 'stores'; import stores from 'stores';
import BaseStore from './BaseStore'; import BaseStore from './BaseStore';
import ErrorsStore from './ErrorsStore';
import UiStore from './UiStore'; import UiStore from './UiStore';
import Collection from 'models/Collection'; import Collection from 'models/Collection';
import naturalSort from 'shared/utils/naturalSort'; import naturalSort from 'shared/utils/naturalSort';
@ -32,7 +31,6 @@ class CollectionsStore extends BaseStore {
@observable isLoaded: boolean = false; @observable isLoaded: boolean = false;
@observable isFetching: boolean = false; @observable isFetching: boolean = false;
errors: ErrorsStore;
ui: UiStore; ui: UiStore;
@computed @computed
@ -106,7 +104,7 @@ class CollectionsStore extends BaseStore {
}); });
return res; return res;
} catch (e) { } catch (e) {
this.errors.add('Failed to load collections'); this.ui.showToast('Failed to load collections');
} finally { } finally {
this.isFetching = false; this.isFetching = false;
} }
@ -134,7 +132,7 @@ class CollectionsStore extends BaseStore {
return collection; return collection;
} catch (e) { } catch (e) {
this.errors.add('Something went wrong'); this.ui.showToast('Something went wrong');
} finally { } finally {
this.isFetching = false; this.isFetching = false;
} }
@ -156,7 +154,6 @@ class CollectionsStore extends BaseStore {
constructor(options: Options) { constructor(options: Options) {
super(); super();
this.errors = stores.errors;
this.ui = options.ui; this.ui = options.ui;
this.on('collections.delete', (data: { id: string }) => { this.on('collections.delete', (data: { id: string }) => {

View File

@ -6,7 +6,6 @@ import invariant from 'invariant';
import BaseStore from 'stores/BaseStore'; import BaseStore from 'stores/BaseStore';
import Document from 'models/Document'; import Document from 'models/Document';
import ErrorsStore from 'stores/ErrorsStore';
import UiStore from 'stores/UiStore'; import UiStore from 'stores/UiStore';
import type { PaginationParams } from 'types'; import type { PaginationParams } from 'types';
@ -14,7 +13,6 @@ export const DEFAULT_PAGINATION_LIMIT = 25;
type Options = { type Options = {
ui: UiStore, ui: UiStore,
errors: ErrorsStore,
}; };
type FetchOptions = { type FetchOptions = {
@ -29,7 +27,6 @@ class DocumentsStore extends BaseStore {
@observable isLoaded: boolean = false; @observable isLoaded: boolean = false;
@observable isFetching: boolean = false; @observable isFetching: boolean = false;
errors: ErrorsStore;
ui: UiStore; ui: UiStore;
/* Computed */ /* Computed */
@ -114,7 +111,7 @@ class DocumentsStore extends BaseStore {
}); });
return data; return data;
} catch (e) { } catch (e) {
this.errors.add('Failed to load documents'); this.ui.showToast('Failed to load documents');
} finally { } finally {
this.isFetching = false; this.isFetching = false;
} }
@ -200,7 +197,7 @@ class DocumentsStore extends BaseStore {
return document; return document;
} catch (e) { } catch (e) {
this.errors.add('Failed to load document'); this.ui.showToast('Failed to load document');
} finally { } finally {
this.isFetching = false; this.isFetching = false;
} }
@ -230,7 +227,6 @@ class DocumentsStore extends BaseStore {
constructor(options: Options) { constructor(options: Options) {
super(); super();
this.errors = options.errors;
this.ui = options.ui; this.ui = options.ui;
this.on('documents.delete', (data: { id: string }) => { this.on('documents.delete', (data: { id: string }) => {

View File

@ -1,20 +0,0 @@
// @flow
import { observable, action } from 'mobx';
class ErrorsStore {
@observable data = observable.array([]);
/* Actions */
@action
add = (message: string): void => {
this.data.push(message);
};
@action
remove = (index: number): void => {
this.data.splice(index, 1);
};
}
export default ErrorsStore;

View File

@ -1,27 +0,0 @@
/* eslint-disable */
import ErrorsStore from './ErrorsStore';
// Actions
describe('ErrorsStore', () => {
let store;
beforeEach(() => {
store = new ErrorsStore();
});
test('#add should add errors', () => {
expect(store.data.length).toBe(0);
store.add('first error');
store.add('second error');
expect(store.data.length).toBe(2);
});
test('#remove should remove errors', () => {
store.add('first error');
store.add('second error');
expect(store.data.length).toBe(2);
store.remove(0);
expect(store.data.length).toBe(1);
expect(store.data[0]).toBe('second error');
});
});

View File

@ -3,8 +3,7 @@ import { observable, computed, action, runInAction, ObservableMap } from 'mobx';
import { client } from 'utils/ApiClient'; import { client } from 'utils/ApiClient';
import _ from 'lodash'; import _ from 'lodash';
import invariant from 'invariant'; import invariant from 'invariant';
import stores from './'; import UiStore from './UiStore';
import ErrorsStore from './ErrorsStore';
import BaseStore from './BaseStore'; import BaseStore from './BaseStore';
import Integration from 'models/Integration'; import Integration from 'models/Integration';
@ -15,7 +14,7 @@ class IntegrationsStore extends BaseStore {
@observable isLoaded: boolean = false; @observable isLoaded: boolean = false;
@observable isFetching: boolean = false; @observable isFetching: boolean = false;
errors: ErrorsStore; ui: UiStore;
@computed @computed
get orderedData(): Integration[] { get orderedData(): Integration[] {
@ -43,7 +42,7 @@ class IntegrationsStore extends BaseStore {
}); });
return res; return res;
} catch (e) { } catch (e) {
this.errors.add('Failed to load integrations'); this.ui.showToast('Failed to load integrations');
} finally { } finally {
this.isFetching = false; this.isFetching = false;
} }
@ -63,9 +62,9 @@ class IntegrationsStore extends BaseStore {
return this.data.get(id); return this.data.get(id);
}; };
constructor() { constructor(options: { ui: UiStore }) {
super(); super();
this.errors = stores.errors; this.ui = options.ui;
this.on('integrations.delete', (data: { id: string }) => { this.on('integrations.delete', (data: { id: string }) => {
this.remove(data.id); this.remove(data.id);

View File

@ -11,6 +11,7 @@ class UiStore {
@observable progressBarVisible: boolean = false; @observable progressBarVisible: boolean = false;
@observable editMode: boolean = false; @observable editMode: boolean = false;
@observable mobileSidebarVisible: boolean = false; @observable mobileSidebarVisible: boolean = false;
@observable toasts: string[] = observable.array([]);
/* Actions */ /* Actions */
@action @action
@ -79,6 +80,16 @@ class UiStore {
hideMobileSidebar() { hideMobileSidebar() {
this.mobileSidebarVisible = false; this.mobileSidebarVisible = false;
} }
@action
showToast = (message: string): void => {
this.toasts.push(message);
};
@action
removeToast = (index: number): void => {
this.toasts.splice(index, 1);
};
} }
export default UiStore; export default UiStore;

View File

@ -0,0 +1,27 @@
/* eslint-disable */
import UiStore from './UiStore';
// Actions
describe('UiStore', () => {
let store;
beforeEach(() => {
store = new UiStore();
});
test('#add should add errors', () => {
expect(store.data.length).toBe(0);
store.showToast('first error');
store.showToast('second error');
expect(store.toasts.length).toBe(2);
});
test('#remove should remove errors', () => {
store.showToast('first error');
store.showToast('second error');
expect(store.toasts.length).toBe(2);
store.removeToast(0);
expect(store.toasts.length).toBe(1);
expect(store.toasts[0]).toBe('second error');
});
});

View File

@ -1,18 +1,15 @@
// @flow // @flow
import AuthStore from './AuthStore'; import AuthStore from './AuthStore';
import UiStore from './UiStore'; import UiStore from './UiStore';
import ErrorsStore from './ErrorsStore';
import DocumentsStore from './DocumentsStore'; import DocumentsStore from './DocumentsStore';
import SharesStore from './SharesStore'; import SharesStore from './SharesStore';
const ui = new UiStore(); const ui = new UiStore();
const errors = new ErrorsStore();
const stores = { const stores = {
user: null, // Including for Layout user: null, // Including for Layout
auth: new AuthStore(), auth: new AuthStore(),
ui, ui,
errors, documents: new DocumentsStore({ ui }),
documents: new DocumentsStore({ ui, errors }),
shares: new SharesStore(), shares: new SharesStore(),
}; };

View File

@ -8,7 +8,7 @@
"build:analyze": "NODE_ENV=production webpack --config webpack.config.prod.js --json > stats.json", "build:analyze": "NODE_ENV=production webpack --config webpack.config.prod.js --json > stats.json",
"build": "npm run clean && npm run build:webpack", "build": "npm run clean && npm run build:webpack",
"start": "NODE_ENV=production node index.js", "start": "NODE_ENV=production node index.js",
"dev": "NODE_ENV=development nodemon --watch server index.js", "dev": "NODE_ENV=development node index.js",
"lint": "npm run lint:flow && npm run lint:js", "lint": "npm run lint:flow && npm run lint:js",
"lint:js": "eslint app server", "lint:js": "eslint app server",
"lint:flow": "flow", "lint:flow": "flow",

View File

@ -34,7 +34,10 @@ module.exports = {
include: [ include: [
path.join(__dirname, 'app'), path.join(__dirname, 'app'),
path.join(__dirname, 'shared'), path.join(__dirname, 'shared'),
] ],
options: {
cacheDirectory: true
}
}, },
{ test: /\.json$/, loader: 'json-loader' }, { test: /\.json$/, loader: 'json-loader' },
// inline base64 URLs for <=8k images, direct URLs for the rest // inline base64 URLs for <=8k images, direct URLs for the rest