refactor: leverage DocumentExplorer for DocumentMove

This commit is contained in:
Apoorv Mishra committed 2023-01-28 12:17:00 +05:30
1 parent e88f8403fb
commit 0ddddeeabc
5 files changed
+120 -181

No files matched your search

+4 -8
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} />,
});
}
},
+8 -1
View File
@@ -144,7 +144,14 @@ function DocumentExplorer({ onSubmit, onSelect, items }: 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 {
@@ -233,7 +240,7 @@ function DocumentExplorer({ onSubmit, onSelect, items }: Props) {
icon={icon}
title={title}
depth={node.depth as number}
hasChildren={node.children.length > 0}
hasChildren={hasChildren(index)}
/>
);
};
+1 -4
View File
@@ -510,10 +510,7 @@ class DocumentScene extends React.Component<Props> {
onRequestClose={this.goBack}
isOpen
>
<DocumentMove
document={document}
onRequestClose={this.goBack}
/>
<DocumentMove document={document} />
</Modal>
)}
/>
+103 -165
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("Couldn’t 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);
+4 -3
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 you’d like the option of referencing or restoring the {{noun}} in the future, consider archiving it instead.": "If you’d 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",
"Couldn’t move the document, try again?": "Couldn’t move the document, try again?",
"Move to <em>{{ location }}</em>": "Move to <em>{{ location }}</em>",
"Couldn’t create the document, try again?": "Couldn’t 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.",