Merge master

This commit is contained in:
Tom Moor 2017-09-13 19:18:49 -07:00
commit 00d18ceda3
27 changed files with 581 additions and 144 deletions

View File

@ -17,32 +17,6 @@ type Props = {
component?: string, component?: string,
}; };
const Wrapper = styled.div`
display: inline;
margin-left: ${props => (props.hasEmoji ? '-1.2em' : 0)}
`;
const Anchor = styled.a`
visibility: hidden;
padding-left: .25em;
color: #dedede;
&:hover {
color: #cdcdcd;
}
`;
// $FlowIssue I don't know
const titleStyles = component => styled(component)`
position: relative;
&:hover {
${Anchor} {
visibility: visible;
}
}
`;
function Heading(props: Props) { function Heading(props: Props) {
const { const {
parent, parent,
@ -58,7 +32,7 @@ function Heading(props: Props) {
const showPlaceholder = placeholder && firstHeading && !node.text; const showPlaceholder = placeholder && firstHeading && !node.text;
const slugish = _.escape(`${component}-${slug(node.text)}`); const slugish = _.escape(`${component}-${slug(node.text)}`);
const showHash = readOnly && !!slugish; const showHash = readOnly && !!slugish;
const Component = titleStyles(component); const Component = component;
const emoji = editor.props.emoji || ''; const emoji = editor.props.emoji || '';
const title = node.text.trim(); const title = node.text.trim();
const startsWithEmojiAndSpace = const startsWithEmojiAndSpace =
@ -76,4 +50,32 @@ function Heading(props: Props) {
); );
} }
const Wrapper = styled.div`
display: inline;
margin-left: ${props => (props.hasEmoji ? '-1.2em' : 0)}
`;
const Anchor = styled.a`
visibility: hidden;
padding-left: .25em;
color: #dedede;
&:hover {
color: #cdcdcd;
}
`;
export const Heading1 = styled(Heading)`
&:hover {
${Anchor} {
visibility: visible;
}
}
`;
export const Heading2 = Heading1.withComponent('h2');
export const Heading3 = Heading1.withComponent('h3');
export const Heading4 = Heading1.withComponent('h4');
export const Heading5 = Heading1.withComponent('h5');
export const Heading6 = Heading1.withComponent('h6');
export default Heading; export default Heading;

View File

@ -6,7 +6,14 @@ import InlineCode from './components/InlineCode';
import Image from './components/Image'; import Image from './components/Image';
import Link from './components/Link'; import Link from './components/Link';
import ListItem from './components/ListItem'; import ListItem from './components/ListItem';
import Heading from './components/Heading'; import {
Heading1,
Heading2,
Heading3,
Heading4,
Heading5,
Heading6,
} from './components/Heading';
import Paragraph from './components/Paragraph'; import Paragraph from './components/Paragraph';
import type { Props, Node, Transform } from './types'; import type { Props, Node, Transform } from './types';
@ -47,12 +54,12 @@ const createSchema = () => {
image: Image, image: Image,
link: Link, link: Link,
'list-item': ListItem, 'list-item': ListItem,
heading1: (props: Props) => <Heading placeholder {...props} />, heading1: (props: Props) => <Heading1 placeholder {...props} />,
heading2: (props: Props) => <Heading component="h2" {...props} />, heading2: (props: Props) => <Heading2 {...props} />,
heading3: (props: Props) => <Heading component="h3" {...props} />, heading3: (props: Props) => <Heading3 {...props} />,
heading4: (props: Props) => <Heading component="h4" {...props} />, heading4: (props: Props) => <Heading4 {...props} />,
heading5: (props: Props) => <Heading component="h5" {...props} />, heading5: (props: Props) => <Heading5 {...props} />,
heading6: (props: Props) => <Heading component="h6" {...props} />, heading6: (props: Props) => <Heading6 {...props} />,
}, },
rules: [ rules: [

View File

@ -0,0 +1,21 @@
// @flow
import React from 'react';
import Icon from './Icon';
import type { Props } from './Icon';
export default function NextIcon(props: Props) {
return (
<Icon {...props}>
<svg
fill="#000000"
height="24"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
<path d="M0 0h24v24H0z" fill="none" />
</svg>
</Icon>
);
}

View File

@ -24,7 +24,7 @@ const RealInput = styled.input`
background: none; background: none;
&::placeholder { &::placeholder {
color: ${color.slateLight}; color: ${color.slate};
} }
`; `;
@ -55,7 +55,7 @@ const LabelText = styled.div`
export type Props = { export type Props = {
type: string, type: string,
value: string, value?: string,
label?: string, label?: string,
className?: string, className?: string,
}; };

View File

@ -0,0 +1,29 @@
// @flow
import React from 'react';
import { observer } from 'mobx-react';
import Flex from 'components/Flex';
import styled from 'styled-components';
import { size } from 'styles/constants';
type Props = {
label: React.Element<*> | string,
children: React.Element<*>,
};
const Labeled = ({ label, children, ...props }: Props) => (
<Flex column {...props}>
<Header>{label}</Header>
{children}
</Flex>
);
const Header = styled(Flex)`
margin-bottom: ${size.medium};
font-size: 13px;
font-weight: 500;
text-transform: uppercase;
color: #9FA6AB;
letter-spacing: 0.04em;
`;
export default observer(Labeled);

View File

@ -0,0 +1,3 @@
// @flow
import Labeled from './Labeled';
export default Labeled;

View File

@ -43,7 +43,7 @@ const activeStyle = {
{!canDropToImport && {!canDropToImport &&
<SidebarLink to={doc.url}>{doc.title}</SidebarLink>} <SidebarLink to={doc.url}>{doc.title}</SidebarLink>}
{(document.pathToDocument.includes(doc.id) || {(document.pathToDocument.map(entry => entry.id).includes(doc.id) ||
document.id === doc.id) && document.id === doc.id) &&
<Children column> <Children column>
{doc.children && this.renderDocuments(doc.children, depth + 1)} {doc.children && this.renderDocuments(doc.children, depth + 1)}

View File

@ -1,5 +1,6 @@
// @flow // @flow
import React from 'react'; import React from 'react';
import { observer } from 'mobx-react';
import styled from 'styled-components'; import styled from 'styled-components';
import ReactModal from 'react-modal'; import ReactModal from 'react-modal';
import { color } from 'styles/constants'; import { color } from 'styles/constants';
@ -75,4 +76,4 @@ const Close = styled.a`
} }
`; `;
export default Modal; export default observer(Modal);

View File

@ -39,6 +39,8 @@ import RouteSidebarHidden from 'components/RouteSidebarHidden';
import flatpages from 'static/flatpages'; import flatpages from 'static/flatpages';
import { matchDocumentSlug } from 'utils/routeHelpers';
let DevTools; let DevTools;
if (__DEV__) { if (__DEV__) {
DevTools = require('mobx-react-devtools').default; // eslint-disable-line global-require DevTools = require('mobx-react-devtools').default; // eslint-disable-line global-require
@ -93,8 +95,6 @@ const RedirectDocument = ({ match }: { match: Object }) => (
<Redirect to={`/doc/${match.params.documentSlug}`} /> <Redirect to={`/doc/${match.params.documentSlug}`} />
); );
const matchDocumentSlug = ':documentSlug([0-9a-zA-Z-]*-[a-zA-z0-9]{10,15})';
render( render(
<div style={{ display: 'flex', flex: 1, height: '100%' }}> <div style={{ display: 'flex', flex: 1, height: '100%' }}>
<Provider {...stores}> <Provider {...stores}>
@ -123,6 +123,11 @@ render(
path={`/doc/${matchDocumentSlug}`} path={`/doc/${matchDocumentSlug}`}
component={Document} component={Document}
/> />
<Route
exact
path={`/doc/${matchDocumentSlug}/move`}
component={Document}
/>
<Route exact path="/search" component={Search} /> <Route exact path="/search" component={Search} />
<Route exact path="/search/:query" component={Search} /> <Route exact path="/search/:query" component={Search} />
@ -132,7 +137,7 @@ render(
<RouteSidebarHidden <RouteSidebarHidden
exact exact
path={`/doc/${matchDocumentSlug}/:edit`} path={`/doc/${matchDocumentSlug}/edit`}
component={Document} component={Document}
/> />
<RouteSidebarHidden <RouteSidebarHidden

View File

@ -99,7 +99,7 @@ class Collection extends BaseModel {
return false; return false;
}; };
updateData(data: Object = {}) { @action updateData(data: Object = {}) {
this.data = data; this.data = data;
extendObservable(this, data); extendObservable(this, data);
} }
@ -113,6 +113,17 @@ class Collection extends BaseModel {
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();
}); });
this.on(
'collections.update',
(data: { id: string, collection: Collection }) => {
// FIXME: calling this.updateData won't update the
// UI. Some mobx issue
if (data.id === this.id) this.fetch();
}
);
this.on('documents.move', (data: { collectionId: string }) => {
if (data.collectionId === this.id) this.fetch();
});
} }
} }

View File

@ -47,11 +47,17 @@ class Document extends BaseModel {
return !!this.lastViewedAt && this.lastViewedAt < this.updatedAt; return !!this.lastViewedAt && this.lastViewedAt < this.updatedAt;
} }
@computed get pathToDocument(): Array<string> { @computed get pathToDocument(): Array<{ id: string, title: string }> {
let path; let path;
const traveler = (nodes, previousPath) => { const traveler = (nodes, previousPath) => {
nodes.forEach(childNode => { nodes.forEach(childNode => {
const newPath = [...previousPath, childNode.id]; const newPath = [
...previousPath,
{
id: childNode.id,
title: childNode.title,
},
];
if (childNode.id === this.id) { if (childNode.id === this.id) {
path = newPath; path = newPath;
return; return;
@ -170,6 +176,11 @@ class Document extends BaseModel {
this.updateData(res.data); this.updateData(res.data);
this.hasPendingChanges = false; this.hasPendingChanges = false;
}); });
this.emit('collections.update', {
id: this.collection.id,
collection: this.collection,
});
} catch (e) { } catch (e) {
this.errors.add('Document failed saving'); this.errors.add('Document failed saving');
} finally { } finally {
@ -179,6 +190,24 @@ class Document extends BaseModel {
return this; return this;
}; };
@action move = async (parentDocumentId: ?string) => {
try {
const res = await client.post('/documents.move', {
id: this.id,
parentDocument: parentDocumentId,
});
invariant(res && res.data, 'Data not available');
this.updateData(res.data);
this.emit('documents.move', {
id: this.id,
collectionId: this.collection.id,
});
} catch (e) {
this.errors.add('Error while moving the document');
}
return;
};
@action delete = async () => { @action delete = async () => {
try { try {
await client.post('/documents.delete', { id: this.id }); await client.post('/documents.delete', { id: this.id });

View File

@ -2,13 +2,21 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import get from 'lodash/get'; import get from 'lodash/get';
import styled from 'styled-components'; import styled from 'styled-components';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react'; import { observer, inject } from 'mobx-react';
import { withRouter, Prompt } from 'react-router'; import { withRouter, Prompt } from 'react-router';
import keydown from 'react-keydown';
import Flex from 'components/Flex'; import Flex from 'components/Flex';
import { color, layout } from 'styles/constants'; import { color, layout } from 'styles/constants';
import { collectionUrl } from 'utils/routeHelpers'; import {
collectionUrl,
updateDocumentUrl,
matchDocumentEdit,
matchDocumentMove,
} from 'utils/routeHelpers';
import Document from 'models/Document'; import Document from 'models/Document';
import DocumentMove from './components/DocumentMove';
import UiStore from 'stores/UiStore'; import UiStore from 'stores/UiStore';
import DocumentsStore from 'stores/DocumentsStore'; import DocumentsStore from 'stores/DocumentsStore';
import DocumentMenu from 'menus/DocumentMenu'; import DocumentMenu from 'menus/DocumentMenu';
@ -39,17 +47,16 @@ type Props = {
@observer class DocumentScene extends Component { @observer class DocumentScene extends Component {
props: Props; props: Props;
savedTimeout: number; savedTimeout: number;
state: {
newDocument?: Document, @observable editCache: ?string;
}; @observable newDocument: ?Document;
state = { @observable isDragging = false;
isDragging: false, @observable isLoading = false;
isLoading: false, @observable isSaving = false;
isSaving: false, @observable showAsSaved = false;
newDocument: undefined, @observable notFound = false;
showAsSaved: false,
notFound: false, @observable moveModalOpen: boolean = false;
};
componentDidMount() { componentDidMount() {
this.loadDocument(this.props); this.loadDocument(this.props);
@ -60,7 +67,7 @@ type Props = {
nextProps.match.params.documentSlug !== nextProps.match.params.documentSlug !==
this.props.match.params.documentSlug this.props.match.params.documentSlug
) { ) {
this.setState({ notFound: false }); this.notFound = false;
this.loadDocument(nextProps); this.loadDocument(nextProps);
} }
} }
@ -70,6 +77,12 @@ type Props = {
this.props.ui.clearActiveDocument(); this.props.ui.clearActiveDocument();
} }
@keydown('m')
goToMove(event) {
event.preventDefault();
if (this.document) this.props.history.push(`${this.document.url}/move`);
}
loadDocument = async props => { loadDocument = async props => {
if (props.newDocument) { if (props.newDocument) {
const newDocument = new Document({ const newDocument = new Document({
@ -77,7 +90,7 @@ type Props = {
title: '', title: '',
text: '', text: '',
}); });
this.setState({ newDocument }); this.newDocument = newDocument;
} else { } else {
let document = this.document; let document = this.document;
if (document) { if (document) {
@ -89,16 +102,23 @@ type Props = {
if (document) { if (document) {
this.props.ui.setActiveDocument(document); this.props.ui.setActiveDocument(document);
// Cache data if user enters edit mode and cancels
this.editCache = document.text;
document.view(); document.view();
// Update url to match the current one
this.props.history.replace(
updateDocumentUrl(this.props.match.url, document.url)
);
} else { } else {
// Render 404 with search // Render 404 with search
this.setState({ notFound: true }); this.notFound = true;
} }
} }
}; };
get document() { get document() {
if (this.state.newDocument) return this.state.newDocument; if (this.newDocument) return this.newDocument;
return this.props.documents.getByUrl( return this.props.documents.getByUrl(
`/doc/${this.props.match.params.documentSlug}` `/doc/${this.props.match.params.documentSlug}`
); );
@ -115,36 +135,38 @@ type Props = {
this.props.history.push(`${this.document.collection.url}/new`); this.props.history.push(`${this.document.collection.url}/new`);
}; };
handleCloseMoveModal = () => (this.moveModalOpen = false);
handleOpenMoveModal = () => (this.moveModalOpen = true);
onSave = async (redirect: boolean = false) => { onSave = async (redirect: boolean = false) => {
if (this.document && !this.document.allowSave) return; if (this.document && !this.document.allowSave) return;
let document = this.document; let document = this.document;
if (!document) return; if (!document) return;
this.setState({ isLoading: true, isSaving: true }); this.isLoading = true;
this.isSaving = true;
document = await document.save(); document = await document.save();
this.setState({ isLoading: false }); this.isLoading = false;
if (redirect || this.props.newDocument) { if (redirect || this.props.newDocument) {
this.props.history.push(document.url); this.props.history.push(document.url);
} else { } else {
this.showAsSaved(); this.toggleShowAsSaved();
} }
}; };
showAsSaved() { toggleShowAsSaved() {
this.setState({ showAsSaved: true, isSaving: false }); this.showAsSaved = true;
this.savedTimeout = setTimeout( this.isSaving = false;
() => this.setState({ showAsSaved: false }), this.savedTimeout = setTimeout(() => (this.showAsSaved = false), 2000);
2000
);
} }
onImageUploadStart = () => { onImageUploadStart = () => {
this.setState({ isLoading: true }); this.isLoading = true;
}; };
onImageUploadStop = () => { onImageUploadStop = () => {
this.setState({ isLoading: false }); this.isLoading = false;
}; };
onChange = text => { onChange = text => {
@ -156,6 +178,7 @@ type Props = {
let url; let url;
if (this.document && this.document.url) { if (this.document && this.document.url) {
url = this.document.url; url = this.document.url;
if (this.editCache) this.document.updateData({ text: this.editCache });
} else { } else {
url = collectionUrl(this.props.match.params.id); url = collectionUrl(this.props.match.params.id);
} }
@ -163,11 +186,11 @@ type Props = {
}; };
onStartDragging = () => { onStartDragging = () => {
this.setState({ isDragging: true }); this.isDragging = true;
}; };
onStopDragging = () => { onStopDragging = () => {
this.setState({ isDragging: false }); this.isDragging = false;
}; };
renderNotFound() { renderNotFound() {
@ -176,23 +199,26 @@ type Props = {
render() { render() {
const isNew = this.props.newDocument; const isNew = this.props.newDocument;
const isEditing = !!this.props.match.params.edit || isNew; const isMoving = this.props.match.path === matchDocumentMove;
const isEditing = this.props.match.path === matchDocumentEdit || isNew;
const isFetching = !this.document; const isFetching = !this.document;
const titleText = get(this.document, 'title', ''); const titleText = get(this.document, 'title', '');
const document = this.document; const document = this.document;
if (this.state.notFound) { if (this.notFound) {
return this.renderNotFound(); return this.renderNotFound();
} }
return ( return (
<Container column auto> <Container column auto>
{this.state.isDragging && {isMoving && document && <DocumentMove document={document} />}
{this.isDragging &&
<DropHere align="center" justify="center"> <DropHere align="center" justify="center">
Drop files here to import into Atlas. Drop files here to import into Atlas.
</DropHere>} </DropHere>}
{titleText && <PageTitle title={titleText} />} {titleText && <PageTitle title={titleText} />}
{this.state.isLoading && <LoadingIndicator />} {this.isLoading && <LoadingIndicator />}
{isFetching && {isFetching &&
<CenteredContent> <CenteredContent>
<LoadingState /> <LoadingState />
@ -231,11 +257,11 @@ type Props = {
<HeaderAction> <HeaderAction>
{isEditing {isEditing
? <SaveAction ? <SaveAction
isSaving={this.state.isSaving} isSaving={this.isSaving}
onClick={this.onSave.bind(this, true)} onClick={this.onSave.bind(this, true)}
disabled={ disabled={
!(this.document && this.document.allowSave) || !(this.document && this.document.allowSave) ||
this.state.isSaving this.isSaving
} }
isNew={!!isNew} isNew={!!isNew}
/> />

View File

@ -0,0 +1,153 @@
// @flow
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { observable, action } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router';
import ArrowKeyNavigation from 'boundless-arrow-key-navigation';
import _ from 'lodash';
import styled from 'styled-components';
import { size } from 'styles/constants';
import Modal from 'components/Modal';
import Input from 'components/Input';
import Labeled from 'components/Labeled';
import Flex from 'components/Flex';
import PathToDocument from './components/PathToDocument';
import Document from 'models/Document';
import DocumentsStore from 'stores/DocumentsStore';
type Props = {
match: Object,
history: Object,
document: Document,
documents: DocumentsStore,
};
@observer class DocumentMove extends Component {
props: Props;
firstDocument: HTMLElement;
@observable isSaving: boolean;
@observable resultIds: Array<string> = []; // Document IDs
@observable searchTerm: ?string = null;
@observable isFetching = false;
componentDidMount() {
this.setDefaultResult();
}
handleKeyDown = ev => {
// Down
if (ev.which === 40) {
ev.preventDefault();
if (this.firstDocument) {
const element = ReactDOM.findDOMNode(this.firstDocument);
// $FlowFixMe
if (element && element.focus) element.focus();
}
}
};
handleClose = () => {
this.props.history.push(this.props.document.url);
};
handleFilter = (e: SyntheticInputEvent) => {
const value = e.target.value;
this.searchTerm = value;
this.updateSearchResults();
};
updateSearchResults = _.debounce(() => {
this.search();
}, 250);
setFirstDocumentRef = ref => {
this.firstDocument = ref;
};
@action setDefaultResult() {
this.resultIds = this.props.document.collection.documents.map(
doc => doc.id
);
}
@action search = async () => {
this.isFetching = true;
if (this.searchTerm) {
try {
this.resultIds = await this.props.documents.search(this.searchTerm);
} catch (e) {
console.error('Something went wrong');
}
} else {
this.setDefaultResult();
}
this.isFetching = false;
};
render() {
const { document, documents } = this.props;
return (
<Modal isOpen onRequestClose={this.handleClose} title="Move document">
<Section>
<Labeled label="Current location">
<PathToDocument documentId={document.id} documents={documents} />
</Labeled>
</Section>
<Section column>
<Labeled label="Choose a new location">
<Input
type="text"
placeholder="Filter by document name"
onKeyDown={this.handleKeyDown}
onChange={this.handleFilter}
required
autoFocus
/>
</Labeled>
<Flex column>
<StyledArrowKeyNavigation
mode={ArrowKeyNavigation.mode.VERTICAL}
defaultActiveChildIndex={0}
>
<PathToDocument
document={document}
documents={documents}
ref={ref => this.setFirstDocumentRef(ref)}
onSuccess={this.handleClose}
/>
{this.resultIds.map((documentId, index) => (
<PathToDocument
key={documentId}
documentId={documentId}
documents={documents}
document={document}
onSuccess={this.handleClose}
/>
))}
</StyledArrowKeyNavigation>
</Flex>
</Section>
</Modal>
);
}
}
const Section = styled(Flex)`
margin-bottom: ${size.huge};
`;
const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
display: flex;
flex-direction: column;
flex: 1;
`;
export default withRouter(inject('documents')(DocumentMove));

View File

@ -0,0 +1,99 @@
// @flow
import React from 'react';
import { observer } from 'mobx-react';
import _ from 'lodash';
import invariant from 'invariant';
import styled from 'styled-components';
import { color } from 'styles/constants';
import Flex from 'components/Flex';
import ChevronIcon from 'components/Icon/ChevronIcon';
import Document from 'models/Document';
import DocumentsStore from 'stores/DocumentsStore';
const ResultWrapper = styled.div`
display: flex;
margin-bottom: 10px;
color: ${color.text};
cursor: default;
`;
const ResultWrapperLink = ResultWrapper.withComponent('a').extend`
padding-top: 3px;
padding-left: 5px;
&:hover,
&:active,
&:focus {
margin-left: 0px;
border-radius: 2px;
background: ${color.black};
color: ${color.smokeLight};
outline: none;
cursor: pointer;
}
`;
type Props = {
documentId?: string,
onSuccess?: Function,
documents: DocumentsStore,
document?: Document,
ref?: Function,
selectable?: boolean,
};
@observer class PathToDocument extends React.Component {
props: Props;
get resultDocument(): ?Document {
const { documentId } = this.props;
if (documentId) return this.props.documents.getById(documentId);
}
handleSelect = async (event: SyntheticEvent) => {
const { document, onSuccess } = this.props;
invariant(onSuccess && document, 'onSuccess unavailable');
event.preventDefault();
await document.move(this.resultDocument ? this.resultDocument.id : null);
onSuccess();
};
render() {
const { document, onSuccess, ref } = this.props;
// $FlowIssue we'll always have a document
const { collection } = document || this.resultDocument;
const Component = onSuccess ? ResultWrapperLink : ResultWrapper;
return (
<Component
innerRef={ref}
selectable
href={!!onSuccess}
onClick={onSuccess && this.handleSelect}
>
{collection.name}
{this.resultDocument &&
<Flex>
{' '}
<ChevronIcon />
{' '}
{this.resultDocument.pathToDocument
.map(doc => <span key={doc.id}>{doc.title}</span>)
.reduce((prev, curr) => [prev, <ChevronIcon />, curr])}
</Flex>}
{document &&
<Flex>
{' '}
<ChevronIcon />
{' '}{document.title}
</Flex>}
</Component>
);
}
}
export default PathToDocument;

View File

@ -0,0 +1,3 @@
// @flow
import DocumentMove from './DocumentMove';
export default DocumentMove;

View File

@ -2,18 +2,20 @@
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import keydown from 'react-keydown'; import keydown from 'react-keydown';
import { observer } from 'mobx-react'; import { observable, action } from 'mobx';
import { observer, inject } from 'mobx-react';
import _ from 'lodash'; import _ from 'lodash';
import Flex from 'components/Flex'; import DocumentsStore from 'stores/DocumentsStore';
import { withRouter } from 'react-router'; import { withRouter } from 'react-router';
import { searchUrl } from 'utils/routeHelpers'; import { searchUrl } from 'utils/routeHelpers';
import styled from 'styled-components'; import styled from 'styled-components';
import ArrowKeyNavigation from 'boundless-arrow-key-navigation'; import ArrowKeyNavigation from 'boundless-arrow-key-navigation';
import Flex from 'components/Flex';
import CenteredContent from 'components/CenteredContent'; import CenteredContent from 'components/CenteredContent';
import LoadingIndicator from 'components/LoadingIndicator'; import LoadingIndicator from 'components/LoadingIndicator';
import SearchField from './components/SearchField'; import SearchField from './components/SearchField';
import SearchStore from './SearchStore';
import DocumentPreview from 'components/DocumentPreview'; import DocumentPreview from 'components/DocumentPreview';
import PageTitle from 'components/PageTitle'; import PageTitle from 'components/PageTitle';
@ -21,6 +23,7 @@ import PageTitle from 'components/PageTitle';
type Props = { type Props = {
history: Object, history: Object,
match: Object, match: Object,
documents: DocumentsStore,
notFound: ?boolean, notFound: ?boolean,
}; };
@ -53,11 +56,12 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
@observer class Search extends React.Component { @observer class Search extends React.Component {
firstDocument: HTMLElement; firstDocument: HTMLElement;
props: Props; props: Props;
store: SearchStore;
constructor(props: Props) { @observable resultIds: Array<string> = []; // Document IDs
super(props); @observable searchTerm: ?string = null;
this.store = new SearchStore(); @observable isFetching = false;
componentDidMount() {
this.updateSearchResults(); this.updateSearchResults();
} }
@ -91,9 +95,26 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
}; };
updateSearchResults = _.debounce(() => { updateSearchResults = _.debounce(() => {
this.store.search(this.props.match.params.query); this.search(this.props.match.params.query);
}, 250); }, 250);
@action search = async (query: string) => {
this.searchTerm = query;
this.isFetching = true;
if (query) {
try {
this.resultIds = await this.props.documents.search(query);
} catch (e) {
console.error('Something went wrong');
}
} else {
this.resultIds = [];
}
this.isFetching = false;
};
updateQuery = query => { updateQuery = query => {
this.props.history.replace(searchUrl(query)); this.props.history.replace(searchUrl(query));
}; };
@ -103,20 +124,21 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
}; };
get title() { get title() {
const query = this.store.searchTerm; const query = this.searchTerm;
const title = 'Search'; const title = 'Search';
if (query) return `${query} - ${title}`; if (query) return `${query} - ${title}`;
return title; return title;
} }
render() { render() {
const { documents } = this.props;
const query = this.props.match.params.query; const query = this.props.match.params.query;
const hasResults = this.store.documents.length > 0; const hasResults = this.resultIds.length > 0;
return ( return (
<Container auto> <Container auto>
<PageTitle title={this.title} /> <PageTitle title={this.title} />
{this.store.isFetching && <LoadingIndicator />} {this.isFetching && <LoadingIndicator />}
{this.props.notFound && {this.props.notFound &&
<div> <div>
<h1>Not Found</h1> <h1>Not Found</h1>
@ -125,7 +147,7 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
</div>} </div>}
<ResultsWrapper pinToTop={hasResults} column auto> <ResultsWrapper pinToTop={hasResults} column auto>
<SearchField <SearchField
searchTerm={this.store.searchTerm} searchTerm={this.searchTerm}
onKeyDown={this.handleKeyDown} onKeyDown={this.handleKeyDown}
onChange={this.updateQuery} onChange={this.updateQuery}
value={query || ''} value={query || ''}
@ -135,15 +157,20 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
mode={ArrowKeyNavigation.mode.VERTICAL} mode={ArrowKeyNavigation.mode.VERTICAL}
defaultActiveChildIndex={0} defaultActiveChildIndex={0}
> >
{this.store.documents.map((document, index) => ( {this.resultIds.map((documentId, index) => {
const document = documents.getById(documentId);
if (document)
return (
<DocumentPreview <DocumentPreview
innerRef={ref => index === 0 && this.setFirstDocumentRef(ref)} innerRef={ref =>
key={document.id} index === 0 && this.setFirstDocumentRef(ref)}
key={documentId}
document={document} document={document}
highlight={this.store.searchTerm} highlight={this.searchTerm}
showCollection showCollection
/> />
))} );
})}
</StyledArrowKeyNavigation> </StyledArrowKeyNavigation>
</ResultList> </ResultList>
</ResultsWrapper> </ResultsWrapper>
@ -152,4 +179,4 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
} }
} }
export default withRouter(Search); export default withRouter(inject('documents')(Search));

View File

@ -1,37 +0,0 @@
// @flow
import { observable, action, runInAction } from 'mobx';
import invariant from 'invariant';
import { client } from 'utils/ApiClient';
import Document from 'models/Document';
class SearchStore {
@observable documents: Array<Document> = [];
@observable searchTerm: ?string = null;
@observable isFetching = false;
/* Actions */
@action search = async (query: string) => {
this.searchTerm = query;
this.isFetching = true;
if (query) {
try {
const res = await client.get('/documents.search', { query });
invariant(res && res.data, 'res or res.data missing');
const { data } = res;
runInAction('search document', () => {
this.documents = data.map(documentData => new Document(documentData));
});
} catch (e) {
console.error('Something went wrong');
}
} else {
this.documents = [];
}
this.isFetching = false;
};
}
export default SearchStore;

View File

@ -1,8 +1,9 @@
- `Cmd+Enter` - Save and exit document editor - `Cmd+Enter` - Save and exit document editor
- `Cmd+S` - Save document and continue editing - `Cmd+s` - Save document and continue editing
- `Cmd+Esc` - Cancel edit - `Cmd+Esc` - Cancel edit
- `/` or `t` - Jump to search - `/` or `t` - Jump to search
- `d` - Jump to dashboard - `d` - Jump to dashboard
- `c` - Compose within a collection - `c` - Compose within a collection
- `e` - Edit document - `e` - Edit document
- `m` - Move document
- `?` - This guide - `?` - This guide

View File

@ -104,6 +104,14 @@ class DocumentsStore extends BaseStore {
await this.fetchAll('starred'); await this.fetchAll('starred');
}; };
@action search = async (query: string): Promise<*> => {
const res = await client.get('/documents.search', { query });
invariant(res && res.data, 'res or res.data missing');
const { data } = res;
data.forEach(documentData => this.add(new Document(documentData)));
return data.map(documentData => documentData.id);
};
@action fetch = async (id: string): Promise<*> => { @action fetch = async (id: string): Promise<*> => {
this.isFetching = true; this.isFetching = true;
@ -138,8 +146,11 @@ class DocumentsStore extends BaseStore {
return this.data.get(id); return this.data.get(id);
}; };
/**
* Match documents by the url ID as the title slug can change
*/
getByUrl = (url: string): ?Document => { getByUrl = (url: string): ?Document => {
return _.find(this.data.values(), { url }); return _.find(this.data.values(), doc => url.endsWith(doc.urlId));
}; };
constructor(options: Options) { constructor(options: Options) {

View File

@ -38,3 +38,19 @@ export function searchUrl(query?: string): string {
export function notFoundUrl(): string { export function notFoundUrl(): string {
return '/404'; return '/404';
} }
export const matchDocumentSlug =
':documentSlug([0-9a-zA-Z-]*-[a-zA-z0-9]{10,15})';
export const matchDocumentEdit = `/doc/${matchDocumentSlug}/edit`;
export const matchDocumentMove = `/doc/${matchDocumentSlug}/move`;
/**
* Replace full url's document part with the new one in case
* the document slug has been updated
*/
export function updateDocumentUrl(oldUrl: string, newUrl: string): string {
// Update url to match the current one
const urlParts = oldUrl.split('/');
return [newUrl, urlParts.slice(3)].join('/');
}

View File

@ -96,6 +96,7 @@
"eslint-plugin-prettier": "^2.0.1", "eslint-plugin-prettier": "^2.0.1",
"eslint-plugin-react": "^6.10.3", "eslint-plugin-react": "^6.10.3",
"exports-loader": "0.6.3", "exports-loader": "0.6.3",
"extract-text-webpack-plugin": "1.0.1",
"fbemitter": "^2.1.1", "fbemitter": "^2.1.1",
"file-loader": "0.9.0", "file-loader": "0.9.0",
"flow-typed": "^2.1.2", "flow-typed": "^2.1.2",

View File

@ -211,6 +211,8 @@ router.post('documents.create', auth(), async ctx => {
await ownerCollection.addDocumentToStructure(document, index); await ownerCollection.addDocumentToStructure(document, index);
} }
document.collection = ownerCollection;
ctx.body = { ctx.body = {
data: await presentDocument(ctx, document), data: await presentDocument(ctx, document),
}; };
@ -279,6 +281,10 @@ router.post('documents.move', auth(), async ctx => {
await collection.deleteDocument(document); await collection.deleteDocument(document);
await collection.addDocumentToStructure(document, index); await collection.addDocumentToStructure(document, index);
} }
// Update collection
document.collection = collection;
document.collection = collection;
ctx.body = { ctx.body = {
data: await presentDocument(ctx, document), data: await presentDocument(ctx, document),

View File

@ -17,6 +17,7 @@ async function present(ctx: Object, document: Document, options: ?Options) {
const data = { const data = {
id: document.id, id: document.id,
url: document.getUrl(), url: document.getUrl(),
urlId: document.urlId,
private: document.private, private: document.private,
title: document.title, title: document.title,
text: document.text, text: document.text,

View File

@ -1,6 +1,7 @@
/* eslint-disable */ /* eslint-disable */
var webpack = require('webpack'); var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
const commonWebpackConfig = require('./webpack.config'); const commonWebpackConfig = require('./webpack.config');
@ -18,6 +19,7 @@ const developmentWebpackConfig = Object.assign(commonWebpackConfig, {
developmentWebpackConfig.plugins.push( developmentWebpackConfig.plugins.push(
new webpack.optimize.OccurenceOrderPlugin() new webpack.optimize.OccurenceOrderPlugin()
); );
developmentWebpackConfig.plugins.push(new ExtractTextPlugin('styles.css'));
developmentWebpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); developmentWebpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
developmentWebpackConfig.plugins.push(new webpack.NoErrorsPlugin()); developmentWebpackConfig.plugins.push(new webpack.NoErrorsPlugin());
developmentWebpackConfig.plugins.push( developmentWebpackConfig.plugins.push(

View File

@ -1,6 +1,7 @@
/* eslint-disable */ /* eslint-disable */
const path = require('path'); const path = require('path');
const webpack = require('webpack'); const webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
require('dotenv').config({ silent: true }); require('dotenv').config({ silent: true });
@ -40,7 +41,7 @@ module.exports = {
}, },
{ {
test: /\.css$/, test: /\.css$/,
loader: 'style-loader!css-loader?sourceMap', loader: ExtractTextPlugin.extract('style-loader', 'css-loader'),
}, },
{ test: /\.md/, loader: 'raw-loader' }, { test: /\.md/, loader: 'raw-loader' },
], ],

View File

@ -2,6 +2,7 @@
var path = require('path'); var path = require('path');
var webpack = require('webpack'); var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
commonWebpackConfig = require('./webpack.config'); commonWebpackConfig = require('./webpack.config');
@ -20,6 +21,9 @@ productionWebpackConfig.plugins.push(
template: 'server/static/index.html', template: 'server/static/index.html',
}) })
); );
productionWebpackConfig.plugins.push(
new ExtractTextPlugin('styles.[hash].css')
);
productionWebpackConfig.plugins.push( productionWebpackConfig.plugins.push(
new webpack.optimize.OccurenceOrderPlugin() new webpack.optimize.OccurenceOrderPlugin()
); );

View File

@ -306,7 +306,7 @@ async@^0.9.0:
version "0.9.2" version "0.9.2"
resolved "https://registry.yarnpkg.com/async/-/async-0.9.2.tgz#aea74d5e61c1f899613bf64bda66d4c78f2fd17d" resolved "https://registry.yarnpkg.com/async/-/async-0.9.2.tgz#aea74d5e61c1f899613bf64bda66d4c78f2fd17d"
async@^1.3.0, async@^1.4.0: async@^1.3.0, async@^1.4.0, async@^1.5.0:
version "1.5.2" version "1.5.2"
resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a"
@ -3031,6 +3031,14 @@ extglob@^0.3.1:
dependencies: dependencies:
is-extglob "^1.0.0" is-extglob "^1.0.0"
extract-text-webpack-plugin@1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/extract-text-webpack-plugin/-/extract-text-webpack-plugin-1.0.1.tgz#c95bf3cbaac49dc96f1dc6e072549fbb654ccd2c"
dependencies:
async "^1.5.0"
loader-utils "^0.2.3"
webpack-sources "^0.1.0"
extsprintf@1.3.0, extsprintf@^1.2.0: extsprintf@1.3.0, extsprintf@^1.2.0:
version "1.3.0" version "1.3.0"
resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05"
@ -5294,7 +5302,7 @@ load-json-file@^2.0.0:
pify "^2.0.0" pify "^2.0.0"
strip-bom "^3.0.0" strip-bom "^3.0.0"
loader-utils@0.2.x, loader-utils@^0.2.11, loader-utils@^0.2.14, loader-utils@~0.2.5: loader-utils@0.2.x, loader-utils@^0.2.11, loader-utils@^0.2.14, loader-utils@^0.2.3, loader-utils@~0.2.5:
version "0.2.17" version "0.2.17"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-0.2.17.tgz#f86e6374d43205a6e6c60e9196f17c0299bfb348" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-0.2.17.tgz#f86e6374d43205a6e6c60e9196f17c0299bfb348"
dependencies: dependencies:
@ -8186,7 +8194,7 @@ source-map@0.5.6:
version "0.5.6" version "0.5.6"
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.6.tgz#75ce38f52bf0733c5a7f0c118d81334a2bb5f412" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.6.tgz#75ce38f52bf0733c5a7f0c118d81334a2bb5f412"
source-map@^0.5.3, source-map@^0.5.6, source-map@^0.5.7, source-map@~0.5.0, source-map@~0.5.1: source-map@^0.5.3, source-map@^0.5.6, source-map@^0.5.7, source-map@~0.5.0, source-map@~0.5.1, source-map@~0.5.3:
version "0.5.7" version "0.5.7"
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc"
@ -9096,6 +9104,13 @@ webpack-hot-middleware@2.x:
querystring "^0.2.0" querystring "^0.2.0"
strip-ansi "^3.0.0" strip-ansi "^3.0.0"
webpack-sources@^0.1.0:
version "0.1.5"
resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-0.1.5.tgz#aa1f3abf0f0d74db7111c40e500b84f966640750"
dependencies:
source-list-map "~0.1.7"
source-map "~0.5.3"
webpack@1.13.2: webpack@1.13.2:
version "1.13.2" version "1.13.2"
resolved "https://registry.yarnpkg.com/webpack/-/webpack-1.13.2.tgz#f11a96f458eb752970a86abe746c0704fabafaf3" resolved "https://registry.yarnpkg.com/webpack/-/webpack-1.13.2.tgz#f11a96f458eb752970a86abe746c0704fabafaf3"