Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(desktop): route drop-zone drags through the native in-place import
Elian Doran059e7420ab15
diff --git a/apps/client/src/widgets/dialogs/import/anytype.tsx b/apps/client/src/widgets/dialogs/import/anytype.tsxindex b5ed4094b3..f63b3f4c9e 100644--- a/apps/client/src/widgets/dialogs/import/anytype.tsx+++ b/apps/client/src/widgets/dialogs/import/anytype.tsx@@ -15,7 +15,7 @@ function AnytypePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPaconst [shrinkImages, setShrinkImages] = useState(compressImages);// `format: "anytype"` routes the upload/native import to the Anytype importer, overriding the .zip// extension's default (the generic zip importer).- const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "anytype", parentNoteId, shrinkImages, closeDialog });+ const { hasSelection, displayNames, onChange, onBrowse, onNativeDrop, doImport } = useProviderImport({ format: "anytype", parentNoteId, shrinkImages, closeDialog });// Keep the latest import handler in a ref so the footer effect depends only on whether a file is// selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop@@ -38,7 +38,7 @@ function AnytypePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa<Card heading={t("anytype_import.choose_file")}><CardSection><OptionsRow name="import-file" description={t("anytype_import.description_long")} stacked>- <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} accept=".zip" />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} onNativeDrop={onNativeDrop} displayNames={displayNames} accept=".zip" /></OptionsRow><OptionsRowWithTogglename="shrink-images"diff --git a/apps/client/src/widgets/dialogs/import/files.tsx b/apps/client/src/widgets/dialogs/import/files.tsxindex 187d289288..0a033bfd0d 100644--- a/apps/client/src/widgets/dialogs/import/files.tsx+++ b/apps/client/src/widgets/dialogs/import/files.tsx@@ -87,6 +87,19 @@ function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPane}}, []);+ // Desktop: route a drop through the native in-place path too. Handle it natively only when *every*+ // dropped file resolved to a real path (the rest — folders, browser drags — fall back to upload so+ // nothing is silently dropped).+ const onNativeDrop = useCallback(async (dropped: File[]) => {+ const pick = await window.electronApi?.nativeImport.grantDroppedFiles(dropped);+ if (pick?.status !== "selected" || pick.files?.length !== dropped.length) {+ return false;+ }+ setFiles(null);+ setNativeFiles(pick.files);+ return true;+ }, []);+// Keep the latest import handler in a ref so the footer effect depends only on whether files are// selected, never on doImport's identity — otherwise re-pushing the footer on every option toggle// would loop with the parent re-rendering us back (see the other panels for the same reasoning).@@ -111,6 +124,7 @@ function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPane// On desktop, browsing opens the native dialog so the chosen files (zips especially)// are read in place. Drag-and-drop still uses the upload route via onChange.onBrowse={utils.isElectron() ? () => void doNativeBrowse() : undefined}+ onNativeDrop={utils.isElectron() ? onNativeDrop : undefined}displayNames={nativeFiles?.map((file) => file.fileName)}/></CardSection>diff --git a/apps/client/src/widgets/dialogs/import/keep.tsx b/apps/client/src/widgets/dialogs/import/keep.tsxindex 7e0a6ae20d..49aa213f61 100644--- a/apps/client/src/widgets/dialogs/import/keep.tsx+++ b/apps/client/src/widgets/dialogs/import/keep.tsx@@ -15,7 +15,7 @@ function KeepPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelconst [shrinkImages, setShrinkImages] = useState(compressImages);// `format: "keep"` routes the upload/native import to the Google Keep importer, overriding the .zip// extension's default (the generic zip importer).- const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "keep", parentNoteId, shrinkImages, closeDialog });+ const { hasSelection, displayNames, onChange, onBrowse, onNativeDrop, doImport } = useProviderImport({ format: "keep", parentNoteId, shrinkImages, closeDialog });// Keep the latest import handler in a ref so the footer effect depends only on whether a file is// selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop@@ -38,7 +38,7 @@ function KeepPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanel<Card heading={t("keep_import.choose_file")}><CardSection><OptionsRow name="import-file" description={t("keep_import.description_long")} stacked>- <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} accept=".zip" />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} onNativeDrop={onNativeDrop} displayNames={displayNames} accept=".zip" /></OptionsRow><OptionsRowWithTogglename="shrink-images"diff --git a/apps/client/src/widgets/dialogs/import/notion.tsx b/apps/client/src/widgets/dialogs/import/notion.tsxindex 52fc875095..ba87a64974 100644--- a/apps/client/src/widgets/dialogs/import/notion.tsx+++ b/apps/client/src/widgets/dialogs/import/notion.tsx@@ -15,7 +15,7 @@ function NotionPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanconst [shrinkImages, setShrinkImages] = useState(compressImages);// `format: "notion"` routes the upload/native import to the Notion importer, overriding the .zip// extension's default (the generic zip importer).- const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "notion", parentNoteId, shrinkImages, closeDialog });+ const { hasSelection, displayNames, onChange, onBrowse, onNativeDrop, doImport } = useProviderImport({ format: "notion", parentNoteId, shrinkImages, closeDialog });// Keep the latest import handler in a ref so the footer effect depends only on whether a file is// selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop@@ -38,7 +38,7 @@ function NotionPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPan<Card heading={t("notion_import.choose_file")}><CardSection><OptionsRow name="import-file" description={t("notion_import.description_long")} stacked>- <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} accept=".zip" />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} onNativeDrop={onNativeDrop} displayNames={displayNames} accept=".zip" /></OptionsRow><OptionsRowWithTogglename="shrink-images"diff --git a/apps/client/src/widgets/dialogs/import/obsidian.tsx b/apps/client/src/widgets/dialogs/import/obsidian.tsxindex dc6a9d5931..b5c5d01bd1 100644--- a/apps/client/src/widgets/dialogs/import/obsidian.tsx+++ b/apps/client/src/widgets/dialogs/import/obsidian.tsx@@ -15,7 +15,7 @@ function ObsidianPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPconst [shrinkImages, setShrinkImages] = useState(compressImages);// `format: "obsidian"` routes the upload/native import to the Obsidian importer, overriding the .zip// extension's default (the generic zip importer).- const { hasSelection, displayNames, onChange, onBrowse, doImport } = useProviderImport({ format: "obsidian", parentNoteId, shrinkImages, closeDialog });+ const { hasSelection, displayNames, onChange, onBrowse, onNativeDrop, doImport } = useProviderImport({ format: "obsidian", parentNoteId, shrinkImages, closeDialog });// Keep the latest import handler in a ref so the footer effect depends only on whether a file is// selected, never on doImport's identity — otherwise re-pushing the footer on every change would loop@@ -38,7 +38,7 @@ function ObsidianPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderP<Card heading={t("obsidian_import.choose_file")}><CardSection><p className="import-files-description">{t("obsidian_import.description_long")}</p>- <FileDropZone onChange={onChange} onBrowse={onBrowse} displayNames={displayNames} />+ <FileDropZone onChange={onChange} onBrowse={onBrowse} onNativeDrop={onNativeDrop} displayNames={displayNames} /><OptionsRowWithTogglename="shrink-images"label={t("import.shrinkImages")}diff --git a/apps/client/src/widgets/dialogs/import/useProviderImport.ts b/apps/client/src/widgets/dialogs/import/useProviderImport.tsindex 231059da5a..65524faf31 100644--- a/apps/client/src/widgets/dialogs/import/useProviderImport.ts+++ b/apps/client/src/widgets/dialogs/import/useProviderImport.ts@@ -20,6 +20,8 @@ interface ProviderImport {onChange: (files: FileList | null) => void;/** Desktop-only native browse (reads the zip in place); undefined elsewhere. */onBrowse?: () => void;+ /** Desktop-only native drop (reads the dropped zip in place); undefined elsewhere. */+ onNativeDrop?: (files: File[]) => Promise<boolean>;doImport: () => Promise<void>;}@@ -49,6 +51,18 @@ export default function useProviderImport({ format, parentNoteId, shrinkImages,setNativeFile(pick.files[0]);}, []);+ // Desktop: route a dropped archive through the native in-place path. A provider takes a single file, so+ // resolve just the first; fall back to upload if it didn't resolve to a real path.+ const nativeDrop = useCallback(async (dropped: File[]) => {+ const pick = await window.electronApi?.nativeImport.grantDroppedFiles(dropped.slice(0, 1));+ if (pick?.status !== "selected" || !pick.files?.length) {+ return false;+ }+ setFile(null);+ setNativeFile(pick.files[0]);+ return true;+ }, []);+const doImport = useCallback(async () => {// Close immediately and let the shared import toasts (registered in import.ts) report progress,// completion and any error. Swallow rejections so these void-ed calls don't raise unhandled ones.@@ -75,6 +89,7 @@ export default function useProviderImport({ format, parentNoteId, shrinkImages,displayNames: nativeFile ? [nativeFile.fileName] : undefined,onChange,onBrowse: utils.isElectron() ? () => void browse() : undefined,+ onNativeDrop: utils.isElectron() ? nativeDrop : undefined,doImport};}diff --git a/apps/client/src/widgets/react/FileDropZone.tsx b/apps/client/src/widgets/react/FileDropZone.tsxindex ad4c9e308c..35dfcb5836 100644--- a/apps/client/src/widgets/react/FileDropZone.tsx+++ b/apps/client/src/widgets/react/FileDropZone.tsx@@ -21,6 +21,11 @@ export interface FileDropZoneProps {* filenames are known but which aren't `File` objects. When non-empty it wins; dropping files clears it.*/displayNames?: string[];+ /**+ * Desktop only: given the dropped files, try to route them through the native (in-place) import. Return+ * `true` if handled — the upload `onChange` is then skipped; return `false` to fall back to upload.+ */+ onNativeDrop?: (files: File[]) => Promise<boolean>;}/**@@ -28,7 +33,7 @@ export interface FileDropZoneProps {* picker. Selected files are listed inside. Drop-in replacement for {@link FormFileUpload} — same* `onChange(files)` / `multiple` contract.*/-export default function FileDropZone({ name, onChange, multiple, accept, onBrowse, displayNames }: FileDropZoneProps) {+export default function FileDropZone({ name, onChange, multiple, accept, onBrowse, displayNames, onNativeDrop }: FileDropZoneProps) {const inputRef = useRef<HTMLInputElement>(null);const [files, setFiles] = useState<File[]>([]);const [dragging, setDragging] = useState(false);@@ -65,15 +70,21 @@ export default function FileDropZone({ name, onChange, multiple, accept, onBrows}}, []);- const onDrop = useCallback((e: DragEvent) => {+ const onDrop = useCallback(async (e: DragEvent) => {e.preventDefault();dragDepth.current = 0;setDragging(false);const dropped = e.dataTransfer?.files;- if (dropped && dropped.length) {- update(dropped);+ if (!dropped || !dropped.length) {+ return;+ }+ // On desktop, try the native in-place route first; only fall back to upload if it didn't handle the+ // drop. Capture the File list before any await so it survives the event being recycled.+ if (onNativeDrop && await onNativeDrop(Array.from(dropped))) {+ return;}- }, [update]);+ update(dropped);+ }, [update, onNativeDrop]);// An external (native) selection takes precedence over whatever the in-page input/drop produced.const selectedNames = displayNames?.length ? displayNames : files.map((file) => file.name);@@ -87,7 +98,7 @@ export default function FileDropZone({ name, onChange, multiple, accept, onBrowsonDragEnter={onDragEnter}onDragOver={(e) => e.preventDefault()}onDragLeave={onDragLeave}- onDrop={onDrop}+ onDrop={(e) => void onDrop(e)}><inputref={inputRef}diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex b2d0af6ea1..ffe0651443 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -50,6 +50,12 @@ vi.mock("electron", () => ({ipcRendererListeners.set(channel, filtered);}}+ },+ // Maps a dropped File to its on-disk path; here we read a test-only `path` field off the fake File.+ webUtils: {+ getPathForFile(file: { path?: string }) {+ return file.path ?? "";+ }}}));@@ -637,5 +643,12 @@ describe("preload script", () => {await nativeImport().importFromToken(opts);expect(ipcRendererInvoked).toContainEqual({ channel: "import-from-token", args: [opts] });});++ it("grantDroppedFiles resolves File objects to paths and forwards only those (dropping unresolved)", async () => {+ const grantDroppedFiles = nativeImport().grantDroppedFiles as (files: unknown[]) => Promise<unknown>;+ // The second file has no backing path (a script-built blob / browser drag) → getPathForFile yields "".+ await grantDroppedFiles([{ path: "/data/a.zip" }, { /* no path */ }]);+ expect(ipcRendererInvoked).toContainEqual({ channel: "import-grant-dropped", args: [["/data/a.zip"]] });+ });});});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex a8d50ed506..bad2ba8e3b 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -1,5 +1,5 @@import type { ElectronApi, ElectronContextMenuParams, NativeImportOptions, OneNoteLoginResult, RendererStartupMetric } from "@triliumnext/commons";-import { contextBridge, ipcRenderer, webFrame } from "electron";+import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";contextBridge.exposeInMainWorld("electronApi", {window: {@@ -214,6 +214,14 @@ contextBridge.exposeInMainWorld("electronApi", {pickFiles() {return ipcRenderer.invoke("import-pick-files");},+ grantDroppedFiles(files: File[]) {+ // Resolve each dropped File to its on-disk path here in the preload: getPathForFile returns a+ // real path only for a genuinely user-supplied file (empty for anything a script built), so the+ // File is the capability. Only the resolved paths cross to the main process — the path-accepting+ // channel is never exposed to the renderer, so a script can't smuggle in an arbitrary path.+ const paths = files.map((file) => webUtils.getPathForFile(file)).filter((path) => !!path);+ return ipcRenderer.invoke("import-grant-dropped", paths);+ },importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean; format?: string }) {return ipcRenderer.invoke("import-from-token", opts);}diff --git a/apps/desktop/src/services/import.spec.ts b/apps/desktop/src/services/import.spec.tsindex 83b378ae7c..07f382a2c0 100644--- a/apps/desktop/src/services/import.spec.ts+++ b/apps/desktop/src/services/import.spec.ts@@ -25,9 +25,13 @@ function dialogReturns(filePaths: string[] | undefined) {vi.mock("i18next", () => ({ t: (key: string) => key }));-// --- fs mock: the handler reads non-zip files into a buffer; zips are read in place (no readFile) ----const fsMock = vi.hoisted(() => ({ readFile: vi.fn<(...args: unknown[]) => Promise<Buffer>>(async () => Buffer.from("data")) }));-vi.mock("fs/promises", () => ({ readFile: fsMock.readFile }));+// --- fs mock: the handler reads non-zip files into a buffer; zips are read in place (no readFile). stat is+// used by import-grant-dropped to reject anything that isn't a regular file. ---+const fsMock = vi.hoisted(() => ({+ readFile: vi.fn<(...args: unknown[]) => Promise<Buffer>>(async () => Buffer.from("data")),+ stat: vi.fn<(...args: unknown[]) => Promise<{ isFile: () => boolean }>>(async () => ({ isFile: () => true }))+}));+vi.mock("fs/promises", () => ({ readFile: fsMock.readFile, stat: fsMock.stat }));// --- core mock: stub the dispatch pipeline so we can assert what the handler calls ---const coreMock = vi.hoisted(() => ({@@ -69,6 +73,9 @@ function pick() {function importFromToken(opts: object) {return electronMock.handlers.get("import-from-token")?.({}, opts) as Promise<{ status: string; importedNoteId?: string; message?: string }>;}+function grantDropped(paths: string[]) {+ return electronMock.handlers.get("import-grant-dropped")?.({}, paths) as Promise<{ status: string; files?: { token: string; fileName: string }[] }>;+}describe("desktop native import — capability token", () => {beforeEach(() => {@@ -77,6 +84,7 @@ describe("desktop native import — capability token", () => {coreMock.tokenCounter = 0;coreMock.dispatch.mockResolvedValue({ noteId: "imported1" });fsMock.readFile.mockResolvedValue(Buffer.from("data"));+ fsMock.stat.mockResolvedValue({ isFile: () => true });electronMock.getFocusedWindow.mockReturnValue({});setupImportHandlers();});@@ -101,6 +109,37 @@ describe("desktop native import — capability token", () => {expect(coreMock.dispatch).not.toHaveBeenCalled();});+ it("grants tokens for dropped files (same capability as the dialog)", async () => {+ const result = await grantDropped(["/data/a.zip", "/data/b.md"]);++ expect(result.status).toBe("selected");+ expect(result.files?.map((f) => f.fileName)).toEqual(["a.zip", "b.md"]);+ expect(result.files?.every((f) => !!f.token)).toBe(true);+ // The token redeems to the original path, proving the grant is wired to it.+ const redeemed = await importFromToken({ token: result.files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true });+ expect(redeemed.status).toBe("imported");+ const [, file] = coreMock.dispatch.mock.calls[0];+ expect(file).toMatchObject({ path: "/data/a.zip" });+ });++ it("skips dropped paths that aren't regular files (e.g. a folder)", async () => {+ fsMock.stat.mockImplementation(async (p: unknown) => ({ isFile: () => p === "/data/file.zip" }));++ const result = await grantDropped(["/data/folder", "/data/file.zip"]);++ expect(result.status).toBe("selected");+ expect(result.files?.map((f) => f.fileName)).toEqual(["file.zip"]);+ });++ it("returns cancelled when no dropped path resolves (caller falls back to upload)", async () => {+ // An empty path list is what the preload sends when getPathForFile resolved nothing (e.g. a browser drag).+ expect(await grantDropped([])).toEqual({ status: "cancelled" });+ // A path that can't be stat'd (missing/unreadable) is skipped too.+ fsMock.stat.mockRejectedValue(new Error("ENOENT"));+ expect(await grantDropped(["/data/gone.zip"])).toEqual({ status: "cancelled" });+ expect(coreMock.dispatch).not.toHaveBeenCalled();+ });+it("imports a granted zip in place (dispatch receives a { path } file, never read into a buffer)", async () => {vi.useFakeTimers();try {diff --git a/apps/desktop/src/services/import.ts b/apps/desktop/src/services/import.tsindex 05497ce46c..a78b51620a 100644--- a/apps/desktop/src/services/import.ts+++ b/apps/desktop/src/services/import.ts@@ -1,7 +1,7 @@import type { NativeImportOptions, NativeImportPickResult, NativeImportResult } from "@triliumnext/commons";import { becca, becca_loader, cls, type File, getLog, importDispatchService, type ImportOptions, TaskContext, utils as coreUtils } from "@triliumnext/core";import { default as electron } from "electron";-import { readFile } from "fs/promises";+import { readFile, stat } from "fs/promises";import { t } from "i18next";import { basename, extname } from "path";@@ -51,6 +51,24 @@ export function setupImportHandlers() {};});+ electron.ipcMain.handle("import-grant-dropped", async (_e, paths: string[]): Promise<NativeImportPickResult> => {+ // Paths come from the preload's getPathForFile (user-dropped files only); mint a grant for each, the+ // same capability the OS dialog hands out. Skip anything that isn't a regular file (a dropped folder,+ // or a path that vanished) so the renderer falls back to the upload route instead of failing later.+ const files: { token: string; fileName: string }[] = [];+ for (const path of paths) {+ try {+ if ((await stat(path)).isFile()) {+ files.push({ token: grantFileAccess(path), fileName: basename(path) });+ }+ } catch {+ // Unreadable/missing path — skip it.+ }+ }++ return files.length > 0 ? { status: "selected", files } : { status: "cancelled" };+ });+electron.ipcMain.handle("import-from-token", async (_e, opts: ImportFromTokenOpts): Promise<NativeImportResult> => {const path = redeemFileAccess(opts.token);if (!path) {diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 98a20b4210..e52b7ea325 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -577,6 +577,15 @@ export interface NativeImportResult {export interface ElectronNativeImportApi {/** Prompts a native "open file" dialog (multi-select, any type) and returns single-use tokens for the chosen files. */pickFiles(): Promise<NativeImportPickResult>;+ /**+ * Resolves files the user dropped onto a drop zone to capability tokens, so a drag-and-drop import takes+ * the same in-place (streamed) path as the dialog. The `File` is the unforgeable capability: the path is+ * obtained via `webUtils.getPathForFile`, which yields a real path only for a genuinely user-supplied+ * file and an empty string for anything a script constructed — so a script can't smuggle in an arbitrary+ * path. Returns `cancelled` when no dropped file resolved (e.g. dragged from a browser, not the OS), so+ * the caller falls back to the normal upload route.+ */+ grantDroppedFiles(files: File[]): Promise<NativeImportPickResult>;/*** Imports the file behind `token` into `parentNoteId`. Progress/success/error are reported over the* WebSocket via `taskId`, matching the HTTP import path. When importing several files in one batch, set