Skip to content

Build your personal knowledge base with Trilium Notes

test(client): cover provider-import hook & FileDropZone selection logic

Elian Doranf3144867c91c
diff --git a/apps/client/src/widgets/dialogs/import/useProviderImport.spec.tsx b/apps/client/src/widgets/dialogs/import/useProviderImport.spec.tsx
new file mode 100644
index 0000000000..2ef693e8f7
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/import/useProviderImport.spec.tsx
@@ -0,0 +1,212 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import useProviderImport from "./useProviderImport";
+
+const uploadFiles = vi.fn((..._args: unknown[]) => Promise.resolve());
+const isElectron = vi.fn(() => false);
+
+vi.mock("../../../services/import.js", () => ({ default: { uploadFiles: (...args: unknown[]) => uploadFiles(...args) } }));
+vi.mock("../../../services/utils.js", () => ({
+ default: {
+ isElectron: () => isElectron(),
+ randomString: () => "rnd1234567"
+ }
+}));
+
+type Hook = ReturnType<typeof useProviderImport>;
+type Args = Parameters<typeof useProviderImport>[0];
+
+let hook: Hook | undefined;
+
+function Probe(args: Args) {
+ hook = useProviderImport(args);
+ return null;
+}
+
+/** Builds a FileList-like the hook can index (it only reads `[0]` and `.length`). */
+function fileListOf(...files: File[]): FileList {
+ return Object.assign(files.slice(), { item: (i: number) => files[i] ?? null }) as unknown as FileList;
+}
+
+describe("useProviderImport", () => {
+ let container: HTMLElement;
+ let closeDialog: ReturnType<typeof vi.fn>;
+ let pickFiles: ReturnType<typeof vi.fn>;
+ let grantDroppedFiles: ReturnType<typeof vi.fn>;
+ let importFromToken: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ isElectron.mockReturnValue(false);
+ closeDialog = vi.fn();
+ pickFiles = vi.fn();
+ grantDroppedFiles = vi.fn();
+ importFromToken = vi.fn(async () => ({}));
+ (window as unknown as { electronApi?: unknown }).electronApi = {
+ nativeImport: { pickFiles, grantDroppedFiles, importFromToken }
+ };
+ hook = undefined;
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ delete (window as unknown as { electronApi?: unknown }).electronApi;
+ });
+
+ async function mount(overrides: Partial<Args> = {}) {
+ const args = { format: "obsidian", parentNoteId: "p1", shrinkImages: false, closeDialog, ...overrides } as Args;
+ await act(async () => {
+ render(<Probe {...args} />, container);
+ });
+ }
+
+ function current(): Hook {
+ if (!hook) {
+ throw new Error("hook is not mounted");
+ }
+ return hook;
+ }
+
+ describe("selection", () => {
+ it("starts with no selection and no native browse/drop off desktop", async () => {
+ await mount();
+ expect(current().hasSelection).toBe(false);
+ expect(current().displayNames).toBeUndefined();
+ expect(current().onBrowse).toBeUndefined();
+ expect(current().onNativeDrop).toBeUndefined();
+ });
+
+ it("marks a selection once a file is chosen via the upload route", async () => {
+ await mount();
+ const file = new File(["x"], "vault.zip");
+ await act(async () => current().onChange(fileListOf(file)));
+ expect(current().hasSelection).toBe(true);
+ // The upload route has no display name override — FileDropZone shows the File itself.
+ expect(current().displayNames).toBeUndefined();
+ });
+
+ it("clears the selection when onChange receives no files", async () => {
+ await mount();
+ await act(async () => current().onChange(fileListOf(new File(["x"], "vault.zip"))));
+ await act(async () => current().onChange(null));
+ expect(current().hasSelection).toBe(false);
+ });
+
+ it("exposes native browse/drop on desktop", async () => {
+ isElectron.mockReturnValue(true);
+ await mount();
+ expect(current().onBrowse).toBeInstanceOf(Function);
+ expect(current().onNativeDrop).toBeInstanceOf(Function);
+ });
+ });
+
+ describe("native browse (desktop)", () => {
+ beforeEach(() => isElectron.mockReturnValue(true));
+
+ it("stores the native pick and shows its filename, clearing any upload file", async () => {
+ await mount();
+ await act(async () => current().onChange(fileListOf(new File(["x"], "dropped.zip"))));
+ pickFiles.mockResolvedValueOnce({ status: "selected", files: [{ token: "tok", fileName: "Vault.zip" }] });
+
+ await act(async () => {
+ current().onBrowse?.();
+ });
+
+ expect(current().hasSelection).toBe(true);
+ expect(current().displayNames).toEqual(["Vault.zip"]);
+ });
+
+ it("ignores a cancelled pick", async () => {
+ await mount();
+ pickFiles.mockResolvedValueOnce({ status: "cancelled" });
+ await act(async () => {
+ current().onBrowse?.();
+ });
+ expect(current().hasSelection).toBe(false);
+ });
+ });
+
+ describe("native drop (desktop)", () => {
+ beforeEach(() => isElectron.mockReturnValue(true));
+
+ it("routes a dropped archive through the native path and reports it was handled", async () => {
+ await mount();
+ grantDroppedFiles.mockResolvedValueOnce({ status: "selected", files: [{ token: "tok", fileName: "Vault.zip" }] });
+
+ let handled: boolean | undefined;
+ await act(async () => {
+ handled = await current().onNativeDrop?.([new File(["x"], "Vault.zip"), new File(["y"], "extra.zip")]);
+ });
+
+ expect(handled).toBe(true);
+ // A provider takes a single file, so only the first dropped file is granted.
+ expect(grantDroppedFiles).toHaveBeenCalledWith([expect.any(File)]);
+ expect(grantDroppedFiles.mock.calls[0][0]).toHaveLength(1);
+ expect(current().displayNames).toEqual(["Vault.zip"]);
+ });
+
+ it("falls back to upload (returns false) when the drop did not resolve to a path", async () => {
+ await mount();
+ grantDroppedFiles.mockResolvedValueOnce({ status: "cancelled" });
+ let handled: boolean | undefined;
+ await act(async () => {
+ handled = await current().onNativeDrop?.([new File(["x"], "folder")]);
+ });
+ expect(handled).toBe(false);
+ expect(current().hasSelection).toBe(false);
+ });
+ });
+
+ describe("doImport", () => {
+ it("does nothing when nothing is selected", async () => {
+ await mount();
+ await act(async () => current().doImport());
+ expect(uploadFiles).not.toHaveBeenCalled();
+ expect(importFromToken).not.toHaveBeenCalled();
+ expect(closeDialog).not.toHaveBeenCalled();
+ });
+
+ it("uploads the chosen file with the provider format and safe-import flags", async () => {
+ await mount({ shrinkImages: true });
+ const file = new File(["x"], "vault.zip");
+ await act(async () => current().onChange(fileListOf(file)));
+ await act(async () => current().doImport());
+
+ expect(closeDialog).toHaveBeenCalled();
+ expect(uploadFiles).toHaveBeenCalledWith("notes", "p1", [file], {
+ format: "obsidian",
+ safeImport: "true",
+ shrinkImages: "true"
+ });
+ });
+
+ it("imports a native pick in place via the capability token instead of uploading", async () => {
+ isElectron.mockReturnValue(true);
+ await mount({ shrinkImages: true });
+ pickFiles.mockResolvedValueOnce({ status: "selected", files: [{ token: "tok-1", fileName: "Vault.zip" }] });
+ await act(async () => {
+ current().onBrowse?.();
+ });
+
+ await act(async () => current().doImport());
+
+ expect(closeDialog).toHaveBeenCalled();
+ expect(uploadFiles).not.toHaveBeenCalled();
+ expect(importFromToken).toHaveBeenCalledTimes(1);
+ expect(importFromToken).toHaveBeenCalledWith(
+ expect.objectContaining({
+ token: "tok-1",
+ parentNoteId: "p1",
+ format: "obsidian",
+ last: true,
+ options: expect.objectContaining({ safeImport: true, shrinkImages: true, explodeArchives: true })
+ })
+ );
+ });
+ });
+});
diff --git a/apps/client/src/widgets/react/FileDropZone.spec.tsx b/apps/client/src/widgets/react/FileDropZone.spec.tsx
new file mode 100644
index 0000000000..e04018ad00
--- /dev/null
+++ b/apps/client/src/widgets/react/FileDropZone.spec.tsx
@@ -0,0 +1,85 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import FileDropZone from "./FileDropZone";
+
+// Note: the drag-and-drop branch (onDrop → onNativeDrop fallback) isn't exercised here — happy-dom doesn't
+// dispatch drag/drop events to preact listeners. That decision logic (native-handled vs. upload fallback)
+// is covered at the hook level in dialogs/import/useProviderImport.spec.tsx, which drives onNativeDrop
+// directly. This spec covers FileDropZone's own additions: the external-selection display and browse override.
+
+describe("FileDropZone", () => {
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ const zone = () => container.querySelector(".file-drop-zone") as HTMLElement;
+ const filenames = () => Array.from(container.querySelectorAll(".file-drop-zone-filename")).map((el) => el.textContent);
+
+ it("notifies a null selection on mount", async () => {
+ const onChange = vi.fn();
+ await act(async () => render(<FileDropZone onChange={onChange} />, container));
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+
+ it("forwards multiple and accept to the underlying file input", async () => {
+ await act(async () => render(<FileDropZone onChange={vi.fn()} multiple accept=".zip" />, container));
+ const input = container.querySelector("input[type=file]") as HTMLInputElement;
+ expect(input.multiple).toBe(true);
+ expect(input.getAttribute("accept")).toBe(".zip");
+ });
+
+ describe("displayNames (external selection)", () => {
+ it("shows externally-provided names and marks the zone as having files", async () => {
+ await act(async () => render(<FileDropZone onChange={vi.fn()} displayNames={["Vault.zip"]} />, container));
+ expect(filenames()).toEqual(["Vault.zip"]);
+ expect(zone().className).toContain("has-files");
+ });
+
+ it("lists every external name when several are provided", async () => {
+ await act(async () => render(<FileDropZone onChange={vi.fn()} displayNames={["a.zip", "b.zip"]} />, container));
+ expect(filenames()).toEqual(["a.zip", "b.zip"]);
+ });
+
+ it("shows no selection when there is neither an external nor an internal one", async () => {
+ await act(async () => render(<FileDropZone onChange={vi.fn()} />, container));
+ expect(filenames()).toEqual([]);
+ expect(zone().className).not.toContain("has-files");
+ });
+ });
+
+ describe("onBrowse override", () => {
+ it("calls the override and prevents the in-page file input from opening", async () => {
+ const onBrowse = vi.fn();
+ await act(async () => render(<FileDropZone onChange={vi.fn()} onBrowse={onBrowse} />, container));
+
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });
+ await act(async () => {
+ zone().dispatchEvent(click);
+ });
+
+ expect(onBrowse).toHaveBeenCalledTimes(1);
+ expect(click.defaultPrevented).toBe(true);
+ });
+
+ it("does not intercept the click when no override is provided", async () => {
+ await act(async () => render(<FileDropZone onChange={vi.fn()} />, container));
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });
+ await act(async () => {
+ zone().dispatchEvent(click);
+ });
+ // Without an override the label keeps its default behaviour (opening the native input).
+ expect(click.defaultPrevented).toBe(false);
+ });
+ });
+});