Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

8.0 KB
Raw Blame
import { isNil } from '@activepieces/core-utils';
import {
  FlowAction,
  FlowTrigger,
  FlowTriggerType,
  Step,
  flowStructureUtil,
} from '@activepieces/shared';
import { t } from 'i18next';
import { Play } from 'lucide-react';
import { useContext, useEffect } from 'react';
import { toast } from 'sonner';

import { useBuilderStateContext } from '@/app/builder/builder-hooks';
import { LoadingSpinner } from '@/components/custom/spinner';
import { Button } from '@/components/ui/button';
import { pieceSelectorUtils } from '@/features/pieces';

import { DynamicPropertiesContext } from '../piece-properties/dynamic-properties-context';

import {
  useActionTestRunner,
  useTriggerTestRunner,
} from './test-runner-context';
import { TestButtonTooltip } from './test-step-tooltip';

const SOFT_PRIMARY_CTA_CLASSES =
  'w-full justify-center bg-accent-3 enabled:hover:bg-accent-4 enabled:hover:text-accent-11 text-accent-11 border-accent-6';

const TestStepCTAButton = () => {
  const [selectedStep, flowVersion, setStepDataPanelOpen, run, saving] =
    useBuilderStateContext((state) => [
      state.selectedStep,
      state.flowVersion,
      state.setStepDataPanelOpen,
      state.run,
      state.saving,
    ]);

  const currentStep = selectedStep
    ? flowStructureUtil.getStep(selectedStep, flowVersion.trigger)
    : null;

  if (!currentStep) {
    return null;
  }

  const sampleDataExists = !isNil(
    currentStep.settings?.sampleData?.lastTestDate,
  );
  const onOpenPanel = () => setStepDataPanelOpen(true);

  if (isFlowAction(currentStep)) {
    return (
      <ActionCTAButton
        currentStep={currentStep}
        sampleDataExists={sampleDataExists}
        onOpenPanel={onOpenPanel}
        saving={saving}
        hasRun={!isNil(run)}
      />
    );
  }

  if (isPieceTrigger(currentStep)) {
    if (
      pieceSelectorUtils.isManualTrigger({
        pieceName: currentStep.settings.pieceName,
        triggerName: currentStep.settings.triggerName ?? '',
      })
    ) {
      return null;
    }
    return (
      <TriggerCTAButton
        sampleDataExists={sampleDataExists}
        stepIsValid={currentStep.valid !== false}
        onOpenPanel={onOpenPanel}
        saving={saving}
        hasRun={!isNil(run)}
      />
    );
  }

  return null;
};

const isFlowAction = (step: Step): step is FlowAction =>
  flowStructureUtil.isAction(step.type);

const isPieceTrigger = (
  step: Step,
): step is Extract<FlowTrigger, { type: FlowTriggerType.PIECE }> =>
  step.type === FlowTriggerType.PIECE;

type ActionCTAButtonProps = {
  currentStep: FlowAction;
  sampleDataExists: boolean;
  onOpenPanel: () => void;
  saving: boolean;
  hasRun: boolean;
};

const ActionCTAButton = ({
  currentStep,
  sampleDataExists,
  onOpenPanel,
  saving,
  hasRun,
}: ActionCTAButtonProps) => {
  const stepIsValid = currentStep.valid !== false;
  const { isLoadingDynamicProperties } = useContext(DynamicPropertiesContext);
  const runner = useActionTestRunner();
  const runnerBusy = runner?.isTesting ?? false;
  useConfigureStepShortcutToast(stepIsValid || runnerBusy);

  const fireTest = () => {
    onOpenPanel();
    runner?.fireTest();
  };

  if (hasRun) {
    return (
      <CTAShell>
        <TestButtonTooltip saving={saving} invalid={false}>
          <Button
            variant="outline"
            onClick={onOpenPanel}
            disabled={saving}
            className={SOFT_PRIMARY_CTA_CLASSES}
            size="sm"
          >
            {t('Show Data')}
          </Button>
        </TestButtonTooltip>
      </CTAShell>
    );
  }

  const testDisabled = saving || !stepIsValid || isLoadingDynamicProperties;
  return (
    <CTAShell>
      {sampleDataExists && (
        <Button
          variant="outline"
          onClick={onOpenPanel}
          disabled={saving}
          className="w-full justify-center"
          size="sm"
        >
          {t('Show Data')}
        </Button>
      )}
      {runnerBusy ? (
        <TestInProgressButton
          label={t('Testing...')}
          onOpenPanel={onOpenPanel}
          testId="test-step-button"
        />
      ) : (
        <TestButtonTooltip saving={saving} invalid={!stepIsValid}>
          <Button
            variant="outline"
            onClick={fireTest}
            disabled={testDisabled}
            keyboardShortcut="G"
            onKeyboardShortcut={fireTest}
            className={SOFT_PRIMARY_CTA_CLASSES}
            size="sm"
            data-testid="test-step-button"
          >
            <Play className="size-4 fill-current" />
            {sampleDataExists ? t('Retest Step') : t('Test Step')}
          </Button>
        </TestButtonTooltip>
      )}
    </CTAShell>
  );
};

type TriggerCTAButtonProps = {
  sampleDataExists: boolean;
  stepIsValid: boolean;
  onOpenPanel: () => void;
  saving: boolean;
  hasRun: boolean;
};

const TriggerCTAButton = ({
  sampleDataExists,
  stepIsValid,
  onOpenPanel,
  saving,
  hasRun,
}: TriggerCTAButtonProps) => {
  const runner = useTriggerTestRunner();
  const runnerBusy = runner?.isTesting ?? false;
  useConfigureStepShortcutToast(stepIsValid || runnerBusy);

  const fireTest = () => {
    onOpenPanel();
    runner?.fireTest();
  };

  if (hasRun) {
    return (
      <CTAShell>
        <Button
          variant="outline"
          onClick={onOpenPanel}
          disabled={saving}
          className={SOFT_PRIMARY_CTA_CLASSES}
          size="sm"
        >
          {t('Show Data')}
        </Button>
      </CTAShell>
    );
  }

  const runnerReady = runner?.canFireTest ?? false;
  const testDisabled = saving || !runnerReady;
  return (
    <CTAShell>
      {sampleDataExists && (
        <Button
          variant="outline"
          onClick={onOpenPanel}
          disabled={saving}
          className="w-full justify-center"
          size="sm"
        >
          {t('Show Data')}
        </Button>
      )}
      {runnerBusy ? (
        <TestInProgressButton
          label={t('Testing Trigger')}
          onOpenPanel={onOpenPanel}
          testId="test-trigger-button"
        />
      ) : (
        <TestButtonTooltip saving={saving} invalid={!stepIsValid}>
          <Button
            variant="outline"
            onClick={fireTest}
            disabled={testDisabled}
            keyboardShortcut="G"
            onKeyboardShortcut={fireTest}
            className={SOFT_PRIMARY_CTA_CLASSES}
            size="sm"
            data-testid="test-trigger-button"
          >
            <Play className="size-4 fill-current" />
            {sampleDataExists ? t('Retest Trigger') : t('Test Trigger')}
          </Button>
        </TestButtonTooltip>
      )}
    </CTAShell>
  );
};

const useConfigureStepShortcutToast = (stepIsValid: boolean) => {
  useEffect(() => {
    if (stepIsValid) return;
    const isMac = /(Mac)/i.test(navigator.userAgent);
    const onKeyDown = (e: KeyboardEvent) => {
      const isCtrlG =
        e.key.toLowerCase() === 'g' && (isMac ? e.metaKey : e.ctrlKey);
      if (!isCtrlG) return;
      toast.error(t('Configure step first'));
    };
    document.addEventListener('keydown', onKeyDown);
    return () => document.removeEventListener('keydown', onKeyDown);
  }, [stepIsValid]);
};

type TestInProgressButtonProps = {
  label: string;
  onOpenPanel: () => void;
  testId: string;
};

const TestInProgressButton = ({
  label,
  onOpenPanel,
  testId,
}: TestInProgressButtonProps) => (
  <Button
    variant="outline"
    onClick={onOpenPanel}
    keyboardShortcut="G"
    onKeyboardShortcut={onOpenPanel}
    className={SOFT_PRIMARY_CTA_CLASSES}
    size="sm"
    data-testid={testId}
  >
    <LoadingSpinner className="size-4 stroke-current" />
    {label}
  </Button>
);

const CTAShell = ({ children }: { children: React.ReactNode }) => (
  <div
    data-test-panel-trigger
    className="relative px-3 py-3 bg-gray-1 z-10 flex flex-col gap-2 shrink-0"
  >
    <div
      aria-hidden
      className="pointer-events-none absolute -top-6 left-0 right-0 h-6 bg-gradient-to-t from-gray-1 to-transparent"
    />
    {children}
  </div>
);

TestStepCTAButton.displayName = 'TestStepCTAButton';
export { TestStepCTAButton };