editableText.tsx 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import {useCallback, useEffect, useRef, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  4. import Input from 'sentry/components/input';
  5. import TextOverflow from 'sentry/components/textOverflow';
  6. import {IconEdit} from 'sentry/icons/iconEdit';
  7. import space from 'sentry/styles/space';
  8. import {defined} from 'sentry/utils';
  9. import useKeypress from 'sentry/utils/useKeyPress';
  10. import useOnClickOutside from 'sentry/utils/useOnClickOutside';
  11. type Props = {
  12. onChange: (value: string) => void;
  13. value: string;
  14. 'aria-label'?: string;
  15. autoSelect?: boolean;
  16. errorMessage?: React.ReactNode;
  17. isDisabled?: boolean;
  18. maxLength?: number;
  19. name?: string;
  20. successMessage?: React.ReactNode;
  21. };
  22. function EditableText({
  23. value,
  24. onChange,
  25. name,
  26. errorMessage,
  27. successMessage,
  28. maxLength,
  29. isDisabled = false,
  30. autoSelect = false,
  31. 'aria-label': ariaLabel,
  32. }: Props) {
  33. const [isEditing, setIsEditing] = useState(false);
  34. const [inputValue, setInputValue] = useState(value);
  35. const isEmpty = !inputValue.trim();
  36. const innerWrapperRef = useRef<HTMLDivElement>(null);
  37. const labelRef = useRef<HTMLDivElement>(null);
  38. const inputRef = useRef<HTMLInputElement>(null);
  39. const enter = useKeypress('Enter');
  40. const esc = useKeypress('Escape');
  41. function revertValueAndCloseEditor() {
  42. if (value !== inputValue) {
  43. setInputValue(value);
  44. }
  45. if (isEditing) {
  46. setIsEditing(false);
  47. }
  48. }
  49. // check to see if the user clicked outside of this component
  50. useOnClickOutside(innerWrapperRef, () => {
  51. if (!isEditing) {
  52. return;
  53. }
  54. if (isEmpty) {
  55. displayStatusMessage('error');
  56. return;
  57. }
  58. if (inputValue !== value) {
  59. onChange(inputValue);
  60. displayStatusMessage('success');
  61. }
  62. setIsEditing(false);
  63. });
  64. const onEnter = useCallback(() => {
  65. if (enter) {
  66. if (isEmpty) {
  67. displayStatusMessage('error');
  68. return;
  69. }
  70. if (inputValue !== value) {
  71. onChange(inputValue);
  72. displayStatusMessage('success');
  73. }
  74. setIsEditing(false);
  75. }
  76. }, [enter, inputValue, onChange]);
  77. const onEsc = useCallback(() => {
  78. if (esc) {
  79. revertValueAndCloseEditor();
  80. }
  81. }, [esc]);
  82. useEffect(() => {
  83. revertValueAndCloseEditor();
  84. }, [isDisabled, value]);
  85. // focus the cursor in the input field on edit start
  86. useEffect(() => {
  87. if (isEditing) {
  88. const inputElement = inputRef.current;
  89. if (defined(inputElement)) {
  90. inputElement.focus();
  91. }
  92. }
  93. }, [isEditing]);
  94. useEffect(() => {
  95. if (isEditing) {
  96. // if Enter is pressed, save the value and close the editor
  97. onEnter();
  98. // if Escape is pressed, revert the value and close the editor
  99. onEsc();
  100. }
  101. }, [onEnter, onEsc, isEditing]); // watch the Enter and Escape key presses
  102. function displayStatusMessage(status: 'error' | 'success') {
  103. if (status === 'error') {
  104. if (errorMessage) {
  105. addErrorMessage(errorMessage);
  106. }
  107. return;
  108. }
  109. if (successMessage) {
  110. addSuccessMessage(successMessage);
  111. }
  112. }
  113. function handleInputChange(event: React.ChangeEvent<HTMLInputElement>) {
  114. setInputValue(event.target.value);
  115. }
  116. function handleEditClick() {
  117. setIsEditing(true);
  118. }
  119. return (
  120. <Wrapper isDisabled={isDisabled} isEditing={isEditing}>
  121. {isEditing ? (
  122. <InputWrapper
  123. ref={innerWrapperRef}
  124. isEmpty={isEmpty}
  125. data-test-id="editable-text-input"
  126. >
  127. <StyledInput
  128. aria-label={ariaLabel}
  129. name={name}
  130. ref={inputRef}
  131. value={inputValue}
  132. onChange={handleInputChange}
  133. onFocus={event => autoSelect && event.target.select()}
  134. maxLength={maxLength}
  135. />
  136. <InputLabel>{inputValue}</InputLabel>
  137. </InputWrapper>
  138. ) : (
  139. <Label
  140. onClick={isDisabled ? undefined : handleEditClick}
  141. ref={labelRef}
  142. isDisabled={isDisabled}
  143. data-test-id="editable-text-label"
  144. >
  145. <InnerLabel>{inputValue}</InnerLabel>
  146. {!isDisabled && <IconEdit />}
  147. </Label>
  148. )}
  149. </Wrapper>
  150. );
  151. }
  152. export default EditableText;
  153. const Label = styled('div')<{isDisabled: boolean}>`
  154. display: grid;
  155. grid-auto-flow: column;
  156. align-items: center;
  157. gap: ${space(1)};
  158. cursor: ${p => (p.isDisabled ? 'default' : 'pointer')};
  159. `;
  160. const InnerLabel = styled(TextOverflow)`
  161. border-top: 1px solid transparent;
  162. border-bottom: 1px dotted ${p => p.theme.gray200};
  163. `;
  164. const InputWrapper = styled('div')<{isEmpty: boolean}>`
  165. display: inline-block;
  166. background: ${p => p.theme.gray100};
  167. border-radius: ${p => p.theme.borderRadius};
  168. margin: -${space(0.5)} -${space(1)};
  169. padding: ${space(0.5)} ${space(1)};
  170. max-width: calc(100% + ${space(2)});
  171. `;
  172. const StyledInput = styled(Input)`
  173. border: none !important;
  174. background: transparent;
  175. height: auto;
  176. min-height: 34px;
  177. padding: 0;
  178. &,
  179. &:focus,
  180. &:active,
  181. &:hover {
  182. box-shadow: none;
  183. }
  184. `;
  185. const InputLabel = styled('div')`
  186. height: 0;
  187. opacity: 0;
  188. white-space: pre;
  189. padding: 0 ${space(1)};
  190. `;
  191. const Wrapper = styled('div')<{isDisabled: boolean; isEditing: boolean}>`
  192. display: flex;
  193. ${p =>
  194. p.isDisabled &&
  195. `
  196. ${InnerLabel} {
  197. border-bottom-color: transparent;
  198. }
  199. `}
  200. `;