editableText.tsx 5.0 KB

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