-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathSuggestionMention.js
331 lines (283 loc) · 12.8 KB
/
SuggestionMention.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
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useImperativeHandle, useRef, useState} from 'react';
import _ from 'underscore';
import * as Expensicons from '@components/Icon/Expensicons';
import MentionSuggestions from '@components/MentionSuggestions';
import {usePersonalDetails} from '@components/OnyxProvider';
import useArrowKeyFocusManager from '@hooks/useArrowKeyFocusManager';
import useLocalize from '@hooks/useLocalize';
import usePrevious from '@hooks/usePrevious';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import * as SuggestionsUtils from '@libs/SuggestionUtils';
import * as UserUtils from '@libs/UserUtils';
import CONST from '@src/CONST';
import * as SuggestionProps from './suggestionProps';
/**
* Check if this piece of string looks like a mention
* @param {String} str
* @returns {Boolean}
*/
const isMentionCode = (str) => CONST.REGEX.HAS_AT_MOST_TWO_AT_SIGNS.test(str);
const defaultSuggestionsValues = {
suggestedMentions: [],
atSignIndex: -1,
shouldShowSuggestionMenu: false,
mentionPrefix: '',
};
const propTypes = {
/** A ref to this component */
forwardedRef: PropTypes.shape({current: PropTypes.shape({})}),
...SuggestionProps.implementationBaseProps,
};
const defaultProps = {
forwardedRef: null,
};
function SuggestionMention({
value,
setValue,
selection,
setSelection,
isComposerFullSize,
updateComment,
composerHeight,
forwardedRef,
isAutoSuggestionPickerLarge,
measureParentContainer,
isComposerFocused,
}) {
const personalDetails = usePersonalDetails() || CONST.EMPTY_OBJECT;
const {translate, formatPhoneNumber} = useLocalize();
const previousValue = usePrevious(value);
const [suggestionValues, setSuggestionValues] = useState(defaultSuggestionsValues);
const isMentionSuggestionsMenuVisible = !_.isEmpty(suggestionValues.suggestedMentions) && suggestionValues.shouldShowSuggestionMenu;
const [highlightedMentionIndex, setHighlightedMentionIndex] = useArrowKeyFocusManager({
isActive: isMentionSuggestionsMenuVisible,
maxIndex: suggestionValues.suggestedMentions.length - 1,
shouldExcludeTextAreaNodes: false,
});
// Used to decide whether to block the suggestions list from showing to prevent flickering
const shouldBlockCalc = useRef(false);
/**
* Replace the code of mention and update selection
* @param {Number} highlightedMentionIndex
*/
const insertSelectedMention = useCallback(
(highlightedMentionIndexInner) => {
const commentBeforeAtSign = value.slice(0, suggestionValues.atSignIndex);
const mentionObject = suggestionValues.suggestedMentions[highlightedMentionIndexInner];
const mentionCode = mentionObject.text === CONST.AUTO_COMPLETE_SUGGESTER.HERE_TEXT ? CONST.AUTO_COMPLETE_SUGGESTER.HERE_TEXT : `@${mentionObject.login}`;
const commentAfterMention = value.slice(suggestionValues.atSignIndex + suggestionValues.mentionPrefix.length + 1);
updateComment(`${commentBeforeAtSign}${mentionCode} ${SuggestionsUtils.trimLeadingSpace(commentAfterMention)}`, true);
setSelection({
start: suggestionValues.atSignIndex + mentionCode.length + CONST.SPACE_LENGTH,
end: suggestionValues.atSignIndex + mentionCode.length + CONST.SPACE_LENGTH,
});
setSuggestionValues((prevState) => ({
...prevState,
suggestedMentions: [],
}));
},
[value, suggestionValues.atSignIndex, suggestionValues.suggestedMentions, suggestionValues.mentionPrefix, updateComment, setSelection],
);
/**
* Clean data related to suggestions
*/
const resetSuggestions = useCallback(() => {
setSuggestionValues(defaultSuggestionsValues);
}, []);
/**
* Listens for keyboard shortcuts and applies the action
*
* @param {Object} e
*/
const triggerHotkeyActions = useCallback(
(e) => {
const suggestionsExist = suggestionValues.suggestedMentions.length > 0;
if (((!e.shiftKey && e.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey) || e.key === CONST.KEYBOARD_SHORTCUTS.TAB.shortcutKey) && suggestionsExist) {
e.preventDefault();
if (suggestionValues.suggestedMentions.length > 0) {
insertSelectedMention(highlightedMentionIndex);
return true;
}
}
if (e.key === CONST.KEYBOARD_SHORTCUTS.ESCAPE.shortcutKey) {
e.preventDefault();
if (suggestionsExist) {
resetSuggestions();
}
return true;
}
},
[highlightedMentionIndex, insertSelectedMention, resetSuggestions, suggestionValues.suggestedMentions.length],
);
const getMentionOptions = useCallback(
(personalDetailsParam, searchValue = '') => {
const suggestions = [];
if (CONST.AUTO_COMPLETE_SUGGESTER.HERE_TEXT.includes(searchValue.toLowerCase())) {
suggestions.push({
text: CONST.AUTO_COMPLETE_SUGGESTER.HERE_TEXT,
alternateText: translate('mentionSuggestions.hereAlternateText'),
icons: [
{
source: Expensicons.Megaphone,
type: 'avatar',
},
],
});
}
const filteredPersonalDetails = _.filter(_.values(personalDetailsParam), (detail) => {
// If we don't have user's primary login, that member is not known to the current user and hence we do not allow them to be mentioned
if (!detail.login || detail.isOptimisticPersonalDetail) {
return false;
}
const displayName = PersonalDetailsUtils.getDisplayNameOrDefault(detail);
const displayText = displayName === formatPhoneNumber(detail.login) ? displayName : `${displayName} ${detail.login}`;
if (searchValue && !displayText.toLowerCase().includes(searchValue.toLowerCase())) {
return false;
}
return true;
});
const sortedPersonalDetails = _.sortBy(filteredPersonalDetails, (detail) => detail.displayName || detail.login);
_.each(_.first(sortedPersonalDetails, CONST.AUTO_COMPLETE_SUGGESTER.MAX_AMOUNT_OF_SUGGESTIONS - suggestions.length), (detail) => {
suggestions.push({
text: PersonalDetailsUtils.getDisplayNameOrDefault(detail),
alternateText: formatPhoneNumber(detail.login),
login: detail.login,
icons: [
{
name: detail.login,
source: UserUtils.getAvatar(detail.avatar, detail.accountID),
type: 'avatar',
fallbackIcon: detail.fallbackIcon,
},
],
});
});
return suggestions;
},
[translate, formatPhoneNumber],
);
const calculateMentionSuggestion = useCallback(
(selectionEnd) => {
if (shouldBlockCalc.current || selectionEnd < 1 || !isComposerFocused) {
shouldBlockCalc.current = false;
resetSuggestions();
return;
}
const valueAfterTheCursor = value.substring(selectionEnd);
const indexOfFirstSpecialCharOrEmojiAfterTheCursor = valueAfterTheCursor.search(CONST.REGEX.MENTION_BREAKER);
let suggestionEndIndex;
if (indexOfFirstSpecialCharOrEmojiAfterTheCursor === -1) {
// We didn't find a special char/whitespace/emoji after the cursor, so we will use the entire string
suggestionEndIndex = value.length;
} else {
suggestionEndIndex = indexOfFirstSpecialCharOrEmojiAfterTheCursor + selectionEnd;
}
const leftString = value.substring(0, suggestionEndIndex);
const words = leftString.split(CONST.REGEX.SPACE_OR_EMOJI);
const lastWord = _.last(words);
const secondToLastWord = words[words.length - 3];
let atSignIndex;
let suggestionWord;
let prefix;
// Detect if the last two words contain a mention (two words are needed to detect a mention with a space in it)
if (lastWord.startsWith('@')) {
atSignIndex = leftString.lastIndexOf(lastWord);
suggestionWord = lastWord;
prefix = suggestionWord.substring(1);
} else if (secondToLastWord && secondToLastWord.startsWith('@') && secondToLastWord.length > 1) {
atSignIndex = leftString.lastIndexOf(secondToLastWord);
suggestionWord = `${secondToLastWord} ${lastWord}`;
prefix = suggestionWord.substring(1);
} else {
prefix = lastWord.substring(1);
}
const nextState = {
suggestedMentions: [],
atSignIndex,
mentionPrefix: prefix,
};
const isCursorBeforeTheMention = valueAfterTheCursor.startsWith(suggestionWord);
if (!isCursorBeforeTheMention && isMentionCode(suggestionWord)) {
const suggestions = getMentionOptions(personalDetails, prefix);
nextState.suggestedMentions = suggestions;
nextState.shouldShowSuggestionMenu = !_.isEmpty(suggestions);
}
setSuggestionValues((prevState) => ({
...prevState,
...nextState,
}));
setHighlightedMentionIndex(0);
},
[getMentionOptions, personalDetails, resetSuggestions, setHighlightedMentionIndex, value, isComposerFocused],
);
useEffect(() => {
if (value.length < previousValue.length) {
// A workaround to not show the suggestions list when the user deletes a character before the mention.
// It is caused by a buggy behavior of the TextInput on iOS. Should be fixed after migration to Fabric.
// See: https://github.com/facebook/react-native/pull/36930#issuecomment-1593028467
return;
}
calculateMentionSuggestion(selection.end);
}, [selection, value, previousValue, calculateMentionSuggestion]);
const updateShouldShowSuggestionMenuToFalse = useCallback(() => {
setSuggestionValues((prevState) => {
if (prevState.shouldShowSuggestionMenu) {
return {...prevState, shouldShowSuggestionMenu: false};
}
return prevState;
});
}, []);
const setShouldBlockSuggestionCalc = useCallback(
(shouldBlockSuggestionCalc) => {
shouldBlockCalc.current = shouldBlockSuggestionCalc;
},
[shouldBlockCalc],
);
const onClose = useCallback(() => {
setSuggestionValues((prevState) => ({...prevState, suggestedMentions: []}));
}, []);
const getSuggestions = useCallback(() => suggestionValues.suggestedMentions, [suggestionValues]);
useImperativeHandle(
forwardedRef,
() => ({
resetSuggestions,
triggerHotkeyActions,
setShouldBlockSuggestionCalc,
updateShouldShowSuggestionMenuToFalse,
getSuggestions,
}),
[resetSuggestions, setShouldBlockSuggestionCalc, triggerHotkeyActions, updateShouldShowSuggestionMenuToFalse, getSuggestions],
);
if (!isMentionSuggestionsMenuVisible) {
return null;
}
return (
<MentionSuggestions
onClose={onClose}
highlightedMentionIndex={highlightedMentionIndex}
mentions={suggestionValues.suggestedMentions}
comment={value}
updateComment={setValue}
colonIndex={suggestionValues.colonIndex}
prefix={suggestionValues.mentionPrefix}
onSelect={insertSelectedMention}
isComposerFullSize={isComposerFullSize}
isMentionPickerLarge={isAutoSuggestionPickerLarge}
composerHeight={composerHeight}
measureParentContainer={measureParentContainer}
/>
);
}
SuggestionMention.propTypes = propTypes;
SuggestionMention.defaultProps = defaultProps;
SuggestionMention.displayName = 'SuggestionMention';
const SuggestionMentionWithRef = React.forwardRef((props, ref) => (
<SuggestionMention
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
forwardedRef={ref}
/>
));
SuggestionMentionWithRef.displayName = 'SuggestionMentionWithRef';
export default SuggestionMentionWithRef;