-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.js
executable file
·367 lines (325 loc) · 14.7 KB
/
index.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
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {View} from 'react-native';
import {scrollTo} from 'react-native-reanimated';
import _ from 'underscore';
import EmojiPickerMenuItem from '@components/EmojiPicker/EmojiPickerMenuItem';
import Text from '@components/Text';
import TextInput from '@components/TextInput';
import useArrowKeyFocusManager from '@hooks/useArrowKeyFocusManager';
import useLocalize from '@hooks/useLocalize';
import useSingleExecution from '@hooks/useSingleExecution';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import * as Browser from '@libs/Browser';
import canFocusInputOnScreenFocus from '@libs/canFocusInputOnScreenFocus';
import * as EmojiUtils from '@libs/EmojiUtils';
import isEnterWhileComposition from '@libs/KeyboardShortcut/isEnterWhileComposition';
import * as ReportUtils from '@libs/ReportUtils';
import CONST from '@src/CONST';
import BaseEmojiPickerMenu from './BaseEmojiPickerMenu';
import emojiPickerMenuPropTypes from './emojiPickerMenuPropTypes';
import useEmojiPickerMenu from './useEmojiPickerMenu';
const propTypes = {
/** The ref to the search input (may be null on small screen widths) */
forwardedRef: PropTypes.func,
...emojiPickerMenuPropTypes,
};
const defaultProps = {
forwardedRef: () => {},
};
const throttleTime = Browser.isMobile() ? 200 : 50;
function EmojiPickerMenu({forwardedRef, onEmojiSelected, activeEmoji}) {
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {isSmallScreenWidth, windowWidth} = useWindowDimensions();
const {translate} = useLocalize();
const {singleExecution} = useSingleExecution();
const {
allEmojis,
headerEmojis,
headerRowIndices,
filteredEmojis,
headerIndices,
setFilteredEmojis,
setHeaderIndices,
isListFiltered,
suggestEmojis,
preferredSkinTone,
listStyle,
emojiListRef,
spacersIndexes,
} = useEmojiPickerMenu();
// Ref for the emoji search input
const searchInputRef = useRef(null);
// We want consistent auto focus behavior on input between native and mWeb so we have some auto focus management code that will
// prevent auto focus when open picker for mobile device
const shouldFocusInputOnScreenFocus = canFocusInputOnScreenFocus();
const [arePointerEventsDisabled, setArePointerEventsDisabled] = useState(false);
const [isFocused, setIsFocused] = useState(false);
const [isUsingKeyboardMovement, setIsUsingKeyboardMovement] = useState(false);
const [highlightEmoji, setHighlightEmoji] = useState(false);
const [highlightFirstEmoji, setHighlightFirstEmoji] = useState(false);
const mouseMoveHandler = useCallback(() => {
if (!arePointerEventsDisabled) {
return;
}
setArePointerEventsDisabled(false);
}, [arePointerEventsDisabled]);
const onFocusedIndexChange = useCallback(
(newIndex) => {
if (filteredEmojis.length === 0) {
return;
}
if (highlightFirstEmoji) {
setHighlightFirstEmoji(false);
}
if (!isUsingKeyboardMovement) {
setIsUsingKeyboardMovement(true);
}
// If the input is not focused and the new index is out of range, focus the input
if (newIndex < 0 && !searchInputRef.current.isFocused() && shouldFocusInputOnScreenFocus) {
searchInputRef.current.focus();
}
},
[filteredEmojis.length, highlightFirstEmoji, isUsingKeyboardMovement, shouldFocusInputOnScreenFocus],
);
const disabledIndexes = useMemo(() => (isListFiltered ? [] : [...headerIndices, ...spacersIndexes]), [headerIndices, isListFiltered, spacersIndexes]);
const [focusedIndex, setFocusedIndex] = useArrowKeyFocusManager({
maxIndex: filteredEmojis.length - 1,
// Spacers indexes need to be disabled so that the arrow keys don't focus them. All headers are hidden when list is filtered
disabledIndexes,
itemsPerRow: CONST.EMOJI_NUM_PER_ROW,
initialFocusedIndex: -1,
disableCyclicTraversal: true,
onFocusedIndexChange,
disableHorizontalKeys: isFocused,
// We pass true without checking visibility of the component because if the popover is not visible this picker won't be mounted
isActive: true,
});
const filterEmojis = _.throttle((searchTerm) => {
const [normalizedSearchTerm, newFilteredEmojiList] = suggestEmojis(searchTerm);
if (emojiListRef.current) {
scrollTo(emojiListRef, 0, 0, false);
}
if (normalizedSearchTerm === '') {
// There are no headers when searching, so we need to re-make them sticky when there is no search term
setFilteredEmojis(allEmojis);
setHeaderIndices(headerRowIndices);
setFocusedIndex(-1);
setHighlightEmoji(false);
return;
}
// Remove sticky header indices. There are no headers while searching and we don't want to make emojis sticky
setFilteredEmojis(newFilteredEmojiList);
setHeaderIndices([]);
setHighlightFirstEmoji(true);
setIsUsingKeyboardMovement(false);
}, throttleTime);
const keyDownHandler = useCallback(
(keyBoardEvent) => {
if (keyBoardEvent.key.startsWith('Arrow')) {
if (!isFocused || keyBoardEvent.key === 'ArrowUp' || keyBoardEvent.key === 'ArrowDown') {
keyBoardEvent.preventDefault();
}
return;
}
// Select the currently highlighted emoji if enter is pressed
if (!isEnterWhileComposition(keyBoardEvent) && keyBoardEvent.key === CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey) {
let indexToSelect = focusedIndex;
if (highlightFirstEmoji) {
indexToSelect = 0;
}
const item = filteredEmojis[indexToSelect];
if (!item) {
return;
}
const emoji = lodashGet(item, ['types', preferredSkinTone], item.code);
onEmojiSelected(emoji, item);
// On web, avoid this Enter default input action; otherwise, it will add a new line in the subsequently focused composer.
keyBoardEvent.preventDefault();
// On mWeb, avoid propagating this Enter keystroke to Pressable child component; otherwise, it will trigger the onEmojiSelected callback again.
keyBoardEvent.stopPropagation();
return;
}
// Enable keyboard movement if tab or enter is pressed or if shift is pressed while the input
// is not focused, so that the navigation and tab cycling can be done using the keyboard without
// interfering with the input behaviour.
if (keyBoardEvent.key === 'Tab' || keyBoardEvent.key === 'Enter' || (keyBoardEvent.key === 'Shift' && searchInputRef.current && !searchInputRef.current.isFocused())) {
setIsUsingKeyboardMovement(true);
}
// We allow typing in the search box if any key is pressed apart from Arrow keys.
if (searchInputRef.current && !searchInputRef.current.isFocused() && ReportUtils.shouldAutoFocusOnKeyPress(keyBoardEvent)) {
searchInputRef.current.focus();
}
},
[filteredEmojis, focusedIndex, highlightFirstEmoji, isFocused, onEmojiSelected, preferredSkinTone],
);
/**
* Setup and attach keypress/mouse handlers for highlight navigation.
*/
const setupEventHandlers = useCallback(() => {
if (!document) {
return;
}
// Keyboard events are not bubbling on TextInput in RN-Web, Bubbling was needed for this event to trigger
// event handler attached to document root. To fix this, trigger event handler in Capture phase.
document.addEventListener('keydown', keyDownHandler, true);
// Re-enable pointer events and hovering over EmojiPickerItems when the mouse moves
document.addEventListener('mousemove', mouseMoveHandler);
}, [keyDownHandler, mouseMoveHandler]);
/**
* Cleanup all mouse/keydown event listeners that we've set up
*/
const cleanupEventHandlers = useCallback(() => {
if (!document) {
return;
}
document.removeEventListener('keydown', keyDownHandler, true);
document.removeEventListener('mousemove', mouseMoveHandler);
}, [keyDownHandler, mouseMoveHandler]);
useEffect(() => {
// This callback prop is used by the parent component using the constructor to
// get a ref to the inner textInput element e.g. if we do
// <constructor ref={el => this.textInput = el} /> this will not
// return a ref to the component, but rather the HTML element by default
if (shouldFocusInputOnScreenFocus && forwardedRef && _.isFunction(forwardedRef)) {
forwardedRef(searchInputRef.current);
}
setupEventHandlers();
return () => {
cleanupEventHandlers();
};
}, [forwardedRef, shouldFocusInputOnScreenFocus, cleanupEventHandlers, setupEventHandlers]);
const scrollToHeader = useCallback(
(headerIndex) => {
if (!emojiListRef.current) {
return;
}
const calculatedOffset = Math.floor(headerIndex / CONST.EMOJI_NUM_PER_ROW) * CONST.EMOJI_PICKER_HEADER_HEIGHT;
scrollTo(emojiListRef, 0, calculatedOffset, true);
},
[emojiListRef],
);
/**
* Given an emoji item object, render a component based on its type.
* Items with the code "SPACER" return nothing and are used to fill rows up to 8
* so that the sticky headers function properly.
*
* @param {Object} item
* @param {Number} index
* @returns {*}
*/
const renderItem = useCallback(
({item, index, target}) => {
const {code, types} = item;
if (item.spacer) {
return null;
}
if (item.header) {
return (
<View style={[styles.emojiHeaderContainer, target === 'StickyHeader' ? styles.stickyHeaderEmoji(isSmallScreenWidth, windowWidth) : undefined]}>
<Text style={styles.textLabelSupporting}>{translate(`emojiPicker.headers.${code}`)}</Text>
</View>
);
}
const emojiCode = types && types[preferredSkinTone] ? types[preferredSkinTone] : code;
const isEmojiFocused = index === focusedIndex && isUsingKeyboardMovement;
const shouldEmojiBeHighlighted =
(index === focusedIndex && highlightEmoji) || (Boolean(activeEmoji) && EmojiUtils.getRemovedSkinToneEmoji(emojiCode) === EmojiUtils.getRemovedSkinToneEmoji(activeEmoji));
const shouldFirstEmojiBeHighlighted = index === 0 && highlightFirstEmoji;
return (
<EmojiPickerMenuItem
onPress={singleExecution((emoji) => onEmojiSelected(emoji, item))}
onHoverIn={() => {
setHighlightEmoji(false);
setHighlightFirstEmoji(false);
if (!isUsingKeyboardMovement) {
return;
}
setIsUsingKeyboardMovement(false);
}}
emoji={emojiCode}
onFocus={() => setFocusedIndex(index)}
isFocused={isEmojiFocused}
isHighlighted={shouldFirstEmojiBeHighlighted || shouldEmojiBeHighlighted}
/>
);
},
[
preferredSkinTone,
focusedIndex,
isUsingKeyboardMovement,
highlightEmoji,
highlightFirstEmoji,
singleExecution,
styles,
isSmallScreenWidth,
windowWidth,
translate,
onEmojiSelected,
setFocusedIndex,
activeEmoji,
],
);
return (
<View
style={[
styles.emojiPickerContainer,
StyleUtils.getEmojiPickerStyle(isSmallScreenWidth),
// Disable pointer events so that onHover doesn't get triggered when the items move while we're scrolling
arePointerEventsDisabled ? styles.pointerEventsNone : styles.pointerEventsAuto,
]}
>
<View style={[styles.ph4, styles.pb3, styles.pt2]}>
<TextInput
label={translate('common.search')}
accessibilityLabel={translate('common.search')}
role={CONST.ROLE.PRESENTATION}
onChangeText={filterEmojis}
defaultValue=""
ref={searchInputRef}
autoFocus={shouldFocusInputOnScreenFocus}
onFocus={() => {
setFocusedIndex(-1);
setIsFocused(true);
setIsUsingKeyboardMovement(false);
}}
onBlur={() => setIsFocused(false)}
autoCorrect={false}
blurOnSubmit={filteredEmojis.length > 0}
/>
</View>
<BaseEmojiPickerMenu
isFiltered={isListFiltered}
headerEmojis={headerEmojis}
scrollToHeader={scrollToHeader}
listWrapperStyle={[
listStyle,
// Set scrollPaddingTop to consider sticky headers while scrolling
{scrollPaddingTop: isListFiltered ? 0 : CONST.EMOJI_PICKER_ITEM_HEIGHT},
styles.flexShrink1,
]}
ref={emojiListRef}
data={filteredEmojis}
renderItem={renderItem}
extraData={[focusedIndex, preferredSkinTone]}
stickyHeaderIndices={headerIndices}
/>
</View>
);
}
EmojiPickerMenu.displayName = 'EmojiPickerMenu';
EmojiPickerMenu.propTypes = propTypes;
EmojiPickerMenu.defaultProps = defaultProps;
const EmojiPickerMenuWithRef = React.forwardRef((props, ref) => (
<EmojiPickerMenu
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
forwardedRef={ref}
/>
));
EmojiPickerMenuWithRef.displayName = 'EmojiPickerMenuWithRef';
export default EmojiPickerMenuWithRef;