StackdriverPicker.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import React from 'react';
  2. import _ from 'lodash';
  3. import Select from 'app/core/components/Select/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. groupName?: string;
  13. variables?: Variable[];
  14. }
  15. interface State {
  16. options: any[];
  17. }
  18. export class StackdriverPicker extends React.Component<Props, State> {
  19. static defaultProps = {
  20. variables: [],
  21. options: [],
  22. groupName: 'Options',
  23. };
  24. constructor(props) {
  25. super(props);
  26. this.state = { options: [] };
  27. }
  28. componentDidMount() {
  29. this.setState({ options: this.buildOptions(this.props) });
  30. }
  31. componentWillReceiveProps(nextProps: Props) {
  32. if (nextProps.options.length > 0 || nextProps.variables.length) {
  33. this.setState({ options: this.buildOptions(nextProps) });
  34. }
  35. }
  36. shouldComponentUpdate(nextProps: Props) {
  37. const nextOptions = this.buildOptions(nextProps);
  38. return nextProps.value !== this.props.value || !_.isEqual(nextOptions, this.state.options);
  39. }
  40. buildOptions({ variables = [], groupName = '', options }) {
  41. return variables.length > 0
  42. ? [
  43. this.getVariablesGroup(),
  44. {
  45. label: groupName,
  46. expanded: true,
  47. options,
  48. },
  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. }