Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

2.1 KB
Raw Blame
// Desktop implementation - Tauri native file dialogs
import type {
  FileWithPath,
  FileDialogOptions,
} from "@editor-core/services/fileDialogService";
import { createQuickKey } from "@editor/types/fileContext";
import { getDocumentFileDialogFilter } from "@editor/utils/fileDialogUtils";

export type { FileWithPath, FileDialogOptions };

/** Whether cancelling the picker should finish instead of opening a browser fallback. */
export const hasNativeFileDialog = true;

/**
 * Open native file dialog and read selected files (Desktop/Tauri only)
 */
export async function openFileDialog(
  options?: FileDialogOptions,
): Promise<FileWithPath[]> {
  try {
    const { open } = await import("@tauri-apps/plugin-dialog");
    const { readFile } = await import("@tauri-apps/plugin-fs");

    console.log("[FileDialog] Opening file dialog...");
    const selectedPaths = await open({
      multiple: options?.multiple ?? true,
      filters: options?.filters ?? getDocumentFileDialogFilter(),
    });

    if (!selectedPaths) {
      console.log("[FileDialog] User cancelled");
      return [];
    }

    const paths = Array.isArray(selectedPaths)
      ? selectedPaths
      : [selectedPaths];
    console.log(`[FileDialog] Selected ${paths.length} file(s):`, paths);

    const filesWithPaths: FileWithPath[] = [];

    for (const filePath of paths) {
      try {
        console.log(`[FileDialog] Reading file: ${filePath}`);
        const fileData = await readFile(filePath);
        const fileName = filePath.split(/[/\\]/).pop() || "document";
        const file = new File([fileData], fileName, {
          type: fileName.endsWith(".pdf") ? "application/pdf" : undefined,
        });
        const quickKey = createQuickKey(file);
        console.log(
          `[FileDialog] Created File: ${fileName}, quickKey: ${quickKey}`,
        );

        filesWithPaths.push({
          file,
          path: filePath,
          quickKey,
        });
      } catch (error) {
        console.error(`[FileDialog] Failed to read ${filePath}:`, error);
      }
    }

    return filesWithPaths;
  } catch (error) {
    console.error("[FileDialog] Error:", error);
    return [];
  }
}