booleanField.tsx 2.7 KB

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