Change "Move" dialog appearance to match that of "Publish" dialog (#4787)

* refactor: receive items as props in DocumentExplore

* refactor: leverage DocumentExplorer for DocumentMove

* fix: keyboard shortcut for moving document

* refactor: cleanup

* Revert "refactor: cleanup"

This reverts commit 9a0a98eff22934aeffa48d0bf899629b6e61617c.

* fix: get rid of extra parent container

* Revert "fix: get rid of extra parent container"

This reverts commit 908eaf2bba5c8d6d1f4eeeaeb9674bc906af08f4.

* refactor: remove PathToDocument component
This commit is contained in:
Apoorv Mishra
2023-01-28 22:33:56 +05:30
committed by GitHub
parent 0c572ac2c4
commit 7dbc419bbf
8 changed files with 150 additions and 345 deletions

View File

@@ -581,15 +581,11 @@ export const moveDocument = createAction({
} }
stores.dialogs.openModal({ stores.dialogs.openModal({
title: t("Move {{ documentName }}", { title: t("Move {{ documentType }}", {
documentName: document.noun, documentType: document.noun,
}), }),
content: ( isCentered: true,
<DocumentMove content: <DocumentMove document={document} />,
document={document}
onRequestClose={stores.dialogs.closeAllModals}
/>
),
}); });
} }
}, },

View File

@@ -1,5 +1,5 @@
import FuzzySearch from "fuzzy-search"; import FuzzySearch from "fuzzy-search";
import { includes, difference, concat, filter, flatten } from "lodash"; import { includes, difference, concat, filter } from "lodash";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import { StarredIcon, DocumentIcon } from "outline-icons"; import { StarredIcon, DocumentIcon } from "outline-icons";
import * as React from "react"; import * as React from "react";
@@ -18,11 +18,10 @@ import EmojiIcon from "~/components/Icons/EmojiIcon";
import { Outline } from "~/components/Input"; import { Outline } from "~/components/Input";
import InputSearch from "~/components/InputSearch"; import InputSearch from "~/components/InputSearch";
import Text from "~/components/Text"; import Text from "~/components/Text";
import useCollectionTrees from "~/hooks/useCollectionTrees";
import useMobile from "~/hooks/useMobile"; import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores"; import useStores from "~/hooks/useStores";
import { isModKey } from "~/utils/keyboard"; import { isModKey } from "~/utils/keyboard";
import { flattenTree, ancestors, descendants } from "~/utils/tree"; import { ancestors, descendants } from "~/utils/tree";
type Props = { type Props = {
/** Action taken upon submission of selected item, could be publish, move etc. */ /** Action taken upon submission of selected item, could be publish, move etc. */
@@ -30,14 +29,16 @@ type Props = {
/** A side-effect of item selection */ /** A side-effect of item selection */
onSelect: (item: NavigationNode | null) => void; onSelect: (item: NavigationNode | null) => void;
/** Items to be shown in explorer */
items: NavigationNode[];
}; };
function DocumentExplorer({ onSubmit, onSelect }: Props) { function DocumentExplorer({ onSubmit, onSelect, items }: Props) {
const isMobile = useMobile(); const isMobile = useMobile();
const { collections, documents } = useStores(); const { collections, documents } = useStores();
const { t } = useTranslation(); const { t } = useTranslation();
const theme = useTheme(); const theme = useTheme();
const collectionTrees = useCollectionTrees();
const [searchTerm, setSearchTerm] = React.useState<string>(); const [searchTerm, setSearchTerm] = React.useState<string>();
const [selectedNode, selectNode] = React.useState<NavigationNode | null>( const [selectedNode, selectNode] = React.useState<NavigationNode | null>(
@@ -58,16 +59,11 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
const VERTICAL_PADDING = 6; const VERTICAL_PADDING = 6;
const HORIZONTAL_PADDING = 24; const HORIZONTAL_PADDING = 24;
const allNodes = React.useMemo(
() => flatten(collectionTrees.map(flattenTree)),
[collectionTrees]
);
const searchIndex = React.useMemo(() => { const searchIndex = React.useMemo(() => {
return new FuzzySearch(allNodes, ["title"], { return new FuzzySearch(items, ["title"], {
caseSensitive: false, caseSensitive: false,
}); });
}, [allNodes]); }, [items]);
React.useEffect(() => { React.useEffect(() => {
if (searchTerm) { if (searchTerm) {
@@ -83,12 +79,12 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
if (searchTerm) { if (searchTerm) {
results = searchIndex.search(searchTerm); results = searchIndex.search(searchTerm);
} else { } else {
results = allNodes.filter((r) => r.type === "collection"); results = items.filter((item) => item.type === "collection");
} }
setInitialScrollOffset(0); setInitialScrollOffset(0);
setNodes(results); setNodes(results);
}, [searchTerm, allNodes, searchIndex]); }, [searchTerm, items, searchIndex]);
React.useEffect(() => { React.useEffect(() => {
onSelect(selectedNode); onSelect(selectedNode);
@@ -148,7 +144,14 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
return selectedNodeId === nodeId; return selectedNodeId === nodeId;
}; };
const hasChildren = (node: number) => {
return nodes[node].children.length > 0;
};
const toggleCollapse = (node: number) => { const toggleCollapse = (node: number) => {
if (!hasChildren(node)) {
return;
}
if (isExpanded(node)) { if (isExpanded(node)) {
collapse(node); collapse(node);
} else { } else {
@@ -237,7 +240,7 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
icon={icon} icon={icon}
title={title} title={title}
depth={node.depth as number} depth={node.depth as number}
hasChildren={node.children.length > 0} hasChildren={hasChildren(index)}
/> />
); );
}; };

View File

@@ -1,122 +0,0 @@
import { observer } from "mobx-react";
import { GoToIcon } from "outline-icons";
import * as React from "react";
import styled from "styled-components";
import { DocumentPath } from "~/stores/CollectionsStore";
import Collection from "~/models/Collection";
import Document from "~/models/Document";
import Flex from "~/components/Flex";
import CollectionIcon from "~/components/Icons/CollectionIcon";
type Props = {
result: DocumentPath;
document?: Document | null | undefined;
collection: Collection | null | undefined;
onSuccess?: () => void;
style?: React.CSSProperties;
ref?: (element: React.ElementRef<"div"> | null | undefined) => void;
};
@observer
class PathToDocument extends React.Component<Props> {
handleClick = async (ev: React.SyntheticEvent) => {
ev.preventDefault();
const { document, result, onSuccess } = this.props;
if (!document) {
return;
}
if (result.type === "document") {
await document.move(result.collectionId, result.id);
} else {
await document.move(result.collectionId);
}
if (onSuccess) {
onSuccess();
}
};
render() {
const { result, collection, document, ref, style } = this.props;
const Component = document ? ResultWrapperLink : ResultWrapper;
if (!result) {
return <div />;
}
return (
// @ts-expect-error ts-migrate(2604) FIXME: JSX element type 'Component' does not have any con... Remove this comment to see the full error message
<Component
ref={ref}
onClick={this.handleClick}
href=""
style={style}
role="option"
selectable
>
{collection && <CollectionIcon collection={collection} />}
&nbsp;
{result.path
.map((doc) => <Title key={doc.id}>{doc.title}</Title>)
// @ts-expect-error ts-migrate(2739) FIXME: Type 'Element[]' is missing the following properti... Remove this comment to see the full error message
.reduce((prev, curr) => [prev, <StyledGoToIcon />, curr])}
{document && (
<DocumentTitle>
{" "}
<StyledGoToIcon /> <Title>{document.title}</Title>
</DocumentTitle>
)}
</Component>
);
}
}
const DocumentTitle = styled(Flex)``;
const Title = styled.span`
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const StyledGoToIcon = styled(GoToIcon)`
fill: ${(props) => props.theme.divider};
`;
const ResultWrapper = styled.div`
display: flex;
margin-bottom: 10px;
user-select: none;
color: ${(props) => props.theme.text};
cursor: default;
svg {
flex-shrink: 0;
}
`;
const ResultWrapperLink = styled(ResultWrapper.withComponent("a"))`
padding: 8px 4px;
${DocumentTitle} {
display: none;
}
svg {
flex-shrink: 0;
}
&:hover,
&:active,
&:focus {
background: ${(props) => props.theme.listItemHoverBackground};
outline: none;
${DocumentTitle} {
display: flex;
}
}
`;
export default PathToDocument;

View File

@@ -6,7 +6,6 @@ import * as React from "react";
import { WithTranslation, withTranslation } from "react-i18next"; import { WithTranslation, withTranslation } from "react-i18next";
import { import {
Prompt, Prompt,
Route,
RouteComponentProps, RouteComponentProps,
StaticContext, StaticContext,
withRouter, withRouter,
@@ -28,7 +27,6 @@ import ConnectionStatus from "~/components/ConnectionStatus";
import ErrorBoundary from "~/components/ErrorBoundary"; import ErrorBoundary from "~/components/ErrorBoundary";
import Flex from "~/components/Flex"; import Flex from "~/components/Flex";
import LoadingIndicator from "~/components/LoadingIndicator"; import LoadingIndicator from "~/components/LoadingIndicator";
import Modal from "~/components/Modal";
import PageTitle from "~/components/PageTitle"; import PageTitle from "~/components/PageTitle";
import PlaceholderDocument from "~/components/PlaceholderDocument"; import PlaceholderDocument from "~/components/PlaceholderDocument";
import RegisterKeyDown from "~/components/RegisterKeyDown"; import RegisterKeyDown from "~/components/RegisterKeyDown";
@@ -39,7 +37,6 @@ import { replaceTitleVariables } from "~/utils/date";
import { emojiToUrl } from "~/utils/emoji"; import { emojiToUrl } from "~/utils/emoji";
import { isModKey } from "~/utils/keyboard"; import { isModKey } from "~/utils/keyboard";
import { import {
documentMoveUrl,
documentHistoryUrl, documentHistoryUrl,
editDocumentUrl, editDocumentUrl,
documentUrl, documentUrl,
@@ -226,15 +223,15 @@ class DocumentScene extends React.Component<Props> {
} }
}; };
goToMove = (ev: KeyboardEvent) => { onMove = (ev: React.MouseEvent | KeyboardEvent) => {
if (!this.props.readOnly) {
return;
}
ev.preventDefault(); ev.preventDefault();
const { document, abilities } = this.props; const { document, dialogs, t, abilities } = this.props;
if (abilities.move) { if (abilities.move) {
this.props.history.push(documentMoveUrl(document)); dialogs.openModal({
title: t("Move document"),
isCentered: true,
content: <DocumentMove document={document} />,
});
} }
}; };
@@ -476,7 +473,7 @@ class DocumentScene extends React.Component<Props> {
}} }}
/> />
)} )}
<RegisterKeyDown trigger="m" handler={this.goToMove} /> <RegisterKeyDown trigger="m" handler={this.onMove} />
<RegisterKeyDown trigger="e" handler={this.goToEdit} /> <RegisterKeyDown trigger="e" handler={this.goToEdit} />
<RegisterKeyDown trigger="Escape" handler={this.goBack} /> <RegisterKeyDown trigger="Escape" handler={this.goBack} />
<RegisterKeyDown trigger="h" handler={this.goToHistory} /> <RegisterKeyDown trigger="h" handler={this.goToHistory} />
@@ -502,21 +499,6 @@ class DocumentScene extends React.Component<Props> {
column column
auto auto
> >
<Route
path={`${document.url}/move`}
component={() => (
<Modal
title={`Move ${document.noun}`}
onRequestClose={this.goBack}
isOpen
>
<DocumentMove
document={document}
onRequestClose={this.goBack}
/>
</Modal>
)}
/>
<PageTitle <PageTitle
title={document.titleWithDefault.replace(document.emoji || "", "")} title={document.titleWithDefault.replace(document.emoji || "", "")}
favicon={document.emoji ? emojiToUrl(document.emoji) : undefined} favicon={document.emoji ? emojiToUrl(document.emoji) : undefined}

View File

@@ -1,194 +1,132 @@
import FuzzySearch from "fuzzy-search"; import { flatten } from "lodash";
import { last } from "lodash";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import { useMemo, useState } from "react";
import * as React from "react"; import * as React from "react";
import { useTranslation } from "react-i18next"; import { useTranslation, Trans } from "react-i18next";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList as List } from "react-window";
import styled from "styled-components"; import styled from "styled-components";
import { DocumentPath } from "~/stores/CollectionsStore"; import { NavigationNode } from "@shared/types";
import Document from "~/models/Document"; import Document from "~/models/Document";
import Button from "~/components/Button";
import DocumentExplorer from "~/components/DocumentExplorer";
import Flex from "~/components/Flex"; import Flex from "~/components/Flex";
import { Outline } from "~/components/Input"; import Text from "~/components/Text";
import InputSearch from "~/components/InputSearch"; import useCollectionTrees from "~/hooks/useCollectionTrees";
import Labeled from "~/components/Labeled";
import PathToDocument from "~/components/PathToDocument";
import useStores from "~/hooks/useStores"; import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts"; import useToasts from "~/hooks/useToasts";
import { flattenTree } from "~/utils/tree";
type Props = { type Props = {
document: Document; document: Document;
onRequestClose: () => void;
}; };
function DocumentMove({ document, onRequestClose }: Props) { function DocumentMove({ document }: Props) {
const [searchTerm, setSearchTerm] = useState<string>(); const { dialogs } = useStores();
const { collections, documents } = useStores();
const { showToast } = useToasts(); const { showToast } = useToasts();
const { t } = useTranslation(); const { t } = useTranslation();
const collectionTrees = useCollectionTrees();
const [selectedPath, selectPath] = React.useState<NavigationNode | null>(
null
);
const searchIndex = useMemo(() => { const moveOptions = React.useMemo(() => {
const paths = collections.pathsToDocuments; // filter out the document itself and also its parent doc if any
const nodes = flatten(collectionTrees.map(flattenTree)).filter(
// Build index (node) => node.id !== document.id && node.id !== document.parentDocumentId
const indexeableDocuments: DocumentPath[] = [];
paths.forEach((path) => {
const doc = documents.get(path.id);
if (!doc || !doc.isTemplate) {
indexeableDocuments.push(path);
}
});
return new FuzzySearch<DocumentPath>(indexeableDocuments, ["title"], {
caseSensitive: false,
sort: true,
});
}, [documents, collections.pathsToDocuments]);
const results = useMemo(() => {
const onlyShowCollections = document.isTemplate;
let results: DocumentPath[] = [];
if (collections.isLoaded) {
if (searchTerm) {
results = searchIndex.search(searchTerm);
} else {
results = searchIndex.haystack;
}
}
if (onlyShowCollections) {
results = results.filter((result) => result.type === "collection");
} else {
// Exclude document if on the path to result, or the same result
results = results.filter(
(result) =>
!result.path.map((doc) => doc.id).includes(document.id) &&
last(result.path.map((doc) => doc.id)) !== document.parentDocumentId
);
}
return results;
}, [document, collections, searchTerm, searchIndex]);
const handleSuccess = () => {
showToast(t("Document moved"), {
type: "info",
});
onRequestClose();
};
const handleFilter = (ev: React.ChangeEvent<HTMLInputElement>) => {
setSearchTerm(ev.target.value);
};
const renderPathToCurrentDocument = () => {
const result = collections.getPathForDocument(document.id);
if (result) {
return (
<PathToDocument
result={result}
collection={collections.get(result.collectionId)}
/>
);
}
return null;
};
const row = ({
index,
data,
style,
}: {
index: number;
data: DocumentPath[];
style: React.CSSProperties;
}) => {
const result = data[index];
return (
<PathToDocument
result={result}
document={document}
collection={collections.get(result.collectionId)}
onSuccess={handleSuccess}
style={style}
/>
); );
if (document.isTemplate) {
// only show collections with children stripped off to prevent node expansion
return nodes
.filter((node) => node.type === "collection")
.map((node) => ({ ...node, children: [] }));
}
return nodes;
}, [
collectionTrees,
document.id,
document.parentDocumentId,
document.isTemplate,
]);
const move = async () => {
if (!selectedPath) {
showToast(t("Select a location to move"), {
type: "info",
});
return;
}
try {
const { type, id: parentDocumentId } = selectedPath;
const collectionId = selectedPath.collectionId as string;
if (type === "document") {
await document.move(collectionId, parentDocumentId);
} else {
await document.move(collectionId);
}
showToast(t("Document moved"), {
type: "success",
});
dialogs.closeAllModals();
} catch (err) {
showToast(t("Couldnt move the document, try again?"), {
type: "error",
});
}
}; };
const data = results;
if (!document || !collections.isLoaded) {
return null;
}
return ( return (
<Flex column> <FlexContainer column>
<Section> <DocumentExplorer
<Labeled label={t("Current location")}> items={moveOptions}
{renderPathToCurrentDocument()} onSubmit={move}
</Labeled> onSelect={selectPath}
</Section> />
<Footer justify="space-between" align="center" gap={8}>
<Section column> <StyledText type="secondary">
<Labeled label={t("Choose a new location")} /> {selectedPath ? (
<Input <Trans
type="search" defaults="Move to <em>{{ location }}</em>"
onChange={handleFilter} values={{
placeholder={`${t("Search collections & documents")}`} location: selectedPath.title,
label={t("Choose a new location")} }}
labelHidden components={{
required em: <strong />,
autoFocus }}
/> />
<Results> ) : (
<AutoSizer> t("Select a location to move")
{({ width, height }: { width: number; height: number }) => ( )}
<Flex role="listbox" column> </StyledText>
<List <Button disabled={!selectedPath} onClick={move}>
key={data.length} {t("Move")}
width={width} </Button>
height={height} </Footer>
itemData={data} </FlexContainer>
itemCount={data.length}
itemSize={40}
itemKey={(index, data) => data[index].id}
>
{row}
</List>
</Flex>
)}
</AutoSizer>
</Results>
</Section>
</Flex>
); );
} }
const Input = styled(InputSearch)` const FlexContainer = styled(Flex)`
${Outline} { margin-left: -24px;
border-bottom-left-radius: 0; margin-right: -24px;
border-bottom-right-radius: 0; margin-bottom: -24px;
padding: 4px 0; outline: none;
}
`; `;
const Results = styled.div` const Footer = styled(Flex)`
padding: 0; height: 64px;
height: 40vh; border-top: 1px solid ${(props) => props.theme.horizontalRule};
border: 1px solid ${(props) => props.theme.inputBorder}; padding-left: 24px;
border-top: 0; padding-right: 24px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
`; `;
const Section = styled(Flex)` const StyledText = styled(Text)`
margin-bottom: 24px; white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 0;
`; `;
export default observer(DocumentMove); export default observer(DocumentMove);

View File

@@ -1,3 +1,4 @@
import { flatten } from "lodash";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import * as React from "react"; import * as React from "react";
import { useTranslation, Trans } from "react-i18next"; import { useTranslation, Trans } from "react-i18next";
@@ -8,8 +9,10 @@ import Button from "~/components/Button";
import DocumentExplorer from "~/components/DocumentExplorer"; import DocumentExplorer from "~/components/DocumentExplorer";
import Flex from "~/components/Flex"; import Flex from "~/components/Flex";
import Text from "~/components/Text"; import Text from "~/components/Text";
import useCollectionTrees from "~/hooks/useCollectionTrees";
import useStores from "~/hooks/useStores"; import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts"; import useToasts from "~/hooks/useToasts";
import { flattenTree } from "~/utils/tree";
type Props = { type Props = {
/** Document to publish */ /** Document to publish */
@@ -20,10 +23,14 @@ function DocumentPublish({ document }: Props) {
const { dialogs } = useStores(); const { dialogs } = useStores();
const { showToast } = useToasts(); const { showToast } = useToasts();
const { t } = useTranslation(); const { t } = useTranslation();
const collectionTrees = useCollectionTrees();
const [selectedPath, selectPath] = React.useState<NavigationNode | null>( const [selectedPath, selectPath] = React.useState<NavigationNode | null>(
null null
); );
const publishOptions = React.useMemo(
() => flatten(collectionTrees.map(flattenTree)),
[collectionTrees]
);
const publish = async () => { const publish = async () => {
if (!selectedPath) { if (!selectedPath) {
@@ -60,7 +67,11 @@ function DocumentPublish({ document }: Props) {
return ( return (
<FlexContainer column> <FlexContainer column>
<DocumentExplorer onSubmit={publish} onSelect={selectPath} /> <DocumentExplorer
items={publishOptions}
onSubmit={publish}
onSelect={selectPath}
/>
<Footer justify="space-between" align="center" gap={8}> <Footer justify="space-between" align="center" gap={8}>
<StyledText type="secondary"> <StyledText type="secondary">
{selectedPath ? ( {selectedPath ? (

View File

@@ -68,10 +68,6 @@ export function editDocumentUrl(doc: Document): string {
return `${doc.url}/edit`; return `${doc.url}/edit`;
} }
export function documentMoveUrl(doc: Document): string {
return `${doc.url}/move`;
}
export function documentInsightsUrl(doc: Document): string { export function documentInsightsUrl(doc: Document): string {
return `${doc.url}/insights`; return `${doc.url}/insights`;
} }

View File

@@ -45,7 +45,7 @@
"Open random document": "Open random document", "Open random document": "Open random document",
"Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"", "Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"",
"Move": "Move", "Move": "Move",
"Move {{ documentName }}": "Move {{ documentName }}", "Move {{ documentType }}": "Move {{ documentType }}",
"Archive": "Archive", "Archive": "Archive",
"Document archived": "Document archived", "Document archived": "Document archived",
"Delete": "Delete", "Delete": "Delete",
@@ -507,9 +507,10 @@
"Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history and <em>{{ any }} nested document</em>._plural": "Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history and <em>{{ any }} nested documents</em>.", "Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history and <em>{{ any }} nested document</em>._plural": "Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history and <em>{{ any }} nested documents</em>.",
"If youd like the option of referencing or restoring the {{noun}} in the future, consider archiving it instead.": "If youd like the option of referencing or restoring the {{noun}} in the future, consider archiving it instead.", "If youd like the option of referencing or restoring the {{noun}} in the future, consider archiving it instead.": "If youd like the option of referencing or restoring the {{noun}} in the future, consider archiving it instead.",
"Archiving": "Archiving", "Archiving": "Archiving",
"Select a location to move": "Select a location to move",
"Document moved": "Document moved", "Document moved": "Document moved",
"Current location": "Current location", "Couldnt move the document, try again?": "Couldnt move the document, try again?",
"Choose a new location": "Choose a new location", "Move to <em>{{ location }}</em>": "Move to <em>{{ location }}</em>",
"Couldnt create the document, try again?": "Couldnt create the document, try again?", "Couldnt create the document, try again?": "Couldnt create the document, try again?",
"Document permanently deleted": "Document permanently deleted", "Document permanently deleted": "Document permanently deleted",
"Are you sure you want to permanently delete the <em>{{ documentTitle }}</em> document? This action is immediate and cannot be undone.": "Are you sure you want to permanently delete the <em>{{ documentTitle }}</em> document? This action is immediate and cannot be undone.", "Are you sure you want to permanently delete the <em>{{ documentTitle }}</em> document? This action is immediate and cannot be undone.": "Are you sure you want to permanently delete the <em>{{ documentTitle }}</em> document? This action is immediate and cannot be undone.",