mirror of
https://github.com/outline/outline.git
synced 2026-06-13 11:25:03 +03:00
267835ce6f
* Add missing controls to starred documents * refactor * refactor * fix: Enter does not submit * fix: Reordering child docs in starred section * refactor: Rename editTitle to labelText, remove non-null assertion * Refactor draggable for consistency * refactor * Remove star icon * fix: Allow drag and drop importing into starred * tsc
84 lines
2.3 KiB
TypeScript
84 lines
2.3 KiB
TypeScript
import invariant from "invariant";
|
||
import { useState, useCallback } from "react";
|
||
import { useTranslation } from "react-i18next";
|
||
import { useHistory } from "react-router-dom";
|
||
import { toast } from "sonner";
|
||
import { useSidebarContext } from "~/components/Sidebar/components/SidebarContext";
|
||
import useStores from "~/hooks/useStores";
|
||
import { documentPath } from "~/utils/routeHelpers";
|
||
|
||
let importingLock = false;
|
||
|
||
export default function useImportDocument(
|
||
collectionId?: string | null,
|
||
documentId?: string
|
||
): {
|
||
handleFiles: (files: File[]) => Promise<void>;
|
||
isImporting: boolean;
|
||
} {
|
||
const { documents } = useStores();
|
||
const sidebarContext = useSidebarContext();
|
||
const [isImporting, setImporting] = useState(false);
|
||
const { t } = useTranslation();
|
||
const history = useHistory();
|
||
const handleFiles = useCallback(
|
||
async (files = []) => {
|
||
if (importingLock) {
|
||
return;
|
||
}
|
||
|
||
// Because this is the onChange handler it's possible for the change to be
|
||
// from previously selecting a file to not selecting a file – aka empty
|
||
if (!files.length) {
|
||
return;
|
||
}
|
||
|
||
setImporting(true);
|
||
importingLock = true;
|
||
|
||
try {
|
||
let cId = collectionId;
|
||
const redirect = files.length === 1;
|
||
|
||
if (documentId && !collectionId) {
|
||
const document = await documents.fetch(documentId);
|
||
invariant(document, "Document not available");
|
||
cId = document.collectionId;
|
||
}
|
||
|
||
for (const file of files) {
|
||
const toastId = toast.loading(`${t("Uploading")}…`);
|
||
|
||
try {
|
||
const doc = await documents.import(file, documentId, cId, {
|
||
publish: true,
|
||
});
|
||
|
||
if (redirect) {
|
||
history.push({
|
||
pathname: documentPath(doc),
|
||
state: { sidebarContext },
|
||
});
|
||
}
|
||
} catch (err) {
|
||
toast.error(err.message);
|
||
} finally {
|
||
toast.dismiss(toastId);
|
||
}
|
||
}
|
||
} catch (err) {
|
||
toast.error(`${t("Could not import file")}. ${err.message}`);
|
||
} finally {
|
||
setImporting(false);
|
||
importingLock = false;
|
||
}
|
||
},
|
||
[t, documents, history, collectionId, sidebarContext, documentId]
|
||
);
|
||
|
||
return {
|
||
handleFiles,
|
||
isImporting,
|
||
};
|
||
}
|