editableText.tsx 5.4 KB

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