MetricSelect.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import React from 'react';
  2. import _ from 'lodash';
  3. import Select from './Select';
  4. import { Variable } from 'app/types/templates';
  5. export interface Props {
  6. onChange: (value: string) => void;
  7. options: any[];
  8. isSearchable: boolean;
  9. value: string;
  10. placeholder?: string;
  11. className?: string;
  12. variables?: Variable[];
  13. }
  14. interface State {
  15. options: any[];
  16. }
  17. export class MetricSelect extends React.Component<Props, State> {
  18. static defaultProps = {
  19. variables: [],
  20. options: [],
  21. };
  22. constructor(props) {
  23. super(props);
  24. this.state = { options: [] };
  25. }
  26. componentDidMount() {
  27. this.setState({ options: this.buildOptions(this.props) });
  28. }
  29. componentWillReceiveProps(nextProps: Props) {
  30. if (nextProps.options.length > 0 || nextProps.variables.length) {
  31. this.setState({ options: this.buildOptions(nextProps) });
  32. }
  33. }
  34. shouldComponentUpdate(nextProps: Props) {
  35. const nextOptions = this.buildOptions(nextProps);
  36. return nextProps.value !== this.props.value || !_.isEqual(nextOptions, this.state.options);
  37. }
  38. buildOptions({ variables = [], options }) {
  39. return variables.length > 0
  40. ? [
  41. this.getVariablesGroup(),
  42. // {
  43. // label: groupName,
  44. // expanded: true,
  45. // options,
  46. // },
  47. ...options,
  48. ]
  49. : options;
  50. }
  51. getVariablesGroup() {
  52. return {
  53. label: 'Template Variables',
  54. options: this.props.variables.map(v => ({
  55. label: `$${v.name}`,
  56. value: `$${v.name}`,
  57. })),
  58. };
  59. }
  60. getSelectedOption() {
  61. const { options } = this.state;
  62. const allOptions = options.every(o => o.options) ? _.flatten(options.map(o => o.options)) : options;
  63. return allOptions.find(option => option.value === this.props.value);
  64. }
  65. render() {
  66. const { placeholder, className, isSearchable, onChange } = this.props;
  67. const { options } = this.state;
  68. const selectedOption = this.getSelectedOption();
  69. return (
  70. <Select
  71. className={className}
  72. isMulti={false}
  73. isClearable={false}
  74. backspaceRemovesValue={false}
  75. onChange={item => onChange(item.value)}
  76. options={options}
  77. isSearchable={isSearchable}
  78. maxMenuHeight={500}
  79. placeholder={placeholder}
  80. noOptionsMessage={() => 'No options found'}
  81. value={selectedOption}
  82. />
  83. );
  84. }
  85. }