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({
title: t("Move {{ documentName }}", {
documentName: document.noun,
title: t("Move {{ documentType }}", {
documentType: document.noun,
}),
content: (
<DocumentMove
document={document}
onRequestClose={stores.dialogs.closeAllModals}
/>
),
isCentered: true,
content: <DocumentMove document={document} />,
});
}
},

View File

@@ -1,5 +1,5 @@
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 { StarredIcon, DocumentIcon } from "outline-icons";
import * as React from "react";
@@ -18,11 +18,10 @@ import EmojiIcon from "~/components/Icons/EmojiIcon";
import { Outline } from "~/components/Input";
import InputSearch from "~/components/InputSearch";
import Text from "~/components/Text";
import useCollectionTrees from "~/hooks/useCollectionTrees";
import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores";
import { isModKey } from "~/utils/keyboard";
import { flattenTree, ancestors, descendants } from "~/utils/tree";
import { ancestors, descendants } from "~/utils/tree";
type Props = {
/** Action taken upon submission of selected item, could be publish, move etc. */
@@ -30,14 +29,16 @@ type Props = {
/** A side-effect of item selection */
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 { collections, documents } = useStores();
const { t } = useTranslation();
const theme = useTheme();
const collectionTrees = useCollectionTrees();
const [searchTerm, setSearchTerm] = React.useState<string>();
const [selectedNode, selectNode] = React.useState<NavigationNode | null>(
@@ -58,16 +59,11 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
const VERTICAL_PADDING = 6;
const HORIZONTAL_PADDING = 24;
const allNodes = React.useMemo(
() => flatten(collectionTrees.map(flattenTree)),
[collectionTrees]
);
const searchIndex = React.useMemo(() => {
return new FuzzySearch(allNodes, ["title"], {
return new FuzzySearch(items, ["title"], {
caseSensitive: false,
});
}, [allNodes]);
}, [items]);
React.useEffect(() => {
if (searchTerm) {
@@ -83,12 +79,12 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
if (searchTerm) {
results = searchIndex.search(searchTerm);
} else {
results = allNodes.filter((r) => r.type === "collection");
results = items.filter((item) => item.type === "collection");
}
setInitialScrollOffset(0);
setNodes(results);
}, [searchTerm, allNodes, searchIndex]);
}, [searchTerm, items, searchIndex]);
React.useEffect(() => {
onSelect(selectedNode);
@@ -148,7 +144,14 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
return selectedNodeId === nodeId;
};
const hasChildren = (node: number) => {
return nodes[node].children.length > 0;
};
const toggleCollapse = (node: number) => {
if (!hasChildren(node)) {
return;
}
if (isExpanded(node)) {
collapse(node);
} else {
@@ -237,7 +240,7 @@ function DocumentExplorer({ onSubmit, onSelect }: Props) {
icon={icon}
title={title}
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 {
Prompt,
Route,
RouteComponentProps,
StaticContext,
withRouter,
@@ -28,7 +27,6 @@ import ConnectionStatus from "~/components/ConnectionStatus";
import ErrorBoundary from "~/components/ErrorBoundary";
import Flex from "~/components/Flex";
import LoadingIndicator from "~/components/LoadingIndicator";
import Modal from "~/components/Modal";
import PageTitle from "~/components/PageTitle";
import PlaceholderDocument from "~/components/PlaceholderDocument";
import RegisterKeyDown from "~/components/RegisterKeyDown";
@@ -39,7 +37,6 @@ import { replaceTitleVariables } from "~/utils/date";
import { emojiToUrl } from "~/utils/emoji";
import { isModKey } from "~/utils/keyboard";
import {
documentMoveUrl,
documentHistoryUrl,
editDocumentUrl,
documentUrl,
@@ -226,15 +223,15 @@ class DocumentScene extends React.Component<Props> {
}
};
goToMove = (ev: KeyboardEvent) => {
if (!this.props.readOnly) {
return;
}
onMove = (ev: React.MouseEvent | KeyboardEvent) => {
ev.preventDefault();
const { document, abilities } = this.props;
const { document, dialogs, t, abilities } = this.props;
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="Escape" handler={this.goBack} />
<RegisterKeyDown trigger="h" handler={this.goToHistory} />
@@ -502,21 +499,6 @@ class DocumentScene extends React.Component<Props> {
column
auto
>
<Route
path={`${document.url}/move`}
component={() => (
<Modal
title={`Move ${document.noun}`}
onRequestClose={this.goBack}
isOpen
>
<DocumentMove
document={document}
onRequestClose={this.goBack}
/>
</Modal>
)}
/>
<PageTitle
title={document.titleWithDefault.replace(document.emoji || "", "")}
favicon={document.emoji ? emojiToUrl(document.emoji) : undefined}

View File

@@ -1,194 +1,132 @@
import FuzzySearch from "fuzzy-search";
import { last } from "lodash";
import { flatten } from "lodash";
import { observer } from "mobx-react";
import { useMemo, useState } from "react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList as List } from "react-window";
import { useTranslation, Trans } from "react-i18next";
import styled from "styled-components";
import { DocumentPath } from "~/stores/CollectionsStore";
import { NavigationNode } from "@shared/types";
import Document from "~/models/Document";
import Button from "~/components/Button";
import DocumentExplorer from "~/components/DocumentExplorer";
import Flex from "~/components/Flex";
import { Outline } from "~/components/Input";
import InputSearch from "~/components/InputSearch";
import Labeled from "~/components/Labeled";
import PathToDocument from "~/components/PathToDocument";
import Text from "~/components/Text";
import useCollectionTrees from "~/hooks/useCollectionTrees";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
import { flattenTree } from "~/utils/tree";
type Props = {
document: Document;
onRequestClose: () => void;
};
function DocumentMove({ document, onRequestClose }: Props) {
const [searchTerm, setSearchTerm] = useState<string>();
const { collections, documents } = useStores();
function DocumentMove({ document }: Props) {
const { dialogs } = useStores();
const { showToast } = useToasts();
const { t } = useTranslation();
const collectionTrees = useCollectionTrees();
const [selectedPath, selectPath] = React.useState<NavigationNode | null>(
null
);
const searchIndex = useMemo(() => {
const paths = collections.pathsToDocuments;
// Build index
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}
/>
const moveOptions = React.useMemo(() => {
// filter out the document itself and also its parent doc if any
const nodes = flatten(collectionTrees.map(flattenTree)).filter(
(node) => node.id !== document.id && node.id !== document.parentDocumentId
);
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 (
<Flex column>
<Section>
<Labeled label={t("Current location")}>
{renderPathToCurrentDocument()}
</Labeled>
</Section>
<Section column>
<Labeled label={t("Choose a new location")} />
<Input
type="search"
onChange={handleFilter}
placeholder={`${t("Search collections & documents")}`}
label={t("Choose a new location")}
labelHidden
required
autoFocus
/>
<Results>
<AutoSizer>
{({ width, height }: { width: number; height: number }) => (
<Flex role="listbox" column>
<List
key={data.length}
width={width}
height={height}
itemData={data}
itemCount={data.length}
itemSize={40}
itemKey={(index, data) => data[index].id}
>
{row}
</List>
</Flex>
)}
</AutoSizer>
</Results>
</Section>
</Flex>
<FlexContainer column>
<DocumentExplorer
items={moveOptions}
onSubmit={move}
onSelect={selectPath}
/>
<Footer justify="space-between" align="center" gap={8}>
<StyledText type="secondary">
{selectedPath ? (
<Trans
defaults="Move to <em>{{ location }}</em>"
values={{
location: selectedPath.title,
}}
components={{
em: <strong />,
}}
/>
) : (
t("Select a location to move")
)}
</StyledText>
<Button disabled={!selectedPath} onClick={move}>
{t("Move")}
</Button>
</Footer>
</FlexContainer>
);
}
const Input = styled(InputSearch)`
${Outline} {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
padding: 4px 0;
}
const FlexContainer = styled(Flex)`
margin-left: -24px;
margin-right: -24px;
margin-bottom: -24px;
outline: none;
`;
const Results = styled.div`
padding: 0;
height: 40vh;
border: 1px solid ${(props) => props.theme.inputBorder};
border-top: 0;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
const Footer = styled(Flex)`
height: 64px;
border-top: 1px solid ${(props) => props.theme.horizontalRule};
padding-left: 24px;
padding-right: 24px;
`;
const Section = styled(Flex)`
margin-bottom: 24px;
const StyledText = styled(Text)`
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 0;
`;
export default observer(DocumentMove);

View File

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

View File

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

View File

@@ -45,7 +45,7 @@
"Open random document": "Open random document",
"Search documents for \"{{searchQuery}}\"": "Search documents for \"{{searchQuery}}\"",
"Move": "Move",
"Move {{ documentName }}": "Move {{ documentName }}",
"Move {{ documentType }}": "Move {{ documentType }}",
"Archive": "Archive",
"Document archived": "Document archived",
"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>.",
"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",
"Select a location to move": "Select a location to move",
"Document moved": "Document moved",
"Current location": "Current location",
"Choose a new location": "Choose a new location",
"Couldnt move the document, try again?": "Couldnt move the document, try again?",
"Move to <em>{{ location }}</em>": "Move to <em>{{ location }}</em>",
"Couldnt create the document, try again?": "Couldnt create the document, try again?",
"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.",