MetricSelect.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. isSearchable: true,
  22. };
  23. constructor(props) {
  24. super(props);
  25. this.state = { options: [] };
  26. }
  27. componentDidMount() {
  28. this.setState({ options: this.buildOptions(this.props) });
  29. }
  30. componentWillReceiveProps(nextProps: Props) {
  31. if (nextProps.options.length > 0 || nextProps.variables.length) {
  32. this.setState({ options: this.buildOptions(nextProps) });
  33. }
  34. }
  35. shouldComponentUpdate(nextProps: Props) {
  36. const nextOptions = this.buildOptions(nextProps);
  37. return nextProps.value !== this.props.value || !_.isEqual(nextOptions, this.state.options);
  38. }
  39. buildOptions({ variables = [], options }) {
  40. return variables.length > 0
  41. ? [
  42. this.getVariablesGroup(),
  43. // {
  44. // label: groupName,
  45. // expanded: true,
  46. // options,
  47. // },
  48. ...options,
  49. ]
  50. : options;
  51. }
  52. getVariablesGroup() {
  53. return {
  54. label: 'Template Variables',
  55. options: this.props.variables.map(v => ({
  56. label: `$${v.name}`,
  57. value: `$${v.name}`,
  58. })),
  59. };
  60. }
  61. getSelectedOption() {
  62. const { options } = this.state;
  63. const allOptions = options.every(o => o.options) ? _.flatten(options.map(o => o.options)) : options;
  64. return allOptions.find(option => option.value === this.props.value);
  65. }
  66. render() {
  67. const { placeholder, className, isSearchable, onChange } = this.props;
  68. const { options } = this.state;
  69. const selectedOption = this.getSelectedOption();
  70. return (
  71. <Select
  72. className={className}
  73. isMulti={false}
  74. isClearable={false}
  75. backspaceRemovesValue={false}
  76. onChange={item => onChange(item.value)}
  77. options={options}
  78. isSearchable={isSearchable}
  79. maxMenuHeight={500}
  80. placeholder={placeholder}
  81. noOptionsMessage={() => 'No options found'}
  82. value={selectedOption}
  83. />
  84. );
  85. }
  86. }