All files / src/components/icons IconSelect.tsx

7.69% Statements 2/26
0% Branches 0/8
0% Functions 0/8
8% Lines 2/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77              67x                 67x                                                                                                                        
import React, { useState } from 'react';
import { Select } from 'antd';
import * as Icons from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { EditableComponentDefaultStyle } from '@config/base';
import ErrorBoundary from '../ErrorBoundary';
 
const { Option } = Select;
 
interface IconSelectProps {
  value?: unknown;
  onChange: (value: string) => void;
  readonly?: boolean;
  zIndex: number;
}
 
const IconSelect: React.FC<IconSelectProps> = ({ value, onChange, readonly }) => {
  const { t } = useTranslation();
  const [searchTerm, setSearchTerm] = useState<string>('');
 
  const iconEntries = Object.entries(Icons);
 
  const filteredIcons = iconEntries
    .filter(([iconName]) => /^[A-Z]/.test(iconName))
    .filter(([iconName]) => iconName.toLowerCase().includes(searchTerm.toLowerCase()));
 
  const handleSearch = (val: string): void => {
    setSearchTerm(val);
  };
 
  const renderOption = (iconName: string, IconComponent: React.ComponentType<unknown>): JSX.Element => (
    <Option key={iconName} value={iconName}>
      <ErrorBoundary>
        <IconComponent /> - {iconName}
      </ErrorBoundary>
    </Option>
  );
 
  const renderReadOnly = (): JSX.Element => {
    if (value == null) {
      return <></>;
    }
    const iconEntry = iconEntries.find(([iconName]) => iconName === value);
    if (!iconEntry) {
      return <>{value}</>;
    }
 
    const [, IconComponent] = iconEntry;
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const elem = <IconComponent />;
    return (<>{elem} <span style={{ fontSize: "80%" }}>{value}</span></>);
  };
 
  if (readonly) {
    return renderReadOnly();
  }
 
  return (
    <Select
      showSearch
      value={value ? String(value) : undefined}
      onChange={onChange}
      onSearch={handleSearch}
      filterOption={false}
      placeholder={t('iconSelect.placeholder')}
      className="icon-select"
      style={EditableComponentDefaultStyle}
    >
      {filteredIcons.map(([iconName, IconComponent]) => renderOption(
        iconName, IconComponent as React.ComponentType<unknown>))}
    </Select>
  );
};
 
export default IconSelect;