All files / enumDropdown enumDropdown.tsx

71.43% Statements 20/28
37.5% Branches 3/8
85.71% Functions 6/7
68% Lines 17/25
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 651x 1x 1x                               1x         1x 1x   1x               1x 1x 1x       1x   3x       1x 2x 1x   1x                         1x  
import { enumNames, lazy } from '@fuselab/ui-shared/lib';
import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib-commonjs/Dropdown';
import * as React from 'react';
 
export interface DropdownAttributes<T> {
  val: T;
  enumType: object;
}
 
export interface DropdownActions<T> {
  change(t: T);
}
 
export type EnumDropdownProps<T> = DropdownAttributes<T> & DropdownActions<T>;
 
/**
 * render enum type as dropdown
 */
export class EnumDropdown<T> extends React.Component<EnumDropdownProps<T>> {
  constructor(props: EnumDropdownProps<T>) {
    super(props);
  }
 
  public render(): JSX.Element {
    const key: any = this.props.val;
 
    return (
      <Dropdown
        selectedKey={key}
        onChanged={this.changeSelection}
        options={this.options}
      />);
  }
 
  private get options(): IDropdownOption[] {
    let names = enumNames(this.props.enumType);
    Iif (names.length === 0) {
      names = Object.keys(this.props.enumType);
    }
 
    return names.map(
      key => {
        return { key: this.props.enumType[key] as number, text: key };
      });
  }
 
  @lazy()
  private get changeSelection(): (option: IDropdownOption, index: number) => void {
    const enumType = this.props.enumType;
 
    return (option, index) => {
      const key = option.key;
      if (typeof key === 'string') {
        const keyIndex = parseInt(key, 10);
        if (isNaN(keyIndex)) {
          this.props.change(key as any);
 
          return;
        }
      }
      this.props.change(enumType[enumType[key]]);
    };
  }
}