-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
emoji_search.js
287 lines (257 loc) · 8.73 KB
/
emoji_search.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
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_elements/cr_search_field/cr_search_field.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {EmojiButton} from './emoji_button.js';
import {EmojiCategoryButton} from './emoji_category_button.js';
import Fuse from './fuse.js';
import {CategoryEnum, EmojiGroupData, EmojiVariants} from './types.js';
/**
* @typedef {!Array<{item: !EmojiVariants}>} FuseResults
*/
let FuseResults;
export class EmojiSearch extends PolymerElement {
static get is() {
return 'emoji-search';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/** @type {EmojiGroupData} */
emojiData: {type: Array, readonly: true},
/** @type {EmojiGroupData} */
emoticonData: {type: Array, readonly: true},
/** @type {!string} */
search: {type: String, notify: true},
/** @private {!Array<!EmojiVariants>} */
emojiList: {
type: Array,
computed: 'computeEmojiList(emojiData,emojiData.length)',
observer: 'onEmojiListChanged'
},
/** @private {!Array<!EmojiVariants>} */
emoticonList: {
type: Array,
computed: 'computeEmojiList(emoticonData)',
observer: 'onEmoticonListChanged'
},
/** @private {!Array<!EmojiVariants>} */
emojiResults:
{type: Array, computed: 'computeSearchResults(search, \'emoji\')'},
/** @private {!Array<!EmojiVariants>} */
emoticonResults:
{type: Array, computed: 'computeSearchResults(search, \'emoticon\')'},
/** @private {!boolean} */
v2Enabled: {
type: Boolean,
value: false,
reflectToAttribute: true,
readonly: true
}
};
}
constructor() {
super();
const fuseConfig = {
threshold: 0.0, // Exact match only.
ignoreLocation: true, // Match in all locations.
keys: [
{name: 'base.name', weight: 10}, // Increase scoring of emoji name.
'base.keywords',
]
};
this.emojiFuse = new Fuse([], fuseConfig);
this.emoticonFuse = new Fuse([], fuseConfig);
this.addEventListener('scroll', () => {
this.onSearchScroll();
});
}
ready() {
super.ready();
this.addEventListener('search', ev => this.onSearch(ev.detail));
this.$.search.getSearchInput().addEventListener(
'keydown',
(ev) => this.onSearchKeyDown(/** @type {KeyboardEvent} */ (ev)));
this.addEventListener(
'keydown', ev => this.onKeyDown(/** @type {KeyboardEvent} */ (ev)));
}
onSearch(newSearch) {
this.search = newSearch;
}
/**
* Event handler for keydown anywhere in the search component.
* Used to move the focused result up/down on arrow presses.
* @param {KeyboardEvent} ev
*/
onKeyDown(ev) {
const isUp = ev.key === 'ArrowUp';
const isDown = ev.key === 'ArrowDown';
const isEnter = ev.key === 'Enter';
// get emoji-button which has focus.
/** @type {Element} */
const focusedResult = this.shadowRoot.querySelector('.result:focus-within');
if (isEnter && focusedResult) {
focusedResult.click();
}
if (!isUp && !isDown)
return;
ev.preventDefault();
ev.stopPropagation();
if (!focusedResult)
return;
const prev = focusedResult.previousElementSibling;
const next = focusedResult.nextElementSibling;
// moving up from first result focuses search box.
// need to check classList in case prev is sr-only.
if (isUp && prev && !prev.classList.contains('result')) {
this.$.search.getSearchInput().focus();
return;
}
const newResult = isDown ? next : prev;
if (newResult) {
newResult.focus();
}
}
/**
* Event handler for keydown on the search input. Used to switch focus to the
* results list on down arrow or enter key presses.
* @param {KeyboardEvent} ev
*/
onSearchKeyDown(ev) {
// if not searching or no results, do nothing.
if (!this.search ||
(this.emojiResults.length === 0 && this.emoticonResults.length === 0))
return;
const isDown = ev.key === 'ArrowDown';
const isEnter = ev.key === 'Enter';
const isTab = ev.key === 'Tab';
if (isDown || isEnter || isTab) {
ev.preventDefault();
ev.stopPropagation();
if (!this.v2Enabled) {
// focus first item in result list.
const firstButton = this.shadowRoot.querySelector('.result');
firstButton.focus();
// if there is only one result, select it on enter.
if (isEnter && this.emojiResults.length === 1) {
firstButton.querySelector('emoji-button').click();
}
} else {
const emojiButton = this.shadowRoot.querySelector('emoji-group')
.shadowRoot.querySelector('emoji-button');
const emoticonButton =
this.shadowRoot.querySelector('emoticon-group')
.shadowRoot.querySelector('.emoticon-button');
if (this.emojiResults.length > 0) {
emojiButton.shadowRoot.querySelector('#emoji-button').focus();
} else if (this.emoticonResults.length > 0) {
emoticonButton.focus();
}
if (isEnter && this.emojiResults.length === 1 &&
this.emoticonResults.length === 0) {
emojiButton.shadowRoot.querySelector('#emoji-button').click();
} else if (
isEnter && this.emojiResults.length === 0 &&
this.emoticonResults.length === 1) {
emoticonButton.click();
}
}
}
}
/**
* Format the emoji data for search:
* 1) Remove duplicates.
* 2) Remove groupings.
* @param {!EmojiGroupData} emojiData
* @param {number} emojiDataLength Used to trick polymer into calling this
* when the emojidata is updated via push
* @return {!Array<!EmojiVariants>}
*/
computeEmojiList(emojiData, emojiDataLength) {
return Array.from(
new Map(emojiData.map(group => group.emoji).flat(1).map(emoji => {
// The Fuse search library in ChromeOS doesn't support prefix
// matching. A workaround is appending a space before all name and
// keyword labels. This allows us to force a prefix matching by
// prepending a space on users' searches. E.g. for the Emoji "smile
// face", we store " smile face", if the user searches for "fa", the
// search will be " fa" and will match " smile face", but not "
// infant".
emoji.base.name = ' ' + emoji.base.name;
emoji.base.keywords =
emoji.base.keywords.map(keyword => ' ' + keyword);
return [emoji.base.string, emoji];
})).values());
}
onSearchScroll() {
if (!this.v2Enabled) {
this.$['search-shadow'].style.boxShadow =
this.shadowRoot.getElementById('results').scrollTop > 0 ?
'var(--cr-elevation-3)' :
'none';
}
}
/**
*
* @param {!Array<!EmojiVariants>} emojiList
* @suppress {missingProperties}
*/
onEmojiListChanged(emojiList) {
// suppressed property error due to Fuse being untyped.
this.emojiFuse.setCollection(emojiList);
}
/**
*
* @param {!Array<!EmojiVariants>} emoticonList
* @suppress {missingProperties}
*/
onEmoticonListChanged(emoticonList) {
this.emoticonFuse.setCollection(emoticonList);
}
/**
* @param {?string} search
* @param {CategoryEnum} category
*/
computeSearchResults(search, category) {
if (!search)
return [];
// Add an initial space to force prefix matching only.
const prefixSearchTerm = ` ${search}`;
let fuseResults = [];
if (!this.v2Enabled) {
fuseResults = this.emojiFuse.search(prefixSearchTerm);
} else {
switch (category) {
case CategoryEnum.EMOJI:
fuseResults = this.emojiFuse.search(prefixSearchTerm);
break;
case CategoryEnum.EMOTICON:
fuseResults = this.emoticonFuse.search(prefixSearchTerm);
break;
default:
throw new Error('Unknown category.');
}
}
return fuseResults.map(item => item.item);
}
onResultClick(ev) {
ev.currentTarget.querySelector('emoji-button')
.shadowRoot.querySelector('button')
.click();
}
/**
* @param {!Array<!EmojiVariants>} emojiResults
* @param {!Array<!EmojiVariants>} emoticonResults
* @returns {boolean}
*/
isSearchResultEmpty(emojiResults, emoticonResults) {
if (!this.v2Enabled) {
return emojiResults.length === 0;
}
return emojiResults.length === 0 && emoticonResults.length === 0;
}
}
customElements.define(EmojiSearch.is, EmojiSearch);