-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathSuggestionMention.tsx
490 lines (429 loc) · 21.2 KB
/
SuggestionMention.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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import {Str} from 'expensify-common';
import lodashMapValues from 'lodash/mapValues';
import lodashSortBy from 'lodash/sortBy';
import type {ForwardedRef} from 'react';
import React, {forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import type {OnyxCollection} from 'react-native-onyx';
import {useOnyx} from 'react-native-onyx';
import * as Expensicons from '@components/Icon/Expensicons';
import type {Mention} from '@components/MentionSuggestions';
import MentionSuggestions from '@components/MentionSuggestions';
import {usePersonalDetails} from '@components/OnyxProvider';
import useArrowKeyFocusManager from '@hooks/useArrowKeyFocusManager';
import useCurrentReportID from '@hooks/useCurrentReportID';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useDebounce from '@hooks/useDebounce';
import useLocalize from '@hooks/useLocalize';
import localeCompare from '@libs/LocaleCompare';
import * as LoginUtils from '@libs/LoginUtils';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import getPolicyEmployeeAccountIDs from '@libs/PolicyEmployeeListUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as SuggestionsUtils from '@libs/SuggestionUtils';
import {isValidRoomName} from '@libs/ValidationUtils';
import * as ReportUserActions from '@userActions/Report';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {PersonalDetails, PersonalDetailsList, Report} from '@src/types/onyx';
import type {SuggestionsRef} from './ReportActionCompose';
import type {SuggestionProps} from './Suggestions';
type SuggestionValues = {
suggestedMentions: Mention[];
atSignIndex: number;
shouldShowSuggestionMenu: boolean;
mentionPrefix: string;
prefixType: string;
};
/**
* Check if this piece of string looks like a mention
*/
const isMentionCode = (str: string): boolean => CONST.REGEX.HAS_AT_MOST_TWO_AT_SIGNS.test(str);
const defaultSuggestionsValues: SuggestionValues = {
suggestedMentions: [],
atSignIndex: -1,
shouldShowSuggestionMenu: false,
mentionPrefix: '',
prefixType: '',
};
type SuggestionPersonalDetailsList = Record<
string,
| (PersonalDetails & {
weight: number;
})
| null
>;
function getDisplayName(details: PersonalDetails) {
const displayNameFromAccountID = ReportUtils.getDisplayNameForParticipant({accountID: details.accountID});
if (!displayNameFromAccountID) {
return details.login?.length ? details.login : '';
}
return displayNameFromAccountID;
}
/**
* Comparison function to sort users. It compares weights, display names, and accountIDs in that order
*/
function compareUserInList(first: PersonalDetails & {weight: number}, second: PersonalDetails & {weight: number}) {
if (first.weight !== second.weight) {
return first.weight - second.weight;
}
const displayNameLoginOrder = localeCompare(getDisplayName(first), getDisplayName(second));
if (displayNameLoginOrder !== 0) {
return displayNameLoginOrder;
}
return first.accountID - second.accountID;
}
function SuggestionMention(
{value, selection, setSelection, updateComment, isAutoSuggestionPickerLarge, measureParentContainerAndReportCursor, isComposerFocused, isGroupPolicyReport, policyID}: SuggestionProps,
ref: ForwardedRef<SuggestionsRef>,
) {
const personalDetails = usePersonalDetails();
const {translate, formatPhoneNumber} = useLocalize();
const [suggestionValues, setSuggestionValues] = useState(defaultSuggestionsValues);
const suggestionValuesRef = useRef(suggestionValues);
// eslint-disable-next-line react-compiler/react-compiler
suggestionValuesRef.current = suggestionValues;
const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const isMentionSuggestionsMenuVisible = !!suggestionValues.suggestedMentions.length && suggestionValues.shouldShowSuggestionMenu;
const currentReportID = useCurrentReportID();
const currentReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${currentReportID?.currentReportID}`];
// Smaller weight means higher order in suggestion list
const getPersonalDetailsWeight = useCallback(
(detail: PersonalDetails, policyEmployeeAccountIDs: number[]): number => {
if (ReportUtils.isReportParticipant(detail.accountID, currentReport)) {
return 0;
}
if (policyEmployeeAccountIDs.includes(detail.accountID)) {
return 1;
}
return 2;
},
[currentReport],
);
const weightedPersonalDetails: PersonalDetailsList | SuggestionPersonalDetailsList | undefined = useMemo(() => {
const policyEmployeeAccountIDs = getPolicyEmployeeAccountIDs(policyID);
if (!ReportUtils.isGroupChat(currentReport) && !ReportUtils.doesReportBelongToWorkspace(currentReport, policyEmployeeAccountIDs, policyID)) {
return personalDetails;
}
return lodashMapValues(personalDetails, (detail) =>
detail
? {
...detail,
weight: getPersonalDetailsWeight(detail, policyEmployeeAccountIDs),
}
: null,
);
}, [policyID, currentReport, personalDetails, getPersonalDetailsWeight]);
const [highlightedMentionIndex, setHighlightedMentionIndex] = useArrowKeyFocusManager({
isActive: isMentionSuggestionsMenuVisible,
maxIndex: suggestionValues.suggestedMentions.length - 1,
shouldExcludeTextAreaNodes: false,
});
// Used to store the selection index of the last inserted mention
const suggestionInsertionIndexRef = useRef<number | null>(null);
// Used to detect if the selection has changed since the last suggestion insertion
// If so, we reset the suggestionInsertionIndexRef
// eslint-disable-next-line react-compiler/react-compiler
const hasSelectionChanged = !(selection.end === selection.start && selection.start === suggestionInsertionIndexRef.current);
if (hasSelectionChanged) {
// eslint-disable-next-line react-compiler/react-compiler
suggestionInsertionIndexRef.current = null;
}
// Used to decide whether to block the suggestions list from showing to prevent flickering
const shouldBlockCalc = useRef(false);
/**
* Search for reports suggestions in server.
*
* The function is debounced to not perform requests on every keystroke.
*/
const debouncedSearchInServer = useDebounce(
useCallback(() => {
const foundSuggestionsCount = suggestionValues.suggestedMentions.length;
if (suggestionValues.prefixType === '#' && foundSuggestionsCount < 5 && isGroupPolicyReport) {
ReportUserActions.searchInServer(suggestionValues.mentionPrefix, policyID);
}
}, [suggestionValues.suggestedMentions.length, suggestionValues.prefixType, suggestionValues.mentionPrefix, policyID, isGroupPolicyReport]),
CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME,
);
const formatLoginPrivateDomain = useCallback(
(displayText = '', userLogin = '') => {
if (userLogin !== displayText) {
return displayText;
}
// If the emails are not in the same private domain, we also return the displayText
if (!LoginUtils.areEmailsFromSamePrivateDomain(displayText, currentUserPersonalDetails.login ?? '')) {
return Str.removeSMSDomain(displayText);
}
// Otherwise, the emails must be of the same private domain, so we should remove the domain part
return displayText.split('@').at(0);
},
[currentUserPersonalDetails.login],
);
const getMentionCode = useCallback(
(mention: Mention, mentionType: string): string => {
if (mentionType === '#') {
// room mention case
return mention.handle ?? '';
}
return mention.text === CONST.AUTO_COMPLETE_SUGGESTER.HERE_TEXT ? CONST.AUTO_COMPLETE_SUGGESTER.HERE_TEXT : `@${formatLoginPrivateDomain(mention.handle, mention.handle)}`;
},
[formatLoginPrivateDomain],
);
/**
* Replace the code of mention and update selection
*/
const insertSelectedMention = useCallback(
(highlightedMentionIndexInner: number) => {
const commentBeforeAtSign = value.slice(0, suggestionValues.atSignIndex);
const mentionObject = suggestionValues.suggestedMentions.at(highlightedMentionIndexInner);
if (!mentionObject || highlightedMentionIndexInner === -1) {
return;
}
const mentionCode = getMentionCode(mentionObject, suggestionValues.prefixType);
const commentAfterMention = value.slice(suggestionValues.atSignIndex + suggestionValues.mentionPrefix.length + 1);
updateComment(`${commentBeforeAtSign}${mentionCode} ${SuggestionsUtils.trimLeadingSpace(commentAfterMention)}`, true);
const selectionPosition = suggestionValues.atSignIndex + mentionCode.length + CONST.SPACE_LENGTH;
setSelection({
start: selectionPosition,
end: selectionPosition,
});
suggestionInsertionIndexRef.current = selectionPosition;
setSuggestionValues((prevState) => ({
...prevState,
suggestedMentions: [],
shouldShowSuggestionMenu: false,
}));
},
[
value,
suggestionValues.atSignIndex,
suggestionValues.suggestedMentions,
suggestionValues.prefixType,
suggestionValues.mentionPrefix.length,
getMentionCode,
updateComment,
setSelection,
],
);
/**
* Clean data related to suggestions
*/
const resetSuggestions = useCallback(() => {
setSuggestionValues(defaultSuggestionsValues);
}, []);
/**
* Listens for keyboard shortcuts and applies the action
*/
const triggerHotkeyActions = useCallback(
(event: KeyboardEvent) => {
const suggestionsExist = suggestionValues.suggestedMentions.length > 0;
if (((!event.shiftKey && event.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey) || event.key === CONST.KEYBOARD_SHORTCUTS.TAB.shortcutKey) && suggestionsExist) {
event.preventDefault();
if (suggestionValues.suggestedMentions.length > 0) {
insertSelectedMention(highlightedMentionIndex);
return true;
}
}
if (event.key === CONST.KEYBOARD_SHORTCUTS.ESCAPE.shortcutKey) {
event.preventDefault();
if (suggestionsExist) {
resetSuggestions();
}
return true;
}
},
[highlightedMentionIndex, insertSelectedMention, resetSuggestions, suggestionValues.suggestedMentions.length],
);
const getUserMentionOptions = useCallback(
(personalDetailsParam: PersonalDetailsList | SuggestionPersonalDetailsList | undefined, searchValue = ''): Mention[] => {
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: CONST.ICON_TYPE_AVATAR,
},
],
});
}
const filteredPersonalDetails = Object.values(personalDetailsParam ?? {}).filter((detail, index, array) => {
// 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;
}
// We don't want to mention system emails like notifications@expensify.com
if (CONST.RESTRICTED_EMAILS.includes(detail.login) || CONST.RESTRICTED_ACCOUNT_IDS.includes(detail.accountID)) {
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;
}
// Given the mention is inserted by user, we don't want to show the mention options unless the
// selection index changes. In that case, suggestionInsertionIndexRef.current will be null.
// See https://github.com/Expensify/App/issues/38358 for more context
if (suggestionInsertionIndexRef.current) {
return false;
}
// on staging server, in specific cases (see issue) BE returns duplicated personalDetails
// entries with the same `login` which we need to filter out
return array.findIndex((arrayDetail) => arrayDetail?.login === detail?.login) === index;
}) as Array<PersonalDetails & {weight: number}>;
// At this point we are sure that the details are not null, since empty user details have been filtered in the previous step
const sortedPersonalDetails = filteredPersonalDetails.sort(compareUserInList);
sortedPersonalDetails.slice(0, CONST.AUTO_COMPLETE_SUGGESTER.MAX_AMOUNT_OF_SUGGESTIONS - suggestions.length).forEach((detail) => {
suggestions.push({
text: formatLoginPrivateDomain(PersonalDetailsUtils.getDisplayNameOrDefault(detail), detail?.login),
alternateText: `@${formatLoginPrivateDomain(detail?.login, detail?.login)}`,
handle: detail?.login,
icons: [
{
name: detail?.login,
source: detail?.avatar ?? Expensicons.FallbackAvatar,
type: CONST.ICON_TYPE_AVATAR,
fallbackIcon: detail?.fallbackIcon,
id: detail?.accountID,
},
],
});
});
return suggestions;
},
[translate, formatPhoneNumber, formatLoginPrivateDomain],
);
const getRoomMentionOptions = useCallback(
(searchTerm: string, reportBatch: OnyxCollection<Report>): Mention[] => {
const filteredRoomMentions: Mention[] = [];
Object.values(reportBatch ?? {}).forEach((report) => {
if (!ReportUtils.canReportBeMentionedWithinPolicy(report, policyID)) {
return;
}
if (report?.reportName?.toLowerCase().includes(searchTerm.toLowerCase())) {
filteredRoomMentions.push({
text: report.reportName,
handle: report.reportName,
alternateText: report.reportName,
});
}
});
return lodashSortBy(filteredRoomMentions, 'handle').slice(0, CONST.AUTO_COMPLETE_SUGGESTER.MAX_AMOUNT_OF_SUGGESTIONS);
},
[policyID],
);
const calculateMentionSuggestion = useCallback(
(newValue: string, selectionStart?: number, selectionEnd?: number) => {
if (selectionEnd !== selectionStart || !selectionEnd || shouldBlockCalc.current || selectionEnd < 1 || !isComposerFocused) {
shouldBlockCalc.current = false;
resetSuggestions();
return;
}
const afterLastBreakLineIndex = newValue.lastIndexOf('\n', selectionEnd - 1) + 1;
const leftString = newValue.substring(afterLastBreakLineIndex, selectionEnd);
const words = leftString.split(CONST.REGEX.SPACE_OR_EMOJI);
const lastWord: string = words.at(-1) ?? '';
const secondToLastWord = words.at(-3);
let atSignIndex: number | undefined;
let suggestionWord = '';
let prefix: string;
let prefixType = '';
// 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('@') || lastWord.startsWith('#')) {
atSignIndex = leftString.lastIndexOf(lastWord) + afterLastBreakLineIndex;
suggestionWord = lastWord;
prefix = suggestionWord.substring(1);
prefixType = suggestionWord.substring(0, 1);
} else if (secondToLastWord && secondToLastWord.startsWith('@') && secondToLastWord.length > 1) {
atSignIndex = leftString.lastIndexOf(secondToLastWord) + afterLastBreakLineIndex;
suggestionWord = `${secondToLastWord} ${lastWord}`;
prefix = suggestionWord.substring(1);
prefixType = suggestionWord.substring(0, 1);
} else {
prefix = lastWord.substring(1);
}
const nextState: Partial<SuggestionValues> = {
suggestedMentions: [],
atSignIndex,
mentionPrefix: prefix,
prefixType,
};
if (isMentionCode(suggestionWord) && prefixType === '@') {
const suggestions = getUserMentionOptions(weightedPersonalDetails, prefix);
nextState.suggestedMentions = suggestions;
nextState.shouldShowSuggestionMenu = !!suggestions.length;
}
const shouldDisplayRoomMentionsSuggestions = isGroupPolicyReport && (isValidRoomName(suggestionWord.toLowerCase()) || prefix === '');
if (prefixType === '#' && shouldDisplayRoomMentionsSuggestions) {
// Filter reports by room name and current policy
nextState.suggestedMentions = getRoomMentionOptions(prefix, reports);
// Even if there are no reports, we should show the suggestion menu - to perform live search
nextState.shouldShowSuggestionMenu = true;
}
// Early return if there is no update
const currentState = suggestionValuesRef.current;
if (currentState.suggestedMentions.length === 0 && nextState.suggestedMentions?.length === 0) {
return;
}
setSuggestionValues((prevState) => ({
...prevState,
...nextState,
}));
setHighlightedMentionIndex(0);
},
[isComposerFocused, isGroupPolicyReport, setHighlightedMentionIndex, resetSuggestions, getUserMentionOptions, weightedPersonalDetails, getRoomMentionOptions, reports],
);
useEffect(() => {
calculateMentionSuggestion(value, selection.start, selection.end);
}, [value, selection, calculateMentionSuggestion]);
useEffect(() => {
debouncedSearchInServer();
}, [suggestionValues.suggestedMentions.length, suggestionValues.prefixType, policyID, value, debouncedSearchInServer]);
const updateShouldShowSuggestionMenuToFalse = useCallback(() => {
setSuggestionValues((prevState) => {
if (prevState.shouldShowSuggestionMenu) {
return {...prevState, shouldShowSuggestionMenu: false};
}
return prevState;
});
}, []);
const setShouldBlockSuggestionCalc = useCallback(
(shouldBlockSuggestionCalc: boolean) => {
shouldBlockCalc.current = shouldBlockSuggestionCalc;
},
[shouldBlockCalc],
);
const getSuggestions = useCallback(() => suggestionValues.suggestedMentions, [suggestionValues]);
const getIsSuggestionsMenuVisible = useCallback(() => isMentionSuggestionsMenuVisible, [isMentionSuggestionsMenuVisible]);
useImperativeHandle(
ref,
() => ({
resetSuggestions,
triggerHotkeyActions,
setShouldBlockSuggestionCalc,
updateShouldShowSuggestionMenuToFalse,
getSuggestions,
getIsSuggestionsMenuVisible,
}),
[resetSuggestions, setShouldBlockSuggestionCalc, triggerHotkeyActions, updateShouldShowSuggestionMenuToFalse, getSuggestions, getIsSuggestionsMenuVisible],
);
if (!isMentionSuggestionsMenuVisible) {
return null;
}
return (
<MentionSuggestions
highlightedMentionIndex={highlightedMentionIndex}
mentions={suggestionValues.suggestedMentions}
prefix={suggestionValues.mentionPrefix}
onSelect={insertSelectedMention}
isMentionPickerLarge={!!isAutoSuggestionPickerLarge}
measureParentContainerAndReportCursor={measureParentContainerAndReportCursor}
resetSuggestions={resetSuggestions}
/>
);
}
SuggestionMention.displayName = 'SuggestionMention';
export default forwardRef(SuggestionMention);
export {compareUserInList};