Skip to content

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

6.4 KB
Raw Blame
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useEndpointEnabled } from "@editor/hooks/useEndpointConfig";
import { useAllFiles, useFileSelection } from "@editor/contexts/FileContext";
import { useViewScopedFiles } from "@editor/hooks/tools/shared/useViewScopedFiles";
import { detectFileExtension } from "@editor/utils/fileUtils";
import { isImageFormat } from "@editor/utils/convertUtils";

import { createToolFlow } from "@editor/components/tools/shared/createToolFlow";

import ConvertSettings from "@editor/components/tools/convert/ConvertSettings";

import { useConvertParameters } from "@editor/hooks/tools/convert/useConvertParameters";
import { useConvertOperation } from "@editor/hooks/tools/convert/useConvertOperation";
import { BaseToolProps, ToolComponent } from "@editor/types/tool";

const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
  const { t } = useTranslation();
  const { files: activeFiles } = useAllFiles();
  const { setSelectedFiles } = useFileSelection();
  const selectedFiles = useViewScopedFiles();

  // Selecting a source format narrows the working selection to the loaded files that match it. This
  // is an editor convenience; ConvertSettings itself is FileContext-free so it can also render in
  // the automation and pipeline surfaces, which have no loaded files.
  const handleSourceFormatSelected = (fromExtension: string) => {
    if (activeFiles.length === 0) {
      setSelectedFiles([]);
      return;
    }
    const matching = activeFiles.filter((file) => {
      const ext = detectFileExtension(file.name);
      if (fromExtension === "any") return true;
      if (fromExtension === "image") return isImageFormat(ext);
      return ext === fromExtension;
    });
    setSelectedFiles(matching.map((file) => file.fileId));
  };

  const convertParams = useConvertParameters();
  const convertOperation = useConvertOperation(convertParams.parameters);

  const { enabled: endpointEnabled, loading: endpointLoading } =
    useEndpointEnabled(convertParams.getEndpointName());

  // Prevent reset immediately after operation completes (when consumeFiles auto-selects outputs)
  const skipNextSelectionResetRef = useRef(false);
  const previousSelectionRef = useRef<string>("");

  const hasResults =
    convertOperation.files.length > 0 ||
    convertOperation.downloadUrl !== null ||
    !!convertOperation.errorMessage;
  const settingsCollapsed = hasResults;

  // When operation completes, flag the next selection change to skip reset
  useEffect(() => {
    if (hasResults) {
      skipNextSelectionResetRef.current = true;
    }
  }, [hasResults]);

  // Reset results when user manually changes file selection
  useEffect(() => {
    const currentSelection = selectedFiles
      .map((f) => f.fileId)
      .sort()
      .join(",");

    if (currentSelection === previousSelectionRef.current) return; // No change

    // Skip reset if this is the auto-selection after operation completed
    // Don't analyze file types - would change parameters and trigger another reset
    if (skipNextSelectionResetRef.current) {
      skipNextSelectionResetRef.current = false;
      previousSelectionRef.current = currentSelection;
      return;
    }

    // User manually selected different files
    if (selectedFiles.length > 0) {
      previousSelectionRef.current = currentSelection;
      convertParams.analyzeFileTypes(selectedFiles);
      if (hasResults) {
        convertOperation.resetResults();
        onPreviewFile?.(null);
      }
    } else {
      previousSelectionRef.current = "";
      if (activeFiles.length === 0) {
        convertParams.resetParameters();
      }
    }
  }, [selectedFiles]);

  useEffect(() => {
    // Reset when user changes conversion parameters (but not during operation)
    if (!convertOperation.isLoading && !skipNextSelectionResetRef.current) {
      convertOperation.resetResults();
      onPreviewFile?.(null);
    }
  }, [
    convertParams.parameters.fromExtension,
    convertParams.parameters.toExtension,
  ]);

  const handleConvert = async () => {
    try {
      await convertOperation.executeOperation(
        convertParams.parameters,
        selectedFiles,
      );
      if (convertOperation.files && onComplete) {
        onComplete(convertOperation.files);
      }
    } catch (error) {
      if (onError) {
        onError(
          error instanceof Error ? error.message : "Convert operation failed",
        );
      }
    }
  };

  const handleThumbnailClick = (file: File) => {
    onPreviewFile?.(file);
    sessionStorage.setItem("previousMode", "convert");
  };

  const handleSettingsReset = () => {
    skipNextSelectionResetRef.current = false;
    convertOperation.resetResults();
    onPreviewFile?.(null);
  };

  const handleUndo = async () => {
    await convertOperation.undoOperation();
    onPreviewFile?.(null);
  };

  const eligibleFiles =
    convertOperation.getEligibleFiles?.(
      convertParams.parameters,
      selectedFiles,
    ) ?? selectedFiles;

  return createToolFlow({
    files: {
      selectedFiles: eligibleFiles,
      isCollapsed: hasResults,
    },
    steps: [
      {
        title: t("convert.settings", "Settings"),
        isCollapsed: settingsCollapsed,
        onCollapsedClick: settingsCollapsed ? handleSettingsReset : undefined,
        content: (
          <ConvertSettings
            parameters={convertParams.parameters}
            onParameterChange={convertParams.updateParameter}
            getAvailableToExtensions={convertParams.getAvailableToExtensions}
            selectedFiles={eligibleFiles}
            onSourceFormatSelected={handleSourceFormatSelected}
            disabled={endpointLoading}
          />
        ),
      },
    ],
    executeButton: {
      text: t("convert.convertFiles", "Convert Files"),
      loadingText: t("convert.converting", "Converting..."),
      onClick: handleConvert,
      isVisible: !hasResults,
      endpointEnabled: endpointEnabled,
      paramsValid: convertParams.validateParameters(),
      testId: "convert-button",
    },
    review: {
      isVisible: hasResults,
      operation: convertOperation,
      title: t("convert.conversionResults", "Conversion Results"),
      onFileClick: handleThumbnailClick,
      onUndo: handleUndo,
      testId: "conversion-results",
    },
  });
};

// Static method to get the operation hook for automation
Convert.tool = () => useConvertOperation;

export default Convert as ToolComponent;