selectField.tsx 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import {Component} from 'react';
  2. import {OptionsType, OptionTypeBase, ValueType} from 'react-select';
  3. import {openConfirmModal} from 'sentry/components/confirm';
  4. import SelectControl, {
  5. ControlProps,
  6. } from 'sentry/components/forms/controls/selectControl';
  7. import FormField from 'sentry/components/forms/formField';
  8. import {t} from 'sentry/locale';
  9. import {Choices, SelectValue} from 'sentry/types';
  10. // XXX(epurkhiser): This is wrong, it should not be inheriting these props
  11. import {InputFieldProps} from './inputField';
  12. export interface SelectFieldProps<OptionType extends OptionTypeBase>
  13. extends InputFieldProps,
  14. Omit<ControlProps<OptionType>, 'onChange'> {
  15. /**
  16. * Should the select be clearable?
  17. */
  18. allowClear?: boolean;
  19. /**
  20. * Should the select allow empty values?
  21. */
  22. allowEmpty?: boolean;
  23. /**
  24. * Allow specific options to be 'confirmed' with a confirmation message.
  25. *
  26. * The key is the value that should be confirmed, the value is the message
  27. * to display in the confirmation modal.
  28. *
  29. * XXX: This only works when using the new-style options format, and _only_
  30. * if the value object has a `value` attribute in the option. The types do
  31. * not correctly reflect this so be careful!
  32. */
  33. confirm?: Record<string, React.ReactNode>;
  34. /**
  35. * A label that is shown inside the select control.
  36. */
  37. inFieldLabel?: string;
  38. }
  39. function getChoices<T extends OptionTypeBase>(props: SelectFieldProps<T>): Choices {
  40. const choices = props.choices;
  41. if (typeof choices === 'function') {
  42. return choices(props);
  43. }
  44. if (choices === undefined) {
  45. return [];
  46. }
  47. return choices;
  48. }
  49. /**
  50. * Required to type guard for OptionsType<T> which is a readonly Array
  51. */
  52. function isArray<T extends OptionTypeBase>(
  53. maybe: T | OptionsType<T>
  54. ): maybe is OptionsType<T> {
  55. return Array.isArray(maybe);
  56. }
  57. export default class SelectField<OptionType extends SelectValue<any>> extends Component<
  58. SelectFieldProps<OptionType>
  59. > {
  60. static defaultProps = {
  61. allowClear: false,
  62. allowEmpty: false,
  63. placeholder: '--',
  64. escapeMarkup: true,
  65. multiple: false,
  66. small: false,
  67. formatMessageValue: (value, props) =>
  68. (getChoices(props).find(choice => choice[0] === value) || [null, value])[1],
  69. };
  70. handleChange = (
  71. onBlur: InputFieldProps['onBlur'],
  72. onChange: InputFieldProps['onChange'],
  73. optionObj: ValueType<OptionType, boolean>
  74. ) => {
  75. let value: any = undefined;
  76. // If optionObj is empty, then it probably means that the field was "cleared"
  77. if (!optionObj) {
  78. value = optionObj;
  79. } else if (this.props.multiple && isArray(optionObj)) {
  80. // List of optionObjs
  81. value = optionObj.map(({value: val}) => val);
  82. } else if (!isArray(optionObj)) {
  83. value = optionObj.value;
  84. }
  85. onChange?.(value, {});
  86. onBlur?.(value, {});
  87. };
  88. render() {
  89. const {allowClear, confirm, multiple, ...otherProps} = this.props;
  90. return (
  91. <FormField {...otherProps}>
  92. {({id, onChange, onBlur, required: _required, children: _children, ...props}) => (
  93. <SelectControl
  94. {...props}
  95. inputId={id}
  96. clearable={allowClear}
  97. multiple={multiple}
  98. styles={{
  99. control: provided => ({
  100. ...provided,
  101. height: 'auto',
  102. }),
  103. ...props.styles,
  104. }}
  105. onChange={val => {
  106. try {
  107. if (!confirm) {
  108. this.handleChange(onBlur, onChange, val);
  109. return;
  110. }
  111. // Support 'confirming' selections. This only works with
  112. // `val` objects that use the new-style options format
  113. const previousValue = props.value?.toString();
  114. // `val` may be null if clearing the select for an optional field
  115. const newValue = val?.value?.toString();
  116. // Value not marked for confirmation, or hasn't changed
  117. if (!confirm[newValue] || previousValue === newValue) {
  118. this.handleChange(onBlur, onChange, val);
  119. return;
  120. }
  121. openConfirmModal({
  122. onConfirm: () => this.handleChange(onBlur, onChange, val),
  123. message: confirm[val?.value] ?? t('Continue with these changes?'),
  124. });
  125. } catch (e) {
  126. // Swallow expected error to prevent bubbling up.
  127. if (e.message === 'Invalid selection. Field cannot be empty.') {
  128. return;
  129. }
  130. throw e;
  131. }
  132. }}
  133. />
  134. )}
  135. </FormField>
  136. );
  137. }
  138. }