forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEditableValue.js
95 lines (86 loc) · 2.21 KB
/
EditableValue.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import React, {Fragment, useCallback, useRef} from 'react';
import Button from '../Button';
import ButtonIcon from '../ButtonIcon';
import styles from './EditableValue.css';
import {useEditableValue} from '../hooks';
type OverrideValueFn = (path: Array<string | number>, value: any) => void;
type EditableValueProps = {|
dataType: string,
initialValue: any,
overrideValueFn: OverrideValueFn,
path: Array<string | number>,
|};
export default function EditableValue({
dataType,
initialValue,
overrideValueFn,
path,
}: EditableValueProps) {
const inputRef = useRef<HTMLInputElement | null>(null);
const {
editableValue,
hasPendingChanges,
isValid,
parsedValue,
reset,
update,
} = useEditableValue(initialValue);
const handleChange = useCallback(({target}) => update(target.value), [
update,
]);
const handleKeyDown = useCallback(
event => {
// Prevent keydown events from e.g. change selected element in the tree
event.stopPropagation();
switch (event.key) {
case 'Enter':
if (isValid && hasPendingChanges) {
overrideValueFn(path, parsedValue);
}
break;
case 'Escape':
reset();
break;
default:
break;
}
},
[hasPendingChanges, isValid, overrideValueFn, parsedValue, reset],
);
let placeholder = '';
if (editableValue === undefined) {
placeholder = '(undefined)';
} else {
placeholder = 'Enter valid JSON';
}
return (
<Fragment>
<input
autoComplete="new-password"
className={isValid ? styles.Input : styles.Invalid}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={placeholder}
ref={inputRef}
type="text"
value={editableValue}
/>
{hasPendingChanges && (
<Button
className={styles.ResetButton}
onClick={reset}
title="Reset value">
<ButtonIcon type="undo" />
</Button>
)}
</Fragment>
);
}