Fixes to editing

This commit is contained in:
Jori Lallo
2016-07-06 21:37:52 -07:00
parent 459c393154
commit 6f33caca45
4 changed files with 189 additions and 150 deletions

View File

@@ -17,13 +17,13 @@ import { client } from 'utils/ApiClient';
@observer @observer
class MarkdownEditor extends React.Component { class MarkdownEditor extends React.Component {
static propTypes = { static propTypes = {
text: React.PropTypes.string.isRequired, text: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired,
replaceText: React.PropTypes.func.isRequired, replaceText: React.PropTypes.func.isRequired,
// This is actually not used but it triggers // This is actually not used but it triggers
// re-render to help with CodeMirror focus issues // re-render to help with CodeMirror focus issues
preview: React.PropTypes.bool.isRequired, preview: React.PropTypes.bool,
} }
getEditorInstance = () => { getEditorInstance = () => {

View File

@@ -1,8 +1,10 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import { observer } from 'mobx-react'; import { observer } from 'mobx-react';
import { browserHistory } from 'react-router'; import { browserHistory, withRouter } from 'react-router';
import store from './DocumentEditStore'; import DocumentEditStore, {
DOCUMENT_EDIT_SETTINGS,
} from './DocumentEditStore';
import Switch from 'components/Switch'; import Switch from 'components/Switch';
import Layout, { Title, HeaderAction } from 'components/Layout'; import Layout, { Title, HeaderAction } from 'components/Layout';
@@ -14,26 +16,43 @@ import DropdownMenu, { MenuItem } from 'components/DropdownMenu';
import EditorLoader from './components/EditorLoader'; import EditorLoader from './components/EditorLoader';
import SaveAction from './components/SaveAction'; import SaveAction from './components/SaveAction';
import styles from './DocumentEdit.scss'; const DISREGARD_CHANGES = `You have unsaved changes.
import classNames from 'classnames/bind'; Are you sure you want to disgard them?`;
const cx = classNames.bind(styles);
@withRouter
@observer @observer
class DocumentEdit extends Component { class DocumentEdit extends Component {
static store;
static propTypes = {
route: React.PropTypes.object.isRequired,
router: React.PropTypes.object.isRequired,
params: React.PropTypes.object,
}
state = {
scrollTop: 0,
}
constructor(props) {
super(props);
this.store = new DocumentEditStore(
JSON.parse(localStorage[DOCUMENT_EDIT_SETTINGS] || '{}')
);
}
componentDidMount = () => { componentDidMount = () => {
// This is a bit hacky, should find a better way
store.reset();
if (this.props.route.newDocument) { if (this.props.route.newDocument) {
store.atlasId = this.props.params.id; this.store.atlasId = this.props.params.id;
store.newDocument = true; this.store.newDocument = true;
} else if (this.props.route.newChildDocument) { } else if (this.props.route.newChildDocument) {
store.documentId = this.props.params.id; this.store.documentId = this.props.params.id;
store.newChildDocument = true; this.store.newChildDocument = true;
store.fetchDocument(); this.store.fetchDocument();
} else { } else {
store.documentId = this.props.params.id; this.store.documentId = this.props.params.id;
store.newDocument = false; this.store.newDocument = false;
store.fetchDocument(); this.store.fetchDocument();
} }
// Load editor async // Load editor async
@@ -41,6 +60,14 @@ class DocumentEdit extends Component {
.then(({ Editor }) => { .then(({ Editor }) => {
this.setState({ Editor }); this.setState({ Editor });
}); });
// Set onLeave hook
this.props.router.setRouteLeaveHook(this.props.route, () => {
if (this.store.hasPendingChanges) {
return confirm(DISREGARD_CHANGES);
}
return;
});
} }
onSave = () => { onSave = () => {
@@ -48,10 +75,10 @@ class DocumentEdit extends Component {
// alert("Please add a title before saving (hint: Write a markdown header)"); // alert("Please add a title before saving (hint: Write a markdown header)");
// return // return
// } // }
if (store.newDocument || store.newChildDocument) { if (this.store.newDocument || this.store.newChildDocument) {
store.saveDocument(); this.store.saveDocument();
} else { } else {
store.updateDocument(); this.store.updateDocument();
} }
} }
@@ -59,43 +86,37 @@ class DocumentEdit extends Component {
browserHistory.goBack(); browserHistory.goBack();
} }
state = {
scrollTop: 0,
}
onScroll = (scrollTop) => { onScroll = (scrollTop) => {
this.setState({ this.setState({
scrollTop: scrollTop, scrollTop,
}) });
}
onPreviewToggle = () => {
store.togglePreview();
} }
render() { render() {
console.log("DocumentEdit#render", this.store.preview);
let title = ( let title = (
<Title <Title
truncate={ 60 } truncate={ 60 }
placeholder={ "Untitle document" } placeholder={ "Untitle document" }
> >
{ store.title } { this.store.title }
</Title> </Title>
); );
let titleText = store.title; let titleText = this.store.title;
const actions = ( const actions = (
<Flex direction="row"> <Flex direction="row">
<HeaderAction> <HeaderAction>
<SaveAction <SaveAction
onClick={ this.onSave } onClick={ this.onSave }
disabled={ store.isSaving } disabled={ this.store.isSaving }
/> />
</HeaderAction> </HeaderAction>
<DropdownMenu label="More"> <DropdownMenu label="More">
<MenuItem onClick={ this.onPreviewToggle }> <MenuItem onClick={ this.store.togglePreview }>
Preview <Switch checked={ store.preview } /> Preview <Switch checked={ this.store.preview } />
</MenuItem> </MenuItem>
<MenuItem onClick={ this.onCancel }> <MenuItem onClick={ this.onCancel }>
Cancel Cancel
@@ -109,16 +130,16 @@ class DocumentEdit extends Component {
actions={ actions } actions={ actions }
title={ title } title={ title }
titleText={ titleText } titleText={ titleText }
fixed={ true } fixed
loading={ store.isSaving } loading={ this.store.isSaving }
> >
{ (store.isFetching || !('Editor' in this.state)) ? ( { (this.store.isFetching || !('Editor' in this.state)) ? (
<CenteredContent> <CenteredContent>
<AtlasPreviewLoading /> <AtlasPreviewLoading />
</CenteredContent> </CenteredContent>
) : ( ) : (
<this.state.Editor <this.state.Editor
store={ store } store={ this.store }
scrollTop={ this.state.scrollTop } scrollTop={ this.state.scrollTop }
onScroll={ this.onScroll } onScroll={ this.onScroll }
/> />

View File

@@ -1,6 +1,5 @@
import { observable, action, computed, autorun, toJS } from 'mobx'; import { observable, action, toJS, autorun } from 'mobx';
import { client } from 'utils/ApiClient'; import { client } from 'utils/ApiClient';
import localforage from 'localforage';
import { browserHistory } from 'react-router'; import { browserHistory } from 'react-router';
import emojify from 'utils/emojify'; import emojify from 'utils/emojify';
@@ -8,19 +7,25 @@ const DOCUMENT_EDIT_SETTINGS = 'DOCUMENT_EDIT_SETTINGS';
const parseHeader = (text) => { const parseHeader = (text) => {
const firstLine = text.split(/\r?\n/)[0]; const firstLine = text.split(/\r?\n/)[0];
if (firstLine) {
const match = firstLine.match(/^#+ +(.*)$/); const match = firstLine.match(/^#+ +(.*)$/);
if (match) { if (match) {
return emojify(match[1]); return emojify(match[1]);
} else {
return '';
} }
} }
return '';
};
const documentEditStore = new class DocumentEditStore { class DocumentEditStore {
@observable documentId = null; @observable documentId = null;
@observable atlasId = null; @observable atlasId = null;
@observable parentDocument; @observable parentDocument;
@observable title; @observable title;
@observable text; @observable text;
@observable hasPendingChanges = false;
@observable newDocument; @observable newDocument;
@observable newChildDocument; @observable newChildDocument;
@@ -36,7 +41,7 @@ const documentEditStore = new class DocumentEditStore {
try { try {
const data = await client.post('/documents.info', { const data = await client.post('/documents.info', {
id: this.documentId, id: this.documentId,
}) });
if (this.newChildDocument) { if (this.newChildDocument) {
this.parentDocument = data.data; this.parentDocument = data.data;
} else { } else {
@@ -45,12 +50,12 @@ const documentEditStore = new class DocumentEditStore {
this.text = text; this.text = text;
} }
} catch (e) { } catch (e) {
console.error("Something went wrong"); console.error('Something went wrong');
} }
this.isFetching = false; this.isFetching = false;
} }
@action saveDocument = async (nextPath) => { @action saveDocument = async () => {
if (this.isSaving) return; if (this.isSaving) return;
this.isSaving = true; this.isSaving = true;
@@ -61,8 +66,10 @@ const documentEditStore = new class DocumentEditStore {
atlas: this.atlasId || this.parentDocument.atlas.id, atlas: this.atlasId || this.parentDocument.atlas.id,
title: this.title, title: this.title,
text: this.text, text: this.text,
}) });
const { id } = data.data; const { id } = data.data;
this.hasPendingChanges = false;
browserHistory.push(`/documents/${id}`); browserHistory.push(`/documents/${id}`);
} catch (e) { } catch (e) {
console.error("Something went wrong"); console.error("Something went wrong");
@@ -70,17 +77,19 @@ const documentEditStore = new class DocumentEditStore {
this.isSaving = false; this.isSaving = false;
} }
@action updateDocument = async (nextPath) => { @action updateDocument = async () => {
if (this.isSaving) return; if (this.isSaving) return;
this.isSaving = true; this.isSaving = true;
try { try {
const data = await client.post('/documents.update', { await client.post('/documents.update', {
id: this.documentId, id: this.documentId,
title: this.title, title: this.title,
text: this.text, text: this.text,
}) });
this.hasPendingChanges = false;
browserHistory.push(`/documents/${this.documentId}`); browserHistory.push(`/documents/${this.documentId}`);
} catch (e) { } catch (e) {
console.error("Something went wrong"); console.error("Something went wrong");
@@ -91,6 +100,7 @@ const documentEditStore = new class DocumentEditStore {
@action updateText = (text) => { @action updateText = (text) => {
this.text = text; this.text = text;
this.title = parseHeader(text); this.title = parseHeader(text);
this.hasPendingChanges = true;
} }
@action updateTitle = (title) => { @action updateTitle = (title) => {
@@ -99,6 +109,7 @@ const documentEditStore = new class DocumentEditStore {
@action replaceText = (args) => { @action replaceText = (args) => {
this.text = this.text.replace(args.original, args.new); this.text = this.text.replace(args.original, args.new);
this.hasPendingChanges = true;
} }
@action togglePreview = () => { @action togglePreview = () => {
@@ -110,20 +121,27 @@ const documentEditStore = new class DocumentEditStore {
this.text = '# Lets start with a title\n\nAnd continue from there...'; this.text = '# Lets start with a title\n\nAnd continue from there...';
} }
constructor() { // Generic
// Rehydrate settings
localforage.getItem(DOCUMENT_EDIT_SETTINGS) persistSettings = () => {
.then(data => { localStorage[DOCUMENT_EDIT_SETTINGS] = JSON.stringify({
this.preview = data.preview; preview: toJS(this.preview),
}); });
} }
}();
constructor(settings) {
// Rehydrate settings
this.preview = settings.preview
// Persist settings to localStorage // Persist settings to localStorage
// TODO: This could be done more selectively
autorun(() => { autorun(() => {
localforage.setItem(DOCUMENT_EDIT_SETTINGS, { this.persistSettings();
preview: documentEditStore.preview,
});
}); });
}
};
export default documentEditStore; export default DocumentEditStore;
export {
DOCUMENT_EDIT_SETTINGS
};

View File

@@ -2,7 +2,7 @@ import emojiMapping from './emoji-mapping.json';
const EMOJI_REGEX = /:([A-Za-z0-9_\-\+]+?):/gm; const EMOJI_REGEX = /:([A-Za-z0-9_\-\+]+?):/gm;
const emojify = (text) => { const emojify = (text='') => {
const emojis = text.match(EMOJI_REGEX) || []; const emojis = text.match(EMOJI_REGEX) || [];
let emojifiedText = text; let emojifiedText = text;