/
Picker.tsx
914 lines (804 loc) 路 24.7 KB
/
Picker.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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
/* eslint-disable no-magic-numbers */
import React from 'react';
import debounce from 'lodash/debounce';
import {
useEmojiData,
UseEmojiDataOptions,
CanonicalEmoji,
Path,
Source,
EmojiDataManager,
} from 'interweave-emoji';
import { Hexcode, SkinTone } from 'emojibase';
import EmojiList from './EmojiList';
import SkinTonePalette from './SkinTonePalette';
import GroupTabs from './GroupTabs';
import PreviewBar from './PreviewBar';
import SearchBar from './SearchBar';
import Context from './Context';
import {
GROUPS,
GROUP_KEY_COMMONLY_USED,
GROUP_KEY_SMILEYS_EMOTION,
GROUP_KEY_SEARCH_RESULTS,
GROUP_KEY_NONE,
SKIN_TONES,
SKIN_KEY_NONE,
KEY_COMMONLY_USED,
KEY_SKIN_TONE,
COMMON_MODE_RECENT,
COMMON_MODE_FREQUENT,
CONTEXT_CLASSNAMES,
CONTEXT_MESSAGES,
SEARCH_THROTTLE,
GROUP_KEY_VARIATIONS,
} from './constants';
import {
CommonEmoji,
CommonMode,
Context as EmojiContext,
DisplayOrder,
GroupKey,
SkinToneKey,
GroupEmojiMap,
} from './types';
export interface AllowBlockMap {
[hexcode: string]: boolean;
}
export interface PickerProps {
/** List of emoji hexcodes to only show. */
allowList?: Hexcode[];
/** Focus the search bar on mount. */
autoFocus?: boolean;
/** List of emoji hexcodes to hide. */
blockList?: Hexcode[];
/** Mapping of custom CSS class names. */
classNames?: { [key: string]: string };
/** Icon to display within the clear commonly used button. Omit the icon to hide the button. */
clearIcon?: React.ReactNode;
/** Number of emojis to display horizontally. */
columnCount?: number;
/** Type of commonly used mode. */
commonMode?: CommonMode;
/** Group to select by default. */
defaultGroup?: GroupKey;
/** Skin tone to select by default (if not found in local storage). */
defaultSkinTone?: SkinToneKey;
/** Disable commonly used functionality. */
disableCommonlyUsed?: boolean;
/** Disable and hide group tabs. */
disableGroups?: boolean;
/** Disable and hide preview bar. */
disablePreview?: boolean;
/** Disable and hide search bar. */
disableSearch?: boolean;
/** Disable and hide skin tone palette bar. */
disableSkinTones?: boolean;
/** Order to render components in. */
displayOrder?: DisplayOrder[];
/** Size of the emoji within the preview bar. */
emojiLargeSize: number;
/** Padding around each emoji. */
emojiPadding?: number;
/** Path to an SVG/PNG. Accepts a string or a callback that is passed the hexcode. */
emojiPath: Path;
/** Pixel size of emoji within the list. */
emojiSize: number;
/** Mapping of custom icons for each group tab. */
groupIcons?: { [key: string]: React.ReactNode };
/** Hide emoticons within the preview bar. */
hideEmoticon?: boolean;
/** Hide group headers within the list. */
hideGroupHeaders?: boolean;
/** Hide shortcodes within the preview bar. */
hideShortcodes?: boolean;
/** Max number of commonly used to store. */
maxCommonlyUsed?: number;
/** Max official emoji release version to support. */
maxEmojiVersion?: number;
/** Mapping of custom translation messages. */
messages?: { [key: string]: string };
/** Content to render by default in the preview bar. */
noPreview?: React.ReactNode;
/** Content to render when there are no search results. */
noResults?: React.ReactNode;
/** Callback fired when hovering an emoji. */
onHoverEmoji?: (emoji: CanonicalEmoji, event: React.MouseEvent<HTMLButtonElement>) => void;
/** Callback fired when scrolling the emoji list. */
onScroll?: () => void;
/** Callback fired when a new group is scrolled into view. */
onScrollGroup?: (group: GroupKey) => void;
/** Callback fired when typing in the search field. */
onSearch?: (query: string, event: React.ChangeEvent<HTMLInputElement>) => void;
/** Callback fired when clicking on an emoji. */
onSelectEmoji?: (emoji: CanonicalEmoji, event: React.MouseEvent<HTMLButtonElement>) => void;
/** Callback fired when clicking a group tab. */
onSelectGroup?: (group: GroupKey, event: React.MouseEvent<HTMLButtonElement>) => void;
/** Callback fired when clicking a skin tone. */
onSelectSkinTone?: (skinTone: SkinToneKey, event: React.MouseEvent<HTMLButtonElement>) => void;
/** Number of emoji rows to display vertically. */
rowCount?: number;
/** Mapping of custom icons for each skin tone. */
skinIcons?: { [key: string]: React.ReactNode };
/** Sticky the active group header to the top of the emoji list. */
stickyGroupHeader?: boolean;
/** Custom props to pass to react-window list component. */
virtual?: {
columnPadding?: number;
rowPadding?: number;
};
}
export interface InternalPickerProps extends PickerProps {
/** List of all emojis. */
emojis: CanonicalEmoji[];
/** Data manager instance. */
emojiData: EmojiDataManager;
/** Emoji data source metadata. */
emojiSource: Source;
}
export interface InternalPickerState {
/** Emoji to display in the preview. */
activeEmoji: CanonicalEmoji | null;
/** Index for the highlighted emoji within search results. */
activeEmojiIndex: number;
/** Currently selected group tab. */
activeGroup: GroupKey;
/** Currently selected skin tone. */
activeSkinTone: SkinToneKey;
/** List of emoji hexcodes most commonly used. */
commonEmojis: CanonicalEmoji[];
/** React context. */
context: EmojiContext;
/** List of all emojis with search filtering applied. */
emojis: CanonicalEmoji[];
/** Filtered emojis grouped by group number. */
groupedEmojis: GroupEmojiMap;
/** Group to scroll to on render. */
scrollToGroup: GroupKey | '';
/** Current search query. */
searchQuery: string;
}
const SKIN_MODIFIER_PATTERN = /1F3FB|1F3FC|1F3FD|1F3FE|1F3FF/g;
export class InternalPicker extends React.PureComponent<InternalPickerProps, InternalPickerState> {
static defaultProps: Partial<InternalPickerProps> = {
allowList: [],
autoFocus: false,
blockList: [],
classNames: {},
clearIcon: null,
columnCount: 10,
commonMode: COMMON_MODE_RECENT,
defaultGroup: GROUP_KEY_COMMONLY_USED,
defaultSkinTone: SKIN_KEY_NONE,
disableCommonlyUsed: false,
disableGroups: false,
disablePreview: false,
disableSearch: false,
disableSkinTones: false,
displayOrder: ['preview', 'emojis', 'groups', 'search'],
emojiPadding: 0,
groupIcons: {},
hideEmoticon: false,
hideGroupHeaders: false,
hideShortcodes: false,
maxCommonlyUsed: 30,
maxEmojiVersion: 5,
messages: {},
noPreview: null,
noResults: null,
onHoverEmoji() {},
onScroll() {},
onScrollGroup() {},
onSearch() {},
onSelectEmoji() {},
onSelectGroup() {},
onSelectSkinTone() {},
rowCount: 8,
skinIcons: {},
stickyGroupHeader: false,
virtual: {},
};
allowList: AllowBlockMap;
blockList: AllowBlockMap;
constructor(props: InternalPickerProps) {
super(props);
const { blockList, classNames, defaultSkinTone, messages, allowList } = props as Required<
InternalPickerProps
>;
this.allowList = this.generateAllowBlockMap(allowList);
this.blockList = this.generateAllowBlockMap(blockList);
const searchQuery = '';
const commonEmojis = this.generateCommonEmojis(this.getCommonEmojisFromStorage());
const activeGroup = this.getActiveGroup(commonEmojis.length > 0);
const activeSkinTone = this.getSkinToneFromStorage() || defaultSkinTone;
const emojis = this.generateEmojis(activeSkinTone, searchQuery);
const groupedEmojis = this.groupEmojis(emojis, commonEmojis, searchQuery);
this.state = {
activeEmoji: null,
activeEmojiIndex: -1,
activeGroup,
activeSkinTone,
commonEmojis,
context: {
classNames: {
...CONTEXT_CLASSNAMES,
...classNames,
},
emojiLargeSize: props.emojiLargeSize,
emojiPadding: props.emojiPadding!,
emojiPath: props.emojiPath,
emojiSize: props.emojiSize,
emojiSource: props.emojiSource,
messages: {
...CONTEXT_MESSAGES,
...messages,
},
},
emojis,
groupedEmojis,
scrollToGroup: activeGroup,
searchQuery,
};
}
/**
* Add a common emoji to local storage and update the current state.
*/
addCommonEmoji(emoji: CanonicalEmoji) {
const { commonMode, disableCommonlyUsed, maxCommonlyUsed } = this.props;
const { hexcode } = emoji;
if (disableCommonlyUsed) {
return;
}
const commonEmojis = this.getCommonEmojisFromStorage();
const currentIndex = commonEmojis.findIndex(common => common.hexcode === hexcode);
// Add to the front of the list if it doesnt exist
if (currentIndex === -1) {
commonEmojis.unshift({
count: 1,
hexcode,
});
}
// Move to the front of the list and increase count
if (commonMode === COMMON_MODE_RECENT) {
if (currentIndex >= 1) {
const [common] = commonEmojis.splice(currentIndex, 1);
commonEmojis.unshift({
count: common.count + 1,
hexcode,
});
}
// Increase count and sort by usage
} else if (commonMode === COMMON_MODE_FREQUENT) {
if (currentIndex >= 0) {
commonEmojis[currentIndex].count += 1;
}
commonEmojis.sort((a, b) => b.count - a.count);
}
// Trim to the max and store locally
try {
localStorage.setItem(
KEY_COMMONLY_USED,
JSON.stringify(commonEmojis.slice(0, maxCommonlyUsed)),
);
} catch (error) {
// Do nothing
}
this.setUpdatedState({
commonEmojis: this.generateCommonEmojis(commonEmojis),
});
}
/**
* Filter the dataset with the search query against a set of emoji properties.
*/
// eslint-disable-next-line complexity
filterOrSearch(emoji: CanonicalEmoji, searchQuery: string): boolean {
const { blockList, maxEmojiVersion, allowList } = this.props as Required<InternalPickerProps>;
// Remove blocked emojis and non-allowed emojis
if (
(blockList.length > 0 && this.blockList[emoji.hexcode]) ||
(allowList.length > 0 && !this.allowList[emoji.hexcode])
) {
return false;
}
// Remove emojis released in newer versions (compact doesnt have a version)
if (emoji.version && emoji.version > maxEmojiVersion) {
return false;
}
// No query to filter with
if (!searchQuery) {
return true;
}
const lookups = [];
if (emoji.canonical_shortcodes) {
lookups.push(...emoji.canonical_shortcodes);
}
if (emoji.tags) {
lookups.push(...emoji.tags);
}
if (emoji.annotation) {
lookups.push(emoji.annotation);
}
if (emoji.emoticon) {
lookups.push(emoji.emoticon);
}
const haystack = lookups.join(' ').toLowerCase();
// Support multi-word and case-insensitive searches
return searchQuery
.toLowerCase()
.split(' ')
.some(needle => haystack.includes(needle));
}
/**
* Return the list of emojis filtered with the search query if applicable,
* and with skin tone applied if set.
*/
generateEmojis(skinTone: SkinToneKey, searchQuery: string): CanonicalEmoji[] {
return this.props.emojis
.filter(emoji => this.filterOrSearch(emoji, searchQuery))
.map(emoji => this.getSkinnedEmoji(emoji, skinTone));
}
/**
* Convert the `blockList` or `allowList` prop to a map for quicker lookups.
*/
generateAllowBlockMap(list: string[]): AllowBlockMap {
const map: AllowBlockMap = {};
list.forEach(hexcode => {
if (__DEV__) {
if (hexcode.match(SKIN_MODIFIER_PATTERN)) {
// eslint-disable-next-line no-console
console.warn(
`Hexcode with a skin modifier has been detected: ${hexcode}`,
'Emojis without skin modifiers are required for allow/block lists.',
);
}
}
map[hexcode] = true;
});
return map;
}
/**
* We only store the hexcode character for commonly used emojis,
* so we need to rebuild the list with full emoji objects.
*/
generateCommonEmojis(commonEmojis: CommonEmoji[]): CanonicalEmoji[] {
if (this.props.disableCommonlyUsed) {
return [];
}
const data = this.props.emojiData;
return commonEmojis.map(emoji => data.EMOJIS[emoji.hexcode]).filter(Boolean);
}
/**
* Return the default group while handling commonly used scenarios.
*/
getActiveGroup(hasCommon: boolean): GroupKey {
const { defaultGroup, disableGroups } = this.props;
let group = defaultGroup!;
// Allow commonly used before "none" groups
if (group === GROUP_KEY_COMMONLY_USED) {
if (hasCommon) {
return group;
}
group = GROUP_KEY_SMILEYS_EMOTION;
}
return disableGroups ? GROUP_KEY_NONE : group;
}
/**
* Return the commonly used emojis from local storage.
*/
getCommonEmojisFromStorage(): CommonEmoji[] {
if (this.props.disableCommonlyUsed) {
return [];
}
const common = localStorage.getItem(KEY_COMMONLY_USED);
return common ? JSON.parse(common) : [];
}
/**
* Return an emoji with skin tone if the active skin tone is set,
* otherwise return the default skin tone (yellow).
*/
getSkinnedEmoji(emoji: CanonicalEmoji, skinTone: SkinToneKey): CanonicalEmoji {
if (skinTone === SKIN_KEY_NONE || !emoji.skins) {
return emoji;
}
const toneIndex = SKIN_TONES.findIndex(tone => tone === skinTone);
const skinnedEmoji = (emoji.skins || []).find(
skin =>
!!skin.tone &&
(skin.tone === toneIndex ||
(Array.isArray(skin.tone) && skin.tone.includes(toneIndex as SkinTone))),
);
return (skinnedEmoji || emoji) as CanonicalEmoji;
}
/**
* Return the user's favorite skin tone from local storage.
*/
getSkinToneFromStorage(): SkinToneKey | null {
const tone = localStorage.getItem(KEY_SKIN_TONE);
if (tone) {
return tone as SkinToneKey;
}
return null;
}
/**
* Partition the dataset into multiple arrays based on the group they belong to.
*/
groupEmojis(
emojis: CanonicalEmoji[],
commonEmojis: CanonicalEmoji[],
searchQuery: string,
): GroupEmojiMap {
const { disableGroups } = this.props;
const groups: GroupEmojiMap = {};
// Add commonly used group if not searching
if (!searchQuery && commonEmojis.length > 0) {
groups[GROUP_KEY_COMMONLY_USED] = {
emojis: commonEmojis,
group: GROUP_KEY_COMMONLY_USED,
};
}
// Partition emojis into separate groups
emojis.forEach(emoji => {
let group: GroupKey = GROUP_KEY_NONE;
if (searchQuery) {
group = GROUP_KEY_SEARCH_RESULTS;
} else if (!disableGroups && typeof emoji.group !== 'undefined') {
group = GROUPS[emoji.group];
}
if (!group) {
return;
}
if (groups[group]) {
groups[group].emojis.push(emoji);
} else {
groups[group] = {
emojis: [emoji],
group,
};
}
});
// Sort each group
Object.keys(groups).forEach(group => {
if (group !== GROUP_KEY_COMMONLY_USED) {
groups[group].emojis.sort((a, b) => (a.order || 0) - (b.order || 0));
}
// Remove the group if no emojis
if (groups[group].emojis.length === 0) {
delete groups[group];
}
});
return groups;
}
/**
* Triggered when common emoji cache or variation window is cleared.
*/
private handleClear = () => {
if (this.state.activeGroup === GROUP_KEY_VARIATIONS) {
this.setUpdatedState(
{
activeGroup: this.state.searchQuery
? GROUP_KEY_SEARCH_RESULTS
: GROUP_KEY_SMILEYS_EMOTION,
},
true,
);
} else {
this.setUpdatedState({
commonEmojis: [],
});
localStorage.removeItem(KEY_COMMONLY_USED);
}
};
/**
* Triggered when the mouse hovers an emoji.
*/
private handleEnterEmoji = (
emoji: CanonicalEmoji,
event: React.MouseEvent<HTMLButtonElement>,
) => {
this.setUpdatedState({
activeEmoji: emoji,
});
this.props.onHoverEmoji!(emoji, event);
};
/**
* Triggered when keyboard changes occur.
*/
private handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
const { columnCount = 10 } = this.props;
const { activeEmoji, activeEmojiIndex, emojis, searchQuery } = this.state;
// Keyboard functionality is only available while searching
if (!searchQuery) {
return;
}
// Reset search
if (event.key === 'Escape') {
event.preventDefault();
// @ts-ignore Allow other event
this.handleSearch('', event);
// Select active emoji
} else if (event.key === 'Enter') {
event.preventDefault();
if (activeEmoji) {
// @ts-ignore Allow other event
this.handleSelectEmoji(activeEmoji, event);
}
// Cycle search results
} else {
event.preventDefault();
let nextIndex = -1;
switch (event.key) {
case 'ArrowLeft':
nextIndex = activeEmojiIndex - 1;
break;
case 'ArrowRight':
nextIndex = activeEmojiIndex + 1;
break;
case 'ArrowUp':
nextIndex = activeEmojiIndex - columnCount;
break;
case 'ArrowDown':
nextIndex = activeEmojiIndex + columnCount;
break;
default:
return;
}
if (nextIndex >= 0 && nextIndex < emojis.length) {
this.setUpdatedState({
activeEmojiIndex: nextIndex,
});
// @ts-ignore Allow other event
this.handleEnterEmoji(emojis[nextIndex], event);
}
}
};
/**
* Triggered when the mouse no longer hovers an emoji.
*/
private handleLeaveEmoji = () => {
this.setUpdatedState({
activeEmoji: null,
});
};
/**
* Triggered when a group is scrolled into view.
*/
private handleScrollGroup = (group: GroupKey) => {
this.setUpdatedState({
activeGroup: group,
scrollToGroup: '',
});
this.props.onScrollGroup!(group);
};
/**
* Triggered when the search input field value changes.
*/
private handleSearch = (query: string, event: React.ChangeEvent<HTMLInputElement>) => {
// Bypass custom logic and set immediately
this.setState({
searchQuery: query,
});
this.handleSearchDebounced(query);
this.props.onSearch!(query, event);
};
private handleSearchDebounced = debounce(query => {
this.setUpdatedState({
searchQuery: query,
});
}, SEARCH_THROTTLE);
/**
* Triggered when an emoji is clicked.
*/
private handleSelectEmoji = (
emoji: CanonicalEmoji,
event: React.MouseEvent<HTMLButtonElement>,
) => {
this.addCommonEmoji(emoji);
if (event.shiftKey && emoji.skins && emoji.skins.length > 0) {
// Avoid bulk logic when using `setUpdatedState`
this.setState({
activeEmoji: emoji,
activeEmojiIndex: 0,
activeGroup: GROUP_KEY_VARIATIONS,
emojis: emoji.skins,
groupedEmojis: {
[GROUP_KEY_VARIATIONS]: {
emojis: emoji.skins,
group: GROUP_KEY_VARIATIONS,
},
},
scrollToGroup: GROUP_KEY_VARIATIONS,
});
} else {
this.props.onSelectEmoji!(emoji, event);
}
};
/**
* Triggered when a group tab is clicked. We should reset search and scroll position.
*/
private handleSelectGroup = (group: GroupKey, event: React.MouseEvent<HTMLButtonElement>) => {
this.setUpdatedState({
activeGroup: group,
scrollToGroup: group,
});
this.props.onSelectGroup!(group, event);
};
/**
* Triggered when a skin tone is clicked.
*/
private handleSelectSkinTone = (
skinTone: SkinToneKey,
event: React.MouseEvent<HTMLButtonElement>,
) => {
this.setUpdatedState({
activeSkinTone: skinTone,
});
try {
localStorage.setItem(KEY_SKIN_TONE, skinTone);
} catch (error) {
// Do nothing
}
this.props.onSelectSkinTone!(skinTone, event);
};
/**
* Catch all method to easily update the state. Will automatically handle updates
* and branching based on values being set.
*/
setUpdatedState(nextState: Partial<InternalPickerState>, forceRebuild: boolean = false) {
// eslint-disable-next-line complexity
this.setState(prevState => {
const state = { ...prevState, ...nextState };
const activeGroup = this.getActiveGroup(state.commonEmojis.length > 0);
let rebuildEmojis = false;
// Common emojis have changed
if ('commonEmojis' in nextState) {
rebuildEmojis = true;
// Reset the active group
if (state.commonEmojis.length === 0) {
state.activeGroup = activeGroup;
}
}
// Active group has changed
if ('activeGroup' in nextState) {
// Reset search query
if (state.searchQuery) {
state.searchQuery = '';
rebuildEmojis = true;
}
}
// Active skin tone has changed
if ('activeSkinTone' in nextState) {
rebuildEmojis = true;
}
// Search query has changed
if ('searchQuery' in nextState) {
rebuildEmojis = true;
state.activeGroup = state.searchQuery ? GROUP_KEY_SEARCH_RESULTS : activeGroup;
state.scrollToGroup = state.searchQuery ? GROUP_KEY_SEARCH_RESULTS : activeGroup;
}
// Rebuild the emoji datasets
if (rebuildEmojis || forceRebuild) {
state.emojis = this.generateEmojis(state.activeSkinTone, state.searchQuery);
state.groupedEmojis = this.groupEmojis(state.emojis, state.commonEmojis, state.searchQuery);
const hasResults = state.searchQuery && state.emojis.length > 0;
state.activeEmoji = hasResults ? state.emojis[0] : null;
state.activeEmojiIndex = hasResults ? 0 : -1;
}
return state;
});
}
render() {
const {
autoFocus,
clearIcon,
columnCount,
commonMode,
disableGroups,
disablePreview,
disableSearch,
disableSkinTones,
displayOrder,
groupIcons,
hideEmoticon,
hideGroupHeaders,
hideShortcodes,
noPreview,
noResults,
rowCount,
skinIcons,
stickyGroupHeader,
virtual,
onScroll,
} = this.props as Required<InternalPickerProps>;
const {
activeEmoji,
activeGroup,
activeSkinTone,
commonEmojis,
context,
groupedEmojis,
scrollToGroup,
searchQuery,
} = this.state;
const skinTones = disableSkinTones ? null : (
<SkinTonePalette
key="skin-tones"
activeSkinTone={activeSkinTone}
icons={skinIcons}
onSelect={this.handleSelectSkinTone}
/>
);
const components: { [name: string]: React.ReactElement<unknown> | null } = {
emojis: (
<EmojiList
key="emojis"
{...virtual}
activeEmoji={activeEmoji}
activeGroup={activeGroup}
clearIcon={clearIcon}
columnCount={columnCount}
commonMode={commonMode}
groupedEmojis={groupedEmojis}
hideGroupHeaders={hideGroupHeaders}
noResults={noResults}
rowCount={rowCount}
scrollToGroup={scrollToGroup}
skinTonePalette={displayOrder.includes('skin-tones') ? null : skinTones}
stickyGroupHeader={stickyGroupHeader}
onClear={this.handleClear}
onEnterEmoji={this.handleEnterEmoji}
onLeaveEmoji={this.handleLeaveEmoji}
onScroll={onScroll}
onScrollGroup={this.handleScrollGroup}
onSelectEmoji={this.handleSelectEmoji}
/>
),
groups: disableGroups ? null : (
<GroupTabs
key="groups"
activeGroup={activeGroup}
commonEmojis={commonEmojis}
commonMode={commonMode}
icons={groupIcons}
onSelect={this.handleSelectGroup}
/>
),
preview: disablePreview ? null : (
<PreviewBar
key="preview"
emoji={activeEmoji}
hideEmoticon={hideEmoticon}
hideShortcodes={hideShortcodes}
noPreview={noPreview}
/>
),
search: disableSearch ? null : (
<SearchBar
key="search"
autoFocus={autoFocus}
searchQuery={searchQuery}
onChange={this.handleSearch}
onKeyUp={this.handleKeyUp}
/>
),
'skin-tones': skinTones,
};
return (
<Context.Provider value={context}>
<div className={context.classNames.picker}>{displayOrder.map(key => components[key])}</div>
</Context.Provider>
);
}
}
export default function Picker({
compact,
locale,
throwErrors,
version,
...props
}: PickerProps & UseEmojiDataOptions) {
const [emojis, source, data] = useEmojiData({ compact, locale, throwErrors, version });
if (emojis.length === 0) {
return null;
}
return <InternalPicker {...props} emojis={emojis} emojiData={data} emojiSource={source} />;
}