booleanField.tsx 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import {Component} from 'react';
  2. import Confirm from 'sentry/components/confirm';
  3. import InputField, {InputFieldProps, onEvent} from 'sentry/components/forms/inputField';
  4. import Switch from 'sentry/components/switchButton';
  5. export interface BooleanFieldProps extends InputFieldProps {
  6. confirm?: {
  7. false?: React.ReactNode;
  8. true?: React.ReactNode;
  9. };
  10. }
  11. export default class BooleanField extends Component<BooleanFieldProps> {
  12. coerceValue(value: any) {
  13. return !!value;
  14. }
  15. handleChange = (
  16. value: any,
  17. onChange: onEvent,
  18. onBlur: onEvent,
  19. e: React.FormEvent<HTMLInputElement>
  20. ) => {
  21. // We need to toggle current value because Switch is not an input
  22. const newValue = this.coerceValue(!value);
  23. onChange(newValue, e);
  24. onBlur(newValue, e);
  25. };
  26. render() {
  27. const {confirm, ...fieldProps} = this.props;
  28. return (
  29. <InputField
  30. {...fieldProps}
  31. resetOnError
  32. field={({
  33. onChange,
  34. onBlur,
  35. value,
  36. disabled,
  37. ...props
  38. }: {
  39. disabled: boolean;
  40. onBlur: onEvent;
  41. onChange: onEvent;
  42. type: string;
  43. value: any;
  44. }) => {
  45. // Create a function with required args bound
  46. const handleChange = this.handleChange.bind(this, value, onChange, onBlur);
  47. const {type: _, ...propsWithoutType} = props;
  48. const switchProps = {
  49. ...propsWithoutType,
  50. size: 'lg' as React.ComponentProps<typeof Switch>['size'],
  51. isActive: !!value,
  52. isDisabled: disabled,
  53. toggle: handleChange,
  54. };
  55. if (confirm) {
  56. return (
  57. <Confirm
  58. renderMessage={() => confirm[(!value).toString()]}
  59. onConfirm={() => handleChange({})}
  60. >
  61. {({open}) => (
  62. <Switch
  63. {...switchProps}
  64. toggle={(e: React.MouseEvent) => {
  65. // If we have a `confirm` prop and enabling switch
  66. // Then show confirm dialog, otherwise propagate change as normal
  67. if (confirm[(!value).toString()]) {
  68. // Open confirm modal
  69. open();
  70. return;
  71. }
  72. handleChange(e);
  73. }}
  74. />
  75. )}
  76. </Confirm>
  77. );
  78. }
  79. return <Switch {...switchProps} />;
  80. }}
  81. />
  82. );
  83. }
  84. }