-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
NewChatPage.tsx
executable file
·359 lines (326 loc) · 14.9 KB
/
NewChatPage.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
import isEmpty from 'lodash/isEmpty';
import reject from 'lodash/reject';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {useOnyx} from 'react-native-onyx';
import Button from '@components/Button';
import KeyboardAvoidingView from '@components/KeyboardAvoidingView';
import OfflineIndicator from '@components/OfflineIndicator';
import {useOptionsList} from '@components/OptionListContextProvider';
import {PressableWithFeedback} from '@components/Pressable';
import ReferralProgramCTA from '@components/ReferralProgramCTA';
import ScreenWrapper from '@components/ScreenWrapper';
import SelectCircle from '@components/SelectCircle';
import SelectionList from '@components/SelectionList';
import type {ListItem, SelectionListHandle} from '@components/SelectionList/types';
import UserListItem from '@components/SelectionList/UserListItem';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useDebouncedState from '@hooks/useDebouncedState';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useScreenWrapperTranstionStatus from '@hooks/useScreenWrapperTransitionStatus';
import useStyledSafeAreaInsets from '@hooks/useStyledSafeAreaInsets';
import useThemeStyles from '@hooks/useThemeStyles';
import * as DeviceCapabilities from '@libs/DeviceCapabilities';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import type {OptionData} from '@libs/ReportUtils';
import variables from '@styles/variables';
import * as Report from '@userActions/Report';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {SelectedParticipant} from '@src/types/onyx/NewGroupChatDraft';
type NewChatPageProps = {
isGroupChat?: boolean;
};
const excludedGroupEmails = CONST.EXPENSIFY_EMAILS.filter((value) => value !== CONST.EMAIL.CONCIERGE);
function useOptions({isGroupChat}: NewChatPageProps) {
const [searchTerm, debouncedSearchTerm, setSearchTerm] = useDebouncedState('');
const [selectedOptions, setSelectedOptions] = useState<Array<ListItem & OptionData>>([]);
const [betas] = useOnyx(ONYXKEYS.BETAS);
const [newGroupDraft] = useOnyx(ONYXKEYS.NEW_GROUP_CHAT_DRAFT);
const personalData = useCurrentUserPersonalDetails();
const {didScreenTransitionEnd} = useScreenWrapperTranstionStatus();
const {options: listOptions, areOptionsInitialized} = useOptionsList({
shouldInitialize: didScreenTransitionEnd,
});
const defaultOptions = useMemo(() => {
const filteredOptions = OptionsListUtils.getFilteredOptions(
listOptions.reports ?? [],
listOptions.personalDetails ?? [],
betas ?? [],
'',
selectedOptions,
isGroupChat ? excludedGroupEmails : [],
false,
true,
false,
{},
[],
false,
{},
[],
true,
undefined,
undefined,
0,
undefined,
true,
);
return filteredOptions;
}, [betas, isGroupChat, listOptions.personalDetails, listOptions.reports, selectedOptions]);
const options = useMemo(() => {
const filteredOptions = OptionsListUtils.filterOptions(defaultOptions, debouncedSearchTerm, {
selectedOptions,
excludeLogins: isGroupChat ? excludedGroupEmails : [],
maxRecentReportsToShow: CONST.IOU.MAX_RECENT_REPORTS_TO_SHOW,
});
return filteredOptions;
}, [debouncedSearchTerm, defaultOptions, isGroupChat, selectedOptions]);
const cleanSearchTerm = useMemo(() => debouncedSearchTerm.trim().toLowerCase(), [debouncedSearchTerm]);
const headerMessage = useMemo(() => {
return OptionsListUtils.getHeaderMessage(
options.personalDetails.length + options.recentReports.length !== 0,
!!options.userToInvite,
debouncedSearchTerm.trim(),
selectedOptions.some((participant) => OptionsListUtils.getPersonalDetailSearchTerms(participant).join(' ').toLowerCase?.().includes(cleanSearchTerm)),
);
}, [cleanSearchTerm, debouncedSearchTerm, options.personalDetails.length, options.recentReports.length, options.userToInvite, selectedOptions]);
useEffect(() => {
if (!debouncedSearchTerm.length) {
return;
}
Report.searchInServer(debouncedSearchTerm);
}, [debouncedSearchTerm]);
useEffect(() => {
if (!newGroupDraft?.participants) {
return;
}
const newSelectedOptions: OptionData[] = [];
newGroupDraft.participants.forEach((participant) => {
if (participant.accountID === personalData.accountID) {
return;
}
let participantOption: OptionData | undefined | null = listOptions.personalDetails.find((option) => option.accountID === participant.accountID);
if (!participantOption) {
participantOption = OptionsListUtils.getUserToInviteOption({
searchValue: participant.login,
});
}
if (!participantOption) {
return;
}
newSelectedOptions.push({
...participantOption,
isSelected: true,
});
});
setSelectedOptions(newSelectedOptions);
}, [newGroupDraft?.participants, listOptions.personalDetails, personalData.accountID]);
return {
...options,
searchTerm,
debouncedSearchTerm,
setSearchTerm,
areOptionsInitialized: areOptionsInitialized && didScreenTransitionEnd,
selectedOptions,
setSelectedOptions,
headerMessage,
};
}
function NewChatPage({isGroupChat}: NewChatPageProps) {
const {translate} = useLocalize();
const {isOffline} = useNetwork();
// We need to use isSmallScreenWidth instead of shouldUseNarrowLayout to show offline indicator on small screen only
const {isSmallScreenWidth} = useResponsiveLayout();
const styles = useThemeStyles();
const personalData = useCurrentUserPersonalDetails();
const {insets} = useStyledSafeAreaInsets();
const [isSearchingForReports] = useOnyx(ONYXKEYS.IS_SEARCHING_FOR_REPORTS, {initWithStoredValues: false});
const selectionListRef = useRef<SelectionListHandle>(null);
const {headerMessage, searchTerm, debouncedSearchTerm, setSearchTerm, selectedOptions, setSelectedOptions, recentReports, personalDetails, userToInvite, areOptionsInitialized} =
useOptions({
isGroupChat,
});
const [sections, firstKeyForList] = useMemo(() => {
const sectionsList: OptionsListUtils.CategorySection[] = [];
let firstKey = '';
const formatResults = OptionsListUtils.formatSectionsFromSearchTerm(debouncedSearchTerm, selectedOptions, recentReports, personalDetails);
sectionsList.push(formatResults.section);
if (!firstKey) {
firstKey = OptionsListUtils.getFirstKeyForList(formatResults.section.data);
}
sectionsList.push({
title: translate('common.recents'),
data: recentReports,
shouldShow: !isEmpty(recentReports),
});
if (!firstKey) {
firstKey = OptionsListUtils.getFirstKeyForList(recentReports);
}
sectionsList.push({
title: translate('common.contacts'),
data: personalDetails,
shouldShow: !isEmpty(personalDetails),
});
if (!firstKey) {
firstKey = OptionsListUtils.getFirstKeyForList(personalDetails);
}
if (userToInvite) {
sectionsList.push({
title: undefined,
data: [userToInvite],
shouldShow: true,
});
if (!firstKey) {
firstKey = OptionsListUtils.getFirstKeyForList([userToInvite]);
}
}
return [sectionsList, firstKey];
}, [debouncedSearchTerm, selectedOptions, recentReports, personalDetails, translate, userToInvite]);
/**
* Creates a new 1:1 chat with the option and the current user,
* or navigates to the existing chat if one with those participants already exists.
*/
const createChat = useCallback(
(option?: OptionsListUtils.Option) => {
if (option?.isSelfDM) {
Navigation.dismissModal(option.reportID);
return;
}
let login = '';
if (option?.login) {
login = option.login;
} else if (selectedOptions.length === 1) {
login = selectedOptions[0].login ?? '';
}
if (!login) {
Log.warn('Tried to create chat with empty login');
return;
}
Report.navigateToAndOpenReport([login]);
},
[selectedOptions],
);
const itemRightSideComponent = useCallback(
(item: ListItem & OptionsListUtils.Option, isFocused?: boolean) => {
if (!!item.isSelfDM || (item.accountID && CONST.NON_ADDABLE_ACCOUNT_IDS.includes(item.accountID))) {
return null;
}
/**
* Removes a selected option from list if already selected. If not already selected add this option to the list.
* @param option
*/
function toggleOption(option: ListItem & Partial<OptionData>) {
const isOptionInList = !!option.isSelected;
let newSelectedOptions;
if (isOptionInList) {
newSelectedOptions = reject(selectedOptions, (selectedOption) => selectedOption.login === option.login);
} else {
newSelectedOptions = [...selectedOptions, {...option, isSelected: true, selected: true, reportID: option.reportID ?? '-1'}];
}
selectionListRef?.current?.clearInputAfterSelect?.();
setSelectedOptions(newSelectedOptions);
}
if (item.isSelected) {
return (
<PressableWithFeedback
onPress={() => toggleOption(item)}
disabled={item.isDisabled}
role={CONST.ROLE.BUTTON}
accessibilityLabel={CONST.ROLE.BUTTON}
style={[styles.flexRow, styles.alignItemsCenter, styles.ml3]}
>
<SelectCircle isChecked={item.isSelected} />
</PressableWithFeedback>
);
}
const buttonInnerStyles = isFocused ? styles.buttonDefaultHovered : {};
return (
<Button
onPress={() => toggleOption(item)}
style={[styles.pl2]}
text={translate('newChatPage.addToGroup')}
innerStyles={buttonInnerStyles}
small
/>
);
},
[selectedOptions, setSelectedOptions, styles, translate],
);
const createGroup = useCallback(() => {
if (!personalData || !personalData.login || !personalData.accountID) {
return;
}
const selectedParticipants: SelectedParticipant[] = selectedOptions.map((option: OptionData) => ({login: option.login ?? '', accountID: option.accountID ?? -1}));
const logins = [...selectedParticipants, {login: personalData.login, accountID: personalData.accountID}];
Report.setGroupDraft({participants: logins});
Navigation.navigate(ROUTES.NEW_CHAT_CONFIRM);
}, [selectedOptions, personalData]);
const footerContent = useMemo(
() => (
<>
<ReferralProgramCTA
referralContentType={CONST.REFERRAL_PROGRAM.CONTENT_TYPES.START_CHAT}
style={selectedOptions.length ? styles.mb5 : undefined}
/>
{!!selectedOptions.length && (
<Button
success
large
text={translate('common.next')}
onPress={createGroup}
pressOnEnter
/>
)}
</>
),
[createGroup, selectedOptions.length, styles.mb5, translate],
);
return (
<ScreenWrapper
shouldEnableKeyboardAvoidingView={false}
includeSafeAreaPaddingBottom={isOffline}
shouldShowOfflineIndicator={false}
includePaddingTop={false}
shouldEnablePickerAvoiding={false}
testID={NewChatPage.displayName}
// Disable the focus trap of this page to activate the parent focus trap in `NewChatSelectorPage`.
focusTrapSettings={{active: false}}
>
<KeyboardAvoidingView
style={styles.flex1}
behavior="padding"
// Offset is needed as KeyboardAvoidingView in nested inside of TabNavigator instead of wrapping whole screen.
// This is because when wrapping whole screen the screen was freezing when changing Tabs.
keyboardVerticalOffset={variables.contentHeaderHeight + (insets?.top ?? 0) + variables.tabSelectorButtonHeight + variables.tabSelectorButtonPadding}
>
<SelectionList<OptionsListUtils.Option & ListItem>
ref={selectionListRef}
ListItem={UserListItem}
sections={areOptionsInitialized ? sections : CONST.EMPTY_ARRAY}
textInputValue={searchTerm}
textInputHint={isOffline ? `${translate('common.youAppearToBeOffline')} ${translate('search.resultsAreLimited')}` : ''}
onChangeText={setSearchTerm}
textInputLabel={translate('selectionList.nameEmailOrPhoneNumber')}
headerMessage={headerMessage}
onSelectRow={createChat}
shouldSingleExecuteRowSelect
onConfirm={(e, option) => (selectedOptions.length > 0 ? createGroup() : createChat(option))}
rightHandSideComponent={itemRightSideComponent}
footerContent={footerContent}
showLoadingPlaceholder={!areOptionsInitialized}
shouldPreventDefaultFocusOnSelectRow={!DeviceCapabilities.canUseTouchScreen()}
isLoadingNewOptions={!!isSearchingForReports}
initiallyFocusedOptionKey={firstKeyForList}
shouldTextInputInterceptSwipe
/>
{isSmallScreenWidth && <OfflineIndicator />}
</KeyboardAvoidingView>
</ScreenWrapper>
);
}
NewChatPage.displayName = 'NewChatPage';
export default NewChatPage;