SecretFormField.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { omit } from 'lodash';
  2. import React, { InputHTMLAttributes, FunctionComponent } from 'react';
  3. import { FormField } from '..';
  4. interface Props extends InputHTMLAttributes<HTMLInputElement> {
  5. // Function to use when reset is clicked. Means you have to reset the input value yourself as this is uncontrolled
  6. // component (or do something else if required).
  7. onReset: () => void;
  8. isConfigured: boolean;
  9. label?: string;
  10. labelWidth?: number;
  11. inputWidth?: number;
  12. // Placeholder of the input field when in non configured state.
  13. placeholder?: string;
  14. }
  15. const defaultProps = {
  16. inputWidth: 12,
  17. placeholder: 'Password',
  18. label: 'Password',
  19. };
  20. /**
  21. * Form field that has 2 states configured and not configured. If configured it will not show its contents and adds
  22. * a reset button that will clear the input and makes it accessible. In non configured state it behaves like normal
  23. * form field. This is used for passwords or anything that is encrypted on the server and is later returned encrypted
  24. * to the user (like datasource passwords).
  25. */
  26. export const SecretFormField: FunctionComponent<Props> = ({
  27. label,
  28. labelWidth,
  29. inputWidth,
  30. onReset,
  31. isConfigured,
  32. placeholder,
  33. ...inputProps
  34. }: Props) => {
  35. return (
  36. <FormField
  37. label={label!}
  38. labelWidth={labelWidth}
  39. inputEl={
  40. isConfigured ? (
  41. <>
  42. <input
  43. type="text"
  44. className={`gf-form-input width-${inputWidth! - 2}`}
  45. disabled={true}
  46. value="configured"
  47. {...omit(inputProps, 'value')}
  48. />
  49. <button className="btn btn-secondary gf-form-btn" onClick={onReset}>
  50. reset
  51. </button>
  52. </>
  53. ) : (
  54. <input
  55. type="password"
  56. className={`gf-form-input width-${inputWidth}`}
  57. placeholder={placeholder}
  58. {...inputProps}
  59. />
  60. )
  61. }
  62. />
  63. );
  64. };
  65. SecretFormField.defaultProps = defaultProps;
  66. SecretFormField.displayName = 'SecretFormField';