booleanField.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. value: any;
  43. }) => {
  44. // Create a function with required args bound
  45. const handleChange = this.handleChange.bind(this, value, onChange, onBlur);
  46. const switchProps = {
  47. ...props,
  48. size: 'lg' as React.ComponentProps<typeof Switch>['size'],
  49. isActive: !!value,
  50. isDisabled: disabled,
  51. toggle: handleChange,
  52. };
  53. if (confirm) {
  54. return (
  55. <Confirm
  56. renderMessage={() => confirm[(!value).toString()]}
  57. onConfirm={() => handleChange({})}
  58. >
  59. {({open}) => (
  60. <Switch
  61. {...switchProps}
  62. toggle={(e: React.MouseEvent) => {
  63. // If we have a `confirm` prop and enabling switch
  64. // Then show confirm dialog, otherwise propagate change as normal
  65. if (confirm[(!value).toString()]) {
  66. // Open confirm modal
  67. open();
  68. return;
  69. }
  70. handleChange(e);
  71. }}
  72. />
  73. )}
  74. </Confirm>
  75. );
  76. }
  77. return <Switch {...switchProps} />;
  78. }}
  79. />
  80. );
  81. }
  82. }