Skip to content

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

4.6 KB
Raw Blame
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useViewScopedFiles } from "@editor/hooks/tools/shared/useViewScopedFiles";
import { useFileContext } from "@editor/contexts/file/fileHooks";
import {
  createToolFlow,
  type MiddleStepConfig,
} from "@editor/components/tools/shared/createToolFlow";
import { BaseToolProps, ToolComponent } from "@editor/types/tool";
import { useEndpointEnabled } from "@editor/hooks/useEndpointConfig";
import { useAddAttachmentsParameters } from "@editor/hooks/tools/addAttachments/useAddAttachmentsParameters";
import { useAddAttachmentsOperation } from "@editor/hooks/tools/addAttachments/useAddAttachmentsOperation";
import { useAccordionSteps } from "@editor/hooks/tools/shared/useAccordionSteps";
import AddAttachmentsSettings from "@editor/components/tools/addAttachments/AddAttachmentsSettings";
import { useAddAttachmentsTips } from "@editor/components/tooltips/useAddAttachmentsTips";

const AddAttachments = ({
  onPreviewFile,
  onComplete,
  onError,
}: BaseToolProps) => {
  const { t } = useTranslation();
  const selectedFiles = useViewScopedFiles();
  const { addFiles } = useFileContext();
  const addAttachmentsTips = useAddAttachmentsTips();

  const params = useAddAttachmentsParameters();
  const operation = useAddAttachmentsOperation();

  const { enabled: addEndpointEnabled, loading: endpointLoading } =
    useEndpointEnabled("add-attachments");
  const { enabled: batchEndpointEnabled } = useEndpointEnabled(
    "batch-process-attachments",
  );
  const endpointEnabled = addEndpointEnabled && batchEndpointEnabled;

  useEffect(() => {
    operation.resetResults();
    onPreviewFile?.(null);
  }, [params.parameters]);

  const handleExecute = async () => {
    try {
      await operation.executeOperation(params.parameters, selectedFiles);
      if (operation.files && onComplete) {
        onComplete(operation.files);
      }
    } catch (error) {
      onError?.(
        (error instanceof Error ? error.message : undefined) ||
          t(
            "AddAttachmentsRequest.error.failed",
            "Add attachments operation failed",
          ),
      );
    }
  };

  const hasFiles = selectedFiles.length > 0;
  const hasResults =
    operation.files.length > 0 || operation.downloadUrl !== null;

  enum AddAttachmentsStep {
    NONE = "none",
    ATTACHMENTS = "attachments",
  }

  const accordion = useAccordionSteps<AddAttachmentsStep>({
    noneValue: AddAttachmentsStep.NONE,
    initialStep: AddAttachmentsStep.ATTACHMENTS,
    stateConditions: {
      hasFiles,
      hasResults: false, // Don't collapse when there are results for add attachments
    },
    afterResults: () => {
      operation.resetResults();
      onPreviewFile?.(null);
    },
  });

  const getSteps = () => {
    const steps: MiddleStepConfig[] = [];

    // Step 1: Attachments Selection
    steps.push({
      title: t("AddAttachmentsRequest.attachments", "Select Attachments"),
      isCollapsed: accordion.getCollapsedState(AddAttachmentsStep.ATTACHMENTS),
      onCollapsedClick: () =>
        accordion.handleStepToggle(AddAttachmentsStep.ATTACHMENTS),
      isVisible: true,
      tooltip: addAttachmentsTips,
      content: (
        <AddAttachmentsSettings
          parameters={params.parameters}
          onParameterChange={params.updateParameter}
          disabled={endpointLoading}
          activeFile={selectedFiles[0] || null}
          onFileUpdated={(updatedFile) => {
            void addFiles([updatedFile], { selectFiles: true });
            if (onComplete) {
              onComplete([updatedFile]);
            }
          }}
          onError={(msg) => onError?.(msg)}
        />
      ),
    });

    return steps;
  };

  return createToolFlow({
    files: {
      selectedFiles:
        operation.getEligibleFiles?.(params.parameters, selectedFiles) ??
        selectedFiles,
      isCollapsed: hasResults,
    },
    steps: getSteps(),
    executeButton: {
      text: t("AddAttachmentsRequest.submit", "Add Attachments"),
      isVisible: false,
      loadingText: t("loading"),
      onClick: handleExecute,
      endpointEnabled: endpointEnabled,
      paramsValid: params.validateParameters(),
    },
    review: {
      isVisible: hasResults,
      operation: operation,
      title: t("AddAttachmentsRequest.results.title", "Attachment Results"),
      onFileClick: (file) => onPreviewFile?.(file),
      onUndo: async () => {
        await operation.undoOperation();
        onPreviewFile?.(null);
      },
    },
  });
};

AddAttachments.tool = () => useAddAttachmentsOperation;

export default AddAttachments as ToolComponent;