-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSelectPickerTextArea.component.tsx
More file actions
206 lines (172 loc) · 6.99 KB
/
SelectPickerTextArea.component.tsx
File metadata and controls
206 lines (172 loc) · 6.99 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/*
* Copyright (c) 2024. Devtron Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useEffect, useRef, useState } from 'react'
import { InputActionMeta, SelectInstance, SingleValue } from 'react-select'
import { ReactSelectInputAction } from '@Common/Constants'
import { useThrottledEffect } from '@Common/Helper'
import SelectPicker from './SelectPicker.component'
import { SelectPickerOptionType, SelectPickerTextAreaProps } from './type'
export const SelectPickerTextArea = ({
value,
options,
isCreatable,
onChange,
minHeight,
maxHeight,
refVar,
dependentRefs,
...props
}: SelectPickerTextAreaProps) => {
// STATES
const [inputValue, setInputValue] = useState((value as SingleValue<SelectPickerOptionType<string>>)?.value || '')
// REFS
const selectRef = useRef<SelectInstance<SelectPickerOptionType<string>>>(null)
useEffect(() => {
const inputRef = refVar
if (inputRef) {
inputRef.current = selectRef.current.inputRef as unknown as HTMLTextAreaElement
}
}, [refVar])
useEffect(() => {
const selectValue = value as SingleValue<SelectPickerOptionType<string>>
setInputValue(selectValue?.value || '')
}, [value])
// METHODS
const updateDependentRefsHeight = (height: number) => {
Object.values(dependentRefs || {}).forEach((ref) => {
const dependentRefElement = ref?.current
if (dependentRefElement) {
dependentRefElement.style.height = `${height}px`
}
})
}
const updateRefsHeight = (height: number) => {
const refElement = refVar?.current
if (refElement) {
refElement.style.height = `${height}px`
}
updateDependentRefsHeight(height)
}
const reInitHeight = () => {
updateRefsHeight(minHeight || 0)
let nextHeight = refVar?.current?.scrollHeight || 0
if (dependentRefs) {
Object.values(dependentRefs).forEach((ref) => {
const refElement = ref.current
if (refElement && refElement.scrollHeight > nextHeight) {
nextHeight = refElement.scrollHeight
}
})
}
if (minHeight && nextHeight < minHeight) {
nextHeight = minHeight
}
if (maxHeight && nextHeight > maxHeight) {
nextHeight = maxHeight
}
updateRefsHeight(nextHeight)
}
useThrottledEffect(reInitHeight, 500, [inputValue])
const handleCreateOption = (newValue: string) => {
onChange?.(
{ label: newValue, value: newValue },
{ action: 'create-option', option: { label: newValue, value: newValue } },
)
selectRef.current.blurInput()
}
/**
* Create an option if no option preselectec & input is dirty
* @returns boolean - true if option was created
*/
const updateValueIfOnlyDirty = (): boolean => {
const selectValue = value as SingleValue<SelectPickerOptionType<string>>
if (isCreatable && (!selectValue?.value || selectValue.value !== inputValue)) {
handleCreateOption(inputValue)
return true
}
return false
}
const onInputChange = (newValue: string, { action }: InputActionMeta) => {
if (action === ReactSelectInputAction.inputChange) {
setInputValue(newValue)
if (!newValue) {
onChange?.(null, {
action: 'remove-value',
removedValue: value as SingleValue<SelectPickerOptionType<string>>,
})
}
} else if (action === ReactSelectInputAction.inputBlur) {
if (updateValueIfOnlyDirty()) {
return
}
const selectValue = value as SingleValue<SelectPickerOptionType<string>>
// Reverting input to previously selected value in case of blur event. (no-selection)
setInputValue(selectValue?.value || '')
}
}
const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Enter' && event.shiftKey) {
// Prevent the default Enter key behavior
event.preventDefault()
// Add a new line at the current cursor position
const { selectionStart, selectionEnd } = selectRef.current.inputRef
const updatedText = `${inputValue.slice(0, selectionStart)}\n${inputValue.slice(selectionEnd)}`
setInputValue(updatedText)
const textarea = selectRef.current.inputRef
// Get the caret position
const caretPosition = textarea.selectionStart
// Split the text up to the caret position into lines
const textBeforeCaret = textarea.value.substring(0, caretPosition)
const lines = textBeforeCaret.split('\n')
// Calculate the caret position in pixels
const lineHeight = parseInt(getComputedStyle(textarea).lineHeight, 10)
const caretY = lines.length * lineHeight
// Check if caret is outside of the visible area
const scrollOffset = caretY - textarea.scrollTop
if (scrollOffset < 0) {
// Scroll up if the caret is above the visible area
textarea.scrollTop += scrollOffset
} else if (scrollOffset > textarea.offsetHeight - lineHeight) {
// Scroll down if the caret is below the visible area
textarea.scrollTop += scrollOffset - textarea.offsetHeight + lineHeight
}
// Move the cursor to the next line
// Using setTimeout so that the cursor adjustment happens after React completes its update,
// ensuring the desired cursor position remains intact.
setTimeout(() => {
selectRef.current.inputRef.selectionStart = selectionStart + 1
selectRef.current.inputRef.selectionEnd = selectionStart + 1
})
updateValueIfOnlyDirty()
}
}
return (
<SelectPicker<string, false>
{...props}
isCreatable={isCreatable}
options={options}
selectRef={selectRef}
inputValue={inputValue}
value={value}
onInputChange={onInputChange}
controlShouldRenderValue={false}
onChange={onChange}
onKeyDown={handleKeyDown}
onCreateOption={handleCreateOption}
shouldRenderTextArea
/>
)
}