Skip to content

Commit

Permalink
feat: Drag & drop to import new books
Browse files Browse the repository at this point in the history
  • Loading branch information
phildenhoff committed Nov 29, 2024
1 parent bcc0eca commit 11c8ce8
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/components/organisms/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import {
title as addBookFormTitle,
} from "../molecules/AddBookForm";
import { SwitchLibraryForm } from "../molecules/SwitchLibraryForm";
import { appWindow } from "@tauri-apps/api/window";
import { addBookByDragDrop } from "@/lib/services/library/_internal/addBook";

export const Sidebar = () => {
const { library, state, eventEmitter } = useLibrary();
Expand All @@ -45,6 +47,38 @@ export const Sidebar = () => {
{ close: closeSwitchLibraryModal, open: openSwitchLibraryModal },
] = useDisclosure(false);

useEffect(() => {
let unlisten: (() => void) | undefined;

const setupFileDropListener = async () => {
unlisten = await appWindow.onFileDropEvent((event) => {
if (!library) return;

void (async () => {
if (event.payload.type === "drop") {
const metadataList = await addBookByDragDrop(
library,
event.payload.paths,
);
const firstItem = metadataList[0];
if (firstItem) {
setMetadata(firstItem);
openAddBookModal();
}
}
})();
});
};

void setupFileDropListener();

return () => {
if (unlisten) {
unlisten();
}
};
}, [library, openAddBookModal]);

useEffect(() => {
void (async () => {
setAuthorList(
Expand Down
21 changes: 21 additions & 0 deletions src/lib/services/library/_internal/addBook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,27 @@ import { EventEmitter } from "@/lib/event";
import { dialog } from "@tauri-apps/api";
import type { Library } from "./_types";

export const addBookByDragDrop = async (
library: Library,
paths: string[],
): Promise<ImportableBookMetadata[]> => {
const importableMetadata = [];
for (const path of paths) {
const importableFile = await library.checkFileImportable(path);
if (!importableFile) {
continue;
}
const metadata = await library.getImportableFileMetadata(importableFile);
if (!metadata) {
continue;
}

importableMetadata.push(metadata);
}

return importableMetadata;
};

export const promptToAddBook = async (
library: Library,
): Promise<ImportableBookMetadata | undefined> => {
Expand Down

0 comments on commit 11c8ce8

Please sign in to comment.