-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathUserMentionWrapper.js
More file actions
263 lines (235 loc) · 9.21 KB
/
UserMentionWrapper.js
File metadata and controls
263 lines (235 loc) · 9.21 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import {
CenteredContent,
CircularLoader,
Layer,
Menu,
MenuSectionHeader,
MenuItem,
Popper,
Card,
} from '@dhis2/ui'
import PropTypes from 'prop-types'
import React, { useState, useRef } from 'react'
import i18n from '../../locales/index.js'
import {
resolvedHeaderStyle,
userMentionWrapperClasses,
} from './styles/UserMentionWrapper.style.js'
import { UserList } from './UserList.js'
import { useUserSearchResults } from './useUserSearchResults.js'
const AT_SYMBOL_WIDTH = 14
const getVirtualPopperReference = (ref) => {
const rects = ref.current.getClientRects()
const lastRect = rects[rects.length - 1]
const left = lastRect.left + lastRect.width - AT_SYMBOL_WIDTH
return {
getBoundingClientRect: () => ({
top: lastRect.top,
right: lastRect.right,
bottom: lastRect.bottom,
left,
width: AT_SYMBOL_WIDTH,
height: lastRect.height,
x: left,
}),
}
}
export const UserMentionWrapper = ({
children,
inputReference,
onUserSelect,
}) => {
const [listIsOpen, setListIsOpen] = useState(false)
const [captureText, setCaptureText] = useState(false)
const [capturedText, setCapturedText] = useState('')
const [cloneText, setCloneText] = useState('')
const cloneRef = useRef(null)
const [captureStartPosition, setCaptureStartPosition] = useState(null)
const [selectedUserIndex, setSelectedUserIndex] = useState(0)
const { users, pager, fetching, clear } = useUserSearchResults({
searchText: capturedText,
})
const reset = () => {
setListIsOpen(false)
setCaptureText(false)
setCapturedText('')
setCloneText('')
setCaptureStartPosition(null)
setSelectedUserIndex(0)
clear()
}
// focus the input/textarea when the user list is closed by clicking above the input/textarea
const onClick = () => inputReference.current.focus()
// close the user list when clicking in the input/textarea or outside of it (input/textarea blur)
const onUserListClose = () => reset()
// event bubbles up from the input/textarea
const onInput = ({ target }) => {
const { selectionEnd, value } = target
if (captureText) {
clear()
const spacePosition = value.indexOf(' ', captureStartPosition - 1)
const filterValue = value
.substring(
captureStartPosition,
spacePosition > 0 ? spacePosition : selectionEnd + 1
)
.replace(/\n+/, '')
if (filterValue !== capturedText) {
setCapturedText(filterValue)
} else if (filterValue.length === 0) {
setCapturedText('')
clear()
}
}
}
// event bubbles up from the wrapped input/textarea
const onKeyDown = ({ key, target }) => {
const { selectionStart } = target
if (!captureText && key === '@') {
setListIsOpen(true)
setCaptureText(true)
setCaptureStartPosition(selectionStart + 1)
setCloneText(target.value.substring(0, selectionStart) + '@')
} else if (captureText) {
if (
key === ' ' ||
(key === 'Backspace' && selectionStart <= captureStartPosition)
) {
reset()
} else if (users.length) {
switch (key) {
case 'Enter':
event.preventDefault()
if (selectedUserIndex >= 0) {
onSelect(users[selectedUserIndex])
}
break
case 'ArrowDown':
event.preventDefault()
if (selectedUserIndex < users.length - 1) {
setSelectedUserIndex(selectedUserIndex + 1)
}
break
case 'ArrowUp':
event.preventDefault()
if (selectedUserIndex > 0) {
setSelectedUserIndex(selectedUserIndex - 1)
}
break
default:
// other key strokes, typically the text typed
// the onInput event handler set on the input element is triggering the user lookup
}
}
}
}
const onSelect = (user) => {
const originalValue = inputReference.current.value
const newValue = `${originalValue.slice(
0,
captureStartPosition - 1
)}${originalValue
.slice(captureStartPosition - 1)
.replace(/^@\w*/, `@${user.username} `)}`
reset()
// typically for connected components we want the state to be updated too
// but the logic belongs to the wrapped component, so we just invoke the supplied callback
if (onUserSelect) {
onUserSelect(newValue)
}
// need to refocus on the input/textarea
inputReference.current.focus()
// position the cursor at the end
requestAnimationFrame(
() => inputReference.current.setSelectionRange(-1, -1),
0
)
}
const onUserClick = (user) => () => onSelect(user)
return (
<div
onKeyDown={onKeyDown}
onInput={onInput}
onClick={onClick}
className="wrapper"
>
{children}
<div className="clone">
<p ref={cloneRef}>{cloneText}</p>
</div>
{listIsOpen && (
<Layer onBackdropClick={onUserListClose}>
<Popper
reference={getVirtualPopperReference(cloneRef)}
placement="top-start"
>
<Card>
<div className="container">
<Menu dense>
<MenuSectionHeader
className={
resolvedHeaderStyle.className
}
dense
hideDivider
label={
capturedText === ''
? i18n.t('Search for a user')
: i18n.t(
'Searching for "{{- searchText}}"',
{
searchText:
capturedText,
}
)
}
/>
{fetching && (
<MenuItem
label={
<CenteredContent>
<CircularLoader small />
</CenteredContent>
}
/>
)}
{!fetching && users.length > 0 && (
<UserList
users={users}
selectedUserIndex={
selectedUserIndex
}
onUserClick={onUserClick}
pager={pager}
/>
)}
{capturedText &&
!fetching &&
users.length === 0 && (
<MenuItem
dense
disabled
label={i18n.t(
'No results found'
)}
/>
)}
</Menu>
</div>
</Card>
</Popper>
</Layer>
)}
<style jsx>{userMentionWrapperClasses}</style>
{resolvedHeaderStyle.styles}
</div>
)
}
UserMentionWrapper.defaultProps = {
onUserSelect: Function.prototype,
}
UserMentionWrapper.propTypes = {
inputReference: PropTypes.object.isRequired,
onUserSelect: PropTypes.func.isRequired,
children: PropTypes.node,
}