booleanField.tsx 3.0 KB

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