formField.tsx 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import {PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import classNames from 'classnames';
  4. import FormContext, {
  5. FormContextData,
  6. } from 'sentry/components/deprecatedforms/formContext';
  7. import QuestionTooltip from 'sentry/components/questionTooltip';
  8. import {Meta} from 'sentry/types';
  9. import {defined} from 'sentry/utils';
  10. type Value = string | number | boolean;
  11. type DefaultProps = {
  12. disabled?: boolean;
  13. hideErrorMessage?: boolean;
  14. required?: boolean;
  15. };
  16. type FormFieldProps = DefaultProps & {
  17. name: string;
  18. className?: string;
  19. defaultValue?: any;
  20. disabledReason?: string;
  21. error?: string;
  22. help?: string | React.ReactNode;
  23. label?: React.ReactNode;
  24. meta?: Meta;
  25. onChange?: (value: Value) => void;
  26. style?: object;
  27. value?: Value;
  28. };
  29. type FormFieldState = {
  30. error: string | null;
  31. value: Value;
  32. };
  33. export default class FormField<
  34. Props extends FormFieldProps = FormFieldProps,
  35. State extends FormFieldState = FormFieldState
  36. > extends PureComponent<Props, State> {
  37. static defaultProps: DefaultProps = {
  38. hideErrorMessage: false,
  39. disabled: false,
  40. required: false,
  41. };
  42. constructor(props: Props, context?: any) {
  43. super(props, context);
  44. this.state = {
  45. error: null,
  46. value: this.getValue(props, context),
  47. } as State;
  48. }
  49. componentDidMount() {}
  50. UNSAFE_componentWillReceiveProps(nextProps: Props, nextContext: FormContextData) {
  51. const newError = this.getError(nextProps, nextContext);
  52. if (newError !== this.state.error) {
  53. this.setState({error: newError});
  54. }
  55. if (this.props.value !== nextProps.value || defined(nextContext.form)) {
  56. const newValue = this.getValue(nextProps, nextContext);
  57. if (newValue !== this.state.value) {
  58. this.setValue(newValue);
  59. }
  60. }
  61. }
  62. componentWillUnmount() {}
  63. static contextType = FormContext;
  64. getValue(props: Props, context: FormContextData) {
  65. const form = (context || this.context || {}).form;
  66. props = props || this.props;
  67. if (defined(props.value)) {
  68. return props.value;
  69. }
  70. if (form && form.data.hasOwnProperty(props.name)) {
  71. return defined(form.data[props.name]) ? form.data[props.name] : '';
  72. }
  73. return defined(props.defaultValue) ? props.defaultValue : '';
  74. }
  75. getError(props: Props, context: FormContextData) {
  76. const form = (context || this.context || {}).form;
  77. props = props || this.props;
  78. if (defined(props.error)) {
  79. return props.error;
  80. }
  81. return (form && form.errors[props.name]) || null;
  82. }
  83. getId() {
  84. return `id-${this.props.name}`;
  85. }
  86. coerceValue(value: any) {
  87. return value;
  88. }
  89. onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  90. const value = e.target.value;
  91. this.setValue(value);
  92. };
  93. setValue = (value: Value) => {
  94. const form = (this.context || {}).form;
  95. this.setState(
  96. {
  97. value,
  98. },
  99. () => {
  100. const finalValue = this.coerceValue(this.state.value);
  101. this.props.onChange?.(finalValue);
  102. form?.onFieldChange(this.props.name, finalValue);
  103. }
  104. );
  105. };
  106. getField() {
  107. throw new Error('Must be implemented by child.');
  108. }
  109. getClassName(): string {
  110. throw new Error('Must be implemented by child.');
  111. }
  112. getFinalClassNames() {
  113. const {className, required} = this.props;
  114. const {error} = this.state;
  115. return classNames(className, this.getClassName(), {
  116. 'has-error': !!error,
  117. required,
  118. });
  119. }
  120. renderDisabledReason() {
  121. const {disabled, disabledReason} = this.props;
  122. if (!disabled) {
  123. return null;
  124. }
  125. if (!disabledReason) {
  126. return null;
  127. }
  128. return <QuestionTooltip title={disabledReason} position="top" size="sm" />;
  129. }
  130. render() {
  131. const {label, hideErrorMessage, help, style} = this.props;
  132. const {error} = this.state;
  133. const cx = this.getFinalClassNames();
  134. const shouldShowErrorMessage = error && !hideErrorMessage;
  135. return (
  136. <div style={style} className={cx}>
  137. <div className="controls">
  138. {label && (
  139. <label htmlFor={this.getId()} className="control-label">
  140. {label}
  141. </label>
  142. )}
  143. {this.getField()}
  144. {this.renderDisabledReason()}
  145. {defined(help) && <p className="help-block">{help}</p>}
  146. {shouldShowErrorMessage && <ErrorMessage>{error}</ErrorMessage>}
  147. </div>
  148. </div>
  149. );
  150. }
  151. }
  152. const ErrorMessage = styled('p')`
  153. font-size: ${p => p.theme.fontSizeMedium};
  154. color: ${p => p.theme.red300};
  155. `;