StackdriverPicker.tsx 2.5 KB

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