frontend > app

This commit is contained in:
Tom Moor
2017-10-25 22:49:04 -07:00
parent aa34db8318
commit 4863680d86
239 changed files with 11 additions and 11 deletions

View File

@@ -0,0 +1,91 @@
// @flow
import React from 'react';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react';
import { Redirect } from 'react-router';
import { Link } from 'react-router-dom';
import _ from 'lodash';
import styled from 'styled-components';
import { newDocumentUrl } from 'utils/routeHelpers';
import CollectionsStore from 'stores/CollectionsStore';
import Collection from 'models/Collection';
import CenteredContent from 'components/CenteredContent';
import LoadingListPlaceholder from 'components/LoadingListPlaceholder';
import Button from 'components/Button';
import Flex from 'components/Flex';
import HelpText from 'components/HelpText';
type Props = {
collections: CollectionsStore,
match: Object,
};
@observer class CollectionScene extends React.Component {
props: Props;
collection: ?Collection;
@observable isFetching = true;
@observable redirectUrl;
componentDidMount = () => {
this.fetchDocument(this.props.match.params.id);
};
componentWillReceiveProps(nextProps) {
if (nextProps.match.params.id !== this.props.match.params.id) {
this.fetchDocument(nextProps.match.params.id);
}
}
fetchDocument = async (id: string) => {
const { collections } = this.props;
this.collection = await collections.getById(id);
if (!this.collection) this.redirectUrl = '/404';
if (this.collection && this.collection.documents.length > 0) {
this.redirectUrl = this.collection.documents[0].url;
}
this.isFetching = false;
};
renderNewDocument() {
return (
<NewDocumentContainer auto column justify="center">
<h1>Create a document</h1>
<HelpText>
Publish your first document to start building your collection.
</HelpText>
{this.collection &&
<Action>
<Link to={newDocumentUrl(this.collection)}>
<Button>Create new document</Button>
</Link>
</Action>}
</NewDocumentContainer>
);
}
render() {
return (
<CenteredContent>
{this.redirectUrl && <Redirect to={this.redirectUrl} />}
{this.isFetching
? <LoadingListPlaceholder />
: this.renderNewDocument()}
</CenteredContent>
);
}
}
const NewDocumentContainer = styled(Flex)`
padding-top: 70px;
`;
const Action = styled(Flex)`
margin: 20px 0;
`;
export default inject('collections')(CollectionScene);

View File

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

View File

@@ -0,0 +1,61 @@
// @flow
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { observable } from 'mobx';
import { inject, observer } from 'mobx-react';
import { homeUrl } from 'utils/routeHelpers';
import Button from 'components/Button';
import Flex from 'components/Flex';
import HelpText from 'components/HelpText';
import Collection from 'models/Collection';
import CollectionsStore from 'stores/CollectionsStore';
type Props = {
history: Object,
collection: Collection,
collections: CollectionsStore,
onSubmit: () => void,
};
@observer class CollectionDelete extends Component {
props: Props;
@observable isDeleting: boolean;
handleSubmit = async (ev: SyntheticEvent) => {
ev.preventDefault();
this.isDeleting = true;
const success = await this.props.collection.delete();
if (success) {
this.props.collections.remove(this.props.collection.id);
this.props.history.push(homeUrl());
this.props.onSubmit();
}
this.isDeleting = false;
};
render() {
const { collection } = this.props;
return (
<Flex column>
<form onSubmit={this.handleSubmit}>
<HelpText>
Are you sure? Deleting the
{' '}
<strong>{collection.name}</strong>
{' '}
collection is permanant and will also delete all of the documents within
it, so be careful with that.
</HelpText>
<Button type="submit" danger>
{this.isDeleting ? 'Deleting…' : 'Delete'}
</Button>
</form>
</Flex>
);
}
}
export default inject('collections')(withRouter(CollectionDelete));

View File

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

View File

@@ -0,0 +1,73 @@
// @flow
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { observable } from 'mobx';
import { inject, observer } from 'mobx-react';
import Button from 'components/Button';
import Input from 'components/Input';
import Flex from 'components/Flex';
import HelpText from 'components/HelpText';
import Collection from 'models/Collection';
type Props = {
history: Object,
collection: Collection,
onSubmit: () => void,
};
@observer class CollectionEdit extends Component {
props: Props;
@observable name: string;
@observable isSaving: boolean;
componentWillMount() {
this.name = this.props.collection.name;
}
handleSubmit = async (ev: SyntheticEvent) => {
ev.preventDefault();
this.isSaving = true;
this.props.collection.updateData({ name: this.name });
const success = await this.props.collection.save();
if (success) {
this.props.onSubmit();
}
this.isSaving = false;
};
handleNameChange = (ev: SyntheticInputEvent) => {
this.name = ev.target.value;
};
render() {
return (
<Flex column>
<form onSubmit={this.handleSubmit}>
<HelpText>
You can edit a collection's name at any time, however doing so might
confuse your team mates.
</HelpText>
<Input
type="text"
label="Name"
onChange={this.handleNameChange}
value={this.name}
required
autoFocus
/>
<Button
type="submit"
disabled={this.isSaving || !this.props.collection.name}
>
{this.isSaving ? 'Saving' : 'Save'}
</Button>
</form>
</Flex>
);
}
}
export default inject('collections')(withRouter(CollectionEdit));

View File

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

View File

@@ -0,0 +1,72 @@
// @flow
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { observable } from 'mobx';
import { inject, observer } from 'mobx-react';
import Button from 'components/Button';
import Input from 'components/Input';
import HelpText from 'components/HelpText';
import Collection from 'models/Collection';
import CollectionsStore from 'stores/CollectionsStore';
type Props = {
history: Object,
collections: CollectionsStore,
onSubmit: () => void,
};
@observer class CollectionNew extends Component {
props: Props;
@observable collection: Collection;
@observable name: string = '';
@observable isSaving: boolean;
constructor(props: Props) {
super(props);
this.collection = new Collection();
}
handleSubmit = async (ev: SyntheticEvent) => {
ev.preventDefault();
this.isSaving = true;
this.collection.updateData({ name: this.name });
const success = await this.collection.save();
if (success) {
this.props.collections.add(this.collection);
this.props.onSubmit();
this.props.history.push(this.collection.url);
}
this.isSaving = false;
};
handleNameChange = (ev: SyntheticInputEvent) => {
this.name = ev.target.value;
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<HelpText>
Collections are for grouping your Atlas. They work best when organized
around a topic or internal team Product or Engineering for example.
</HelpText>
<Input
type="text"
label="Name"
onChange={this.handleNameChange}
value={this.name}
required
autoFocus
/>
<Button type="submit" disabled={this.isSaving || !this.name}>
{this.isSaving ? 'Creating…' : 'Create'}
</Button>
</form>
);
}
}
export default inject('collections')(withRouter(CollectionNew));

View File

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

View File

@@ -0,0 +1,75 @@
// @flow
import React, { Component } from 'react';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react';
import styled from 'styled-components';
import DocumentsStore from 'stores/DocumentsStore';
import Flex from 'components/Flex';
import DocumentList from 'components/DocumentList';
import PageTitle from 'components/PageTitle';
import CenteredContent from 'components/CenteredContent';
import { ListPlaceholder } from 'components/LoadingPlaceholder';
const Subheading = styled.h3`
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
color: #9FA6AB;
letter-spacing: 0.04em;
border-bottom: 1px solid #ddd;
padding-bottom: 10px;
margin-top: 30px;
`;
type Props = {
documents: DocumentsStore,
};
@observer class Dashboard extends Component {
props: Props;
@observable isLoaded: boolean = false;
componentDidMount() {
this.loadContent();
}
loadContent = async () => {
await Promise.all([
this.props.documents.fetchRecentlyModified({ limit: 5 }),
this.props.documents.fetchRecentlyViewed({ limit: 5 }),
]);
this.isLoaded = true;
};
render() {
const { documents } = this.props;
const recentlyViewedLoaded = documents.recentlyViewed.length > 0;
const recentlyEditedLoaded = documents.recentlyEdited.length > 0;
const showContent =
this.isLoaded || (recentlyViewedLoaded && recentlyEditedLoaded);
return (
<CenteredContent>
<PageTitle title="Home" />
<h1>Home</h1>
{showContent
? <Flex column>
{recentlyViewedLoaded &&
<Flex column>
<Subheading>Recently viewed</Subheading>
<DocumentList documents={documents.recentlyViewed} />
</Flex>}
{recentlyEditedLoaded &&
<Flex column>
<Subheading>Recently edited</Subheading>
<DocumentList documents={documents.recentlyEdited} />
</Flex>}
</Flex>
: <ListPlaceholder count={5} />}
</CenteredContent>
);
}
}
export default inject('documents')(Dashboard);

View File

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

View File

@@ -0,0 +1,326 @@
// @flow
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,
documentMoveUrl,
documentEditUrl,
documentNewUrl,
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 CollectionsStore from 'stores/CollectionsStore';
import DocumentMenu from 'menus/DocumentMenu';
import SaveAction from './components/SaveAction';
import LoadingPlaceholder from 'components/LoadingPlaceholder';
import Editor from 'components/Editor';
import LoadingIndicator from 'components/LoadingIndicator';
import Collaborators from 'components/Collaborators';
import CenteredContent from 'components/CenteredContent';
import PageTitle from 'components/PageTitle';
import NewDocumentIcon from 'components/Icon/NewDocumentIcon';
import Search from 'scenes/Search';
const DISCARD_CHANGES = `
You have unsaved changes.
Are you sure you want to discard them?
`;
type Props = {
match: Object,
history: Object,
location: Object,
keydown: Object,
documents: DocumentsStore,
collections: CollectionsStore,
newDocument?: boolean,
ui: UiStore,
};
@observer class DocumentScene extends Component {
props: Props;
savedTimeout: number;
@observable editCache: ?string;
@observable newDocument: ?Document;
@observable isLoading = false;
@observable isSaving = false;
@observable notFound = false;
@observable moveModalOpen: boolean = false;
componentWillMount() {
this.loadDocument(this.props);
}
componentWillReceiveProps(nextProps) {
if (
nextProps.match.params.documentSlug !==
this.props.match.params.documentSlug
) {
this.notFound = false;
this.loadDocument(nextProps);
}
}
componentWillUnmount() {
clearTimeout(this.savedTimeout);
this.props.ui.clearActiveDocument();
}
@keydown('m')
goToMove(ev) {
ev.preventDefault();
if (this.document) this.props.history.push(documentMoveUrl(this.document));
}
loadDocument = async props => {
if (props.newDocument) {
const newDocument = new Document({
collection: { id: props.match.params.id },
parentDocument: new URLSearchParams(props.location.search).get(
'parentDocument'
),
title: '',
text: '',
});
this.newDocument = newDocument;
} else {
let document = this.getDocument(props.match.params.documentSlug);
if (document) {
this.props.documents.fetch(props.match.params.documentSlug);
this.props.ui.setActiveDocument(document);
} else {
document = await this.props.documents.fetch(
props.match.params.documentSlug
);
}
if (document) {
this.props.ui.setActiveDocument(document);
// Cache data if user enters edit mode and cancels
this.editCache = document.text;
if (!this.isEditing) document.view();
// Update url to match the current one
this.props.history.replace(
updateDocumentUrl(props.match.url, document.url)
);
} else {
// Render 404 with search
this.notFound = true;
}
}
};
get isEditing() {
return (
this.props.match.path === matchDocumentEdit || this.props.newDocument
);
}
getDocument(documentSlug: ?string) {
if (this.newDocument) return this.newDocument;
return this.props.documents.getByUrl(
`/doc/${documentSlug || this.props.match.params.documentSlug}`
);
}
get document() {
return this.getDocument();
}
onClickEdit = () => {
if (!this.document) return;
this.props.history.push(documentEditUrl(this.document));
};
onClickNew = () => {
if (!this.document) return;
this.props.history.push(documentNewUrl(this.document));
};
handleCloseMoveModal = () => (this.moveModalOpen = false);
handleOpenMoveModal = () => (this.moveModalOpen = true);
onSave = async (redirect: boolean = false) => {
if (this.document && !this.document.allowSave) return;
this.editCache = null;
let document = this.document;
if (!document) return;
this.isLoading = true;
this.isSaving = true;
document = await document.save();
this.isLoading = false;
if (redirect || this.props.newDocument) {
this.props.history.push(document.url);
}
};
onImageUploadStart = () => {
this.isLoading = true;
};
onImageUploadStop = () => {
this.isLoading = false;
};
onChange = text => {
if (!this.document) return;
this.document.updateData({ text }, true);
};
onDiscard = () => {
let url;
if (this.document && this.document.url) {
url = this.document.url;
if (this.editCache) this.document.updateData({ text: this.editCache });
} else {
url = collectionUrl(this.props.match.params.id);
}
this.props.history.push(url);
};
renderNotFound() {
return <Search notFound />;
}
render() {
const isNew = this.props.newDocument;
const isMoving = this.props.match.path === matchDocumentMove;
const document = this.document;
const isFetching = !document;
const titleText =
get(document, 'title', '') ||
this.props.collections.titleForDocument(this.props.location.pathname);
if (this.notFound) {
return this.renderNotFound();
}
return (
<Container column auto>
{isMoving && document && <DocumentMove document={document} />}
{titleText && <PageTitle title={titleText} />}
{this.isLoading && <LoadingIndicator />}
{isFetching &&
<CenteredContent>
<LoadingState />
</CenteredContent>}
{!isFetching &&
document &&
<Flex justify="center" auto>
<Prompt
when={document.hasPendingChanges}
message={DISCARD_CHANGES}
/>
<Editor
key={document.id}
text={document.text}
emoji={document.emoji}
onImageUploadStart={this.onImageUploadStart}
onImageUploadStop={this.onImageUploadStop}
onChange={this.onChange}
onSave={this.onSave}
onCancel={this.onDiscard}
readOnly={!this.isEditing}
/>
<Meta align="center" justify="flex-end" readOnly={!this.isEditing}>
<Flex align="center">
{!isNew &&
!this.isEditing &&
<Collaborators document={document} />}
<HeaderAction>
{this.isEditing
? <SaveAction
isSaving={this.isSaving}
onClick={this.onSave.bind(this, true)}
disabled={
!(this.document && this.document.allowSave) ||
this.isSaving
}
isNew={!!isNew}
/>
: <a onClick={this.onClickEdit}>
Edit
</a>}
</HeaderAction>
{this.isEditing &&
<HeaderAction>
<a onClick={this.onDiscard}>Discard</a>
</HeaderAction>}
{!this.isEditing &&
<HeaderAction>
<DocumentMenu document={document} />
</HeaderAction>}
{!this.isEditing && <Separator />}
<HeaderAction>
{!this.isEditing &&
<a onClick={this.onClickNew}>
<NewDocumentIcon />
</a>}
</HeaderAction>
</Flex>
</Meta>
</Flex>}
</Container>
);
}
}
const Separator = styled.div`
margin-left: 12px;
width: 1px;
height: 20px;
background: ${color.slateLight};
`;
const HeaderAction = styled(Flex)`
justify-content: center;
align-items: center;
padding: 0 0 0 10px;
a {
color: ${color.text};
height: 24px;
}
`;
const Meta = styled(Flex)`
align-items: flex-start;
position: fixed;
top: 0;
right: 0;
padding: ${layout.vpadding} ${layout.hpadding} 8px 8px;
border-radius: 3px;
background: rgba(255, 255, 255, 0.9);
-webkit-backdrop-filter: blur(20px);
`;
const Container = styled(Flex)`
position: relative;
width: 100%;
`;
const LoadingState = styled(LoadingPlaceholder)`
margin: 90px 0;
`;
export default withRouter(
inject('ui', 'user', 'documents', 'collections')(DocumentScene)
);

View File

@@ -0,0 +1,189 @@
// @flow
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { observable, computed } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router';
import { Search } from 'js-search';
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';
import CollectionsStore, { type DocumentPath } from 'stores/CollectionsStore';
type Props = {
match: Object,
history: Object,
document: Document,
documents: DocumentsStore,
collections: CollectionsStore,
};
@observer class DocumentMove extends Component {
props: Props;
firstDocument: HTMLElement;
@observable searchTerm: ?string;
@observable isSaving: boolean;
@computed get searchIndex() {
const { document, collections } = this.props;
const paths = collections.pathsToDocuments;
const index = new Search('id');
index.addIndex('title');
// Build index
const indexeableDocuments = [];
paths.forEach(path => {
// TMP: For now, exclude paths to other collections
if (_.first(path.path).id !== document.collection.id) return;
indexeableDocuments.push(path);
});
index.addDocuments(indexeableDocuments);
return index;
}
@computed get results(): DocumentPath[] {
const { document, collections } = this.props;
let results = [];
if (collections.isLoaded) {
if (this.searchTerm) {
// Search by the keyword
results = this.searchIndex.search(this.searchTerm);
} else {
// Default results, root of the current collection
results = [];
document.collection.documents.forEach(doc => {
const path = collections.getPathForDocument(doc.id);
if (doc && path) {
results.push(path);
}
});
}
}
if (document && document.parentDocumentId) {
// Add root if document does have a parent document
const rootPath = collections.getPathForDocument(document.collection.id);
if (rootPath) {
results = [rootPath, ...results];
}
}
// Exclude root from search results if document is already at the root
if (!document.parentDocumentId) {
results = results.filter(result => result.id !== document.collection.id);
}
// Exclude document if on the path to result, or the same result
results = results.filter(
result =>
!result.path.map(doc => doc.id).includes(document.id) &&
!result.path.map(doc => doc.id).includes(document.parentDocumentId)
);
return results;
}
handleKeyDown = ev => {
// Down
if (ev.which === 40) {
ev.preventDefault();
if (this.firstDocument) {
const element = ReactDOM.findDOMNode(this.firstDocument);
if (element instanceof HTMLElement) element.focus();
}
}
};
handleClose = () => {
this.props.history.push(this.props.document.url);
};
handleFilter = (e: SyntheticInputEvent) => {
this.searchTerm = e.target.value;
};
setFirstDocumentRef = ref => {
this.firstDocument = ref;
};
renderPathToCurrentDocument() {
const { collections, document } = this.props;
const result = collections.getPathForDocument(document.id);
if (result) {
return <PathToDocument result={result} />;
}
}
render() {
const { document, collections } = this.props;
return (
<Modal isOpen onRequestClose={this.handleClose} title="Move document">
{document &&
collections.isLoaded &&
<Flex column>
<Section>
<Labeled label="Current location">
{this.renderPathToCurrentDocument()}
</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}
>
{this.results.map((result, index) => (
<PathToDocument
key={result.id}
result={result}
document={document}
ref={ref => index === 0 && this.setFirstDocumentRef(ref)}
onSuccess={this.handleClose}
/>
))}
</StyledArrowKeyNavigation>
</Flex>
</Section>
</Flex>}
</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', 'collections')(DocumentMove));

View File

@@ -0,0 +1,97 @@
// @flow
import React from 'react';
import { observer } from 'mobx-react';
import invariant from 'invariant';
import _ from 'lodash';
import styled from 'styled-components';
import { color } from 'styles/constants';
import Flex from 'components/Flex';
import GoToIcon from 'components/Icon/GoToIcon';
import Document from 'models/Document';
const ResultWrapper = styled.div`
display: flex;
margin-bottom: 10px;
color: ${color.text};
cursor: default;
`;
const StyledGoToIcon = styled(GoToIcon)`
`;
const ResultWrapperLink = ResultWrapper.withComponent('a').extend`
height: 32px;
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;
${StyledGoToIcon} {
fill: ${color.white};
}
}
`;
type Props = {
result: Object,
document?: Document,
onSuccess?: Function,
ref?: Function,
};
@observer class PathToDocument extends React.Component {
props: Props;
handleClick = async (ev: SyntheticEvent) => {
ev.preventDefault();
const { document, result, onSuccess } = this.props;
invariant(onSuccess && document, 'onSuccess unavailable');
if (result.type === 'document') {
await document.move(result.id);
} else if (
result.type === 'collection' &&
result.id === document.collection.id
) {
await document.move(null);
} else {
throw new Error('Not implemented yet');
}
onSuccess();
};
render() {
const { result, document, ref } = this.props;
const Component = document ? ResultWrapperLink : ResultWrapper;
if (!result) return <div />;
return (
<Component innerRef={ref} onClick={this.handleClick} selectable href>
{result.path
.map(doc => <span key={doc.id}>{doc.title}</span>)
.reduce((prev, curr) => [prev, <StyledGoToIcon />, curr])}
{document &&
<Flex>
{' '}
<StyledGoToIcon />
{' '}{document.title}
</Flex>}
</Component>
);
}
}
export default PathToDocument;

View File

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

View File

@@ -0,0 +1,42 @@
// @flow
import React from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import styled from 'styled-components';
import { pulsate } from 'styles/animations';
import { color } from 'styles/constants';
import Flex from 'components/Flex';
import { randomInteger } from 'utils/random';
const randomValues = Array.from(
new Array(5),
() => `${randomInteger(85, 100)}%`
);
export default (props: Object) => {
return (
<ReactCSSTransitionGroup
transitionName="fadeIn"
transitionAppear
transitionEnter
transitionLeave
transitionAppearTimeout={0}
transitionEnterTimeout={0}
transitionLeaveTimeout={0}
>
<Flex column auto {...props}>
<Mask style={{ width: randomValues[0] }} header />
<Mask style={{ width: randomValues[1] }} />
<Mask style={{ width: randomValues[2] }} />
<Mask style={{ width: randomValues[3] }} />
</Flex>
</ReactCSSTransitionGroup>
);
};
const Mask = styled(Flex)`
height: ${props => (props.header ? 28 : 18)}px;
margin-bottom: ${props => (props.header ? 32 : 14)}px;
background-color: ${color.smoke};
animation: ${pulsate} 1.3s infinite;
`;

View File

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

View File

@@ -0,0 +1,47 @@
// @flow
import React from 'react';
import styled from 'styled-components';
type Props = {
onClick: Function,
disabled?: boolean,
isNew?: boolean,
isSaving?: boolean,
};
class SaveAction extends React.Component {
props: Props;
onClick = (ev: MouseEvent) => {
if (this.props.disabled) return;
ev.preventDefault();
this.props.onClick();
};
render() {
const { isSaving, isNew, disabled } = this.props;
return (
<Link
onClick={this.onClick}
title="Save changes (Cmd+Enter)"
disabled={disabled}
>
{isNew
? isSaving ? 'Publishing…' : 'Publish'
: isSaving ? 'Saving…' : 'Save'}
</Link>
);
}
}
const Link = styled.a`
display: flex;
align-items: center;
opacity: ${props => (props.disabled ? 0.5 : 1)};
pointer-events: ${props => (props.disabled ? 'none' : 'auto')};
cursor: ${props => (props.disabled ? 'default' : 'pointer')};
`;
export default SaveAction;

View File

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

View File

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

View File

@@ -0,0 +1,59 @@
// @flow
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { observable } from 'mobx';
import { inject, observer } from 'mobx-react';
import Button from 'components/Button';
import Flex from 'components/Flex';
import HelpText from 'components/HelpText';
import Document from 'models/Document';
import DocumentsStore from 'stores/DocumentsStore';
type Props = {
history: Object,
document: Document,
documents: DocumentsStore,
onSubmit: () => void,
};
@observer class DocumentDelete extends Component {
props: Props;
@observable isDeleting: boolean;
handleSubmit = async (ev: SyntheticEvent) => {
ev.preventDefault();
this.isDeleting = true;
const { collection } = this.props.document;
const success = await this.props.document.delete();
if (success) {
this.props.history.push(collection.url);
this.props.onSubmit();
}
this.isDeleting = false;
};
render() {
const { document } = this.props;
return (
<Flex column>
<form onSubmit={this.handleSubmit}>
<HelpText>
Are you sure? Deleting the
{' '}
<strong>{document.title}</strong>
{' '}
document is permanant and will also delete all of its history.
</HelpText>
<Button type="submit" danger>
{this.isDeleting ? 'Deleting…' : 'Delete'}
</Button>
</form>
</Flex>
);
}
}
export default inject('documents')(withRouter(DocumentDelete));

View File

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

View File

@@ -0,0 +1,23 @@
// @flow
import React from 'react';
import { Link } from 'react-router-dom';
import CenteredContent from 'components/CenteredContent';
import PageTitle from 'components/PageTitle';
class Error404 extends React.Component {
render() {
return (
<CenteredContent>
<PageTitle title="Not found" />
<h1>Not Found</h1>
<p>We're unable to find the page you're accessing.</p>
<p>Maybe you want to try <Link to="/search">search</Link> instead?</p>
</CenteredContent>
);
}
}
export default Error404;

View File

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

View File

@@ -0,0 +1,23 @@
// @flow
import React from 'react';
import { Link } from 'react-router-dom';
import CenteredContent from 'components/CenteredContent';
import PageTitle from 'components/PageTitle';
class ErrorAuth extends React.Component {
render() {
return (
<CenteredContent>
<PageTitle title="Authentication error" />
<h1>Authentication failed</h1>
<p>
We were unable to log you in. <Link to="/">Please try again.</Link>
</p>
</CenteredContent>
);
}
}
export default ErrorAuth;

View File

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

View File

@@ -0,0 +1,32 @@
// @flow
import React from 'react';
import { observer } from 'mobx-react';
import CenteredContent from 'components/CenteredContent';
import Editor from 'components/Editor';
import PageTitle from 'components/PageTitle';
type Props = {
title: string,
content: string,
};
const Flatpage = observer((props: Props) => {
const { title, content } = props;
return (
<CenteredContent>
<PageTitle title={title} />
<Editor
text={content}
onChange={() => {}}
onSave={() => {}}
onCancel={() => {}}
onImageUploadStart={() => {}}
onImageUploadStop={() => {}}
readOnly
/>
</CenteredContent>
);
});
export default Flatpage;

View File

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

17
app/scenes/Home/Home.js Normal file
View File

@@ -0,0 +1,17 @@
// @flow
import React from 'react';
import { observer, inject } from 'mobx-react';
import { Redirect } from 'react-router';
import AuthStore from 'stores/AuthStore';
type Props = {
auth: AuthStore,
};
const Home = observer((props: Props) => {
if (props.auth.authenticated) return <Redirect to="/dashboard" />;
window.location.href = BASE_URL;
return null;
});
export default inject('auth')(Home);

3
app/scenes/Home/index.js Normal file
View File

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

View File

@@ -0,0 +1,117 @@
// @flow
import React from 'react';
import styled from 'styled-components';
import Key from 'components/Key';
import Flex from 'components/Flex';
import HelpText from 'components/HelpText';
function KeyboardShortcuts() {
return (
<Flex column>
<HelpText>
Atlas is designed to be super fast and easy to use.
All of your usual keyboard shortcuts work here, and there
{"'"}
s Markdown too.
</HelpText>
<h2>Navigation</h2>
<List>
<Keys><Key>e</Key></Keys>
<Label>Edit current document</Label>
<Keys><Key>m</Key></Keys>
<Label>Move current document</Label>
<Keys><Key>/</Key> or <Key>t</Key></Keys>
<Label>Jump to search</Label>
<Keys><Key>d</Key></Keys>
<Label>Jump to dashboard</Label>
<Keys><Key></Key> + <Key>/</Key></Keys>
<Label>Open this guide</Label>
</List>
<h2>Editor</h2>
<List>
<Keys><Key></Key> + <Key>Enter</Key></Keys>
<Label>Save and exit document edit mode</Label>
<Keys><Key></Key> + <Key>S</Key></Keys>
<Label>Save document and continue editing</Label>
<Keys><Key></Key> + <Key>Esc</Key></Keys>
<Label>Cancel editing</Label>
<Keys><Key></Key> + <Key>b</Key></Keys>
<Label>Bold</Label>
<Keys><Key></Key> + <Key>i</Key></Keys>
<Label>Italic</Label>
<Keys><Key></Key> + <Key>u</Key></Keys>
<Label>Underline</Label>
<Keys><Key></Key> + <Key>d</Key></Keys>
<Label>Strikethrough</Label>
<Keys><Key></Key> + <Key>k</Key></Keys>
<Label>Link</Label>
<Keys><Key></Key> + <Key>z</Key></Keys>
<Label>Undo</Label>
<Keys><Key></Key> + <Key>Shift</Key> + <Key>z</Key></Keys>
<Label>Redo</Label>
</List>
<h2>Markdown</h2>
<List>
<Keys><Key>#</Key> <Key>Space</Key></Keys>
<Label>Large header</Label>
<Keys><Key>##</Key> <Key>Space</Key></Keys>
<Label>Medium header</Label>
<Keys><Key>###</Key> <Key>Space</Key></Keys>
<Label>Small header</Label>
<Keys><Key>1.</Key> <Key>Space</Key></Keys>
<Label>Numbered list</Label>
<Keys><Key>-</Key> <Key>Space</Key></Keys>
<Label>Bulleted list</Label>
<Keys><Key>[ ]</Key> <Key>Space</Key></Keys>
<Label>Todo list</Label>
<Keys><Key>&gt;</Key> <Key>Space</Key></Keys>
<Label>Blockquote</Label>
<Keys><Key>---</Key></Keys>
<Label>Horizontal divider</Label>
<Keys><Key>{'```'}</Key></Keys>
<Label>Code block</Label>
<Keys>_italic_</Keys>
<Label>Italic</Label>
<Keys>**bold**</Keys>
<Label>Bold</Label>
<Keys>~~strikethrough~~</Keys>
<Label>Strikethrough</Label>
<Keys>{'`code`'}</Keys>
<Label>Inline code</Label>
</List>
</Flex>
);
}
const List = styled.dl`
width: 100%;
overflow: hidden;
padding: 0;
margin: 0
`;
const Keys = styled.dt`
float: left;
width: 25%;
padding: 0 0 4px;
margin: 0
`;
const Label = styled.dd`
float: left;
width: 75%;
padding: 0 0 4px;
margin: 0
`;
export default KeyboardShortcuts;

View File

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

184
app/scenes/Search/Search.js Normal file
View File

@@ -0,0 +1,184 @@
// @flow
import React from 'react';
import ReactDOM from 'react-dom';
import keydown from 'react-keydown';
import { observable, action } from 'mobx';
import { observer, inject } from 'mobx-react';
import _ from 'lodash';
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 Empty from 'components/Empty';
import Flex from 'components/Flex';
import CenteredContent from 'components/CenteredContent';
import LoadingIndicator from 'components/LoadingIndicator';
import SearchField from './components/SearchField';
import DocumentPreview from 'components/DocumentPreview';
import PageTitle from 'components/PageTitle';
type Props = {
history: Object,
match: Object,
documents: DocumentsStore,
notFound: ?boolean,
};
const Container = styled(CenteredContent)`
> div {
position: relative;
height: 100%;
}
`;
const ResultsWrapper = styled(Flex)`
position: absolute;
transition: all 300ms cubic-bezier(0.65, 0.05, 0.36, 1);
top: ${props => (props.pinToTop ? '0%' : '50%')};
margin-top: ${props => (props.pinToTop ? '40px' : '-75px')};
width: 100%;
`;
const ResultList = styled(Flex)`
opacity: ${props => (props.visible ? '1' : '0')};
transition: all 400ms cubic-bezier(0.65, 0.05, 0.36, 1);
`;
const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)`
display: flex;
flex-direction: column;
flex: 1;
`;
@observer class Search extends React.Component {
firstDocument: HTMLElement;
props: Props;
@observable resultIds: string[] = []; // Document IDs
@observable searchTerm: ?string = null;
@observable isFetching = false;
componentDidMount() {
this.updateSearchResults();
}
componentDidUpdate(prevProps) {
if (prevProps.match.params.query !== this.props.match.params.query) {
this.updateSearchResults();
}
}
@keydown('esc')
goBack() {
this.props.history.goBack();
}
handleKeyDown = ev => {
// Escape
if (ev.which === 27) {
ev.preventDefault();
this.goBack();
}
// Down
if (ev.which === 40) {
ev.preventDefault();
if (this.firstDocument) {
const element = ReactDOM.findDOMNode(this.firstDocument);
// $FlowFixMe
if (element && element.focus) element.focus();
}
}
};
updateSearchResults = _.debounce(() => {
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));
};
setFirstDocumentRef = ref => {
this.firstDocument = ref;
};
get title() {
const query = this.searchTerm;
const title = 'Search';
if (query) return `${query} - ${title}`;
return title;
}
render() {
const { documents, notFound } = this.props;
const query = this.props.match.params.query;
const hasResults = this.resultIds.length > 0;
const showEmpty = !this.isFetching && this.searchTerm && !hasResults;
return (
<Container auto>
<PageTitle title={this.title} />
{this.isFetching && <LoadingIndicator />}
{notFound &&
<div>
<h1>Not Found</h1>
<p>Were unable to find the page youre accessing.</p>
</div>}
<ResultsWrapper pinToTop={hasResults} column auto>
<SearchField
searchTerm={this.searchTerm}
onKeyDown={this.handleKeyDown}
onChange={this.updateQuery}
value={query || ''}
/>
{showEmpty && <Empty>Oop, no matching documents.</Empty>}
<ResultList visible={hasResults}>
<StyledArrowKeyNavigation
mode={ArrowKeyNavigation.mode.VERTICAL}
defaultActiveChildIndex={0}
>
{this.resultIds.map((documentId, index) => {
const document = documents.getById(documentId);
if (!document) return null;
return (
<DocumentPreview
innerRef={ref =>
index === 0 && this.setFirstDocumentRef(ref)}
key={documentId}
document={document}
highlight={this.searchTerm}
showCollection
/>
);
})}
</StyledArrowKeyNavigation>
</ResultList>
</ResultsWrapper>
</Container>
);
}
}
export default withRouter(inject('documents')(Search));

View File

@@ -0,0 +1,67 @@
// @flow
import React, { Component } from 'react';
import SearchIcon from 'components/Icon/SearchIcon';
import Flex from 'components/Flex';
import { color } from 'styles/constants';
import styled from 'styled-components';
class SearchField extends Component {
input: HTMLInputElement;
props: {
onChange: Function,
};
handleChange = (ev: SyntheticEvent) => {
this.props.onChange(ev.currentTarget.value ? ev.currentTarget.value : '');
};
focusInput = (ev: SyntheticEvent) => {
this.input.focus();
};
setRef = (ref: HTMLInputElement) => {
this.input = ref;
};
render() {
return (
<Flex align="center">
<StyledIcon
type="Search"
size={46}
color={color.slateLight}
onClick={this.focusInput}
/>
<StyledInput
{...this.props}
innerRef={this.setRef}
onChange={this.handleChange}
spellCheck="false"
placeholder="search…"
autoFocus
/>
</Flex>
);
}
}
const StyledInput = styled.input`
width: 100%;
padding: 10px;
font-size: 48px;
font-weight: 400;
outline: none;
border: 0;
::-webkit-input-placeholder { color: ${color.slateLight}; }
:-moz-placeholder { color: ${color.slateLight}; }
::-moz-placeholder { color: ${color.slateLight}; }
:-ms-input-placeholder { color: ${color.slateLight}; }
`;
const StyledIcon = styled(SearchIcon)`
position: relative;
top: 4px;
`;
export default SearchField;

View File

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

View File

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

View File

@@ -0,0 +1,161 @@
// @flow
import React from 'react';
import { observer } from 'mobx-react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import ApiKeyRow from './components/ApiKeyRow';
import SettingsStore from './SettingsStore';
import { color } from 'styles/constants';
import Flex from 'components/Flex';
import Button from 'components/Button';
import Input from 'components/Input';
import HelpText from 'components/HelpText';
import SlackAuthLink from 'components/SlackAuthLink';
@observer class Settings extends React.Component {
store: SettingsStore;
constructor() {
super();
this.store = new SettingsStore();
}
render() {
const showSlackSettings = DEPLOYMENT === 'hosted';
return (
<Flex column>
{showSlackSettings &&
<Section>
<h2>Slack</h2>
<HelpText>
Connect Atlas to your Slack to instantly search for your documents
using <code>/atlas</code> command.
</HelpText>
<SlackAuthLink
scopes={['commands']}
redirectUri={`${BASE_URL}/auth/slack/commands`}
>
<img
alt="Add to Slack"
height="40"
width="139"
src="https://platform.slack-edge.com/img/add_to_slack.png"
srcSet="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x"
/>
</SlackAuthLink>
</Section>}
<Section>
<h2>API access</h2>
<HelpText>
Create API tokens to hack on your Atlas.
Learn more in <Link to="/developers">API documentation</Link>.
</HelpText>
{this.store.apiKeys &&
<Table>
<tbody>
{this.store.apiKeys &&
this.store.apiKeys.map(key => (
<ApiKeyRow
id={key.id}
key={key.id}
name={key.name}
secret={key.secret}
onDelete={this.store.deleteApiKey}
/>
))}
</tbody>
</Table>}
<InlineForm
placeholder="Token name"
buttonLabel="Create token"
name="inline_form"
value={this.store.keyName}
onChange={this.store.setKeyName}
onSubmit={this.store.createApiKey}
disabled={this.store.isFetching}
/>
</Section>
</Flex>
);
}
}
class InlineForm extends React.Component {
props: {
placeholder: string,
buttonLabel: string,
name: string,
value: ?string,
onChange: Function,
onSubmit: Function,
disabled?: ?boolean,
};
validationTimeout: number;
state = {
validationError: false,
};
componentWillUnmount() {
clearTimeout(this.validationTimeout);
}
handleSubmit = event => {
event.preventDefault();
if (this.props.value) {
this.props.onSubmit();
} else {
this.setState({
validationError: true,
});
this.validationTimeout = setTimeout(
() =>
this.setState({
validationError: false,
}),
2500
);
}
};
render() {
const { placeholder, value, onChange, buttonLabel } = this.props;
const { validationError } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<Flex auto>
<Input
type="text"
placeholder={validationError ? 'Please add a label' : placeholder}
value={value || ''}
onChange={onChange}
validationError={validationError}
/>
<Button type="submit" value={buttonLabel} />
</Flex>
</form>
);
}
}
const Section = styled.div`
margin-bottom: 40px;
`;
const Table = styled.table`
margin-bottom: 20px;
width: 100%;
td {
margin-right: 20px;
color: ${color.slate};
}
`;
export default Settings;

View File

@@ -0,0 +1,74 @@
// @flow
import { observable, action, runInAction } from 'mobx';
import invariant from 'invariant';
import { client } from 'utils/ApiClient';
import type { ApiKey } from 'types';
class SearchStore {
@observable apiKeys: ApiKey[] = [];
@observable keyName: ?string;
@observable isFetching: boolean = false;
@action fetchApiKeys = async () => {
this.isFetching = true;
try {
const res = await client.post('/apiKeys.list');
invariant(res && res.data, 'Data should be available');
const { data } = res;
runInAction('fetchApiKeys', () => {
this.apiKeys = data;
});
} catch (e) {
console.error('Something went wrong');
}
this.isFetching = false;
};
@action createApiKey = async () => {
this.isFetching = true;
try {
const res = await client.post('/apiKeys.create', {
name: this.keyName ? this.keyName : 'Untitled key',
});
invariant(res && res.data, 'Data should be available');
const { data } = res;
runInAction('createApiKey', () => {
this.apiKeys.push(data);
this.keyName = '';
});
} catch (e) {
console.error('Something went wrong');
}
this.isFetching = false;
};
@action deleteApiKey = async (id: string) => {
this.isFetching = true;
try {
await client.post('/apiKeys.delete', {
id,
});
runInAction('deleteApiKey', () => {
this.fetchApiKeys();
});
} catch (e) {
console.error('Something went wrong');
}
this.isFetching = false;
};
@action setKeyName = (value: SyntheticInputEvent) => {
this.keyName = value.target.value;
};
constructor() {
this.fetchApiKeys();
}
}
export default SearchStore;

View File

@@ -0,0 +1,49 @@
// @flow
import React from 'react';
import { observable } from 'mobx';
import { observer } from 'mobx-react';
import styled from 'styled-components';
import { color } from 'styles/constants';
type Props = {
id: string,
name: ?string,
secret: string,
onDelete: Function,
};
@observer class ApiKeyRow extends React.Component {
props: Props;
@observable disabled: boolean;
onClick = () => {
this.props.onDelete(this.props.id);
this.disabled = true;
};
render() {
const { name, secret } = this.props;
const { disabled } = this;
return (
<tr>
<td>{name}</td>
<td><code>{secret}</code></td>
<td>
<Action role="button" onClick={this.onClick} disabled={disabled}>
Action
</Action>
</td>
</tr>
);
}
}
const Action = styled.span`
font-size: 14px;
color: ${color.text};
opacity: ${({ disabled }) => (disabled ? 0.5 : 1)};
`;
export default ApiKeyRow;

View File

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

View File

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

View File

@@ -0,0 +1,68 @@
// @flow
import React from 'react';
import { Redirect } from 'react-router';
import queryString from 'query-string';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react';
import { client } from 'utils/ApiClient';
import { slackAuth } from 'utils/routeHelpers';
import AuthStore from 'stores/AuthStore';
type Props = {
auth: AuthStore,
location: Object,
};
@observer class SlackAuth extends React.Component {
props: Props;
@observable redirectTo: string;
componentDidMount() {
this.redirect();
}
async redirect() {
const { error, code, state } = queryString.parse(
this.props.location.search
);
if (error) {
if (error === 'access_denied') {
// User selected "Deny" access on Slack OAuth
this.redirectTo = '/dashboard';
} else {
this.redirectTo = '/auth/error';
}
} else if (code) {
if (this.props.location.pathname === '/auth/slack/commands') {
// User adding webhook integrations
try {
await client.post('/auth.slackCommands', { code });
this.redirectTo = '/dashboard';
} catch (e) {
this.redirectTo = '/auth/error';
}
} else {
// Slack authentication
const redirectTo = sessionStorage.getItem('redirectTo');
sessionStorage.removeItem('redirectTo');
const { success } = await this.props.auth.authWithSlack(code, state);
success
? (this.redirectTo = redirectTo || '/dashboard')
: (this.redirectTo = '/auth/error');
}
} else {
// Sign In
window.location.href = slackAuth(this.props.auth.getOauthState());
}
}
render() {
if (this.redirectTo) return <Redirect to={this.redirectTo} />;
return null;
}
}
export default inject('auth')(SlackAuth);

View File

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

View File

@@ -0,0 +1,37 @@
// @flow
import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import CenteredContent from 'components/CenteredContent';
import { ListPlaceholder } from 'components/LoadingPlaceholder';
import Empty from 'components/Empty';
import PageTitle from 'components/PageTitle';
import DocumentList from 'components/DocumentList';
import DocumentsStore from 'stores/DocumentsStore';
@observer class Starred extends Component {
props: {
documents: DocumentsStore,
};
componentDidMount() {
this.props.documents.fetchStarred();
}
render() {
const { isLoaded, isFetching, starred } = this.props.documents;
const showLoading = !isLoaded && isFetching;
const showEmpty = isLoaded && !starred.length;
return (
<CenteredContent column auto>
<PageTitle title="Starred" />
<h1>Starred</h1>
{showLoading && <ListPlaceholder />}
{showEmpty && <Empty>No starred documents yet.</Empty>}
<DocumentList documents={starred} />
</CenteredContent>
);
}
}
export default inject('documents')(Starred);

View File

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