Merge pull request #211 from jorilallo/jori/document-move

WIP Document move
This commit is contained in:
Jori Lallo
2017-09-12 23:39:53 -07:00
committed by GitHub
20 changed files with 446 additions and 71 deletions

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;
&::placeholder {
color: ${color.slateLight};
color: ${color.slate};
}
`;
@@ -55,7 +55,7 @@ const LabelText = styled.div`
export type Props = {
type: string,
value: string,
value?: string,
label?: 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 &&
<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) &&
<Children column>
{doc.children && this.renderDocuments(doc.children, depth + 1)}

View File

@@ -1,5 +1,6 @@
// @flow
import React from 'react';
import { observer } from 'mobx-react';
import styled from 'styled-components';
import ReactModal from 'react-modal';
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 { matchDocumentSlug } from 'utils/routeHelpers';
let DevTools;
if (__DEV__) {
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}`} />
);
const matchDocumentSlug = ':documentSlug([0-9a-zA-Z-]*-[a-zA-z0-9]{10,15})';
render(
<div style={{ display: 'flex', flex: 1, height: '100%' }}>
<Provider {...stores}>
@@ -123,6 +123,11 @@ render(
path={`/doc/${matchDocumentSlug}`}
component={Document}
/>
<Route
exact
path={`/doc/${matchDocumentSlug}/move`}
component={Document}
/>
<Route exact path="/search" component={Search} />
<Route exact path="/search/:query" component={Search} />
@@ -132,7 +137,7 @@ render(
<RouteSidebarHidden
exact
path={`/doc/${matchDocumentSlug}/:edit`}
path={`/doc/${matchDocumentSlug}/edit`}
component={Document}
/>
<RouteSidebarHidden

View File

@@ -115,6 +115,9 @@ class Collection extends BaseModel {
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;
}
@computed get pathToDocument(): Array<string> {
@computed get pathToDocument(): Array<{ id: string, title: string }> {
let path;
const traveler = (nodes, previousPath) => {
nodes.forEach(childNode => {
const newPath = [...previousPath, childNode.id];
const newPath = [
...previousPath,
{
id: childNode.id,
title: childNode.title,
},
];
if (childNode.id === this.id) {
path = newPath;
return;
@@ -174,6 +180,24 @@ class Document extends BaseModel {
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 () => {
try {
await client.post('/documents.delete', { id: this.id });

View File

@@ -2,13 +2,21 @@
import React, { Component } from 'react';
import get from 'lodash/get';
import styled from 'styled-components';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter, Prompt } from 'react-router';
import keydown from 'react-keydown';
import Flex from 'components/Flex';
import { color, layout } from 'styles/constants';
import { collectionUrl, updateDocumentUrl } from 'utils/routeHelpers';
import {
collectionUrl,
updateDocumentUrl,
matchDocumentEdit,
matchDocumentMove,
} from 'utils/routeHelpers';
import Document from 'models/Document';
import DocumentMove from './components/DocumentMove';
import UiStore from 'stores/UiStore';
import DocumentsStore from 'stores/DocumentsStore';
import Menu from './components/Menu';
@@ -51,6 +59,8 @@ type Props = {
notFound: false,
};
@observable moveModalOpen: boolean = false;
componentDidMount() {
this.loadDocument(this.props);
}
@@ -70,6 +80,12 @@ type Props = {
this.props.ui.clearActiveDocument();
}
@keydown('m')
goToMove(event) {
event.preventDefault();
if (this.document) this.props.history.push(`${this.document.url}/move`);
}
loadDocument = async props => {
if (props.newDocument) {
const newDocument = new Document({
@@ -120,6 +136,9 @@ type Props = {
this.props.history.push(`${this.document.collection.url}/new`);
};
handleCloseMoveModal = () => (this.moveModalOpen = false);
handleOpenMoveModal = () => (this.moveModalOpen = true);
onSave = async (redirect: boolean = false) => {
if (this.document && !this.document.allowSave) return;
let document = this.document;
@@ -181,7 +200,8 @@ type Props = {
render() {
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 titleText = get(this.document, 'title', '');
const document = this.document;
@@ -192,6 +212,8 @@ type Props = {
return (
<Container column auto>
{isMoving && document && <DocumentMove document={document} />}
{this.state.isDragging &&
<DropHere align="center" justify="center">
Drop files here to import into Atlas.

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

@@ -51,6 +51,10 @@ type Props = {
}
};
onMove = () => {
this.props.history.push(`${this.props.document.url}/move`);
};
render() {
const document = get(this.props, 'document');
if (document) {
@@ -69,6 +73,7 @@ type Props = {
New document
</DropdownMenuItem>
</div>}
<DropdownMenuItem onClick={this.onMove}>Move</DropdownMenuItem>
<DropdownMenuItem onClick={this.onExport}>Export</DropdownMenuItem>
{allowDelete &&
<DropdownMenuItem onClick={this.onDelete}>Delete</DropdownMenuItem>}

View File

@@ -2,18 +2,20 @@
import React from 'react';
import ReactDOM from 'react-dom';
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 Flex from 'components/Flex';
import DocumentsStore from 'stores/DocumentsStore';
import { withRouter } from 'react-router';
import { searchUrl } from 'utils/routeHelpers';
import styled from 'styled-components';
import ArrowKeyNavigation from 'boundless-arrow-key-navigation';
import Flex from 'components/Flex';
import CenteredContent from 'components/CenteredContent';
import LoadingIndicator from 'components/LoadingIndicator';
import SearchField from './components/SearchField';
import SearchStore from './SearchStore';
import DocumentPreview from 'components/DocumentPreview';
import PageTitle from 'components/PageTitle';
@@ -21,6 +23,7 @@ import PageTitle from 'components/PageTitle';
type Props = {
history: Object,
match: Object,
documents: DocumentsStore,
notFound: ?boolean,
};
@@ -53,11 +56,12 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
@observer class Search extends React.Component {
firstDocument: HTMLElement;
props: Props;
store: SearchStore;
constructor(props: Props) {
super(props);
this.store = new SearchStore();
@observable resultIds: Array<string> = []; // Document IDs
@observable searchTerm: ?string = null;
@observable isFetching = false;
componentDidMount() {
this.updateSearchResults();
}
@@ -91,9 +95,26 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
};
updateSearchResults = _.debounce(() => {
this.store.search(this.props.match.params.query);
this.search(this.props.match.params.query);
}, 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 => {
this.props.history.replace(searchUrl(query));
};
@@ -103,20 +124,21 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
};
get title() {
const query = this.store.searchTerm;
const query = this.searchTerm;
const title = 'Search';
if (query) return `${query} - ${title}`;
return title;
}
render() {
const { documents } = this.props;
const query = this.props.match.params.query;
const hasResults = this.store.documents.length > 0;
const hasResults = this.resultIds.length > 0;
return (
<Container auto>
<PageTitle title={this.title} />
{this.store.isFetching && <LoadingIndicator />}
{this.isFetching && <LoadingIndicator />}
{this.props.notFound &&
<div>
<h1>Not Found</h1>
@@ -125,7 +147,7 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
</div>}
<ResultsWrapper pinToTop={hasResults} column auto>
<SearchField
searchTerm={this.store.searchTerm}
searchTerm={this.searchTerm}
onKeyDown={this.handleKeyDown}
onChange={this.updateQuery}
value={query || ''}
@@ -135,15 +157,20 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
mode={ArrowKeyNavigation.mode.VERTICAL}
defaultActiveChildIndex={0}
>
{this.store.documents.map((document, index) => (
<DocumentPreview
innerRef={ref => index === 0 && this.setFirstDocumentRef(ref)}
key={document.id}
document={document}
highlight={this.store.searchTerm}
showCollection
/>
))}
{this.resultIds.map((documentId, index) => {
const document = documents.getById(documentId);
if (document)
return (
<DocumentPreview
innerRef={ref =>
index === 0 && this.setFirstDocumentRef(ref)}
key={documentId}
document={document}
highlight={this.searchTerm}
showCollection
/>
);
})}
</StyledArrowKeyNavigation>
</ResultList>
</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+S` - Save document and continue editing
- `Cmd+s` - Save document and continue editing
- `Cmd+Esc` - Cancel edit
- `/` or `t` - Jump to search
- `d` - Jump to dashboard
- `c` - Compose within a collection
- `e` - Edit document
- `m` - Move document
- `?` - This guide

View File

@@ -104,6 +104,14 @@ class DocumentsStore extends BaseStore {
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<*> => {
this.isFetching = true;

View File

@@ -39,6 +39,12 @@ export function notFoundUrl(): string {
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

View File

@@ -281,6 +281,8 @@ router.post('documents.move', auth(), async ctx => {
await collection.deleteDocument(document);
await collection.addDocumentToStructure(document, index);
}
// Update collection
document.collection = collection;
document.collection = collection;