-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
OptionsListUtils.js
390 lines (346 loc) · 13.2 KB
/
OptionsListUtils.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
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
/* eslint-disable no-continue */
import _ from 'underscore';
import Onyx from 'react-native-onyx';
import lodashGet from 'lodash.get';
import lodashOrderBy from 'lodash.orderby';
import Str from 'expensify-common/lib/str';
import {getDefaultAvatar} from './actions/PersonalDetails';
import ONYXKEYS from '../ONYXKEYS';
/**
* OptionsListUtils is used to build a list options passed to the OptionsList component. Several different UI views can
* be configured to display different results based on the options passed to the private getOptions() method. Public
* methods should be named for the views they build options for and then exported for use in a component.
*/
let currentUserLogin;
let countryCodeByIP;
// We are initializing a default avatar here so that we use the same default color for each user we are inviting. This
// will update when the OptionsListUtils re-loads. But will stay the same color for the life of the JS session.
const defaultAvatarForUserToInvite = getDefaultAvatar();
/**
* Returns the personal details for an array of logins
*
* @param {Array} logins
* @param {Object} personalDetails
* @returns {Array}
*/
function getPersonalDetailsForLogins(logins, personalDetails) {
return _.map(logins, (login) => {
let personalDetail = personalDetails[login];
if (!personalDetail) {
personalDetail = {
login,
displayName: login,
avatarURL: getDefaultAvatar(login),
};
}
return personalDetail;
});
}
/**
* Returns a string with all relevant search terms
*
* @param {Object} report
* @param {Array} personalDetailList
* @return {String}
*/
function getSearchText(report, personalDetailList) {
const searchTerms = [];
_.each(personalDetailList, (personalDetail) => {
searchTerms.push(personalDetail.displayName);
searchTerms.push(personalDetail.login);
});
if (report) {
searchTerms.push(...report.reportName.split(',').map(name => name.trim()));
searchTerms.push(...report.participants);
}
return _.unique(searchTerms).join(' ');
}
/**
* Creates a report list option
*
* @param {Array<Object>} personalDetailList
* @param {Object} [report]
* @param {Object} draftComments
* @param {Number} activeReportID
* @returns {Object}
*/
function createOption(personalDetailList, report, draftComments, activeReportID, {showChatPreviewLine = false}) {
const hasMultipleParticipants = personalDetailList.length > 1;
const personalDetail = personalDetailList[0];
const hasDraftComment = report
&& (report.reportID !== activeReportID)
&& lodashGet(draftComments, `${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${report.reportID}`, '').length > 0;
const lastActorDetails = report ? _.find(personalDetailList, {login: report.lastActorEmail}) : null;
const lastMessageText = report
? (hasMultipleParticipants && lastActorDetails
? `${lastActorDetails.displayName}: `
: '')
+ report.lastMessageText
: '';
return {
text: report ? report.reportName : personalDetail.displayName,
alternateText: (showChatPreviewLine && lastMessageText) ? lastMessageText : personalDetail.login,
icons: report ? report.icons : [personalDetail.avatarURL],
// It doesn't make sense to provide a login in the case of a report with multiple participants since
// there isn't any one single login to refer to for a report.
login: !hasMultipleParticipants ? personalDetail.login : null,
reportID: report ? report.reportID : null,
isUnread: report ? report.unreadActionCount > 0 : null,
hasDraftComment,
keyForList: report ? String(report.reportID) : personalDetail.login,
searchText: getSearchText(report, personalDetailList),
isPinned: lodashGet(report, 'isPinned', false),
};
}
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: val => currentUserLogin = val && val.email,
});
Onyx.connect({
key: ONYXKEYS.COUNTRY_CODE,
callback: val => countryCodeByIP = val || 1,
});
/**
* Searches for a match when provided with a value
*
* @param {String} searchValue
* @param {String} searchText
* @returns {Boolean}
*/
function isSearchStringMatch(searchValue, searchText) {
const matchRegexes = [
new RegExp(`^${Str.escapeForRegExp(searchValue)}$`, 'i'),
new RegExp(`^${Str.escapeForRegExp(searchValue)}`, 'i'),
new RegExp(Str.escapeForRegExp(searchValue), 'i'),
];
return _.some(matchRegexes, (regex) => {
const valueToSearch = searchText && searchText.replace(new RegExp(/ /g), '');
return regex.test(valueToSearch);
});
}
/**
* Build the options
*
* @param {Object} reports
* @param {Object} personalDetails
* @param {Obejct} draftComments
* @param {Number} activeReportID
* @param {Object} options
* @returns {Object}
* @private
*/
function getOptions(reports, personalDetails, draftComments, activeReportID, {
selectedOptions = [],
maxRecentReportsToShow = 0,
includeMultipleParticipantReports = false,
includePersonalDetails = false,
includeRecentReports = false,
prioritizePinnedReports = false,
sortByLastMessageTimestamp = false,
searchValue = '',
showChatPreviewLine = false,
showReportsWithNoComments = false,
}) {
let recentReportOptions = [];
const pinnedReportOptions = [];
const personalDetailsOptions = [];
const reportMapForLogins = {};
const orderedReports = lodashOrderBy(reports, [
sortByLastMessageTimestamp
? 'lastMessageTimestamp'
: 'lastVisitedTimestamp',
], ['desc']);
const allReportOptions = [];
_.each(orderedReports, (report) => {
const logins = lodashGet(report, ['participants'], []);
// Report data can sometimes be incomplete. If we have no logins or reportID then we will skip this entry.
if (!report.reportID || _.isEmpty(logins)) {
return;
}
// Skip this entry if it has no comments and is not the active report. We will only show reports from
// people we have sent or recieved at least one message with.
const hasNoComments = report.lastMessageTimestamp === 0;
if (!showReportsWithNoComments && hasNoComments && report.reportID !== activeReportID) {
return;
}
const reportPersonalDetails = getPersonalDetailsForLogins(logins, personalDetails);
// Save the report in the map if this is a single participant so we can associate the reportID with the
// personal detail option later.
if (logins.length <= 1) {
reportMapForLogins[logins[0]] = report;
}
allReportOptions.push(createOption(reportPersonalDetails, report, draftComments, activeReportID, {
showChatPreviewLine,
}));
});
const allPersonalDetailsOptions = _.map(personalDetails, personalDetail => (
createOption([personalDetail], reportMapForLogins[personalDetail.login], draftComments, activeReportID, {
showChatPreviewLine,
})
));
// Always exclude already selected options and the currently logged in user
const loginOptionsToExclude = [...selectedOptions, {login: currentUserLogin}];
if (includeRecentReports) {
for (let i = 0; i < allReportOptions.length; i++) {
// Stop adding options to the recentReports array when we reach the maxRecentReportsToShow value
if (recentReportOptions.length > 0 && recentReportOptions.length === maxRecentReportsToShow) {
break;
}
const reportOption = allReportOptions[i];
// Skip if we aren't including multiple participant reports and this report has multiple participants
if (!includeMultipleParticipantReports && !reportOption.login) {
continue;
}
// Check the report to see if it has a single participant and if the participant is already selected
if (reportOption.login && _.some(loginOptionsToExclude, option => option.login === reportOption.login)) {
continue;
}
// Finally check to see if this options is a match for the provided search string if we have one
if (searchValue && !isSearchStringMatch(searchValue, reportOption.searchText)) {
continue;
}
// If the report is pinned and we are using the option to display pinned reports on top then we need to
// collect the pinned reports so we can sort them alphabetically once they are collected
if (prioritizePinnedReports && reportOption.isPinned) {
pinnedReportOptions.push(reportOption);
} else {
recentReportOptions.push(reportOption);
}
// Add this login to the exclude list so it won't appear when we process the personal details
if (reportOption.login) {
loginOptionsToExclude.push({login: reportOption.login});
}
}
}
// If we are prioritizing our pinned reports then shift them to the front and sort them by report name
if (prioritizePinnedReports) {
const sortedPinnedReports = lodashOrderBy(pinnedReportOptions, ['text'], ['asc']);
recentReportOptions = sortedPinnedReports.concat(recentReportOptions);
}
if (includePersonalDetails) {
// Next loop over all personal details removing any that are selectedUsers or recentChats
_.each(allPersonalDetailsOptions, (personalDetailOption) => {
if (_.some(loginOptionsToExclude, loginOptionToExclude => (
loginOptionToExclude.login === personalDetailOption.login
))) {
return;
}
if (searchValue && !isSearchStringMatch(searchValue, personalDetailOption.searchText)) {
return;
}
personalDetailsOptions.push(personalDetailOption);
});
}
let userToInvite = null;
if (searchValue
&& recentReportOptions.length === 0
&& personalDetailsOptions.length === 0
&& _.every(selectedOptions, option => option.login !== searchValue)
&& (Str.isValidEmail(searchValue) || Str.isValidPhone(searchValue))
) {
// If the phone number doesn't have an international code then let's prefix it with the
// current users international code based on their IP address.
const login = (Str.isValidPhone(searchValue) && !searchValue.includes('+'))
? `+${countryCodeByIP}${searchValue}`
: searchValue;
const userInvitePersonalDetails = getPersonalDetailsForLogins([login], personalDetails);
userToInvite = createOption(userInvitePersonalDetails, null, draftComments, activeReportID, {
showChatPreviewLine,
});
userToInvite.icons = [defaultAvatarForUserToInvite];
}
return {
personalDetails: personalDetailsOptions,
recentReports: recentReportOptions,
userToInvite,
};
}
/**
* Build the options for the Search view
*
* @param {Object} reports
* @param {Object} personalDetails
* @param {String} searchValue
* @returns {Object}
*/
function getSearchOptions(
reports,
personalDetails,
searchValue = '',
) {
return getOptions(reports, personalDetails, {}, 0, {
searchValue,
includeRecentReports: true,
includeMultipleParticipantReports: true,
maxRecentReportsToShow: 0, // Unlimited
prioritizePinnedReports: true,
showChatPreviewLine: true,
showReportsWithNoComments: true,
});
}
/**
* Build the options for the New Chat view
*
* @param {Object} reports
* @param {Object} personalDetails
* @param {String} searchValue
* @returns {Object}
*/
function getNewChatOptions(
reports,
personalDetails,
searchValue = '',
) {
return getOptions(reports, personalDetails, {}, 0, {
searchValue,
includePersonalDetails: true,
});
}
/**
* Build the options for the New Group view
*
* @param {Object} reports
* @param {Object} personalDetails
* @param {String} searchValue
* @param {Array} selectedOptions
* @returns {Object}
*/
function getNewGroupOptions(
reports,
personalDetails,
searchValue = '',
selectedOptions = [],
) {
return getOptions(reports, personalDetails, {}, 0, {
searchValue,
selectedOptions,
includeRecentReports: true,
includePersonalDetails: true,
includeMultipleParticipantReports: false,
maxRecentReportsToShow: 5,
});
}
/**
* Build the options for the Sidebar a.k.a. LHN
* @param {Object} reports
* @param {Object} personalDetails
* @param {Obejct} draftComments
* @param {Number} activeReportID
* @returns {Object}
*/
function getSidebarOptions(reports, personalDetails, draftComments, activeReportID) {
return getOptions(reports, personalDetails, draftComments, activeReportID, {
includeRecentReports: true,
includeMultipleParticipantReports: true,
maxRecentReportsToShow: 0, // Unlimited
prioritizePinnedReports: true,
sortByLastMessageTimestamp: true,
showChatPreviewLine: true,
});
}
export {
getSearchOptions,
getNewChatOptions,
getNewGroupOptions,
getSidebarOptions,
};