-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathKeyDisplay.tsx
93 lines (88 loc) · 2.63 KB
/
KeyDisplay.tsx
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
/**
* Component to display the "Property" value for both Collection and Value nodes
*/
import React from 'react'
import { useTreeState } from './contexts'
import { type KeyboardControlsFull, type CollectionKey, type ValueData } from './types'
interface KeyDisplayProps {
canEditKey: boolean
isEditingKey: boolean
pathString: string
path: CollectionKey[]
name: string
handleKeyboard: (
e: React.KeyboardEvent,
eventMap: Partial<Record<keyof KeyboardControlsFull, () => void>>
) => void
handleEditKey: (newKey: string) => void
handleCancel: () => void
keyValueArray?: Array<[string | number, ValueData]>
styles: React.CSSProperties
getNextOrPrevious: (type: 'next' | 'prev') => CollectionKey[] | null
}
export const KeyDisplay: React.FC<KeyDisplayProps> = ({
isEditingKey,
canEditKey,
pathString,
path,
name,
handleKeyboard,
handleEditKey,
handleCancel,
keyValueArray,
styles,
getNextOrPrevious,
}) => {
const { setCurrentlyEditingElement } = useTreeState()
if (!isEditingKey)
return (
<span
className="jer-key-text"
style={{
...styles,
minWidth: `${Math.min(String(name).length + 1, 5)}ch`,
flexShrink: name.length > 10 ? 1 : 0,
}}
onDoubleClick={() => canEditKey && setCurrentlyEditingElement(path, 'key')}
>
{name === '' ? (
<span className={path.length > 0 ? 'jer-empty-string' : undefined}>
{/* display "<empty string>" using pseudo class CSS */}
</span>
) : (
`${name}`
)}
<span className="jer-key-colon">:</span>
</span>
)
return (
<input
className="jer-input-text jer-key-edit"
type="text"
name={pathString}
defaultValue={name}
autoFocus
onFocus={(e) => e.target.select()}
onKeyDown={(e: React.KeyboardEvent) =>
handleKeyboard(e, {
stringConfirm: () => handleEditKey((e.target as HTMLInputElement).value),
cancel: handleCancel,
tabForward: () => {
handleEditKey((e.target as HTMLInputElement).value)
if (keyValueArray) {
const firstChildKey = keyValueArray?.[0][0]
setCurrentlyEditingElement(
firstChildKey ? [...path, firstChildKey] : getNextOrPrevious('next')
)
} else setCurrentlyEditingElement(path)
},
tabBack: () => {
handleEditKey((e.target as HTMLInputElement).value)
setCurrentlyEditingElement(getNextOrPrevious('prev'))
},
})
}
style={{ width: `${String(name).length / 1.5 + 0.5}em` }}
/>
)
}