StackdriverPicker.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import React from 'react';
  2. import _ from 'lodash';
  3. import Select from 'app/core/components/Select/Select';
  4. export interface Props {
  5. onChange: (value: string) => void;
  6. options: any[];
  7. searchable: boolean;
  8. selected: string;
  9. placeholder?: string;
  10. className?: string;
  11. groupName?: string;
  12. templateVariables?: any[];
  13. }
  14. interface State {
  15. options: any[];
  16. }
  17. export class StackdriverPicker extends React.Component<Props, State> {
  18. static defaultProps = {
  19. templateVariables: [],
  20. options: [],
  21. groupName: 'Options',
  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.templateVariables.length) {
  32. this.setState({ options: this.buildOptions(nextProps) });
  33. }
  34. }
  35. shouldComponentUpdate(nextProps: Props) {
  36. const nextOptions = this.buildOptions(nextProps);
  37. return nextProps.selected !== this.props.selected || !_.isEqual(nextOptions, this.state.options);
  38. }
  39. buildOptions({ templateVariables = [], groupName = '', options }) {
  40. return templateVariables.length > 0
  41. ? [
  42. this.getTemplateVariablesGroup(),
  43. {
  44. label: groupName,
  45. expanded: true,
  46. options,
  47. },
  48. ]
  49. : options;
  50. }
  51. getTemplateVariablesGroup() {
  52. return {
  53. label: 'Template Variables',
  54. options: this.props.templateVariables.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.selected);
  64. }
  65. render() {
  66. const { placeholder, className, searchable, 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={searchable}
  78. maxMenuHeight={500}
  79. placeholder={placeholder}
  80. noOptionsMessage={() => 'No options found'}
  81. value={selectedOption}
  82. />
  83. );
  84. }
  85. }