-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfield-name-content.tsx
More file actions
71 lines (61 loc) · 1.72 KB
/
field-name-content.tsx
File metadata and controls
71 lines (61 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import styled from '@emotion/styled';
import { useCallback, useEffect, useRef, useState } from 'react';
import { ellipsisTruncation } from '@/styles/styles';
import { DEFAULT_FIELD_HEIGHT } from '@/utilities/constants';
const InnerFieldName = styled.div`
width: 100%;
min-height: ${DEFAULT_FIELD_HEIGHT}px;
${ellipsisTruncation}
`;
const InlineInput = styled.input`
border: none;
background: none;
height: ${DEFAULT_FIELD_HEIGHT}px;
color: inherit;
font-size: inherit;
font-family: inherit;
font-style: inherit;
width: 100%;
`;
interface FieldNameProps {
name: string;
isEditing: boolean;
onChange: (newName: string) => void;
onCancelEditing: () => void;
}
export const FieldNameContent = ({ name, isEditing, onChange, onCancelEditing }: FieldNameProps) => {
const [value, setValue] = useState(name);
const textInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
setValue(name);
}, [name]);
const handleSubmit = useCallback(() => {
onChange(value);
}, [value, onChange]);
const handleKeyboardEvent = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') handleSubmit();
if (e.key === 'Escape') {
setValue(name);
onCancelEditing();
}
},
[handleSubmit, onCancelEditing, name],
);
const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
}, []);
return isEditing ? (
<InlineInput
type="text"
ref={textInputRef}
value={value}
onChange={handleChange}
onBlur={handleSubmit}
onKeyDown={handleKeyboardEvent}
title="Edit field name"
/>
) : (
<InnerFieldName title={value}>{value}</InnerFieldName>
);
};