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

4.7 KB
Raw Blame
import { isNil } from '@activepieces/core-utils';
import deepEqual from 'deep-equal';
import { t } from 'i18next';
import { useState } from 'react';

import {
  MultiSelect,
  MultiSelectContent,
  MultiSelectItem,
  MultiSelectList,
  MultiSelectSearch,
  MultiSelectTrigger,
  MultiSelectValue,
} from '@/components/custom/multi-select';
import { CommandEmpty } from '@/components/ui/command';

type MultiSelectPiecePropertyProps = {
  placeholder: string;
  options: {
    value: unknown;
    label: string;
  }[];
  onChange: (value: unknown[] | null) => void;
  initialValues?: unknown;
  disabled?: boolean;
  showDeselect?: boolean;
  showRefresh?: boolean;
  loading?: boolean;
  onRefresh?: () => void;
  refreshOnSearch?: (term: string) => void;
  /**Use to show the selected option when search doesn't return the selected option */
  cachedOptions?: {
    value: unknown;
    label: string;
  }[];
  itemExtraContent?: (index: number) => React.ReactNode;
};

const MultiSelectPieceProperty = ({
  placeholder,
  options,
  onChange,
  disabled,
  initialValues,
  showDeselect,
  showRefresh,
  onRefresh,
  loading,
  refreshOnSearch,
  cachedOptions = [],
  itemExtraContent,
}: MultiSelectPiecePropertyProps) => {
  const [searchTerm, setSearchTerm] = useState('');
  const allOptions = [...options, ...cachedOptions];
  const filteredOptions = options
    .map((option, index) => ({
      ...option,
      originalIndex: index,
    }))
    .filter((option) => {
      if (refreshOnSearch) {
        return true;
      }
      return option.label?.toLowerCase()?.includes(searchTerm?.toLowerCase());
    });

  const selectedIndicies =
    initialValues && Array.isArray(initialValues)
      ? initialValues
          .map((value) =>
            allOptions.findIndex((option) => deepEqual(option.value, value)),
          )
          .filter((index) => index > -1)
          .map((index) => String(index))
      : [];
  const sendChanges = (selectedKeys: string[]) => {
    onChange(
      selectedKeys.flatMap((key) => {
        const option = allOptions[Number(key)];
        return isNil(option) ? [] : [option.value];
      }),
    );
  };

  return (
    <MultiSelect
      modal={true}
      value={selectedIndicies}
      onValueChange={sendChanges}
      disabled={disabled}
      items={allOptions.map((opt, index) => ({
        value: String(index),
        label: opt.label,
      }))}
      onSearch={(searchTerm) => {
        setSearchTerm(searchTerm ?? '');
        if (refreshOnSearch) {
          refreshOnSearch(searchTerm ?? '');
        }
      }}
      onOpenChange={(open) => {
        if (!open) {
          setSearchTerm('');
          if (refreshOnSearch && searchTerm.length > 0) {
            refreshOnSearch('');
          }
        }
      }}
    >
      <MultiSelectTrigger
        showDeselect={showDeselect && !disabled}
        onDeselect={() => onChange([])}
        showRefresh={showRefresh && !disabled}
        onRefresh={onRefresh}
        loading={loading}
      >
        {selectedIndicies.length < 10 ? (
          <MultiSelectValue placeholder={placeholder} />
        ) : (
          t('{number} items selected', { number: selectedIndicies.length })
        )}
      </MultiSelectTrigger>
      <MultiSelectContent>
        <MultiSelectSearch placeholder={placeholder} />
        <MultiSelectList>
          {!loading && (
            <>
              <div
                onClick={(e) => {
                  e.stopPropagation();
                  e.preventDefault();
                  onChange(filteredOptions.map((opt) => opt.value));
                }}
              >
                {filteredOptions.length > 1 && (
                  <MultiSelectItem>{t('Select All')}</MultiSelectItem>
                )}
              </div>

              {filteredOptions.map((opt) => (
                <MultiSelectItem
                  key={opt.originalIndex}
                  value={String(opt.originalIndex)}
                >
                  <div className="flex items-center justify-between  w-full min-w-0">
                    <span className="truncate min-w-0">{opt.label}</span>
                    <div className="mr-2">
                      {itemExtraContent?.(opt.originalIndex)}
                    </div>
                  </div>
                </MultiSelectItem>
              ))}
              {filteredOptions.length === 0 && (
                <CommandEmpty>{t('No results found.')}</CommandEmpty>
              )}
            </>
          )}
          {loading && (
            <MultiSelectItem disabled>{t('Loading...')}</MultiSelectItem>
          )}
        </MultiSelectList>
      </MultiSelectContent>
    </MultiSelect>
  );
};

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