Merge branch 'master' of github.com:jorilallo/atlas into update-slate

This commit is contained in:
Tom Moor
2017-12-08 20:22:07 -08:00
24 changed files with 289 additions and 151 deletions

View File

@@ -29,6 +29,10 @@ const Actions = styled(Flex)`
border-radius: 3px; border-radius: 3px;
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
-webkit-backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
@media print {
display: none;
}
`; `;
export default Actions; export default Actions;

View File

@@ -98,13 +98,13 @@ class DocumentPreview extends Component {
<h3> <h3>
<Highlight text={document.title} highlight={highlight} /> <Highlight text={document.title} highlight={highlight} />
{document.starred ? ( {document.starred ? (
<a onClick={this.unstar}> <span onClick={this.unstar}>
<StyledStar solid /> <StyledStar solid />
</a> </span>
) : ( ) : (
<a onClick={this.star}> <span onClick={this.star}>
<StyledStar /> <StyledStar />
</a> </span>
)} )}
</h3> </h3>
<PublishingInfo <PublishingInfo

View File

@@ -96,6 +96,10 @@ const Menu = styled.div`
overflow: hidden; overflow: hidden;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0 4px 8px rgba(0, 0, 0, 0.08), box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0 4px 8px rgba(0, 0, 0, 0.08),
0 2px 4px rgba(0, 0, 0, 0.08); 0 2px 4px rgba(0, 0, 0, 0.08);
@media print {
display: none;
}
`; `;
export default DropdownMenu; export default DropdownMenu;

View File

@@ -227,6 +227,10 @@ const Header = styled(Flex)`
flex-shrink: 0; flex-shrink: 0;
align-items: flex-end; align-items: flex-end;
${({ readOnly }) => !readOnly && 'cursor: text;'}; ${({ readOnly }) => !readOnly && 'cursor: text;'};
@media print {
display: none;
}
`; `;
const StyledEditor = styled(Editor)` const StyledEditor = styled(Editor)`

View File

@@ -93,6 +93,10 @@ const Wrapper = styled.div`
right: 0; right: 0;
top: 150px; top: 150px;
z-index: 100; z-index: 100;
@media print {
display: none;
}
`; `;
const Anchor = styled.a` const Anchor = styled.a`

View File

@@ -197,6 +197,10 @@ const Bar = styled(Flex)`
left: auto; left: auto;
right: -100%; right: -100%;
} }
@media print {
display: none;
}
`; `;
const HiddenInput = styled.input` const HiddenInput = styled.input`

View File

@@ -153,4 +153,8 @@ const Menu = styled.div`
transform: translateY(-6px) scale(1); transform: translateY(-6px) scale(1);
opacity: 1; opacity: 1;
`}; `};
@media print {
display: none;
}
`; `;

View File

@@ -5,8 +5,13 @@ import { observable } from 'mobx';
import CenteredContent from 'components/CenteredContent'; import CenteredContent from 'components/CenteredContent';
import PageTitle from 'components/PageTitle'; import PageTitle from 'components/PageTitle';
type Props = {
children?: ?React.Element<any>,
};
@observer @observer
class ErrorBoundary extends Component { class ErrorBoundary extends Component {
props: Props;
@observable error: boolean = false; @observable error: boolean = false;
componentDidCatch(error: Error, info: Object) { componentDidCatch(error: Error, info: Object) {
@@ -27,9 +32,10 @@ class ErrorBoundary extends Component {
return ( return (
<CenteredContent> <CenteredContent>
<PageTitle title="Something went wrong" /> <PageTitle title="Something went wrong" />
<h1>Something went wrong</h1> <h1>🛸 Something unexpected happened</h1>
<p> <p>
An unrecoverable error occurred. Please try{' '} An unrecoverable error occurred{window.Bugsnag ||
(true && ' and our engineers have been notified')}. Please try{' '}
<a onClick={this.handleReload}>reloading</a>. <a onClick={this.handleReload}>reloading</a>.
</p> </p>
</CenteredContent> </CenteredContent>

View File

@@ -124,6 +124,10 @@ const Container = styled(Flex)`
const Content = styled(Flex)` const Content = styled(Flex)`
margin-left: ${props => (props.editMode ? 0 : layout.sidebarWidth)}; margin-left: ${props => (props.editMode ? 0 : layout.sidebarWidth)};
transition: margin-left 200ms ease-in-out; transition: margin-left 200ms ease-in-out;
@media print {
margin-left: 0;
}
`; `;
export default withRouter(inject('user', 'auth', 'ui', 'documents')(Layout)); export default withRouter(inject('user', 'auth', 'ui', 'documents')(Layout));

View File

@@ -29,7 +29,6 @@ type Props = {
@observer @observer
class Sidebar extends Component { class Sidebar extends Component {
props: Props; props: Props;
scrollable: ?HTMLDivElement;
handleCreateCollection = () => { handleCreateCollection = () => {
this.props.ui.setActiveModal('collection-new'); this.props.ui.setActiveModal('collection-new');
@@ -39,20 +38,6 @@ class Sidebar extends Component {
this.props.ui.setActiveModal('collection-edit'); this.props.ui.setActiveModal('collection-edit');
}; };
setScrollableRef = ref => {
this.scrollable = ref;
};
scrollToActiveDocument = ref => {
const scrollable = this.scrollable;
if (!ref || !scrollable) return;
const container = scrollable.getBoundingClientRect();
const bounds = ref.getBoundingClientRect();
const scrollTop = bounds.top + container.top;
scrollable.scrollTop = scrollTop;
};
render() { render() {
const { auth, ui } = this.props; const { auth, ui } = this.props;
const { user, team } = auth; const { user, team } = auth;
@@ -71,7 +56,7 @@ class Sidebar extends Component {
/> />
<Flex auto column> <Flex auto column>
<Scrollable innerRef={this.setScrollableRef}> <Scrollable>
<Section> <Section>
<SidebarLink to="/dashboard" icon={<HomeIcon />}> <SidebarLink to="/dashboard" icon={<HomeIcon />}>
Home Home
@@ -88,7 +73,6 @@ class Sidebar extends Component {
history={this.props.history} history={this.props.history}
location={this.props.location} location={this.props.location}
onCreateCollection={this.handleCreateCollection} onCreateCollection={this.handleCreateCollection}
activeDocumentRef={this.scrollToActiveDocument}
/> />
</Section> </Section>
</Scrollable> </Scrollable>
@@ -106,6 +90,11 @@ const Container = styled(Flex)`
width: ${layout.sidebarWidth}; width: ${layout.sidebarWidth};
background: ${color.smoke}; background: ${color.smoke};
transition: left 200ms ease-in-out; transition: left 200ms ease-in-out;
@media print {
display: none;
left: 0;
}
`; `;
const Section = styled(Flex)` const Section = styled(Flex)`

View File

@@ -27,7 +27,6 @@ type Props = {
collections: CollectionsStore, collections: CollectionsStore,
documents: DocumentsStore, documents: DocumentsStore,
onCreateCollection: () => void, onCreateCollection: () => void,
activeDocumentRef: HTMLElement => void,
ui: UiStore, ui: UiStore,
}; };
@@ -36,14 +35,7 @@ class Collections extends Component {
props: Props; props: Props;
render() { render() {
const { const { history, location, collections, ui, documents } = this.props;
history,
location,
collections,
ui,
activeDocumentRef,
documents,
} = this.props;
return ( return (
<Flex column> <Flex column>
@@ -55,7 +47,6 @@ class Collections extends Component {
location={location} location={location}
collection={collection} collection={collection}
activeDocument={documents.active} activeDocument={documents.active}
activeDocumentRef={activeDocumentRef}
prefetchDocument={documents.prefetchDocument} prefetchDocument={documents.prefetchDocument}
ui={ui} ui={ui}
/> />
@@ -79,7 +70,6 @@ type CollectionLinkProps = {
collection: Collection, collection: Collection,
ui: UiStore, ui: UiStore,
activeDocument: ?Document, activeDocument: ?Document,
activeDocumentRef: HTMLElement => void,
prefetchDocument: (id: string) => Promise<void>, prefetchDocument: (id: string) => Promise<void>,
}; };
@@ -94,15 +84,32 @@ class CollectionLink extends Component {
this.dropzoneRef.open(); this.dropzoneRef.open();
}; };
render() { renderDocuments() {
const { const {
history, history,
collection, collection,
activeDocument, activeDocument,
ui,
activeDocumentRef,
prefetchDocument, prefetchDocument,
} = this.props; } = this.props;
return (
<CollectionChildren column>
{collection.documents.map(document => (
<DocumentLink
key={document.id}
history={history}
document={document}
activeDocument={activeDocument}
prefetchDocument={prefetchDocument}
depth={0}
/>
))}
</CollectionChildren>
);
}
render() {
const { history, collection, ui } = this.props;
const expanded = collection.id === ui.activeCollectionId; const expanded = collection.id === ui.activeCollectionId;
return ( return (
@@ -119,6 +126,9 @@ class CollectionLink extends Component {
to={collection.url} to={collection.url}
icon={<CollectionIcon expanded={expanded} color={collection.color} />} icon={<CollectionIcon expanded={expanded} color={collection.color} />}
iconColor={collection.color} iconColor={collection.color}
expandedContent={this.renderDocuments()}
hideExpandToggle
expand={expanded}
> >
<CollectionName justify="space-between"> <CollectionName justify="space-between">
{collection.name} {collection.name}
@@ -134,22 +144,6 @@ class CollectionLink extends Component {
/> />
</CollectionAction> </CollectionAction>
</CollectionName> </CollectionName>
{expanded && (
<Children column>
{collection.documents.map(document => (
<DocumentLink
key={document.id}
activeDocumentRef={activeDocumentRef}
history={history}
document={document}
activeDocument={activeDocument}
prefetchDocument={prefetchDocument}
depth={0}
/>
))}
</Children>
)}
</SidebarLink> </SidebarLink>
</StyledDropToImport> </StyledDropToImport>
); );
@@ -206,7 +200,7 @@ const DocumentLink = observer(
expand={showChildren} expand={showChildren}
expandedContent={ expandedContent={
document.children.length ? ( document.children.length ? (
<Children column> <DocumentChildren column>
{document.children.map(childDocument => ( {document.children.map(childDocument => (
<DocumentLink <DocumentLink
key={childDocument.id} key={childDocument.id}
@@ -217,7 +211,7 @@ const DocumentLink = observer(
depth={depth + 1} depth={depth + 1}
/> />
))} ))}
</Children> </DocumentChildren>
) : ( ) : (
undefined undefined
) )
@@ -235,7 +229,7 @@ const CollectionName = styled(Flex)`
padding: 0 0 4px; padding: 0 0 4px;
`; `;
const CollectionAction = styled.a` const CollectionAction = styled.span`
position: absolute; position: absolute;
right: 0; right: 0;
color: ${color.slate}; color: ${color.slate};
@@ -262,7 +256,13 @@ const StyledDropToImport = styled(DropToImport)`
} }
`; `;
const Children = styled(Flex)` const CollectionChildren = styled(Flex)`
margin-top: -4px;
margin-left: 36px;
`;
const DocumentChildren = styled(Flex)`
margin-top: -4px;
margin-left: 12px; margin-left: 12px;
`; `;

View File

@@ -33,7 +33,7 @@ const StyledNavLink = styled(NavLink)`
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
padding: 4px 0; padding: 4px 0;
margin-left: ${({ hasChildren }) => (hasChildren ? '-20px;' : '0')}; margin-left: ${({ iconVisible }) => (iconVisible ? '-20px;' : '0')};
color: ${color.slateDark}; color: ${color.slateDark};
font-size: 15px; font-size: 15px;
cursor: pointer; cursor: pointer;
@@ -52,6 +52,7 @@ type Props = {
icon?: React$Element<*>, icon?: React$Element<*>,
expand?: boolean, expand?: boolean,
expandedContent?: React$Element<*>, expandedContent?: React$Element<*>,
hideExpandToggle?: boolean,
iconColor?: string, iconColor?: string,
}; };
@@ -81,25 +82,35 @@ class SidebarLink extends Component {
}; };
render() { render() {
const { icon, children, onClick, to, expandedContent } = this.props; const {
icon,
children,
onClick,
to,
expandedContent,
expand,
hideExpandToggle,
} = this.props;
const Component = to ? StyledNavLink : StyledDiv; const Component = to ? StyledNavLink : StyledDiv;
const showExpandIcon = expandedContent && !hideExpandToggle;
return ( return (
<Flex column> <Flex column>
<Component <Component
iconVisible={showExpandIcon}
activeStyle={activeStyle} activeStyle={activeStyle}
hasChildren={expandedContent}
onClick={onClick} onClick={onClick}
to={to} to={to}
exact exact
> >
{icon && <IconWrapper>{icon}</IconWrapper>} {icon && <IconWrapper>{icon}</IconWrapper>}
{expandedContent && ( {showExpandIcon && (
<StyledGoTo expanded={this.expanded} onClick={this.handleClick} /> <StyledGoTo expanded={this.expanded} onClick={this.handleClick} />
)} )}
<Content onClick={this.handleExpand}>{children}</Content> <Content onClick={this.handleExpand}>{children}</Content>
</Component> </Component>
{this.expanded && expandedContent} {/* Collection */ expand && hideExpandToggle && expandedContent}
{/* Document */ this.expanded && !hideExpandToggle && expandedContent}
</Flex> </Flex>
); );
} }

View File

@@ -67,6 +67,7 @@ class DocumentMenu extends Component {
<DropdownMenuItem onClick={this.handleExport}> <DropdownMenuItem onClick={this.handleExport}>
Download Download
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={window.print}>Print</DropdownMenuItem>
<DropdownMenuItem onClick={this.handleMove}>Move</DropdownMenuItem> <DropdownMenuItem onClick={this.handleMove}>Move</DropdownMenuItem>
{allowDelete && ( {allowDelete && (
<DropdownMenuItem onClick={this.handleDelete}> <DropdownMenuItem onClick={this.handleDelete}>

View File

@@ -49,6 +49,10 @@ class CollectionScene extends Component {
} }
} }
componentWillUnmount() {
this.props.ui.clearActiveCollection();
}
loadContent = async (id: string) => { loadContent = async (id: string) => {
const { collections } = this.props; const { collections } = this.props;

View File

@@ -45,12 +45,18 @@ class Dashboard extends Component {
{showContent ? ( {showContent ? (
<span> <span>
{hasRecentlyViewed && [ {hasRecentlyViewed && [
<Subheading>Recently viewed</Subheading>, <Subheading key="viewed">Recently viewed</Subheading>,
<DocumentList documents={documents.recentlyViewed} />, <DocumentList
key="viewedDocuments"
documents={documents.recentlyViewed}
/>,
]} ]}
{hasRecentlyEdited && [ {hasRecentlyEdited && [
<Subheading>Recently edited</Subheading>, <Subheading key="edited">Recently edited</Subheading>,
<DocumentList documents={documents.recentlyEdited} />, <DocumentList
key="editedDocuments"
documents={documents.recentlyEdited}
/>,
]} ]}
</span> </span>
) : ( ) : (

View File

@@ -33,6 +33,7 @@ import CenteredContent from 'components/CenteredContent';
import PageTitle from 'components/PageTitle'; import PageTitle from 'components/PageTitle';
import NewDocumentIcon from 'components/Icon/NewDocumentIcon'; import NewDocumentIcon from 'components/Icon/NewDocumentIcon';
import Actions, { Action, Separator } from 'components/Actions'; import Actions, { Action, Separator } from 'components/Actions';
import ErrorBoundary from 'components/ErrorBoundary';
import Search from 'scenes/Search'; import Search from 'scenes/Search';
const DISCARD_CHANGES = ` const DISCARD_CHANGES = `
@@ -62,7 +63,7 @@ class DocumentScene extends Component {
@observable notFound = false; @observable notFound = false;
@observable moveModalOpen: boolean = false; @observable moveModalOpen: boolean = false;
componentWillMount() { componentDidMount() {
this.loadDocument(this.props); this.loadDocument(this.props);
} }
@@ -217,75 +218,77 @@ class DocumentScene extends Component {
return ( return (
<Container column auto> <Container column auto>
{isMoving && document && <DocumentMove document={document} />} <ErrorBoundary key={this.props.location.pathname}>
{titleText && <PageTitle title={titleText} />} {isMoving && document && <DocumentMove document={document} />}
{(this.isLoading || this.isSaving) && <LoadingIndicator />} {titleText && <PageTitle title={titleText} />}
{isFetching && ( {(this.isLoading || this.isSaving) && <LoadingIndicator />}
<CenteredContent> {isFetching && (
<LoadingState /> <CenteredContent>
</CenteredContent> <LoadingState />
)} </CenteredContent>
{!isFetching &&
document && (
<Flex justify="center" auto>
<Prompt
when={document.hasPendingChanges}
message={DISCARD_CHANGES}
/>
<Editor
key={`${document.id}-${document.revision}`}
text={document.text}
emoji={document.emoji}
onImageUploadStart={this.onImageUploadStart}
onImageUploadStop={this.onImageUploadStop}
onChange={this.onChange}
onSave={this.onSave}
onCancel={this.onDiscard}
readOnly={!this.isEditing}
/>
<Actions
align="center"
justify="flex-end"
readOnly={!this.isEditing}
>
{!isNew &&
!this.isEditing && <Collaborators document={document} />}
<Action>
{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>
)}
</Action>
{this.isEditing && (
<Action>
<a onClick={this.onDiscard}>Discard</a>
</Action>
)}
{!this.isEditing && (
<Action>
<DocumentMenu document={document} />
</Action>
)}
{!this.isEditing && <Separator />}
<Action>
{!this.isEditing && (
<a onClick={this.onClickNew}>
<NewDocumentIcon />
</a>
)}
</Action>
</Actions>
</Flex>
)} )}
{!isFetching &&
document && (
<Flex justify="center" auto>
<Prompt
when={document.hasPendingChanges}
message={DISCARD_CHANGES}
/>
<Editor
key={`${document.id}-${document.revision}`}
text={document.text}
emoji={document.emoji}
onImageUploadStart={this.onImageUploadStart}
onImageUploadStop={this.onImageUploadStop}
onChange={this.onChange}
onSave={this.onSave}
onCancel={this.onDiscard}
readOnly={!this.isEditing}
/>
<Actions
align="center"
justify="flex-end"
readOnly={!this.isEditing}
>
{!isNew &&
!this.isEditing && <Collaborators document={document} />}
<Action>
{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>
)}
</Action>
{this.isEditing && (
<Action>
<a onClick={this.onDiscard}>Discard</a>
</Action>
)}
{!this.isEditing && (
<Action>
<DocumentMenu document={document} />
</Action>
)}
{!this.isEditing && <Separator />}
<Action>
{!this.isEditing && (
<a onClick={this.onClickNew}>
<NewDocumentIcon />
</a>
)}
</Action>
</Actions>
</Flex>
)}
</ErrorBoundary>
</Container> </Container>
); );
} }

View File

@@ -2,10 +2,13 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import keydown from 'react-keydown'; import keydown from 'react-keydown';
import Waypoint from 'react-waypoint';
import { observable, action } from 'mobx'; import { observable, action } from 'mobx';
import { observer, inject } from 'mobx-react'; import { observer, inject } from 'mobx-react';
import _ from 'lodash'; import _ from 'lodash';
import DocumentsStore from 'stores/DocumentsStore'; import DocumentsStore, {
DEFAULT_PAGINATION_LIMIT,
} from 'stores/DocumentsStore';
import { withRouter } from 'react-router-dom'; import { withRouter } from 'react-router-dom';
import { searchUrl } from 'utils/routeHelpers'; import { searchUrl } from 'utils/routeHelpers';
@@ -44,6 +47,7 @@ const ResultsWrapper = styled(Flex)`
`; `;
const ResultList = styled(Flex)` const ResultList = styled(Flex)`
margin-bottom: 150px;
opacity: ${props => (props.visible ? '1' : '0')}; opacity: ${props => (props.visible ? '1' : '0')};
transition: all 400ms cubic-bezier(0.65, 0.05, 0.36, 1); transition: all 400ms cubic-bezier(0.65, 0.05, 0.36, 1);
`; `;
@@ -61,6 +65,8 @@ class Search extends Component {
@observable resultIds: string[] = []; // Document IDs @observable resultIds: string[] = []; // Document IDs
@observable query: string = ''; @observable query: string = '';
@observable offset: number = 0;
@observable allowLoadMore: boolean = true;
@observable isFetching = false; @observable isFetching = false;
componentDidMount() { componentDidMount() {
@@ -98,10 +104,27 @@ class Search extends Component {
handleQueryChange = () => { handleQueryChange = () => {
const query = this.props.match.params.query; const query = this.props.match.params.query;
this.query = query ? decodeURIComponent(query) : ''; this.query = query ? decodeURIComponent(query) : '';
this.allowLoadMore = true;
// To prevent "no results" showing before debounce kicks in
if (this.query) this.isFetching = true;
this.fetchResultsDebounced(); this.fetchResultsDebounced();
}; };
fetchResultsDebounced = _.debounce(this.fetchResults, 250); fetchResultsDebounced = _.debounce(this.fetchResults, 350, {
leading: false,
trailing: true,
});
@action
loadMoreResults = async () => {
// Don't paginate if there aren't more results or we're in the middle of fetching
if (!this.allowLoadMore || this.isFetching) return;
// Fetch more results
await this.fetchResults();
};
@action @action
fetchResults = async () => { fetchResults = async () => {
@@ -109,7 +132,19 @@ class Search extends Component {
if (this.query) { if (this.query) {
try { try {
this.resultIds = await this.props.documents.search(this.query); const newResults = await this.props.documents.search(this.query, {
offset: this.offset,
limit: DEFAULT_PAGINATION_LIMIT,
});
this.resultIds = this.resultIds.concat(newResults);
if (
newResults.length === 0 ||
newResults.length < DEFAULT_PAGINATION_LIMIT
) {
this.allowLoadMore = false;
} else {
this.offset += DEFAULT_PAGINATION_LIMIT;
}
} catch (e) { } catch (e) {
console.error('Something went wrong'); console.error('Something went wrong');
} }
@@ -157,7 +192,7 @@ class Search extends Component {
value={this.query} value={this.query}
/> />
{showEmpty && <Empty>No matching documents.</Empty>} {showEmpty && <Empty>No matching documents.</Empty>}
<ResultList visible={hasResults}> <ResultList column visible={hasResults}>
<StyledArrowKeyNavigation <StyledArrowKeyNavigation
mode={ArrowKeyNavigation.mode.VERTICAL} mode={ArrowKeyNavigation.mode.VERTICAL}
defaultActiveChildIndex={0} defaultActiveChildIndex={0}
@@ -178,6 +213,9 @@ class Search extends Component {
); );
})} })}
</StyledArrowKeyNavigation> </StyledArrowKeyNavigation>
{this.allowLoadMore && (
<Waypoint key={this.offset} onEnter={this.loadMoreResults} />
)}
</ResultList> </ResultList>
</ResultsWrapper> </ResultsWrapper>
</Container> </Container>

View File

@@ -17,8 +17,10 @@ import Document from 'models/Document';
import ErrorsStore from 'stores/ErrorsStore'; import ErrorsStore from 'stores/ErrorsStore';
import CacheStore from 'stores/CacheStore'; import CacheStore from 'stores/CacheStore';
import UiStore from 'stores/UiStore'; import UiStore from 'stores/UiStore';
import type { PaginationParams } from 'types';
const DOCUMENTS_CACHE_KEY = 'DOCUMENTS_CACHE_KEY'; const DOCUMENTS_CACHE_KEY = 'DOCUMENTS_CACHE_KEY';
export const DEFAULT_PAGINATION_LIMIT = 25;
type Options = { type Options = {
cache: CacheStore, cache: CacheStore,
@@ -77,7 +79,10 @@ class DocumentsStore extends BaseStore {
/* Actions */ /* Actions */
@action @action
fetchAll = async (request: string = 'list', options: ?Object): Promise<*> => { fetchAll = async (
request: string = 'list',
options: ?PaginationParams
): Promise<*> => {
this.isFetching = true; this.isFetching = true;
try { try {
@@ -99,12 +104,12 @@ class DocumentsStore extends BaseStore {
}; };
@action @action
fetchRecentlyModified = async (options: ?Object): Promise<*> => { fetchRecentlyModified = async (options: ?PaginationParams): Promise<*> => {
return await this.fetchAll('list', options); return await this.fetchAll('list', options);
}; };
@action @action
fetchRecentlyViewed = async (options: ?Object): Promise<*> => { fetchRecentlyViewed = async (options: ?PaginationParams): Promise<*> => {
const data = await this.fetchAll('viewed', options); const data = await this.fetchAll('viewed', options);
runInAction('DocumentsStore#fetchRecentlyViewed', () => { runInAction('DocumentsStore#fetchRecentlyViewed', () => {
@@ -119,8 +124,14 @@ class DocumentsStore extends BaseStore {
}; };
@action @action
search = async (query: string): Promise<*> => { search = async (
const res = await client.get('/documents.search', { query }); query: string,
options?: PaginationParams
): Promise<string[]> => {
const res = await client.get('/documents.search', {
...options,
query,
});
invariant(res && res.data, 'res or res.data missing'); invariant(res && res.data, 'res or res.data missing');
const { data } = res; const { data } = res;
data.forEach(documentData => this.add(new Document(documentData))); data.forEach(documentData => this.add(new Document(documentData)));

View File

@@ -35,6 +35,11 @@ class UiStore {
this.activeCollectionId = collection.id; this.activeCollectionId = collection.id;
}; };
@action
clearActiveCollection = (): void => {
this.activeCollectionId = undefined;
};
@action @action
clearActiveDocument = (): void => { clearActiveDocument = (): void => {
this.activeDocumentId = undefined; this.activeDocumentId = undefined;

View File

@@ -39,12 +39,21 @@ export type Document = {
views: number, views: number,
}; };
// Pagination response in an API call
export type Pagination = { export type Pagination = {
limit: number, limit: number,
nextPath: string, nextPath: string,
offset: number, offset: number,
}; };
// Pagination request params
export type PaginationParams = {
limit?: number,
offset?: number,
sort?: string,
direction?: 'ASC' | 'DESC',
};
export type ApiKey = { export type ApiKey = {
id: string, id: string,
name: ?string, name: ?string,

View File

@@ -154,6 +154,7 @@
"react-modal": "^3.1.2", "react-modal": "^3.1.2",
"react-portal": "^4.0.0", "react-portal": "^4.0.0",
"react-router-dom": "^4.2.0", "react-router-dom": "^4.2.0",
"react-waypoint": "^7.3.1",
"redis": "^2.6.2", "redis": "^2.6.2",
"redis-lock": "^0.1.0", "redis-lock": "^0.1.0",
"rimraf": "^2.5.4", "rimraf": "^2.5.4",

View File

@@ -142,13 +142,17 @@ router.post('documents.revisions', auth(), pagination(), async ctx => {
}; };
}); });
router.post('documents.search', auth(), async ctx => { router.post('documents.search', auth(), pagination(), async ctx => {
const { query } = ctx.body; const { query } = ctx.body;
const { offset, limit } = ctx.state.pagination;
ctx.assertPresent(query, 'query is required'); ctx.assertPresent(query, 'query is required');
const user = await ctx.state.user; const user = await ctx.state.user;
const documents = await Document.searchForUser(user, query); const documents = await Document.searchForUser(user, query, {
offset,
limit,
});
const data = await Promise.all( const data = await Promise.all(
documents.map(async document => await presentDocument(ctx, document)) documents.map(async document => await presentDocument(ctx, document))

View File

@@ -160,16 +160,20 @@ Document.findById = async id => {
} }
}; };
Document.searchForUser = async (user, query, options = {}) => { Document.searchForUser = async (
user,
query,
options = {}
): Promise<Document[]> => {
const limit = options.limit || 15; const limit = options.limit || 15;
const offset = options.offset || 0; const offset = options.offset || 0;
const sql = ` const sql = `
SELECT * FROM documents SELECT *, ts_rank(documents."searchVector", plainto_tsquery('english', :query)) as "searchRanking" FROM documents
WHERE "searchVector" @@ plainto_tsquery('english', :query) AND WHERE "searchVector" @@ plainto_tsquery('english', :query) AND
"teamId" = '${user.teamId}'::uuid AND "teamId" = '${user.teamId}'::uuid AND
"deletedAt" IS NULL "deletedAt" IS NULL
ORDER BY ts_rank(documents."searchVector", plainto_tsquery('english', :query)) DESC ORDER BY "searchRanking" DESC
LIMIT :limit OFFSET :offset; LIMIT :limit OFFSET :offset;
`; `;
@@ -184,10 +188,17 @@ Document.searchForUser = async (user, query, options = {}) => {
}) })
.map(document => document.id); .map(document => document.id);
// Second query to get views for the data
const withViewsScope = { method: ['withViews', user.id] }; const withViewsScope = { method: ['withViews', user.id] };
return Document.scope('defaultScope', withViewsScope).findAll({ const documents = await Document.scope(
'defaultScope',
withViewsScope
).findAll({
where: { id: ids }, where: { id: ids },
}); });
// Order the documents in the same order as the first query
return _.sortBy(documents, doc => ids.indexOf(doc.id));
}; };
// Instance methods // Instance methods

View File

@@ -1825,6 +1825,10 @@ console-control-strings@^1.0.0, console-control-strings@~1.1.0:
version "1.1.0" version "1.1.0"
resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e"
consolidated-events@^1.1.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/consolidated-events/-/consolidated-events-1.1.1.tgz#25395465b35e531395418b7bbecb5ecaf198d179"
constant-case@^2.0.0: constant-case@^2.0.0:
version "2.0.0" version "2.0.0"
resolved "https://registry.yarnpkg.com/constant-case/-/constant-case-2.0.0.tgz#4175764d389d3fa9c8ecd29186ed6005243b6a46" resolved "https://registry.yarnpkg.com/constant-case/-/constant-case-2.0.0.tgz#4175764d389d3fa9c8ecd29186ed6005243b6a46"
@@ -7215,7 +7219,7 @@ prop-types@>=15.5.6, prop-types@^15.5.10, prop-types@^15.5.4, prop-types@^15.5.8
fbjs "^0.8.9" fbjs "^0.8.9"
loose-envify "^1.3.1" loose-envify "^1.3.1"
prop-types@^15.5.7, prop-types@^15.6.0: prop-types@^15.0.0, prop-types@^15.5.7, prop-types@^15.6.0:
version "15.6.0" version "15.6.0"
resolved "https://registry.npmjs.org/prop-types/-/prop-types-15.6.0.tgz#ceaf083022fc46b4a35f69e13ef75aed0d639856" resolved "https://registry.npmjs.org/prop-types/-/prop-types-15.6.0.tgz#ceaf083022fc46b4a35f69e13ef75aed0d639856"
dependencies: dependencies:
@@ -7510,6 +7514,13 @@ react-transform-hmr@^1.0.3:
global "^4.3.0" global "^4.3.0"
react-proxy "^1.1.7" react-proxy "^1.1.7"
react-waypoint@^7.3.1:
version "7.3.1"
resolved "https://registry.yarnpkg.com/react-waypoint/-/react-waypoint-7.3.1.tgz#abb165d9b6c9590f8d82ceafbe61c2c887262a37"
dependencies:
consolidated-events "^1.1.0"
prop-types "^15.0.0"
react@^15.5.4: react@^15.5.4:
version "15.6.2" version "15.6.2"
resolved "https://registry.npmjs.org/react/-/react-15.6.2.tgz#dba0434ab439cfe82f108f0f511663908179aa72" resolved "https://registry.npmjs.org/react/-/react-15.6.2.tgz#dba0434ab439cfe82f108f0f511663908179aa72"