diff --git a/Makefile b/Makefile index ee874f9a72..a10b9261f0 100644 --- a/Makefile +++ b/Makefile @@ -9,10 +9,16 @@ build: test: docker-compose up -d redis postgres s3 + yarn sequelize db:drop --env=test + yarn sequelize db:create --env=test + yarn sequelize db:migrate --env=test yarn test watch: docker-compose up -d redis postgres s3 + yarn sequelize db:drop --env=test + yarn sequelize db:create --env=test + yarn sequelize db:migrate --env=test yarn test:watch destroy: diff --git a/README.md b/README.md index bae6a2068e..1210f3245b 100644 --- a/README.md +++ b/README.md @@ -139,8 +139,16 @@ To add new tests, write your tests with [Jest](https://facebook.github.io/jest/) ```shell # To run all tests -yarn test +make test +# To run backend tests in watch mode +make watch +``` + +Once the test database is created with `make test` you may individually run +frontend and backend tests directly. + +```shell # To run backend tests yarn test:server diff --git a/app/components/BreadcrumbMenu.js b/app/components/BreadcrumbMenu.js index fb372727c7..fa7df3f4bf 100644 --- a/app/components/BreadcrumbMenu.js +++ b/app/components/BreadcrumbMenu.js @@ -1,25 +1,22 @@ // @flow import * as React from "react"; -import { Link } from "react-router-dom"; -import { DropdownMenu, DropdownMenuItem } from "components/DropdownMenu"; +import { DropdownMenu } from "components/DropdownMenu"; +import DropdownMenuItems from "components/DropdownMenu/DropdownMenuItems"; type Props = { label: React.Node, path: Array, }; -export default class BreadcrumbMenu extends React.Component { - render() { - const { path } = this.props; - - return ( - - {path.map((item) => ( - - {item.title} - - ))} - - ); - } +export default function BreadcrumbMenu({ label, path }: Props) { + return ( + + ({ + title: item.title, + to: item.url, + }))} + /> + + ); } diff --git a/app/components/DocumentHistory/components/Revision.js b/app/components/DocumentHistory/components/Revision.js index c8d0774ce3..dbb228a47d 100644 --- a/app/components/DocumentHistory/components/Revision.js +++ b/app/components/DocumentHistory/components/Revision.js @@ -11,11 +11,12 @@ import Avatar from "components/Avatar"; import Flex from "components/Flex"; import Time from "components/Time"; import RevisionMenu from "menus/RevisionMenu"; +import { type Theme } from "types"; import { documentHistoryUrl } from "utils/routeHelpers"; type Props = { - theme: Object, + theme: Theme, showMenu: boolean, selected: boolean, document: Document, diff --git a/app/components/DocumentPreview/DocumentPreview.js b/app/components/DocumentPreview/DocumentPreview.js index 4c91e0094c..6f41db5fd0 100644 --- a/app/components/DocumentPreview/DocumentPreview.js +++ b/app/components/DocumentPreview/DocumentPreview.js @@ -9,6 +9,7 @@ import Document from "models/Document"; import Badge from "components/Badge"; import Button from "components/Button"; import DocumentMeta from "components/DocumentMeta"; +import EventBoundary from "components/EventBoundary"; import Flex from "components/Flex"; import Highlight from "components/Highlight"; import Tooltip from "components/Tooltip"; @@ -123,7 +124,9 @@ class DocumentPreview extends React.Component { )}   - + + + diff --git a/app/components/DropdownMenu/DropdownMenu.js b/app/components/DropdownMenu/DropdownMenu.js index f18ab02168..037ad7ec8a 100644 --- a/app/components/DropdownMenu/DropdownMenu.js +++ b/app/components/DropdownMenu/DropdownMenu.js @@ -18,7 +18,7 @@ type Children = | React.Node | ((options: { closePortal: () => void }) => React.Node); -type Props = { +type Props = {| label?: React.Node, onOpen?: () => void, onClose?: () => void, @@ -27,7 +27,7 @@ type Props = { hover?: boolean, style?: Object, position?: "left" | "right" | "center", -}; +|}; @observer class DropdownMenu extends React.Component { diff --git a/app/components/DropdownMenu/DropdownMenuItems.js b/app/components/DropdownMenu/DropdownMenuItems.js new file mode 100644 index 0000000000..b8f33cd21c --- /dev/null +++ b/app/components/DropdownMenu/DropdownMenuItems.js @@ -0,0 +1,128 @@ +// @flow +import * as React from "react"; +import { Link } from "react-router-dom"; +import DropdownMenu from "./DropdownMenu"; +import DropdownMenuItem from "./DropdownMenuItem"; + +type MenuItem = + | {| + title: React.Node, + to: string, + visible?: boolean, + disabled?: boolean, + |} + | {| + title: React.Node, + onClick: (event: SyntheticEvent<>) => void | Promise, + visible?: boolean, + disabled?: boolean, + |} + | {| + title: React.Node, + href: string, + visible?: boolean, + disabled?: boolean, + |} + | {| + title: React.Node, + visible?: boolean, + disabled?: boolean, + style?: Object, + hover?: boolean, + items: MenuItem[], + |} + | {| + type: "separator", + visible?: boolean, + |} + | {| + type: "heading", + visible?: boolean, + title: React.Node, + |}; + +type Props = {| + items: MenuItem[], +|}; + +export default function DropdownMenuItems({ items }: Props): React.Node { + let filtered = items.filter((item) => item.visible !== false); + + // this block literally just trims unneccessary separators + filtered = filtered.reduce((acc, item, index) => { + // trim separators from start / end + if (item.type === "separator" && index === 0) return acc; + if (item.type === "separator" && index === filtered.length - 1) return acc; + + // trim double separators looking ahead / behind + const prev = filtered[index - 1]; + if (prev && prev.type === "separator" && item.type === "separator") + return acc; + + // otherwise, continue + return [...acc, item]; + }, []); + + return filtered.map((item, index) => { + if (item.to) { + return ( + + {item.title} + + ); + } + + if (item.href) { + return ( + + {item.title} + + ); + } + + if (item.onClick) { + return ( + + {item.title} + + ); + } + + if (item.items) { + return ( + + {item.title} + + } + hover={item.hover} + key={index} + > + + + ); + } + + if (item.type === "separator") { + return
; + } + + return null; + }); +} diff --git a/app/components/Editor.js b/app/components/Editor.js index aea158bce7..66fbcb3aae 100644 --- a/app/components/Editor.js +++ b/app/components/Editor.js @@ -145,9 +145,16 @@ const StyledEditor = styled(RichMarkdownEditor)` } .heading-name { - display: block; - position: relative; - top: -52px; + pointer-events: none; + } + + .heading-name:first-child { + & + h1, + & + h2, + & + h3, + & + h4 { + margin-top: 0; + } } p { diff --git a/app/components/EventBoundary.js b/app/components/EventBoundary.js new file mode 100644 index 0000000000..16b64809b8 --- /dev/null +++ b/app/components/EventBoundary.js @@ -0,0 +1,16 @@ +// @flow + +import * as React from "react"; + +type Props = { + children: React.Node, +}; + +export default function EventBoundary({ children }: Props) { + const handleClick = React.useCallback((event: SyntheticEvent<>) => { + event.preventDefault(); + event.stopPropagation(); + }, []); + + return {children}; +} diff --git a/app/components/Highlight.js b/app/components/Highlight.js index dea98fd573..85f0040bb2 100644 --- a/app/components/Highlight.js +++ b/app/components/Highlight.js @@ -18,6 +18,7 @@ function Highlight({ ...rest }: Props) { let regex; + let index = 0; if (highlight instanceof RegExp) { regex = highlight; } else { @@ -29,8 +30,10 @@ function Highlight({ return ( {highlight - ? replace(text, regex, (tag, index) => ( - {processResult ? processResult(tag) : tag} + ? replace(text, regex, (tag) => ( + + {processResult ? processResult(tag) : tag} + )) : text} diff --git a/app/components/Input.js b/app/components/Input.js index f195a607a6..655ae46a9b 100644 --- a/app/components/Input.js +++ b/app/components/Input.js @@ -33,10 +33,6 @@ const RealInput = styled.input` &::placeholder { color: ${(props) => props.theme.placeholder}; } - - &::-webkit-search-cancel-button { - -webkit-appearance: searchfield-cancel-button; - } `; const Wrapper = styled.div` diff --git a/app/components/InputSearch.js b/app/components/InputSearch.js index 7d594580f0..1ab086e1e9 100644 --- a/app/components/InputSearch.js +++ b/app/components/InputSearch.js @@ -7,11 +7,12 @@ import keydown from "react-keydown"; import { withRouter, type RouterHistory } from "react-router-dom"; import styled, { withTheme } from "styled-components"; import Input from "./Input"; +import { type Theme } from "types"; import { searchUrl } from "utils/routeHelpers"; type Props = { history: RouterHistory, - theme: Object, + theme: Theme, source: string, placeholder?: string, collectionId?: string, diff --git a/app/components/Layout.js b/app/components/Layout.js index fcd6851895..8f58d5a180 100644 --- a/app/components/Layout.js +++ b/app/components/Layout.js @@ -21,6 +21,7 @@ import { LoadingIndicatorBar } from "components/LoadingIndicator"; import Modal from "components/Modal"; import Sidebar from "components/Sidebar"; import SettingsSidebar from "components/Sidebar/Settings"; +import { type Theme } from "types"; import { homeUrl, searchUrl, @@ -35,7 +36,7 @@ type Props = { auth: AuthStore, ui: UiStore, notifications?: React.Node, - theme: Object, + theme: Theme, }; @observer diff --git a/app/components/PaginatedList.js b/app/components/PaginatedList.js index a23ae569df..ba58bf5ac3 100644 --- a/app/components/PaginatedList.js +++ b/app/components/PaginatedList.js @@ -1,5 +1,6 @@ // @flow import ArrowKeyNavigation from "boundless-arrow-key-navigation"; +import { isEqual } from "lodash"; import { observable, action } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; @@ -40,6 +41,9 @@ class PaginatedList extends React.Component { if (prevProps.fetch !== this.props.fetch) { this.fetchResults(); } + if (!isEqual(prevProps.options, this.props.options)) { + this.fetchResults(); + } } fetchResults = async () => { diff --git a/app/components/PathToDocument.js b/app/components/PathToDocument.js index 147e724efe..f9995e79f9 100644 --- a/app/components/PathToDocument.js +++ b/app/components/PathToDocument.js @@ -14,6 +14,7 @@ type Props = { document?: ?Document, collection: ?Collection, onSuccess?: () => void, + style?: Object, ref?: (?React.ElementRef<"div">) => void, }; @@ -34,13 +35,20 @@ class PathToDocument extends React.Component { }; render() { - const { result, collection, document, ref } = this.props; + const { result, collection, document, ref, style } = this.props; const Component = document ? ResultWrapperLink : ResultWrapper; if (!result) return
; return ( - + {collection && }   {result.path @@ -72,21 +80,27 @@ const StyledGoToIcon = styled(GoToIcon)` const ResultWrapper = styled.div` display: flex; margin-bottom: 10px; - margin-left: -4px; user-select: none; color: ${(props) => props.theme.text}; cursor: default; + + svg { + flex-shrink: 0; + } `; const ResultWrapperLink = styled(ResultWrapper.withComponent("a"))` - margin: 0 -8px; padding: 8px 4px; ${DocumentTitle} { display: none; } + svg { + flex-shrink: 0; + } + &:hover, &:active, &:focus { diff --git a/app/components/Sidebar/Main.js b/app/components/Sidebar/Main.js index 75b7eae0a6..13e86d8791 100644 --- a/app/components/Sidebar/Main.js +++ b/app/components/Sidebar/Main.js @@ -69,7 +69,6 @@ class MainSidebar extends React.Component { const { user, team } = auth; if (!user || !team) return null; - const draftDocumentsCount = documents.drafts.length; const can = policies.abilities(team.id); return ( @@ -123,8 +122,8 @@ class MainSidebar extends React.Component { label={ Drafts - {draftDocumentsCount > 0 && ( - + {documents.totalDrafts > 0 && ( + )} } diff --git a/app/components/Sidebar/components/SidebarLink.js b/app/components/Sidebar/components/SidebarLink.js index db4f2f69a0..b56ac8c512 100644 --- a/app/components/Sidebar/components/SidebarLink.js +++ b/app/components/Sidebar/components/SidebarLink.js @@ -5,6 +5,7 @@ import * as React from "react"; import { withRouter, NavLink } from "react-router-dom"; import styled, { withTheme } from "styled-components"; import Flex from "components/Flex"; +import { type Theme } from "types"; type Props = { to?: string | Object, @@ -19,7 +20,7 @@ type Props = { hideDisclosure?: boolean, iconColor?: string, active?: boolean, - theme: Object, + theme: Theme, exact?: boolean, depth?: number, }; diff --git a/app/components/Subheading.js b/app/components/Subheading.js index b7bc5be950..c0716deb54 100644 --- a/app/components/Subheading.js +++ b/app/components/Subheading.js @@ -11,12 +11,11 @@ const H3 = styled.h3` margin-top: 22px; margin-bottom: 12px; line-height: 1; + position: relative; `; const Underline = styled("span")` - position: relative; - top: 1px; - + margin-top: -1px; display: inline-block; font-weight: 500; font-size: 14px; diff --git a/app/components/Tab.js b/app/components/Tab.js index 4c165b76e7..75b9e61d4d 100644 --- a/app/components/Tab.js +++ b/app/components/Tab.js @@ -2,9 +2,10 @@ import * as React from "react"; import { NavLink } from "react-router-dom"; import styled, { withTheme } from "styled-components"; +import { type Theme } from "types"; type Props = { - theme: Object, + theme: Theme, }; const StyledNavLink = styled(NavLink)` diff --git a/app/menus/CollectionMenu.js b/app/menus/CollectionMenu.js index c7ab1d90c6..cba3e7c4af 100644 --- a/app/menus/CollectionMenu.js +++ b/app/menus/CollectionMenu.js @@ -11,7 +11,8 @@ import CollectionDelete from "scenes/CollectionDelete"; import CollectionEdit from "scenes/CollectionEdit"; import CollectionExport from "scenes/CollectionExport"; import CollectionMembers from "scenes/CollectionMembers"; -import { DropdownMenu, DropdownMenuItem } from "components/DropdownMenu"; +import { DropdownMenu } from "components/DropdownMenu"; +import DropdownMenuItems from "components/DropdownMenu/DropdownMenuItems"; import Modal from "components/Modal"; import VisuallyHidden from "components/VisuallyHidden"; import getDataTransferFiles from "utils/getDataTransferFiles"; @@ -139,41 +140,43 @@ class CollectionMenu extends React.Component { /> - {collection && ( - <> - {can.update && ( - - New document - - )} - {can.update && ( - - Import document - - )} - {can.update &&
} - {can.update && ( - - Edit… - - )} - {can.update && ( - - Permissions… - - )} - {can.export && ( - - Export… - - )} - - )} - {can.delete && ( - - Delete… - - )} +
{ } = this.props; const can = policies.abilities(document.id); - const canShareDocuments = can.share && auth.team && auth.team.sharing; + const canShareDocuments = !!(can.share && auth.team && auth.team.sharing); const canViewHistory = can.read && !can.restore; const collection = collections.get(document.collectionId); @@ -183,146 +180,147 @@ class DocumentMenu extends React.Component { onClose={onClose} label={label} > - {can.unarchive && ( - - Restore - - )} - {can.restore && - (collection ? ( - - Restore - - ) : ( - Restore…} - style={{ + -
Choose a collection
- {collections.orderedData.map((collection) => { - const can = policies.abilities(collection.id); + }, + hover: true, + items: [ + { + type: "heading", + title: "Choose a collection", + }, + ...collections.orderedData.map((collection) => { + const can = policies.abilities(collection.id); - return ( - - this.handleRestore(ev, { collectionId: collection.id }) - } - disabled={!can.update} - > - -  {collection.name} - - ); - })} -
- ))} - {showPin && - (document.pinned - ? can.unpin && ( - - Unpin - - ) - : can.pin && ( - - Pin to collection - - ))} - {document.isStarred - ? can.unstar && ( - - Unstar - - ) - : can.star && ( - - Star - - )} - {canShareDocuments && ( - - Share link… - - )} - {showToggleEmbeds && ( - <> - {document.embedsDisabled ? ( - - Enable embeds - - ) : ( - - Disable embeds - - )} - - )} - {!can.restore &&
} - - {can.createChildDocument && ( - - New nested document - - )} - {can.update && !document.isTemplate && ( - - Create template… - - )} - {can.unpublish && ( - - Unpublish - - )} - {can.update && ( - Edit - )} - {can.update && ( - - Duplicate - - )} - {can.archive && ( - - Archive - - )} - {can.delete && ( - - Delete… - - )} - {can.move && ( - Move… - )} -
- {canViewHistory && ( - <> - - History - - - )} - {can.download && ( - - Download - - )} - {showPrint && ( - Print - )} + return { + title: ( + <> + +  {collection.name} + + ), + onClick: (ev) => + this.handleRestore(ev, { collectionId: collection.id }), + disabled: !can.update, + }; + }), + ], + }, + { + title: "Unpin", + onClick: this.handleUnpin, + visible: !!(showPin && document.pinned && can.unpin), + }, + { + title: "Pin to collection", + onClick: this.handlePin, + visible: !!(showPin && !document.pinned && can.pin), + }, + { + title: "Unstar", + onClick: this.handleUnstar, + visible: document.isStarred && !!can.unstar, + }, + { + title: "Star", + onClick: this.handleStar, + visible: !document.isStarred && !!can.star, + }, + { + title: "Share link…", + onClick: this.handleShareLink, + visible: canShareDocuments, + }, + { + title: "Enable embeds", + onClick: document.enableEmbeds, + visible: !!showToggleEmbeds && document.embedsDisabled, + }, + { + title: "Disable embeds", + onClick: document.disableEmbeds, + visible: !!showToggleEmbeds && !document.embedsDisabled, + }, + { + type: "separator", + }, + { + title: "New nested document", + onClick: this.handleNewChild, + visible: !!can.createChildDocument, + }, + { + title: "Create template…", + onClick: this.handleOpenTemplateModal, + visible: !!can.update && !document.isTemplate, + }, + { + title: "Edit", + onClick: this.handleEdit, + visible: !!can.update, + }, + { + title: "Duplicate", + onClick: this.handleDuplicate, + visible: !!can.update, + }, + { + title: "Unpublish", + onClick: this.handleUnpublish, + visible: !!can.unpublish, + }, + { + title: "Archive", + onClick: this.handleArchive, + visible: !!can.archive, + }, + { + title: "Delete…", + onClick: this.handleDelete, + visible: !!can.delete, + }, + { + title: "Move…", + onClick: this.handleMove, + visible: !!can.move, + }, + { + type: "separator", + }, + { + title: "History", + onClick: this.handleDocumentHistory, + visible: canViewHistory, + }, + { + title: "Download", + onClick: this.handleExport, + visible: !!can.download, + }, + { + title: "Print", + onClick: window.print, + visible: !!showPrint, + }, + ]} + /> { onSubmit={this.handleDeleteModalClose} /> - - {group && ( - <> - - Members… - - - {(can.update || can.delete) &&
} - - {can.update && ( - Edit… - )} - - {can.delete && ( - - Delete… - - )} - - )} +
); diff --git a/app/menus/NewChildDocumentMenu.js b/app/menus/NewChildDocumentMenu.js index f6e25d5535..69f9ee425a 100644 --- a/app/menus/NewChildDocumentMenu.js +++ b/app/menus/NewChildDocumentMenu.js @@ -1,13 +1,13 @@ // @flow import { observable } from "mobx"; import { observer, inject } from "mobx-react"; -import { MoreIcon } from "outline-icons"; import * as React from "react"; import { Redirect } from "react-router-dom"; import CollectionsStore from "stores/CollectionsStore"; import Document from "models/Document"; -import { DropdownMenu, DropdownMenuItem } from "components/DropdownMenu"; +import { DropdownMenu } from "components/DropdownMenu"; +import DropdownMenuItems from "components/DropdownMenu/DropdownMenuItems"; import { newDocumentUrl } from "utils/routeHelpers"; type Props = { @@ -39,20 +39,28 @@ class NewChildDocumentMenu extends React.Component { render() { if (this.redirectTo) return ; - const { label, document, collections, ...rest } = this.props; + const { label, document, collections } = this.props; const collection = collections.get(document.collectionId); return ( - } {...rest}> - - - New document in{" "} - {collection ? collection.name : "collection"} - - - - New nested document - + + + New document in{" "} + {collection ? collection.name : "collection"} + + ), + onClick: this.handleNewDocument, + }, + { + title: "New nested document", + onClick: this.handleNewChild, + }, + ]} + /> ); } diff --git a/app/menus/NewDocumentMenu.js b/app/menus/NewDocumentMenu.js index a85d2520c4..7ee4b3e433 100644 --- a/app/menus/NewDocumentMenu.js +++ b/app/menus/NewDocumentMenu.js @@ -10,11 +10,8 @@ import DocumentsStore from "stores/DocumentsStore"; import PoliciesStore from "stores/PoliciesStore"; import Button from "components/Button"; import CollectionIcon from "components/CollectionIcon"; -import { - DropdownMenu, - DropdownMenuItem, - Header, -} from "components/DropdownMenu"; +import { DropdownMenu, Header } from "components/DropdownMenu"; +import DropdownMenuItems from "components/DropdownMenu/DropdownMenuItems"; import { newDocumentUrl } from "utils/routeHelpers"; type Props = { @@ -63,20 +60,18 @@ class NewDocumentMenu extends React.Component { {...rest} >
Choose a collection
- {collections.orderedData.map((collection) => { - const can = policies.abilities(collection.id); - - return ( - this.handleNewDocument(collection.id)} - disabled={!can.update} - > - -  {collection.name} - - ); - })} + ({ + onClick: () => this.handleNewDocument(collection.id), + disabled: !policies.abilities(collection.id).update, + title: ( + <> + +  {collection.name} + + ), + }))} + />
); } diff --git a/app/menus/NewTemplateMenu.js b/app/menus/NewTemplateMenu.js index ed3d94a825..86c99cfb66 100644 --- a/app/menus/NewTemplateMenu.js +++ b/app/menus/NewTemplateMenu.js @@ -9,11 +9,8 @@ import CollectionsStore from "stores/CollectionsStore"; import PoliciesStore from "stores/PoliciesStore"; import Button from "components/Button"; import CollectionIcon from "components/CollectionIcon"; -import { - DropdownMenu, - DropdownMenuItem, - Header, -} from "components/DropdownMenu"; +import { DropdownMenu, Header } from "components/DropdownMenu"; +import DropdownMenuItems from "components/DropdownMenu/DropdownMenuItems"; import { newDocumentUrl } from "utils/routeHelpers"; type Props = { @@ -53,20 +50,18 @@ class NewTemplateMenu extends React.Component { {...rest} >
Choose a collection
- {collections.orderedData.map((collection) => { - const can = policies.abilities(collection.id); - - return ( - this.handleNewDocument(collection.id)} - disabled={!can.update} - > - -  {collection.name} - - ); - })} + ({ + onClick: () => this.handleNewDocument(collection.id), + disabled: !policies.abilities(collection.id).update, + title: ( + <> + +  {collection.name} + + ), + }))} + /> ); } diff --git a/app/menus/UserMenu.js b/app/menus/UserMenu.js index 603eae0d16..cf2c2b3980 100644 --- a/app/menus/UserMenu.js +++ b/app/menus/UserMenu.js @@ -4,7 +4,8 @@ import * as React from "react"; import UsersStore from "stores/UsersStore"; import User from "models/User"; -import { DropdownMenu, DropdownMenuItem } from "components/DropdownMenu"; +import { DropdownMenu } from "components/DropdownMenu"; +import DropdownMenuItems from "components/DropdownMenu/DropdownMenuItems"; type Props = { user: User, @@ -65,31 +66,38 @@ class UserMenu extends React.Component { return ( - {user.isAdmin && ( - - Make {user.name} a member… - - )} - {!user.isAdmin && !user.isSuspended && ( - - Make {user.name} an admin… - - )} - {!user.lastActiveAt && ( - - Revoke invite… - - )} - {user.lastActiveAt && - (user.isSuspended ? ( - - Activate account - - ) : ( - - Suspend account… - - ))} + ); } diff --git a/app/models/User.js b/app/models/User.js index 831b8a7a63..8203355250 100644 --- a/app/models/User.js +++ b/app/models/User.js @@ -1,4 +1,5 @@ // @flow +import { computed } from "mobx"; import BaseModel from "./BaseModel"; class User extends BaseModel { @@ -11,6 +12,11 @@ class User extends BaseModel { lastActiveAt: string; isSuspended: boolean; createdAt: string; + + @computed + get isInvited(): boolean { + return !this.lastActiveAt; + } } export default User; diff --git a/app/scenes/Collection.js b/app/scenes/Collection.js index 40729510c3..fa8e763279 100644 --- a/app/scenes/Collection.js +++ b/app/scenes/Collection.js @@ -36,6 +36,7 @@ import Tab from "components/Tab"; import Tabs from "components/Tabs"; import Tooltip from "components/Tooltip"; import CollectionMenu from "menus/CollectionMenu"; +import { type Theme } from "types"; import { AuthorizationError } from "utils/errors"; import { newDocumentUrl, collectionUrl } from "utils/routeHelpers"; @@ -45,7 +46,7 @@ type Props = { collections: CollectionsStore, policies: PoliciesStore, match: Match, - theme: Object, + theme: Theme, }; @observer diff --git a/app/scenes/CollectionMembers/components/MemberListItem.js b/app/scenes/CollectionMembers/components/MemberListItem.js index dd9cd4f547..227874e819 100644 --- a/app/scenes/CollectionMembers/components/MemberListItem.js +++ b/app/scenes/CollectionMembers/components/MemberListItem.js @@ -45,7 +45,7 @@ const MemberListItem = ({ ) : ( "Never signed in" )} - {!user.lastActiveAt && Invited} + {user.isInvited && Invited} {user.isAdmin && Admin} } diff --git a/app/scenes/CollectionMembers/components/UserListItem.js b/app/scenes/CollectionMembers/components/UserListItem.js index 94d0d8730f..a4950547e9 100644 --- a/app/scenes/CollectionMembers/components/UserListItem.js +++ b/app/scenes/CollectionMembers/components/UserListItem.js @@ -28,7 +28,7 @@ const UserListItem = ({ user, onAdd, canEdit }: Props) => { ) : ( "Never signed in" )} - {!user.lastActiveAt && Invited} + {user.isInvited && Invited} {user.isAdmin && Admin} } diff --git a/app/scenes/Document/components/DataLoader.js b/app/scenes/Document/components/DataLoader.js index 4ead3bd4de..3f3dc08318 100644 --- a/app/scenes/Document/components/DataLoader.js +++ b/app/scenes/Document/components/DataLoader.js @@ -7,6 +7,7 @@ import { observer, inject } from "mobx-react"; import * as React from "react"; import type { RouterHistory, Match } from "react-router-dom"; import { withRouter } from "react-router-dom"; +import { withTheme } from "styled-components"; import parseDocumentSlug from "shared/utils/parseDocumentSlug"; import AuthStore from "stores/AuthStore"; import DocumentsStore from "stores/DocumentsStore"; @@ -22,7 +23,7 @@ import DocumentComponent from "./Document"; import HideSidebar from "./HideSidebar"; import Loading from "./Loading"; import SocketPresence from "./SocketPresence"; -import { type LocationWithState } from "types"; +import { type LocationWithState, type Theme } from "types"; import { NotFoundError, OfflineError } from "utils/errors"; import isInternalUrl from "utils/isInternalUrl"; import { matchDocumentEdit, updateDocumentUrl } from "utils/routeHelpers"; @@ -36,6 +37,7 @@ type Props = {| policies: PoliciesStore, revisions: RevisionsStore, ui: UiStore, + theme: Theme, history: RouterHistory, |}; @@ -49,6 +51,7 @@ class DataLoader extends React.Component { const { documents, match } = this.props; this.document = documents.getByUrl(match.params.documentSlug); this.loadDocument(); + this.updateBackground(); } componentDidUpdate(prevProps: Props) { @@ -73,6 +76,13 @@ class DataLoader extends React.Component { ) { this.loadRevision(); } + this.updateBackground(); + } + + updateBackground() { + // ensure the wider page color always matches the theme. This is to + // account for share links which don't sit in the wider Layout component + window.document.body.style.background = this.props.theme.background; } get isEditing() { @@ -276,5 +286,5 @@ export default withRouter( "revisions", "policies", "shares" - )(DataLoader) + )(withTheme(DataLoader)) ); diff --git a/app/scenes/Document/components/Document.js b/app/scenes/Document/components/Document.js index c4ad6f1e90..720fbb7dcb 100644 --- a/app/scenes/Document/components/Document.js +++ b/app/scenes/Document/components/Document.js @@ -7,7 +7,7 @@ import * as React from "react"; import keydown from "react-keydown"; import { Prompt, Route, withRouter } from "react-router-dom"; import type { RouterHistory, Match } from "react-router-dom"; -import styled, { withTheme } from "styled-components"; +import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; import * as Y from "yjs"; import AuthStore from "stores/AuthStore"; @@ -31,7 +31,8 @@ import KeyboardShortcutsButton from "./KeyboardShortcutsButton"; import MarkAsViewed from "./MarkAsViewed"; import References from "./References"; import MultiplayerExtension from "multiplayer/MultiplayerExtension"; -import { type LocationWithState } from "types"; +import { type LocationWithState, type Theme } from "types"; +import { isCustomDomain } from "utils/domains"; import { emojiToUrl } from "utils/emoji"; import { collectionUrl, @@ -66,7 +67,7 @@ type Props = { }, onCreateLink: (title: string) => string, onSearchLink: (term: string) => any, - theme: Object, + theme: Theme, auth: AuthStore, ui: UiStore, }; @@ -86,7 +87,6 @@ class DocumentScene extends React.Component { componentDidMount() { this.updateIsDirty(); - this.updateBackground(); } componentDidUpdate(prevProps) { @@ -120,8 +120,6 @@ class DocumentScene extends React.Component { this.title = document.title; this.isDirty = true; } - - this.updateBackground(); } componentWillUnmount() { @@ -130,12 +128,6 @@ class DocumentScene extends React.Component { } } - updateBackground() { - // ensure the wider page color always matches the theme. This is to - // account for share links which don't sit in the wider Layout component - window.document.body.style.background = this.props.theme.background; - } - @keydown("m") goToMove(ev) { if (!this.props.readOnly) return; @@ -345,6 +337,12 @@ class DocumentScene extends React.Component { const disableEmbeds = (team && team.documentEmbeds === false) || document.embedsDisabled; + const headings = this.editor.current + ? this.editor.current.getHeadings() + : []; + const showContents = + (ui.tocVisible && readOnly) || (isShare && !!headings.length); + return ( { )} @@ -441,15 +439,7 @@ class DocumentScene extends React.Component { )} }> - {ui.tocVisible && readOnly && ( - - )} + {showContents && } { - {isShare ? : } + {isShare && !isCustomDomain() && } + {!isShare && } ); } @@ -532,7 +523,8 @@ const MaxWidth = styled(Flex)` ${breakpoint("tablet")` padding: 0 24px; margin: 4px auto 12px; - max-width: calc(48px + ${(props) => (props.tocVisible ? "64em" : "46em")}); + max-width: calc(48px + ${(props) => + props.showContents ? "64em" : "46em"}); `}; ${breakpoint("desktopLarge")` @@ -541,5 +533,5 @@ const MaxWidth = styled(Flex)` `; export default withRouter( - inject("ui", "auth", "policies", "revisions")(withTheme(DocumentScene)) + inject("ui", "auth", "policies", "revisions")(DocumentScene) ); diff --git a/app/scenes/Document/components/DocumentMove.js b/app/scenes/Document/components/DocumentMove.js index aab06eb512..dea5f081f1 100644 --- a/app/scenes/Document/components/DocumentMove.js +++ b/app/scenes/Document/components/DocumentMove.js @@ -1,13 +1,12 @@ // @flow -import ArrowKeyNavigation from "boundless-arrow-key-navigation"; import { Search } from "js-search"; import { last } from "lodash"; import { observable, computed } from "mobx"; import { observer, inject } from "mobx-react"; import * as React from "react"; -import ReactDOM from "react-dom"; +import AutoSizer from "react-virtualized-auto-sizer"; +import { FixedSizeList as List } from "react-window"; import styled from "styled-components"; - import CollectionsStore, { type DocumentPath } from "stores/CollectionsStore"; import DocumentsStore from "stores/DocumentsStore"; import UiStore from "stores/UiStore"; @@ -28,7 +27,6 @@ type Props = {| @observer class DocumentMove extends React.Component { - firstDocument: ?PathToDocument; @observable searchTerm: ?string; @observable isSaving: boolean; @@ -87,17 +85,6 @@ class DocumentMove extends React.Component { 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(); - } - } - }; - handleSuccess = () => { this.props.ui.showToast("Document moved"); this.props.onRequestClose(); @@ -107,10 +94,6 @@ class DocumentMove extends React.Component { this.searchTerm = ev.target.value; }; - setFirstDocumentRef = (ref) => { - this.firstDocument = ref; - }; - renderPathToCurrentDocument() { const { collections, document } = this.props; const result = collections.getPathForDocument(document.id); @@ -125,8 +108,24 @@ class DocumentMove extends React.Component { } } + row = ({ index, data, style }) => { + const result = data[index]; + const { document, collections } = this.props; + + return ( + + ); + }; + render() { const { document, collections, onRequestClose } = this.props; + const data = this.results; return ( @@ -145,33 +144,29 @@ class DocumentMove extends React.Component { - - - - {this.results.map((result, index) => ( - - index === 0 && this.setFirstDocumentRef(ref) - } - onSuccess={this.handleSuccess} - /> - ))} - - + + {({ width, height }) => ( + + data[index].id} + > + {this.row} + + + )} + @@ -202,25 +197,18 @@ const Input = styled("input")` `; const NewLocation = styled(Outline)` - flex-direction: column; + display: block; + flex: initial; + height: 40vh; `; -const Results = styled(Flex)` - display: block; - width: 100%; - max-height: 40vh; - overflow-y: auto; - padding: 8px; +const Results = styled.div` + padding: 8px 0; + height: calc(100% - 46px); `; const Section = styled(Flex)` margin-bottom: 24px; `; -const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)` - display: flex; - flex-direction: column; - flex: 1; -`; - export default inject("documents", "collections", "ui")(DocumentMove); diff --git a/app/scenes/Drafts.js b/app/scenes/Drafts.js index 14ae4724e3..fa38201b6b 100644 --- a/app/scenes/Drafts.js +++ b/app/scenes/Drafts.js @@ -1,37 +1,107 @@ // @flow -import { observer, inject } from "mobx-react"; +import { observable } from "mobx"; +import { inject, observer } from "mobx-react"; +import queryString from "query-string"; import * as React from "react"; - +import { type RouterHistory } from "react-router-dom"; +import styled from "styled-components"; import DocumentsStore from "stores/DocumentsStore"; +import CollectionFilter from "scenes/Search/components/CollectionFilter"; +import DateFilter from "scenes/Search/components/DateFilter"; + import Actions, { Action } from "components/Actions"; import CenteredContent from "components/CenteredContent"; import Empty from "components/Empty"; +import Flex from "components/Flex"; import Heading from "components/Heading"; import InputSearch from "components/InputSearch"; import PageTitle from "components/PageTitle"; import PaginatedDocumentList from "components/PaginatedDocumentList"; import Subheading from "components/Subheading"; import NewDocumentMenu from "menus/NewDocumentMenu"; +import { type LocationWithState } from "types"; -type Props = { +type Props = {| documents: DocumentsStore, -}; + history: RouterHistory, + location: LocationWithState, +|}; @observer class Drafts extends React.Component { + @observable params: URLSearchParams = new URLSearchParams( + this.props.location.search + ); + + componentDidUpdate(prevProps) { + if (prevProps.location.search !== this.props.location.search) { + this.handleQueryChange(); + } + } + + handleQueryChange = () => { + this.params = new URLSearchParams(this.props.location.search); + }; + + handleFilterChange = (search) => { + this.props.history.replace({ + pathname: this.props.location.pathname, + search: queryString.stringify({ + ...queryString.parse(this.props.location.search), + ...search, + }), + }); + }; + + get collectionId() { + const id = this.params.get("collectionId"); + return id ? id : undefined; + } + + get dateFilter() { + const id = this.params.get("dateFilter"); + return id ? id : undefined; + } + render() { - const { fetchDrafts, drafts } = this.props.documents; + const { drafts, fetchDrafts } = this.props.documents; + const isFiltered = this.collectionId || this.dateFilter; + const options = { + dateFilter: this.dateFilter, + collectionId: this.collectionId, + }; return ( Drafts + + Documents + + + this.handleFilterChange({ collectionId }) + } + /> + this.handleFilterChange({ dateFilter })} + /> + + + Documents} - empty={You’ve not got any drafts at the moment.} + empty={ + + {isFiltered + ? "No documents found for your filters." + : "You’ve not got any drafts at the moment."} + + } fetch={fetchDrafts} - documents={drafts} - showDraft={false} + documents={drafts(options)} + options={options} showCollection /> @@ -48,4 +118,17 @@ class Drafts extends React.Component { } } +const Filters = styled(Flex)` + opacity: 0.85; + transition: opacity 100ms ease-in-out; + position: absolute; + right: -8px; + bottom: 0; + padding: 0 0 6px; + + &:hover { + opacity: 1; + } +`; + export default inject("documents")(Drafts); diff --git a/app/scenes/GroupMembers/components/GroupMemberListItem.js b/app/scenes/GroupMembers/components/GroupMemberListItem.js index f5fc97c190..be4a255bb3 100644 --- a/app/scenes/GroupMembers/components/GroupMemberListItem.js +++ b/app/scenes/GroupMembers/components/GroupMemberListItem.js @@ -35,7 +35,7 @@ const GroupMemberListItem = ({ ) : ( "Never signed in" )} - {!user.lastActiveAt && Invited} + {user.isInvited && Invited} {user.isAdmin && Admin} } diff --git a/app/scenes/GroupMembers/components/UserListItem.js b/app/scenes/GroupMembers/components/UserListItem.js index 321368c2aa..af63ab4cdd 100644 --- a/app/scenes/GroupMembers/components/UserListItem.js +++ b/app/scenes/GroupMembers/components/UserListItem.js @@ -28,7 +28,7 @@ const UserListItem = ({ user, onAdd, canEdit }: Props) => { ) : ( "Never signed in" )} - {!user.lastActiveAt && Invited} + {user.isInvited && Invited} {user.isAdmin && Admin} } diff --git a/app/scenes/Search/Search.js b/app/scenes/Search/Search.js index 33e5404b15..4b8bbfcae1 100644 --- a/app/scenes/Search/Search.js +++ b/app/scenes/Search/Search.js @@ -302,31 +302,29 @@ class Search extends React.Component { )} {showEmpty && ( - - - - No documents found for your search filters.
- Create a new document? -
- - {this.collectionId ? ( - - ) : ( - - )} -    - - -
-
+ ) : ( + + )} +    + + +
)} @@ -403,7 +401,8 @@ const Filters = styled(Flex)` margin-bottom: 12px; opacity: 0.85; transition: opacity 100ms ease-in-out; - overflow-y: auto; + overflow-y: hidden; + overflow-x: auto; padding: 8px 0; ${breakpoint("tablet")` diff --git a/app/scenes/Search/components/CollectionFilter.js b/app/scenes/Search/components/CollectionFilter.js index 88a5d7c497..de7cad1958 100644 --- a/app/scenes/Search/components/CollectionFilter.js +++ b/app/scenes/Search/components/CollectionFilter.js @@ -5,7 +5,7 @@ import CollectionsStore from "stores/CollectionsStore"; import FilterOptions from "./FilterOptions"; const defaultOption = { - key: undefined, + key: "", label: "Any collection", }; diff --git a/app/scenes/Search/components/DateFilter.js b/app/scenes/Search/components/DateFilter.js index 8fca6047e1..f8fafff129 100644 --- a/app/scenes/Search/components/DateFilter.js +++ b/app/scenes/Search/components/DateFilter.js @@ -3,7 +3,7 @@ import * as React from "react"; import FilterOptions from "./FilterOptions"; const options = [ - { key: undefined, label: "Any time" }, + { key: "", label: "Any time" }, { key: "day", label: "Past day" }, { key: "week", label: "Past week" }, { key: "month", label: "Past month" }, diff --git a/app/scenes/Search/components/FilterOptions.js b/app/scenes/Search/components/FilterOptions.js index b0faa9d72b..68f31d5eef 100644 --- a/app/scenes/Search/components/FilterOptions.js +++ b/app/scenes/Search/components/FilterOptions.js @@ -8,7 +8,7 @@ import FilterOption from "./FilterOption"; type Props = { options: { - key: ?string, + key: string, label: string, note?: string, }[], @@ -20,7 +20,7 @@ type Props = { const FilterOptions = ({ options, - activeKey, + activeKey = "", defaultLabel, selectedPrefix = "", onSelect, diff --git a/app/scenes/Search/components/SearchField.js b/app/scenes/Search/components/SearchField.js index 5d8e897f01..440627c3e7 100644 --- a/app/scenes/Search/components/SearchField.js +++ b/app/scenes/Search/components/SearchField.js @@ -3,11 +3,12 @@ import { SearchIcon } from "outline-icons"; import * as React from "react"; import styled, { withTheme } from "styled-components"; import Flex from "components/Flex"; +import { type Theme } from "types"; type Props = { onChange: (string) => void, defaultValue?: string, - theme: Object, + theme: Theme, }; class SearchField extends React.Component { diff --git a/app/scenes/Search/components/StatusFilter.js b/app/scenes/Search/components/StatusFilter.js index 2a17b55011..7685d69edc 100644 --- a/app/scenes/Search/components/StatusFilter.js +++ b/app/scenes/Search/components/StatusFilter.js @@ -4,7 +4,7 @@ import FilterOptions from "./FilterOptions"; const options = [ { - key: undefined, + key: "", label: "Active documents", note: "Documents in collections you are able to access", }, diff --git a/app/scenes/Search/components/UserFilter.js b/app/scenes/Search/components/UserFilter.js index 1c9e7bddc5..6f9c42e4f5 100644 --- a/app/scenes/Search/components/UserFilter.js +++ b/app/scenes/Search/components/UserFilter.js @@ -5,7 +5,7 @@ import UsersStore from "stores/UsersStore"; import FilterOptions from "./FilterOptions"; const defaultOption = { - key: undefined, + key: "", label: "Any author", }; diff --git a/app/stores/AuthStore.js b/app/stores/AuthStore.js index eeaa4d3c75..091e214fb9 100644 --- a/app/stores/AuthStore.js +++ b/app/stores/AuthStore.js @@ -35,7 +35,9 @@ export default class AuthStore { rootStore: RootStore; constructor(rootStore: RootStore) { - // Rehydrate + this.rootStore = rootStore; + + // attempt to load the previous state of this store from localstorage let data = {}; try { data = JSON.parse(localStorage.getItem(AUTH_STORE) || "{}"); @@ -43,17 +45,10 @@ export default class AuthStore { // no-op Safari private mode } - this.rootStore = rootStore; - this.user = new User(data.user); - this.team = new Team(data.team); - this.token = getCookie("accessToken"); - this.lastSignedIn = getCookie("lastSignedIn"); setImmediate(() => this.fetchConfig()); + this.rehydrate(data); - if (this.token) { - setImmediate(() => this.fetch()); - } - + // persists this entire store to localstorage whenever any keys are changed autorun(() => { try { localStorage.setItem(AUTH_STORE, this.asJson); @@ -61,6 +56,35 @@ export default class AuthStore { // no-op Safari private mode } }); + + // listen to the localstorage value changing in other tabs to react to + // signin/signout events in other tabs and follow suite. + window.addEventListener("storage", (event) => { + if (event.key === AUTH_STORE) { + const data = JSON.parse(event.newValue); + + // if there is no user on the new data then we know the other tab + // signed out and we should do the same. Otherwise, if we're not + // signed in then hydrate from the received data + if (this.token && data.user === null) { + this.logout(); + } else if (!this.token) { + this.rehydrate(data); + } + } + }); + } + + @action + rehydrate(data: { user: User, team: Team }) { + this.user = new User(data.user); + this.team = new Team(data.team); + this.token = getCookie("accessToken"); + this.lastSignedIn = getCookie("lastSignedIn"); + + if (this.token) { + setImmediate(() => this.fetch()); + } } addPolicies = (policies) => { diff --git a/app/stores/DocumentsStore.js b/app/stores/DocumentsStore.js index 5c39a67938..8ecb9675ee 100644 --- a/app/stores/DocumentsStore.js +++ b/app/stores/DocumentsStore.js @@ -3,6 +3,7 @@ import invariant from "invariant"; import { find, orderBy, filter, compact, omitBy } from "lodash"; import { observable, action, computed, runInAction } from "mobx"; import { MAX_TITLE_LENGTH } from "shared/constants"; +import { subtractDate } from "shared/utils/date"; import naturalSort from "shared/utils/naturalSort"; import BaseStore from "stores/BaseStore"; import RootStore from "stores/RootStore"; @@ -168,12 +169,31 @@ export default class DocumentsStore extends BaseStore { } @computed - get drafts(): Document[] { - return filter( + get totalDrafts(): number { + return this.drafts().length; + } + + drafts = (options = {}): Document[] => { + let drafts = filter( orderBy(this.all, "updatedAt", "desc"), (doc) => !doc.publishedAt ); - } + + if (options.dateFilter) { + drafts = filter( + drafts, + (draft) => + new Date(draft.updatedAt) >= + subtractDate(new Date(), options.dateFilter) + ); + } + + if (options.collectionId) { + drafts = filter(drafts, { collectionId: options.collectionId }); + } + + return drafts; + }; @computed get active(): ?Document { diff --git a/app/stores/UsersStore.js b/app/stores/UsersStore.js index 3022a2a373..49240a6110 100644 --- a/app/stores/UsersStore.js +++ b/app/stores/UsersStore.js @@ -32,7 +32,7 @@ export default class UsersStore extends BaseStore { @computed get invited(): User[] { - return filter(this.orderedData, (user) => !user.lastActiveAt); + return filter(this.orderedData, (user) => user.isInvited); } @computed diff --git a/app/types/index.js b/app/types/index.js index 8d8b044432..a30d9260c4 100644 --- a/app/types/index.js +++ b/app/types/index.js @@ -1,7 +1,10 @@ // @flow import { type Location } from "react-router-dom"; +import theme from "shared/styles/theme"; import Document from "models/Document"; +export type Theme = typeof theme; + export type LocationWithState = Location & { state: { [key: string]: string, diff --git a/app/utils/domains.js b/app/utils/domains.js index 29067eabd1..f7796d725c 100644 --- a/app/utils/domains.js +++ b/app/utils/domains.js @@ -1,7 +1,16 @@ // @flow -import { stripSubdomain } from "shared/utils/domains"; +import { parseDomain, stripSubdomain } from "shared/utils/domains"; import env from "env"; export function getCookieDomain(domain: string) { return env.SUBDOMAINS_ENABLED ? stripSubdomain(domain) : domain; } + +export function isCustomDomain() { + const parsed = parseDomain(window.location.origin); + const main = parseDomain(env.URL); + + return ( + parsed && main && (main.domain !== parsed.domain || main.tld !== parsed.tld) + ); +} diff --git a/package.json b/package.json index 1c4e66919b..3a7c1f350f 100644 --- a/package.json +++ b/package.json @@ -123,7 +123,7 @@ "mobx-react": "^6.2.5", "natural-sort": "^1.0.0", "nodemailer": "^4.4.0", - "outline-icons": "^1.21.0-6", + "outline-icons": "^1.21.0", "oy-vey": "^0.10.0", "pg": "^8.3.0", "pg-hstore": "^2.3.3", @@ -143,8 +143,10 @@ "react-modal": "^3.1.2", "react-portal": "^4.0.0", "react-router-dom": "^5.1.2", + "react-virtualized-auto-sizer": "^1.0.2", "react-waypoint": "^9.0.2", - "rich-markdown-editor": "^11.0.3", + "react-window": "^1.8.6", + "rich-markdown-editor": "^11.0.6", "semver": "^7.3.2", "sequelize": "^6.3.4", "sequelize-cli": "^6.2.0", @@ -202,5 +204,5 @@ "dot-prop": "^5.2.0", "js-yaml": "^3.13.1" }, - "version": "0.49.0" + "version": "0.50.0" } \ No newline at end of file diff --git a/server/api/documents.js b/server/api/documents.js index b40a80ea25..7048e1fe30 100644 --- a/server/api/documents.js +++ b/server/api/documents.js @@ -1,6 +1,7 @@ // @flow import Router from "koa-router"; import Sequelize from "sequelize"; +import { subtractDate } from "../../shared/utils/date"; import documentImporter from "../commands/documentImporter"; import documentMover from "../commands/documentMover"; import { NotFoundError, InvalidRequestError } from "../errors"; @@ -359,24 +360,51 @@ router.post("documents.starred", auth(), pagination(), async (ctx) => { }); router.post("documents.drafts", auth(), pagination(), async (ctx) => { - let { sort = "updatedAt", direction } = ctx.body; + let { collectionId, dateFilter, sort = "updatedAt", direction } = ctx.body; if (direction !== "ASC") direction = "DESC"; const user = ctx.state.user; - const collectionIds = await user.collectionIds(); + + if (collectionId) { + ctx.assertUuid(collectionId, "collectionId must be a UUID"); + + const collection = await Collection.scope({ + method: ["withMembership", user.id], + }).findByPk(collectionId); + authorize(user, "read", collection); + } + + const collectionIds = !!collectionId + ? [collectionId] + : await user.collectionIds(); + + const whereConditions = { + userId: user.id, + collectionId: collectionIds, + publishedAt: { [Op.eq]: null }, + updatedAt: undefined, + }; + + if (dateFilter) { + ctx.assertIn( + dateFilter, + ["day", "week", "month", "year"], + "dateFilter must be one of day,week,month,year" + ); + + whereConditions.updatedAt = { + [Op.gte]: subtractDate(new Date(), dateFilter), + }; + } else { + delete whereConditions.updatedAt; + } const collectionScope = { method: ["withCollection", user.id] }; - const viewScope = { method: ["withViews", user.id] }; const documents = await Document.scope( "defaultScope", - collectionScope, - viewScope + collectionScope ).findAll({ - where: { - userId: user.id, - collectionId: collectionIds, - publishedAt: { [Op.eq]: null }, - }, + where: whereConditions, order: [[sort, direction]], offset: ctx.state.pagination.offset, limit: ctx.state.pagination.limit, diff --git a/server/api/shares.test.js b/server/api/shares.test.js index b9b768d880..a7078f24d8 100644 --- a/server/api/shares.test.js +++ b/server/api/shares.test.js @@ -149,9 +149,10 @@ describe("#shares.create", () => { expect(body.data.documentTitle).toBe(document.title); }); - it("should allow creating a share record for document in read-only collection", async () => { + it("should not allow creating a share record with read-only permissions", async () => { const { user, document, collection } = await seed(); collection.private = true; + await collection.save(); await CollectionUser.create({ @@ -164,11 +165,7 @@ describe("#shares.create", () => { const res = await server.post("/api/shares.create", { body: { token: user.getJwtToken(), documentId: document.id }, }); - const body = await res.json(); - - expect(res.status).toEqual(200); - expect(body.data.published).toBe(false); - expect(body.data.documentTitle).toBe(document.title); + expect(res.status).toEqual(403); }); it("should allow creating a share record if link previously revoked", async () => { diff --git a/server/api/team.js b/server/api/team.js index 2f6248681e..3183ea39a2 100644 --- a/server/api/team.js +++ b/server/api/team.js @@ -1,7 +1,7 @@ // @flow import Router from "koa-router"; import auth from "../middlewares/authentication"; -import { Team } from "../models"; +import { Event, Team } from "../models"; import policy from "../policies"; import { presentTeam, presentPolicies } from "../presenters"; @@ -36,8 +36,24 @@ router.post("team.update", auth(), async (ctx) => { } if (avatarUrl !== undefined) team.avatarUrl = avatarUrl; + + const changes = team.changed(); + const data = {}; + await team.save(); + for (const change of changes) { + data[change] = team[change]; + } + + await Event.create({ + name: "teams.update", + actorId: user.id, + teamId: user.teamId, + data, + ip: ctx.request.ip, + }); + ctx.body = { data: presentTeam(team), policies: presentPolicies(user, [team]), diff --git a/server/api/users.js b/server/api/users.js index 7e3b06f70c..7f929afd4e 100644 --- a/server/api/users.js +++ b/server/api/users.js @@ -69,6 +69,14 @@ router.post("users.update", auth(), async (ctx) => { await user.save(); + await Event.create({ + name: "users.update", + actorId: user.id, + userId: user.id, + teamId: user.teamId, + ip: ctx.request.ip, + }); + ctx.body = { data: presentUser(user, { includeDetails: true }), }; diff --git a/server/auth/google.js b/server/auth/google.js index d7f12639de..d52a963949 100644 --- a/server/auth/google.js +++ b/server/auth/google.js @@ -5,7 +5,7 @@ import Router from "koa-router"; import { capitalize } from "lodash"; import Sequelize from "sequelize"; import auth from "../middlewares/authentication"; -import { User, Team, Event } from "../models"; +import { User, Team } from "../models"; const Op = Sequelize.Op; @@ -122,20 +122,6 @@ router.get("google.callback", auth({ required: false }), async (ctx) => { await team.provisionSubdomain(hostname); } - if (isFirstSignin) { - await Event.create({ - name: "users.create", - actorId: user.id, - userId: user.id, - teamId: team.id, - data: { - name: user.name, - service: "google", - }, - ip: ctx.request.ip, - }); - } - // set cookies on response and redirect to team subdomain ctx.signIn(user, team, "google", isFirstSignin); } catch (err) { diff --git a/server/auth/slack.js b/server/auth/slack.js index 698bb69742..c1915e1ad6 100644 --- a/server/auth/slack.js +++ b/server/auth/slack.js @@ -4,14 +4,7 @@ import Router from "koa-router"; import Sequelize from "sequelize"; import { slackAuth } from "../../shared/utils/routeHelpers"; import auth from "../middlewares/authentication"; -import { - Authentication, - Collection, - Integration, - User, - Event, - Team, -} from "../models"; +import { Authentication, Collection, Integration, User, Team } from "../models"; import * as Slack from "../slack"; import { getCookieDomain } from "../utils/domains"; @@ -101,20 +94,6 @@ router.get("slack.callback", auth({ required: false }), async (ctx) => { await team.provisionSubdomain(data.team.domain); } - if (isFirstSignin) { - await Event.create({ - name: "users.create", - actorId: user.id, - userId: user.id, - teamId: team.id, - data: { - name: user.name, - service: "slack", - }, - ip: ctx.request.ip, - }); - } - // set cookies on response and redirect to team subdomain ctx.signIn(user, team, "slack", isFirstSignin); } catch (err) { diff --git a/server/events.js b/server/events.js index 5ed9786b47..f60181c5cf 100644 --- a/server/events.js +++ b/server/events.js @@ -9,6 +9,7 @@ const log = debug("services"); export type UserEvent = | { name: | "users.create" // eslint-disable-line + | "users.signin" | "users.update" | "users.suspend" | "users.activate" @@ -16,6 +17,7 @@ export type UserEvent = userId: string, teamId: string, actorId: string, + ip: string, } | { name: "users.invite", @@ -25,6 +27,7 @@ export type UserEvent = email: string, name: string, }, + ip: string, }; export type DocumentEvent = @@ -43,6 +46,7 @@ export type DocumentEvent = collectionId: string, teamId: string, actorId: string, + ip: string, } | { name: "documents.move", @@ -54,6 +58,7 @@ export type DocumentEvent = collectionIds: string[], documentIds: string[], }, + ip: string, } | { name: | "documents.update" // eslint-disable-line @@ -69,6 +74,7 @@ export type DocumentEvent = autosave: boolean, done: boolean, }, + ip: string, } | { name: "documents.title_change", @@ -81,6 +87,7 @@ export type DocumentEvent = title: string, previousTitle: string, }, + ip: string, }; export type RevisionEvent = { @@ -98,6 +105,7 @@ export type CollectionEvent = collectionId: string, teamId: string, actorId: string, + ip: string, } | { name: "collections.add_user" | "collections.remove_user", @@ -105,6 +113,7 @@ export type CollectionEvent = collectionId: string, teamId: string, actorId: string, + ip: string, } | { name: "collections.add_group" | "collections.remove_group", @@ -139,6 +148,15 @@ export type IntegrationEvent = { modelId: string, teamId: string, actorId: string, + ip: string, +}; + +export type TeamEvent = { + name: "teams.update", + teamId: string, + actorId: string, + data: Object, + ip: string, }; export type Event = @@ -147,7 +165,8 @@ export type Event = | CollectionEvent | IntegrationEvent | GroupEvent - | RevisionEvent; + | RevisionEvent + | TeamEvent; const globalEventsQueue = createQueue("global events"); const serviceEventsQueue = createQueue("service events"); diff --git a/server/middlewares/authentication.js b/server/middlewares/authentication.js index 9ed0899b57..126221334b 100644 --- a/server/middlewares/authentication.js +++ b/server/middlewares/authentication.js @@ -2,7 +2,7 @@ import addMonths from "date-fns/add_months"; import JWT from "jsonwebtoken"; import { AuthenticationError, UserSuspendedError } from "../errors"; -import { User, Team, ApiKey } from "../models"; +import { User, Event, Team, ApiKey } from "../models"; import type { ContextWithState } from "../types"; import { getCookieDomain } from "../utils/domains"; import { getUserForJWT } from "../utils/jwt"; @@ -94,12 +94,7 @@ export default function auth(options?: { required?: boolean } = {}) { ctx.state.user = user; } - ctx.signIn = async ( - user: User, - team: Team, - service, - isFirstSignin = false - ) => { + ctx.signIn = (user: User, team: Team, service, isFirstSignin = false) => { if (user.isSuspended) { return ctx.redirect("/?notice=suspended"); } @@ -107,6 +102,32 @@ export default function auth(options?: { required?: boolean } = {}) { // update the database when the user last signed in user.updateSignedIn(ctx.request.ip); + if (isFirstSignin) { + Event.create({ + name: "users.create", + actorId: user.id, + userId: user.id, + teamId: team.id, + data: { + name: user.name, + service, + }, + ip: ctx.request.ip, + }); + } else { + Event.create({ + name: "users.signin", + actorId: user.id, + userId: user.id, + teamId: team.id, + data: { + name: user.name, + service, + }, + ip: ctx.request.ip, + }); + } + const domain = getCookieDomain(ctx.request.hostname); const expires = addMonths(new Date(), 3); diff --git a/server/models/Event.js b/server/models/Event.js index d5421e3a6e..c0fa2374c4 100644 --- a/server/models/Event.js +++ b/server/models/Event.js @@ -55,7 +55,8 @@ Event.add = (event) => { }; Event.ACTIVITY_EVENTS = [ - "users.create", + "collections.create", + "collections.delete", "documents.publish", "documents.archive", "documents.unarchive", @@ -63,20 +64,19 @@ Event.ACTIVITY_EVENTS = [ "documents.unpin", "documents.delete", "documents.restore", - "collections.create", - "collections.delete", + "users.create", ]; Event.AUDIT_EVENTS = [ "api_keys.create", "api_keys.delete", - "users.create", - "users.promote", - "users.demote", - "users.invite", - "users.suspend", - "users.activate", - "users.delete", + "collections.create", + "collections.update", + "collections.add_user", + "collections.remove_user", + "collections.add_group", + "collections.remove_group", + "collections.delete", "documents.create", "documents.publish", "documents.update", @@ -86,19 +86,22 @@ Event.AUDIT_EVENTS = [ "documents.unpin", "documents.move", "documents.delete", - "shares.create", - "shares.update", - "shares.revoke", "groups.create", "groups.update", "groups.delete", - "collections.create", - "collections.update", - "collections.add_user", - "collections.remove_user", - "collections.add_group", - "collections.remove_group", - "collections.delete", + "shares.create", + "shares.update", + "shares.revoke", + "teams.update", + "users.create", + "users.update", + "users.signin", + "users.promote", + "users.demote", + "users.invite", + "users.suspend", + "users.activate", + "users.delete", ]; export default Event; diff --git a/server/policies/document.js b/server/policies/document.js index 32bf902412..310734a8f3 100644 --- a/server/policies/document.js +++ b/server/policies/document.js @@ -16,18 +16,6 @@ allow(User, ["read", "download"], Document, (user, document) => { return user.teamId === document.teamId; }); -allow(User, ["share"], Document, (user, document) => { - if (document.archivedAt) return false; - if (document.deletedAt) return false; - - // existence of collection option is not required here to account for share tokens - if (document.collection && cannot(user, "read", document.collection)) { - return false; - } - - return user.teamId === document.teamId; -}); - allow(User, ["star", "unstar"], Document, (user, document) => { if (document.archivedAt) return false; if (document.deletedAt) return false; @@ -43,15 +31,14 @@ allow(User, ["star", "unstar"], Document, (user, document) => { return user.teamId === document.teamId; }); -allow(User, "update", Document, (user, document) => { +allow(User, ["update", "share"], Document, (user, document) => { if (document.archivedAt) return false; if (document.deletedAt) return false; - invariant( - document.collection, - "collection is missing, did you forget to include in the query scope?" - ); - if (cannot(user, "update", document.collection)) return false; + // existence of collection option is not required here to account for share tokens + if (document.collection && cannot(user, "update", document.collection)) { + return false; + } return user.teamId === document.teamId; }); diff --git a/server/static/index.html b/server/static/index.html index d5ef94d9ee..2f79916fba 100644 --- a/server/static/index.html +++ b/server/static/index.html @@ -52,6 +52,7 @@ window.Sentry.init({ dsn: "//inject-sentry-dsn//", ignoreErrors: [ + "ResizeObserver loop limit exceeded", "AuthorizationError", "NetworkError", "NotFoundError", diff --git a/shared/utils/date.js b/shared/utils/date.js new file mode 100644 index 0000000000..d19518b55c --- /dev/null +++ b/shared/utils/date.js @@ -0,0 +1,23 @@ +// @flow +import subDays from "date-fns/sub_days"; +import subMonth from "date-fns/sub_months"; +import subWeek from "date-fns/sub_weeks"; +import subYear from "date-fns/sub_years"; + +export function subtractDate( + date: Date, + period: "day" | "week" | "month" | "year" +) { + switch (period) { + case "day": + return subDays(date, 1); + case "week": + return subWeek(date, 1); + case "month": + return subMonth(date, 1); + case "year": + return subYear(date, 1); + default: + return date; + } +} diff --git a/yarn.lock b/yarn.lock index cb930aab48..dd127bee46 100644 --- a/yarn.lock +++ b/yarn.lock @@ -962,10 +962,10 @@ core-js-pure "^3.0.0" regenerator-runtime "^0.13.4" -"@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.4.0", "@babel/runtime@^7.8.4", "@babel/runtime@^7.9.2": - version "7.11.2" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.11.2.tgz#f549c13c754cc40b87644b9fa9f09a6a95fe0736" - integrity sha512-TeWkU52so0mPtDcaCTxNBI/IHiz0pZgr8VEFqXFtZWpYD08ZB6FaSwVAS8MKRQAP3bYKiVjwysOJgMFY28o6Tw== +"@babel/runtime@^7.0.0", "@babel/runtime@^7.1.2", "@babel/runtime@^7.10.2", "@babel/runtime@^7.4.0", "@babel/runtime@^7.8.4", "@babel/runtime@^7.9.2": + version "7.12.5" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.12.5.tgz#410e7e487441e1b360c29be715d870d9b985882e" + integrity sha512-plcc+hbExy3McchJCEQG3knOsuh3HH+Prx1P6cLIkET/0dLuQDEnrT+s27Axgc9bqfsmNUNHfscgMUdBpC9xfg== dependencies: regenerator-runtime "^0.13.4" @@ -7822,6 +7822,11 @@ mem@^4.0.0: mimic-fn "^2.0.0" p-is-promise "^2.0.0" +"memoize-one@>=3.1.1 <6": + version "5.1.1" + resolved "https://registry.yarnpkg.com/memoize-one/-/memoize-one-5.1.1.tgz#047b6e3199b508eaec03504de71229b8eb1d75c0" + integrity sha512-HKeeBpWvqiVJD57ZUAsJNm71eHTykffzcLZVYWiVfQeI1rJtuEaS7hQiEpWfVVk18donPwJEcFKIkCmPJNOhHA== + memoizee@^0.4.14: version "0.4.14" resolved "https://registry.yarnpkg.com/memoizee/-/memoizee-0.4.14.tgz#07a00f204699f9a95c2d9e77218271c7cd610d57" @@ -8538,10 +8543,10 @@ osenv@^0.1.4: os-homedir "^1.0.0" os-tmpdir "^1.0.0" -outline-icons@^1.21.0-3, outline-icons@^1.21.0-6: - version "1.21.0-6" - resolved "https://registry.yarnpkg.com/outline-icons/-/outline-icons-1.21.0-6.tgz#bbf63fe6cc88ca2fe391e6ba6cc8b62a948607e3" - integrity sha512-iEVK2zTEZ3sLFLsko/V6z3AEiM2EAjEUyLIOzAT2cqRglIbaIWdyitotKVMb2hWZo66bSvHxA/Rdvv51sw5RhA== +outline-icons@^1.21.0: + version "1.21.0" + resolved "https://registry.yarnpkg.com/outline-icons/-/outline-icons-1.21.0.tgz#3e85b7959d0864adbf9a0362ded8fb64bcdcb10f" + integrity sha512-EHLv1cpIKzFiGdavSbn5VD3MQRTKpHINFQktm4ZZL42Me2cDj30WMBeMmXjHqOZls0WJNuhCQSYfa7E5ECKR+g== oy-vey@^0.10.0: version "0.10.0" @@ -9255,10 +9260,10 @@ prosemirror-utils@^0.9.6: resolved "https://registry.yarnpkg.com/prosemirror-utils/-/prosemirror-utils-0.9.6.tgz#3d97bd85897e3b535555867dc95a51399116a973" integrity sha512-UC+j9hQQ1POYfMc5p7UFxBTptRiGPR7Kkmbl3jVvU8VgQbkI89tR/GK+3QYC8n+VvBZrtAoCrJItNhWSxX3slA== -prosemirror-view@^1.0.0, prosemirror-view@^1.1.0, prosemirror-view@^1.13.3, prosemirror-view@^1.15.7: - version "1.15.7" - resolved "https://registry.yarnpkg.com/prosemirror-view/-/prosemirror-view-1.15.7.tgz#b6ce82a08b7ffa8ff06b64ab36ec357229c66aa6" - integrity sha512-fSSXphXg+82qb4xNsHT0mX6ro0Wu1/l+WIFO5jYfyjd42r6ZWSg0gFItLgqOVPxoKQOlrPJUhrozTxiqx0EXOg== +prosemirror-view@^1.0.0, prosemirror-view@^1.1.0, prosemirror-view@^1.13.3, prosemirror-view@^1.16.1: + version "1.16.1" + resolved "https://registry.yarnpkg.com/prosemirror-view/-/prosemirror-view-1.16.1.tgz#375794a253151205394bb1ece07bcc2a647c85da" + integrity sha512-7iDdRf2PAIgOnstcxqUxzf8IbHGfxygQs5covfxOHLWKyx7SSLRnBIlwVda54Hr6N26F4t5Kj2jfK7uIBcAKAw== dependencies: prosemirror-model "^1.1.0" prosemirror-state "^1.0.0" @@ -9573,6 +9578,11 @@ react-side-effect@^1.1.0: dependencies: shallowequal "^1.0.1" +react-virtualized-auto-sizer@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/react-virtualized-auto-sizer/-/react-virtualized-auto-sizer-1.0.2.tgz#a61dd4f756458bbf63bd895a92379f9b70f803bd" + integrity sha512-MYXhTY1BZpdJFjUovvYHVBmkq79szK/k7V3MO+36gJkWGkrXKtyr4vCPtpphaTLRAdDNoYEYFZWE8LjN+PIHNg== + react-waypoint@^9.0.2: version "9.0.2" resolved "https://registry.yarnpkg.com/react-waypoint/-/react-waypoint-9.0.2.tgz#d65fb0fe6ff5c1b832a1d01b1462a661fb921e45" @@ -9582,6 +9592,14 @@ react-waypoint@^9.0.2: prop-types "^15.0.0" react-is "^16.6.3" +react-window@^1.8.6: + version "1.8.6" + resolved "https://registry.yarnpkg.com/react-window/-/react-window-1.8.6.tgz#d011950ac643a994118632665aad0c6382e2a112" + integrity sha512-8VwEEYyjz6DCnGBsd+MgkD0KJ2/OXFULyDtorIiTz+QzwoP94tBoA7CnbtyXMm+cCeAUER5KJcPtWl9cpKbOBg== + dependencies: + "@babel/runtime" "^7.0.0" + memoize-one ">=3.1.1 <6" + react@^16.8.6: version "16.13.1" resolved "https://registry.yarnpkg.com/react/-/react-16.13.1.tgz#2e818822f1a9743122c063d6410d85c1e3afe48e" @@ -9998,15 +10016,15 @@ retry-as-promised@^3.2.0: dependencies: any-promise "^1.3.0" -rich-markdown-editor@^11.0.3: - version "11.0.3" - resolved "https://registry.yarnpkg.com/rich-markdown-editor/-/rich-markdown-editor-11.0.3.tgz#08c119d99e7a58ce50e72cdc26044a97a2f1d5de" - integrity sha512-BAdeYIQ00hvMAL0dI2qjNtft8MiA/DlFoyYeH5cuLYYYd14oTaO7aJ2MDVPt7Gly+HZDmvQfhQm6s6Qn5MH0ug== +rich-markdown-editor@^11.0.6: + version "11.0.6" + resolved "https://registry.yarnpkg.com/rich-markdown-editor/-/rich-markdown-editor-11.0.6.tgz#7d052bb5f65dc11de04488e7b25fb36c6d94dfcb" + integrity sha512-GkVM2JoNereX7UZXhJhd4d/YNoi3sSOoihitoElyU57vQ4zDNSesnW4SRRHZy33HBANhzjKaK4qSZdxRbiklgQ== dependencies: copy-to-clipboard "^3.0.8" lodash "^4.17.11" markdown-it-container "^3.0.0" - outline-icons "^1.21.0-3" + outline-icons "^1.21.0" prismjs "^1.19.0" prosemirror-commands "^1.1.4" prosemirror-dropcursor "^1.3.2" @@ -10021,7 +10039,7 @@ rich-markdown-editor@^11.0.3: prosemirror-tables "^1.1.1" prosemirror-transform "1.2.5" prosemirror-utils "^0.9.6" - prosemirror-view "^1.15.7" + prosemirror-view "^1.16.1" react-medium-image-zoom "^3.0.16" react-portal "^4.2.1" refractor "^3.1.0"