All files / src/Select Select.tsx

86.67% Statements 26/30
78.57% Branches 11/14
77.78% Functions 7/9
86.67% Lines 26/30

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300                                                                                          3x                     55x   55x 55x       55x 55x               55x               55x             55x               55x       53x                     55x               55x                             127x                             3x   53x   53x                                                               3x                                                             17x   17x   17x               17x                                 17x                                                                           3x   17x 17x                            
import * as React from 'react';
import { Box as ReakitBox } from 'reakit';
import ConditionalWrap from 'conditional-wrap';
 
import { Size } from '../types';
import { useClassName, createComponent, createElement, createHook, pickCSSProps, omitCSSProps } from '../utils';
import { Box, BoxProps } from '../Box';
import { FieldWrapper, FieldWrapperProps } from '../FieldWrapper';
import { Group } from '../Group';
import { Icon } from '../Icon';
import { Spinner } from '../Spinner';
 
import * as styles from './styles';
 
export type LocalSelectProps = {
  /** Automatically focus on the input */
  autoFocus?: boolean;
  /** Default value of the input */
  defaultValue?: string;
  /** Disables the input */
  disabled?: boolean;
  /** Adds a cute loading indicator to the input field */
  isLoading?: boolean;
  /** Makes the input required and sets aria-invalid to true */
  isRequired?: boolean;
  /** Name of the input field */
  name?: string;
  options: Array<{ label: string; value: any; disabled?: boolean }>;
  /** Alters the size of the input. Can be "small", "medium" or "large" */
  size?: Size;
  /** Hint text to display */
  placeholder?: string;
  /** State of the input. Can be any color in the palette. */
  state?: string;
  /** Value of the input */
  value?: any;
  /** Function to invoke when focus is lost */
  onBlur?: React.FocusEventHandler<HTMLInputElement>;
  /** Function to invoke when input has changed */
  onChange?: React.FormEventHandler<HTMLInputElement>;
  /** Function to invoke when input is focused */
  onFocus?: React.FocusEventHandler<HTMLInputElement>;
};
export type SelectProps = BoxProps & LocalSelectProps;
 
const useProps = createHook<SelectProps>(
  (props, { themeKey, themeKeyOverride }) => {
    const {
      disabled,
      isLoading,
      isRequired,
      onChange,
      options,
      placeholder: _placeholder,
      state,
      ...restProps
    } = props;
 
    let placeholder = _placeholder;
    Iif (isLoading && options.length === 0) {
      placeholder = 'Loading...';
    }
 
    const [isPlaceholderSelected, setIsPlaceholderSelected] = React.useState(Boolean(placeholder));
    const handleChange = React.useCallback(
      e => {
        setIsPlaceholderSelected(false);
        onChange && onChange(e);
      },
      [onChange]
    );
 
    const wrapperClassName = useClassName({
      style: styles.SelectWrapper,
      styleProps: props,
      themeKey,
      themeKeyOverride,
      themeKeySuffix: 'Wrapper',
      prevClassName: restProps.className
    });
    const iconClassName = useClassName({
      style: styles.SelectIcon,
      styleProps: props,
      themeKey,
      themeKeyOverride,
      themeKeySuffix: 'Icon'
    });
    const spinnerClassName = useClassName({
      style: styles.SelectSpinner,
      styleProps: props,
      themeKey,
      themeKeyOverride,
      themeKeySuffix: 'Spinner'
    });
 
    const boxProps = Box.useProps({
      ...omitCSSProps(restProps),
      className: undefined,
      wrapElement: children => (
        <Box className={wrapperClassName} {...pickCSSProps(props)}>
          {children}
          {isLoading ? (
            <Spinner className={spinnerClassName} color="text" />
          ) : (
            <Icon className={iconClassName} icon="chevron-down" />
          )}
        </Box>
      )
    });
 
    const className = useClassName({
      style: styles.Select,
      styleProps: { ...props, isPlaceholderSelected },
      themeKey,
      themeKeyOverride,
      prevClassName: boxProps.className
    });
 
    return {
      ...boxProps,
      className,
      'aria-invalid': state === 'danger',
      'aria-required': isRequired,
      disabled,
      onChange: handleChange,
      children: (
        <React.Fragment>
          {placeholder && (
            <option disabled={typeof restProps.value !== 'undefined'} value="">
              {placeholder}
            </option>
          )}
          {options.map((option, i) => (
            <option
              key={i} // eslint-disable-line
              disabled={disabled || option.disabled}
              value={option.value}
            >
              {option.label}
            </option>
          ))}
        </React.Fragment>
      )
    };
  },
  { themeKey: 'Select' }
);
 
export const Select = createComponent<SelectProps>(
  props => {
    const selectProps = useProps(props);
 
    return createElement({
      children: props.children,
      component: ReakitBox,
      use: props.use,
      htmlProps: selectProps
    });
  },
  {
    attach: {
      useProps
    },
    defaultProps: {
      use: 'select'
    },
    themeKey: 'Select'
  }
);
 
////////////////////////////////////////////////////////////////
 
export type LocalSelectFieldProps = {
  /** Addon component to the input (before). Similar to the addon components in Input. */
  addonBefore?: React.ReactElement<any>;
  /** Addon component to the input (after). Similar to the addon components in Input. */
  addonAfter?: React.ReactElement<any>;
  /** Additional props for the Select component */
  selectProps?: SelectProps;
  /** If addonBefore or addonAfter exists, then the addons will render vertically. */
  orientation?: 'vertical' | 'horizontal';
};
export type SelectFieldProps = BoxProps & FieldWrapperProps & SelectProps & LocalSelectFieldProps;
 
const useSelectFieldProps = createHook<SelectFieldProps>(
  (props, { themeKey, themeKeyOverride }) => {
    const {
      addonAfter,
      addonBefore,
      children,
      autoFocus,
      defaultValue,
      description,
      disabled,
      hint,
      selectProps,
      isLoading,
      isOptional,
      isRequired,
      orientation,
      label,
      name,
      options,
      size,
      placeholder,
      state,
      tooltip,
      tooltipTriggerComponent,
      value,
      onBlur,
      onChange,
      onFocus,
      overrides,
      validationText,
      ...restProps
    } = props;
 
    const boxProps = Box.useProps(restProps);
 
    const className = useClassName({
      style: styles.SelectField,
      styleProps: props,
      themeKey,
      themeKeyOverride,
      prevClassName: boxProps.className
    });
 
    return {
      ...boxProps,
      className,
      children: (
        <FieldWrapper
          description={description}
          hint={hint}
          isOptional={isOptional}
          isRequired={isRequired}
          label={label}
          overrides={overrides}
          state={state}
          tooltip={tooltip}
          tooltipTriggerComponent={tooltipTriggerComponent}
          validationText={validationText}
        >
          {({ elementProps }) => (
            <ConditionalWrap
              condition={addonBefore || addonAfter}
              wrap={(children: React.ReactNode) => (
                <Group orientation={orientation} overrides={overrides}>
                  {children}
                </Group>
              )}
            >
              {addonBefore}
              <Select
                autoFocus={autoFocus}
                defaultValue={defaultValue}
                disabled={disabled}
                isLoading={isLoading}
                isRequired={isRequired}
                name={name}
                size={size}
                options={options}
                placeholder={placeholder}
                state={state}
                value={value}
                onBlur={onBlur}
                onChange={onChange}
                onFocus={onFocus}
                overrides={overrides}
                {...elementProps}
                {...selectProps}
              />
              {addonAfter}
            </ConditionalWrap>
          )}
        </FieldWrapper>
      )
    };
  },
  { themeKey: 'SelectField' }
);
 
export const SelectField = createComponent<SelectFieldProps>(
  props => {
    const SelectFieldProps = useSelectFieldProps(props);
    return createElement({
      children: props.children,
      component: ReakitBox,
      use: props.use,
      htmlProps: SelectFieldProps
    });
  },
  {
    attach: {
      useProps
    },
    themeKey: 'SelectField'
  }
);