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

9.0 KB
Raw Blame
import { isNil } from '@activepieces/core-utils';
import { DropdownState, PropertyType } from '@activepieces/pieces-framework';
import { AUTHENTICATION_PROPERTY_NAME } from '@activepieces/shared';
import deepEqual from 'deep-equal';
import { t } from 'i18next';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { UseFormReturn, useWatch } from 'react-hook-form';

import { useOptionalBuilderStateContext } from '@/app/builder/builder-hooks';
import { SearchableSelect } from '@/components/custom/searchable-select';
import { piecesHooks } from '@/features/pieces';
import { authenticationSession } from '@/lib/authentication-session';

import { MultiSelectPieceProperty } from '../../../components/custom/multi-select-piece-property';

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

const DynamicDropdownPiecePropertyImplementation = React.memo(
  (props: DynamicDropdownProps) => {
    const flowVersion = useOptionalBuilderStateContext(
      (state) => state.flowVersion,
    );
    const readonly =
      useOptionalBuilderStateContext((state) => state.readonly) ?? false;

    const isFirstRender = useRef(true);
    const previousValues = useRef<undefined | unknown[]>(undefined);
    const firstDropdownState = useRef<DropdownState<unknown> | undefined>(
      undefined,
    );
    const valueToRestore = useRef<unknown>(undefined);
    const optionsRequestId = useRef(0);
    const fullListRequestId = useRef(0);
    const propertyPath =
      props.placedInside === 'stepSettings'
        ? `settings.input.${props.propertyName}`
        : props.propertyName;
    const refreshersWithAuth = [
      ...props.refreshers,
      AUTHENTICATION_PROPERTY_NAME,
    ];
    const [dropdownState, setDropdownState] = useState<DropdownState<unknown>>({
      disabled: false,
      placeholder: t('Select an option'),
      options: [],
    });
    const { propertyLoadingFinished, propertyLoadingStarted } = useContext(
      DynamicPropertiesContext,
    );
    const { mutate, isPending, error } = piecesHooks.usePieceOptions<
      PropertyType.DROPDOWN | PropertyType.MULTI_SELECT_DROPDOWN
    >({
      onMutate: () => {
        propertyLoadingStarted(props.propertyName);
      },
      onError: (error) => {
        console.error(error);
        propertyLoadingFinished(props.propertyName);
      },
      onSuccess: () => {
        propertyLoadingFinished(props.propertyName);
      },
    });
    if (error) {
      throw error;
    }

    const refresherValues = useWatch({
      name: refreshersWithAuth.map((refresher) => {
        if (props.placedInside === 'stepSettings') {
          return `settings.input.${refresher}`;
        }
        return refresher;
      }),
      control: props.form.control,
    });

    const restoreValueIfStillInOptions = (options: DropdownState<unknown>) => {
      const previousValue = valueToRestore.current;
      if (isNil(previousValue) || options.options.length === 0) {
        return;
      }
      valueToRestore.current = undefined;
      if (!isNil(props.form.getValues(propertyPath))) {
        return;
      }
      const findMatchingOption = (value: unknown) =>
        options.options.find((option) => deepEqual(option.value, value));
      if (props.multiple) {
        if (!Array.isArray(previousValue)) {
          return;
        }
        const stillPresent = previousValue.flatMap((value) => {
          const option = findMatchingOption(value);
          return isNil(option) ? [] : [option.value];
        });
        if (stillPresent.length > 0) {
          props.onChange(stillPresent);
        }
        return;
      }
      const matchingOption = findMatchingOption(previousValue);
      if (!isNil(matchingOption)) {
        props.onChange(matchingOption.value);
      }
    };

    const refresh = (term?: string) => {
      const input: Record<string, unknown> = {};
      refreshersWithAuth.forEach((refresher, index) => {
        input[refresher] = refresherValues[index];
      });
      const requestId = ++optionsRequestId.current;
      const isFullList = isNil(term) || term === '';
      const fullListId = isFullList ? ++fullListRequestId.current : null;
      mutate(
        {
          request: {
            projectId: authenticationSession.getProjectId()!,
            pieceName: props.pieceName,
            pieceVersion: props.pieceVersion,
            propertyName: props.propertyName,
            actionOrTriggerName: props.actionOrTriggerName,
            input,
            flowVersionId: flowVersion?.id,
            flowId: flowVersion?.flowId,
            searchValue: term,
          },
          propertyType: PropertyType.DROPDOWN,
        },
        {
          onSuccess: (response) => {
            if (requestId === optionsRequestId.current) {
              if (
                !firstDropdownState.current &&
                response.options.options.length > 0
              ) {
                firstDropdownState.current = response.options;
              }
              setDropdownState(response.options);
            }
            if (
              !isNil(fullListId) &&
              fullListId === fullListRequestId.current
            ) {
              restoreValueIfStillInOptions(response.options);
            }
          },
        },
      );
    };

    useEffect(() => {
      if (
        !isFirstRender.current &&
        !deepEqual(previousValues.current, refresherValues)
      ) {
        if (!isNil(props.value)) {
          valueToRestore.current = props.value;
        }
        firstDropdownState.current = undefined;
        props.onChange(null);
      }

      previousValues.current = refresherValues;
      isFirstRender.current = false;
      refresh();
    }, refresherValues);

    const selectOptions = dropdownState.options.map((option) => ({
      label: option.label,
      value: option.value,
    }));
    const singleSelectOptions = withSavedValueNotInList({
      options: selectOptions,
      value: props.value,
      loadsOptionsOnSearch: props.shouldRefreshOnSearch === true,
    });
    const isDisabled = dropdownState.disabled || props.disabled;
    return props.multiple ? (
      <MultiSelectPieceProperty
        placeholder={dropdownState.placeholder ?? t('Select an option')}
        options={selectOptions}
        loading={isPending}
        onChange={(value) => props.onChange(value)}
        disabled={isDisabled}
        initialValues={props.value as unknown[]}
        showDeselect={
          props.showDeselect &&
          !isNil(props.value) &&
          Array.isArray(props.value) &&
          props.value.length > 0 &&
          !isDisabled
        }
        showRefresh={!isPending && !readonly}
        onRefresh={refresh}
        refreshOnSearch={props.shouldRefreshOnSearch ? refresh : undefined}
        cachedOptions={firstDropdownState.current?.options ?? []}
      />
    ) : (
      <SearchableSelect
        options={singleSelectOptions}
        disabled={dropdownState.disabled || props.disabled}
        loading={isPending}
        placeholder={dropdownState.placeholder ?? t('Select an option')}
        value={props.value}
        onChange={(value) => props.onChange(value)}
        showDeselect={
          props.showDeselect && !isNil(props.value) && !props.disabled
        }
        onRefresh={refresh}
        showRefresh={!isPending && !readonly}
        refreshOnSearch={props.shouldRefreshOnSearch ? refresh : undefined}
        cachedOptions={firstDropdownState.current?.options ?? []}
      />
    );
  },
);

const DynamicDropdownPieceProperty = React.memo(
  (props: DynamicDropdownProps) => {
    return (
      <DynamicPropertiesErrorBoundary>
        <DynamicDropdownPiecePropertyImplementation {...props} />
      </DynamicPropertiesErrorBoundary>
    );
  },
);
DynamicDropdownPieceProperty.displayName = 'DynamicDropdownPieceProperty';
DynamicDropdownPiecePropertyImplementation.displayName =
  'DynamicDropdownPiecePropertyImplementation';
export { DynamicDropdownPieceProperty };

function withSavedValueNotInList({
  options,
  value,
  loadsOptionsOnSearch,
}: {
  options: SelectOption[];
  value: unknown;
  loadsOptionsOnSearch: boolean;
}): SelectOption[] {
  const isReadableValue =
    (typeof value === 'string' && value !== '') || typeof value === 'number';
  const isNotInList =
    isReadableValue &&
    !loadsOptionsOnSearch &&
    options.length > 0 &&
    !options.some((option) => deepEqual(option.value, value));
  return isNotInList
    ? [
        {
          label: t('{value} (not in the list)', { value: String(value) }),
          value,
        },
        ...options,
      ]
    : options;
}

type SelectOption = { label: string; value: unknown };

type DynamicDropdownProps = {
  refreshers: string[];
  propertyName: string;
  value?: unknown;
  multiple?: boolean;
  disabled: boolean;
  onChange: (value: unknown | undefined) => void;
  showDeselect?: boolean;
  shouldRefreshOnSearch?: boolean;
  actionOrTriggerName: string;
  pieceName: string;
  pieceVersion: string;
  form: UseFormReturn;
  placedInside: 'stepSettings' | 'predefinedAgentInputs';
};