Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * Emoji picker.
18
 *
19
 * @module core/emoji/picker
20
 * @copyright  2019 Ryan Wyllie <ryan@moodle.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
import LocalStorage from 'core/localstorage';
24
import * as EmojiData from 'core/emoji/data';
25
import {throttle, debounce} from 'core/utils';
26
import {getString} from 'core/str';
27
import {render as renderTemplate} from 'core/templates';
28
 
29
const VISIBLE_ROW_COUNT = 10;
30
const ROW_RENDER_BUFFER_COUNT = 5;
31
const RECENT_EMOJIS_STORAGE_KEY = 'moodle-recent-emojis';
32
const ROW_HEIGHT_RAW = 40;
33
const EMOJIS_PER_ROW = 7;
34
const MAX_RECENT_COUNT = EMOJIS_PER_ROW * 3;
35
const ROW_TYPE = {
36
    EMOJI: 0,
37
    HEADER: 1
38
};
39
const SELECTORS = {
40
    CATEGORY_SELECTOR: '[data-action="show-category"]',
41
    EMOJIS_CONTAINER: '[data-region="emojis-container"]',
42
    EMOJI_PREVIEW: '[data-region="emoji-preview"]',
43
    EMOJI_SHORT_NAME: '[data-region="emoji-short-name"]',
44
    ROW_CONTAINER: '[data-region="row-container"]',
45
    SEARCH_INPUT: '[data-region="search-input"]',
46
    SEARCH_RESULTS_CONTAINER: '[data-region="search-results-container"]'
47
};
48
 
49
/**
50
 * Create the row data for a category.
51
 *
52
 * @method
53
 * @param {String} categoryName The category name
54
 * @param {String} categoryDisplayName The category display name
55
 * @param {Array} emojis The emoji data
56
 * @param {Number} totalRowCount The total number of rows generated so far
57
 * @return {Array}
58
 */
59
const createRowDataForCategory = (categoryName, categoryDisplayName, emojis, totalRowCount) => {
60
    const rowData = [];
61
    rowData.push({
62
        index: totalRowCount + rowData.length,
63
        type: ROW_TYPE.HEADER,
64
        data: {
65
            name: categoryName,
66
            displayName: categoryDisplayName
67
        }
68
    });
69
 
70
    for (let i = 0; i < emojis.length; i += EMOJIS_PER_ROW) {
71
        const rowEmojis = emojis.slice(i, i + EMOJIS_PER_ROW);
72
        rowData.push({
73
            index: totalRowCount + rowData.length,
74
            type: ROW_TYPE.EMOJI,
75
            data: rowEmojis
76
        });
77
    }
78
 
79
    return rowData;
80
};
81
 
82
/**
83
 * Add each row's index to it's value in the row data.
84
 *
85
 * @method
86
 * @param {Array} rowData List of emoji row data
87
 * @return {Array}
88
 */
89
const addIndexesToRowData = (rowData) => {
90
    return rowData.map((data, index) => {
91
        return {...data, index};
92
    });
93
};
94
 
95
/**
96
 * Calculate the scroll position for the beginning of each category from
97
 * the row data.
98
 *
99
 * @method
100
 * @param {Array} rowData List of emoji row data
101
 * @return {Object}
102
 */
103
const getCategoryScrollPositionsFromRowData = (rowData) => {
104
    return rowData.reduce((carry, row, index) => {
105
        if (row.type === ROW_TYPE.HEADER) {
106
            carry[row.data.name] = index * ROW_HEIGHT_RAW;
107
        }
108
        return carry;
109
    }, {});
110
};
111
 
112
/**
113
 * Create a header row element for the category name.
114
 *
115
 * @method
116
 * @param {Number} rowIndex Index of the row in the row data
117
 * @param {String} name The category display name
118
 * @return {Element}
119
 */
120
const createHeaderRow = async(rowIndex, name) => {
121
    const context = {
122
        index: rowIndex,
123
        text: name
124
    };
125
    const html = await renderTemplate('core/emoji/header_row', context);
126
    const temp = document.createElement('div');
127
    temp.innerHTML = html;
128
    return temp.firstChild;
129
};
130
 
131
/**
132
 * Create an emoji row element.
133
 *
134
 * @method
135
 * @param {Number} rowIndex Index of the row in the row data
136
 * @param {Array} emojis The list of emoji data for the row
137
 * @return {Element}
138
 */
139
const createEmojiRow = async(rowIndex, emojis) => {
140
    const context = {
141
        index: rowIndex,
142
        emojis: emojis.map(emojiData => {
143
            const charCodes = emojiData.unified.split('-').map(code => `0x${code}`);
144
            const emojiText = String.fromCodePoint.apply(null, charCodes);
145
            return {
146
                shortnames: `:${emojiData.shortnames.join(': :')}:`,
147
                unified: emojiData.unified,
148
                text: emojiText,
149
                spacer: false
150
            };
151
        }),
152
        spacers: Array(EMOJIS_PER_ROW - emojis.length).fill(true)
153
    };
154
    const html = await renderTemplate('core/emoji/emoji_row', context);
155
    const temp = document.createElement('div');
156
    temp.innerHTML = html;
157
    return temp.firstChild;
158
};
159
 
160
/**
161
 * Check if the element is an emoji element.
162
 *
163
 * @method
164
 * @param {Element} element Element to check
165
 * @return {Bool}
166
 */
167
const isEmojiElement = element => element.getAttribute('data-short-names') !== null;
168
 
169
/**
170
 * Search from an element and up through it's ancestors to fine the category
171
 * selector element and return it.
172
 *
173
 * @method
174
 * @param {Element} element Element to begin searching from
175
 * @return {Element|null}
176
 */
177
const findCategorySelectorFromElement = element => {
178
    if (!element) {
179
        return null;
180
    }
181
 
182
    if (element.getAttribute('data-action') === 'show-category') {
183
        return element;
184
    } else {
185
        return findCategorySelectorFromElement(element.parentElement);
186
    }
187
};
188
 
189
const getCategorySelectorByCategoryName = (root, name) => {
190
    return root.querySelector(`[data-category="${name}"]`);
191
};
192
 
193
/**
194
 * Sets the given category selector element as active.
195
 *
196
 * @method
197
 * @param {Element} root The root picker element
198
 * @param {Element} element The category selector element to make active
199
 */
200
const setCategorySelectorActive = (root, element) => {
201
    const allCategorySelectors = root.querySelectorAll(SELECTORS.CATEGORY_SELECTOR);
202
 
203
    for (let i = 0; i < allCategorySelectors.length; i++) {
204
        const selector = allCategorySelectors[i];
205
        selector.classList.remove('selected');
206
    }
207
 
208
    element.classList.add('selected');
209
};
210
 
211
/**
212
 * Get the category selector element and the scroll positions for the previous and
213
 * next categories for the given scroll position.
214
 *
215
 * @method
216
 * @param {Element} root The picker root element
217
 * @param {Number} position The position to get the category for
218
 * @param {Object} categoryScrollPositions Set of scroll positions for all categories
219
 * @return {Array}
220
 */
221
const getCategoryByScrollPosition = (root, position, categoryScrollPositions) => {
222
    let positions = [];
223
 
224
    if (position < 0) {
225
        position = 0;
226
    }
227
 
228
    // Get all of the category positions.
229
    for (const categoryName in categoryScrollPositions) {
230
        const categoryPosition = categoryScrollPositions[categoryName];
231
        positions.push([categoryPosition, categoryName]);
232
    }
233
 
234
    // Sort the positions in ascending order.
235
    positions.sort(([a], [b]) => {
236
        if (a < b) {
237
            return -1;
238
        } else if (a > b) {
239
            return 1;
240
        } else {
241
            return 0;
242
        }
243
    });
244
 
245
    // Get the current category name as well as the previous and next category
246
    // positions from the sorted list of positions.
247
    const {categoryName, previousPosition, nextPosition} = positions.reduce(
248
        (carry, candidate) => {
249
            const [categoryPosition, categoryName] = candidate;
250
 
251
            if (categoryPosition <= position) {
252
                carry.categoryName = categoryName;
253
                carry.previousPosition = carry.currentPosition;
254
                carry.currentPosition = position;
255
            } else if (carry.nextPosition === null) {
256
                carry.nextPosition = categoryPosition;
257
            }
258
 
259
            return carry;
260
        },
261
        {
262
            categoryName: null,
263
            currentPosition: null,
264
            previousPosition: null,
265
            nextPosition: null
266
        }
267
    );
268
 
269
    return [getCategorySelectorByCategoryName(root, categoryName), previousPosition, nextPosition];
270
};
271
 
272
/**
273
 * Get the list of recent emojis data from local storage.
274
 *
275
 * @method
276
 * @return {Array}
277
 */
278
const getRecentEmojis = () => {
279
    const storedData = LocalStorage.get(RECENT_EMOJIS_STORAGE_KEY);
280
    return storedData ? JSON.parse(storedData) : [];
281
};
282
 
283
/**
284
 * Save the list of recent emojis in local storage.
285
 *
286
 * @method
287
 * @param {Array} recentEmojis List of emoji data to save
288
 */
289
const saveRecentEmoji = (recentEmojis) => {
290
    LocalStorage.set(RECENT_EMOJIS_STORAGE_KEY, JSON.stringify(recentEmojis));
291
};
292
 
293
/**
294
 * Add an emoji data to the set of recent emojis. This function will update the row
295
 * data to ensure that the recent emoji rows are correct and all of the rows are
296
 * re-indexed.
297
 *
298
 * The new set of recent emojis are saved in local storage and the full set of updated
299
 * row data and new emoji row count are returned.
300
 *
301
 * @method
302
 * @param {Array} rowData The emoji rows data
303
 * @param {Number} recentEmojiRowCount Count of the recent emoji rows
304
 * @param {Object} newEmoji The emoji data for the emoji to add to the recent emoji list
305
 * @return {Array}
306
 */
307
const addRecentEmoji = (rowData, recentEmojiRowCount, newEmoji) => {
308
    // The first set of rows is always the recent emojis.
309
    const categoryName = rowData[0].data.name;
310
    const categoryDisplayName = rowData[0].data.displayName;
311
    const recentEmojis = getRecentEmojis();
312
    // Add the new emoji to the start of the list of recent emojis.
313
    let newRecentEmojis = [newEmoji, ...recentEmojis.filter(emoji => emoji.unified != newEmoji.unified)];
314
    // Limit the number of recent emojis.
315
    newRecentEmojis = newRecentEmojis.slice(0, MAX_RECENT_COUNT);
316
    const newRecentEmojiRowData = createRowDataForCategory(categoryName, categoryDisplayName, newRecentEmojis);
317
 
318
    // Save the new list in local storage.
319
    saveRecentEmoji(newRecentEmojis);
320
 
321
    return [
322
        // Return the new rowData and re-index it to make sure it's all correct.
323
        addIndexesToRowData(newRecentEmojiRowData.concat(rowData.slice(recentEmojiRowCount))),
324
        newRecentEmojiRowData.length
325
    ];
326
};
327
 
328
/**
329
 * Calculate which rows should be visible based on the given scroll position. Adds a
330
 * buffer to amount to either side of the total number of requested rows so that
331
 * scrolling the emoji rows container is smooth.
332
 *
333
 * @method
334
 * @param {Number} scrollPosition Scroll position within the emoji container
335
 * @param {Number} visibleRowCount How many rows should be visible
336
 * @param {Array} rowData The emoji rows data
337
 * @return {Array}
338
 */
339
const getRowsToRender = (scrollPosition, visibleRowCount, rowData) => {
340
    const minVisibleRow = scrollPosition > ROW_HEIGHT_RAW ? Math.floor(scrollPosition / ROW_HEIGHT_RAW) : 0;
341
    const start = minVisibleRow >= ROW_RENDER_BUFFER_COUNT ? minVisibleRow - ROW_RENDER_BUFFER_COUNT : minVisibleRow;
342
    const end = minVisibleRow + visibleRowCount + ROW_RENDER_BUFFER_COUNT;
343
    const rows = rowData.slice(start, end);
344
    return rows;
345
};
346
 
347
/**
348
 * Create a row element from the row data.
349
 *
350
 * @method
351
 * @param {Object} rowData The emoji row data
352
 * @return {Element}
353
 */
354
const createRowElement = async(rowData) => {
355
    let row = null;
356
    if (rowData.type === ROW_TYPE.HEADER) {
357
        row = await createHeaderRow(rowData.index, rowData.data.displayName);
358
    } else {
359
        row = await createEmojiRow(rowData.index, rowData.data);
360
    }
361
 
362
    row.style.position = 'absolute';
363
    row.style.left = 0;
364
    row.style.right = 0;
365
    row.style.top = `${rowData.index * ROW_HEIGHT_RAW}px`;
366
 
367
    return row;
368
};
369
 
370
/**
371
 * Check if the given rows match.
372
 *
373
 * @method
374
 * @param {Object} a The first row
375
 * @param {Object} b The second row
376
 * @return {Bool}
377
 */
378
const doRowsMatch = (a, b) => {
379
    if (a.index !== b.index) {
380
        return false;
381
    }
382
 
383
    if (a.type !== b.type) {
384
        return false;
385
    }
386
 
387
    if (typeof a.data != typeof b.data) {
388
        return false;
389
    }
390
 
391
    if (a.type === ROW_TYPE.HEADER) {
392
        return a.data.name === b.data.name;
393
    } else {
394
        if (a.data.length !== b.data.length) {
395
            return false;
396
        }
397
 
398
        for (let i = 0; i < a.data.length; i++) {
399
            if (a.data[i].unified != b.data[i].unified) {
400
                return false;
401
            }
402
        }
403
    }
404
 
405
    return true;
406
};
407
 
408
/**
409
 * Update the visible rows. Deletes any row elements that should no longer
410
 * be visible and creates the newly visible row elements. Any rows that haven't
411
 * changed visibility will be left untouched.
412
 *
413
 * @method
414
 * @param {Element} rowContainer The container element for the emoji rows
415
 * @param {Array} currentRows List of row data that matches the currently visible rows
416
 * @param {Array} nextRows List of row data containing the new list of rows to be made visible
417
 */
418
const renderRows = async(rowContainer, currentRows, nextRows) => {
419
    // We need to add any rows that are in nextRows but not in currentRows.
420
    const toAdd = nextRows.filter(nextRow => !currentRows.some(currentRow => doRowsMatch(currentRow, nextRow)));
421
    // Remember which rows will still be visible so that we can insert our element in the correct place in the DOM.
422
    let toKeep = currentRows.filter(currentRow => nextRows.some(nextRow => doRowsMatch(currentRow, nextRow)));
423
    // We need to remove any rows that are in currentRows but not in nextRows.
424
    const toRemove = currentRows.filter(currentRow => !nextRows.some(nextRow => doRowsMatch(currentRow, nextRow)));
425
    const toRemoveElements = toRemove.map(rowData => rowContainer.querySelectorAll(`[data-row="${rowData.index}"]`));
426
 
427
    // Render all of the templates first.
428
    const rows = await Promise.all(toAdd.map(rowData => createRowElement(rowData)));
429
 
430
    rows.forEach((row, index) => {
431
        const rowData = toAdd[index];
432
        let nextRowIndex = null;
433
 
434
        for (let i = 0; i < toKeep.length; i++) {
435
            const candidate = toKeep[i];
436
            if (candidate.index > rowData.index) {
437
                nextRowIndex = i;
438
                break;
439
            }
440
        }
441
 
442
        // Make sure the elements get added to the DOM in the correct order (ascending by row data index)
443
        // so that they appear naturally in the tab order.
444
        if (nextRowIndex !== null) {
445
            const nextRowData = toKeep[nextRowIndex];
446
            const nextRowNode = rowContainer.querySelector(`[data-row="${nextRowData.index}"]`);
447
 
448
            rowContainer.insertBefore(row, nextRowNode);
449
            toKeep.splice(nextRowIndex, 0, toKeep);
450
        } else {
451
            toKeep.push(rowData);
452
            rowContainer.appendChild(row);
453
        }
454
    });
455
 
456
    toRemoveElements.forEach(rows => {
457
        for (let i = 0; i < rows.length; i++) {
458
            const row = rows[i];
459
            rowContainer.removeChild(row);
460
        }
461
    });
462
};
463
 
464
/**
465
 * Build a function to render the visible emoji rows for a given scroll
466
 * position.
467
 *
468
 * @method
469
 * @param {Element} rowContainer The container element for the emoji rows
470
 * @return {Function}
471
 */
472
const generateRenderRowsAtPositionFunction = (rowContainer) => {
473
    let currentRows = [];
474
    let nextRows = [];
475
    let rowCount = 0;
476
    let isRendering = false;
477
    const renderNextRows = async() => {
478
        if (!nextRows.length) {
479
            return;
480
        }
481
 
482
        if (isRendering) {
483
            return;
484
        }
485
 
486
        isRendering = true;
487
        const nextRowsToRender = nextRows.slice();
488
        nextRows = [];
489
 
490
        await renderRows(rowContainer, currentRows, nextRowsToRender);
491
        currentRows = nextRowsToRender;
492
        isRendering = false;
493
        renderNextRows();
494
    };
495
 
496
    return (scrollPosition, rowData, rowLimit = VISIBLE_ROW_COUNT) => {
497
        nextRows = getRowsToRender(scrollPosition, rowLimit, rowData);
498
        renderNextRows();
499
 
500
        if (rowCount !== rowData.length) {
501
            // Adjust the height of the container to match the number of rows.
502
            rowContainer.style.height = `${rowData.length * ROW_HEIGHT_RAW}px`;
503
        }
504
 
505
        rowCount = rowData.length;
506
    };
507
};
508
 
509
/**
510
 * Show the search results container and hide the emoji container.
511
 *
512
 * @method
513
 * @param {Element} emojiContainer The emojis container
514
 * @param {Element} searchResultsContainer The search results container
515
 */
516
const showSearchResults = (emojiContainer, searchResultsContainer) => {
517
    searchResultsContainer.classList.remove('hidden');
518
    emojiContainer.classList.add('hidden');
519
};
520
 
521
/**
522
 * Hide the search result container and show the emojis container.
523
 *
524
 * @method
525
 * @param {Element} emojiContainer The emojis container
526
 * @param {Element} searchResultsContainer The search results container
527
 * @param {Element} searchInput The search input
528
 */
529
const clearSearch = (emojiContainer, searchResultsContainer, searchInput) => {
530
    searchResultsContainer.classList.add('hidden');
531
    emojiContainer.classList.remove('hidden');
532
    searchInput.value = '';
533
};
534
 
535
/**
536
 * Build function to handle mouse hovering an emoji. Shows the preview.
537
 *
538
 * @method
539
 * @param {Element} emojiPreview The emoji preview element
540
 * @param {Element} emojiShortName The emoji short name element
541
 * @return {Function}
542
 */
543
const getHandleMouseEnter = (emojiPreview, emojiShortName) => {
544
    return (e) => {
545
        const target = e.target;
546
        if (isEmojiElement(target)) {
547
            emojiShortName.textContent = target.getAttribute('data-short-names');
548
            emojiPreview.textContent = target.textContent;
549
        }
550
    };
551
};
552
 
553
/**
554
 * Build function to handle mouse leaving an emoji. Removes the preview.
555
 *
556
 * @method
557
 * @param {Element} emojiPreview The emoji preview element
558
 * @param {Element} emojiShortName The emoji short name element
559
 * @return {Function}
560
 */
561
const getHandleMouseLeave = (emojiPreview, emojiShortName) => {
562
    return (e) => {
563
        const target = e.target;
564
        if (isEmojiElement(target)) {
565
            emojiShortName.textContent = '';
566
            emojiPreview.textContent = '';
567
        }
568
    };
569
};
570
 
571
/**
572
 * Build the function to handle a user clicking something in the picker.
573
 *
574
 * The function currently handles clicking on the category selector or selecting
575
 * a specific emoji.
576
 *
577
 * @method
578
 * @param {Number} recentEmojiRowCount Number of rows of recent emojis
579
 * @param {Element} emojiContainer Container element for the visible of emojis
580
 * @param {Element} searchResultsContainer Contaienr element for the search results
581
 * @param {Element} searchInput Search input element
582
 * @param {Function} selectCallback Callback function to execute when a user selects an emoji
583
 * @param {Function} renderAtPosition Render function to display current visible emojis
584
 * @return {Function}
585
 */
586
const getHandleClick = (
587
    recentEmojiRowCount,
588
    emojiContainer,
589
    searchResultsContainer,
590
    searchInput,
591
    selectCallback,
592
    renderAtPosition
593
) => {
594
    return (e, rowData, categoryScrollPositions) => {
595
        const target = e.target;
596
        let newRowData = rowData;
597
        let newCategoryScrollPositions = categoryScrollPositions;
598
 
599
        // Hide the search results if they are visible.
600
        clearSearch(emojiContainer, searchResultsContainer, searchInput);
601
 
602
        if (isEmojiElement(target)) {
603
            // Emoji selected.
604
            const unified = target.getAttribute('data-unified');
605
            const shortnames = target.getAttribute('data-short-names').replace(/:/g, '').split(' ');
606
            // Build the emoji data from the selected element.
607
            const emojiData = {unified, shortnames};
608
            const currentScrollTop = emojiContainer.scrollTop;
609
            const isRecentEmojiRowVisible = emojiContainer.querySelector(`[data-row="${recentEmojiRowCount - 1}"]`) !== null;
610
            // Save the selected emoji in the recent emojis list.
611
            [newRowData, recentEmojiRowCount] = addRecentEmoji(rowData, recentEmojiRowCount, emojiData);
612
            // Re-index the category scroll positions because the additional recent emoji may have
613
            // changed their positions.
614
            newCategoryScrollPositions = getCategoryScrollPositionsFromRowData(newRowData);
615
 
616
            if (isRecentEmojiRowVisible) {
617
                // If the list of recent emojis is currently visible then we need to re-render the emojis
618
                // to update the display and show the newly selected recent emoji.
619
                renderAtPosition(currentScrollTop, newRowData);
620
            }
621
 
622
            // Call the client's callback function with the selected emoji.
623
            selectCallback(target.textContent);
624
            // Return the newly calculated row data and scroll positions.
625
            return [newRowData, newCategoryScrollPositions];
626
        }
627
 
628
        const categorySelector = findCategorySelectorFromElement(target);
629
        if (categorySelector) {
630
            // Category selector.
631
            const selectedCategory = categorySelector.getAttribute('data-category');
632
            const position = categoryScrollPositions[selectedCategory];
633
            // Scroll the container to the selected category. This will trigger the
634
            // on scroll handler to re-render the visibile emojis.
635
            emojiContainer.scrollTop = position;
636
        }
637
 
638
        return [newRowData, newCategoryScrollPositions];
639
    };
640
};
641
 
642
/**
643
 * Build the function that handles scrolling of the emoji container to display the
644
 * correct emojis.
645
 *
646
 * We render the emoji rows as they are needed rather than all up front so that we
647
 * can avoid adding tends of thousands of elements to the DOM unnecessarily which
648
 * would bog down performance.
649
 *
650
 * @method
651
 * @param {Element} root The picker root element
652
 * @param {Number} currentVisibleRowScrollPosition The current scroll position of the container
653
 * @param {Element} emojiContainer The emojis container element
654
 * @param {Object} initialCategoryScrollPositions Scroll positions for each category
655
 * @param {Function} renderAtPosition Function to render the appropriate emojis for a scroll position
656
 * @return {Function}
657
 */
658
const getHandleScroll = (
659
    root,
660
    currentVisibleRowScrollPosition,
661
    emojiContainer,
662
    initialCategoryScrollPositions,
663
    renderAtPosition
664
) => {
665
    // Scope some local variables to track the scroll positions of the categories. We need to
666
    // recalculate these because adding recent emojis can change those positions by adding
667
    // additional rows.
668
    let [
669
        currentCategoryElement,
670
        previousCategoryPosition,
671
        nextCategoryPosition
672
    ] = getCategoryByScrollPosition(root, emojiContainer.scrollTop, initialCategoryScrollPositions);
673
 
674
    return (categoryScrollPositions, rowData) => {
675
        const newScrollPosition = emojiContainer.scrollTop;
676
        const upperScrollBound = currentVisibleRowScrollPosition + ROW_HEIGHT_RAW;
677
        const lowerScrollBound = currentVisibleRowScrollPosition - ROW_HEIGHT_RAW;
678
        // We only need to update the active category indicator if the user has scrolled into a
679
        // new category scroll position.
680
        const updateActiveCategory = (newScrollPosition >= nextCategoryPosition) ||
681
                       (newScrollPosition < previousCategoryPosition);
682
        // We only need to render new emoji rows if the user has scrolled far enough that a new row
683
        // would be visible (i.e. they've scrolled up or down more than 40px - the height of a row).
684
        const updateRenderRows = (newScrollPosition < lowerScrollBound) || (newScrollPosition > upperScrollBound);
685
 
686
        if (updateActiveCategory) {
687
            // New category is visible so update the active category selector and re-index the
688
            // positions incase anything has changed.
689
            [
690
                currentCategoryElement,
691
                previousCategoryPosition,
692
                nextCategoryPosition
693
            ] = getCategoryByScrollPosition(root, newScrollPosition, categoryScrollPositions);
694
            setCategorySelectorActive(root, currentCategoryElement);
695
        }
696
 
697
        if (updateRenderRows) {
698
            // A new row should be visible so re-render the visible emojis at this new position.
699
            // We request an animation frame from the browser so that we're not blocking anything.
700
            // The animation only needs to occur as soon as the browser is ready not immediately.
701
            requestAnimationFrame(() => {
702
                renderAtPosition(newScrollPosition, rowData);
703
                // Remember the updated position.
704
                currentVisibleRowScrollPosition = newScrollPosition;
705
            });
706
        }
707
    };
708
};
709
 
710
/**
711
 * Build the function that handles search input from the user.
712
 *
713
 * @method
714
 * @param {Element} searchInput The search input element
715
 * @param {Element} searchResultsContainer Container element to display the search results
716
 * @param {Element} emojiContainer Container element for the emoji rows
717
 * @return {Function}
718
 */
719
const getHandleSearch = (searchInput, searchResultsContainer, emojiContainer) => {
720
    const rowContainer = searchResultsContainer.querySelector(SELECTORS.ROW_CONTAINER);
721
    // Build a render function for the search results.
722
    const renderSearchResultsAtPosition = generateRenderRowsAtPositionFunction(rowContainer);
723
    searchResultsContainer.appendChild(rowContainer);
724
 
725
    return async() => {
726
        const searchTerm = searchInput.value.toLowerCase();
727
 
728
        if (searchTerm) {
729
            // Display the search results container and hide the emojis container.
730
            showSearchResults(emojiContainer, searchResultsContainer);
731
 
732
            // Find which emojis match the user's search input.
733
            const matchingEmojis = Object.keys(EmojiData.byShortName).reduce((carry, shortName) => {
734
                if (shortName.includes(searchTerm)) {
735
                    carry.push({
736
                        shortnames: [shortName],
737
                        unified: EmojiData.byShortName[shortName]
738
                    });
739
                }
740
                return carry;
741
            }, []);
742
 
743
            const searchResultsString = await getString('searchresults', 'core');
744
            const rowData = createRowDataForCategory(searchResultsString, searchResultsString, matchingEmojis, 0);
745
            // Show the emoji rows for the search results.
746
            renderSearchResultsAtPosition(0, rowData, rowData.length);
747
        } else {
748
            // Hide the search container and show the emojis container.
749
            clearSearch(emojiContainer, searchResultsContainer, searchInput);
750
        }
751
    };
752
};
753
 
754
/**
755
 * Register the emoji picker event listeners.
756
 *
757
 * @method
758
 * @param {Element} root The picker root element
759
 * @param {Element} emojiContainer Root element containing the list of visible emojis
760
 * @param {Function} renderAtPosition Function to render the visible emojis at a given scroll position
761
 * @param {Number} currentVisibleRowScrollPosition What is the current scroll position
762
 * @param {Function} selectCallback Function to execute when the user picks an emoji
763
 * @param {Object} categoryScrollPositions Scroll positions for where each of the emoji categories begin
764
 * @param {Array} rowData Data representing each of the display rows for hte emoji container
765
 * @param {Number} recentEmojiRowCount Number of rows of recent emojis
766
 */
767
const registerEventListeners = (
768
    root,
769
    emojiContainer,
770
    renderAtPosition,
771
    currentVisibleRowScrollPosition,
772
    selectCallback,
773
    categoryScrollPositions,
774
    rowData,
775
    recentEmojiRowCount
776
) => {
777
    const searchInput = root.querySelector(SELECTORS.SEARCH_INPUT);
778
    const searchResultsContainer = root.querySelector(SELECTORS.SEARCH_RESULTS_CONTAINER);
779
    const emojiPreview = root.querySelector(SELECTORS.EMOJI_PREVIEW);
780
    const emojiShortName = root.querySelector(SELECTORS.EMOJI_SHORT_NAME);
781
    // Build the click handler function.
782
    const clickHandler = getHandleClick(
783
        recentEmojiRowCount,
784
        emojiContainer,
785
        searchResultsContainer,
786
        searchInput,
787
        selectCallback,
788
        renderAtPosition
789
    );
790
    // Build the scroll handler function.
791
    const scrollHandler = getHandleScroll(
792
        root,
793
        currentVisibleRowScrollPosition,
794
        emojiContainer,
795
        categoryScrollPositions,
796
        renderAtPosition
797
    );
798
    const searchHandler = getHandleSearch(searchInput, searchResultsContainer, emojiContainer);
799
 
800
    // Mouse enter/leave events to show the emoji preview on hover or focus.
801
    root.addEventListener('focus', getHandleMouseEnter(emojiPreview, emojiShortName), true);
802
    root.addEventListener('blur', getHandleMouseLeave(emojiPreview, emojiShortName), true);
803
    root.addEventListener('mouseenter', getHandleMouseEnter(emojiPreview, emojiShortName), true);
804
    root.addEventListener('mouseleave', getHandleMouseLeave(emojiPreview, emojiShortName), true);
805
    // User selects an emoji or clicks on one of the emoji category selectors.
806
    root.addEventListener('click', e => {
807
        // Update the row data and category scroll positions because they may have changes if the
808
        // user selects an emoji which updates the recent emojis list.
809
        [rowData, categoryScrollPositions] = clickHandler(e, rowData, categoryScrollPositions);
810
    });
811
    // Throttle the scroll event to only execute once every 50 milliseconds to prevent performance issues
812
    // in the browser when re-rendering the picker emojis. The scroll event fires a lot otherwise.
813
    emojiContainer.addEventListener('scroll', throttle(() => scrollHandler(categoryScrollPositions, rowData), 50));
814
    // Debounce the search input so that it only executes 200 milliseconds after the user has finished typing.
815
    searchInput.addEventListener('input', debounce(searchHandler, 200));
816
};
817
 
818
/**
819
 * Initialise the emoji picker.
820
 *
821
 * @method
822
 * @param {Element} root The root element for the picker
823
 * @param {Function} selectCallback Callback for when the user selects an emoji
824
 */
825
export default (root, selectCallback) => {
826
    const emojiContainer = root.querySelector(SELECTORS.EMOJIS_CONTAINER);
827
    const rowContainer = emojiContainer.querySelector(SELECTORS.ROW_CONTAINER);
828
    const recentEmojis = getRecentEmojis();
829
    // Add the recent emojis category to the list of standard categories.
830
    const allData = [{
831
        name: 'Recent',
832
        emojis: recentEmojis
833
    }, ...EmojiData.byCategory];
834
    let rowData = [];
835
    let recentEmojiRowCount = 0;
836
 
837
    /**
838
     * Split categories data into rows which represent how they will be displayed in the
839
     * picker. Each category will add a row containing the display name for the category
840
     * and a row for every 9 emojis in the category. The row data will be used to calculate
841
     * which emojis should be visible in the picker at any given time.
842
     *
843
     * E.g.
844
     * input = [
845
     *  {name: 'example1', emojis: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]},
846
     *  {name: 'example2', emojis: [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]},
847
     * ]
848
     * output = [
849
     *      {type: 'categoryName': data: 'Example 1'},
850
     *      {type: 'emojiRow': data: [1, 2, 3, 4, 5, 6, 7, 8, 9]},
851
     *      {type: 'emojiRow': data: [10, 11, 12]},
852
     *      {type: 'categoryName': data: 'Example 2'},
853
     *      {type: 'emojiRow': data: [13, 14, 15, 16, 17, 18, 19, 20, 21]},
854
     *      {type: 'emojiRow': data: [22, 23]},
855
     * ]
856
     */
857
    allData.forEach(category => {
858
        const categorySelector = getCategorySelectorByCategoryName(root, category.name);
859
        // Get the display name from the category selector button so that we don't need to
860
        // send an ajax request for the string.
861
        const categoryDisplayName = categorySelector.title;
862
        const categoryRowData = createRowDataForCategory(category.name, categoryDisplayName, category.emojis, rowData.length);
863
 
864
        if (category.name === 'Recent') {
865
            // Remember how many recent emoji rows there are because it needs to be used to
866
            // re-index the row data later when we're adding more recent emojis.
867
            recentEmojiRowCount = categoryRowData.length;
868
        }
869
 
870
        rowData = rowData.concat(categoryRowData);
871
    });
872
 
873
    // Index the row data so that we can calculate which rows should be visible.
874
    rowData = addIndexesToRowData(rowData);
875
    // Calculate the scroll positions for each of the categories within the emoji container.
876
    // These are used to know where to jump to when the user selects a specific category.
877
    const categoryScrollPositions = getCategoryScrollPositionsFromRowData(rowData);
878
    const renderAtPosition = generateRenderRowsAtPositionFunction(rowContainer);
879
    // Display the initial set of emojis.
880
    renderAtPosition(0, rowData);
881
 
882
    registerEventListeners(
883
        root,
884
        emojiContainer,
885
        renderAtPosition,
886
        0,
887
        selectCallback,
888
        categoryScrollPositions,
889
        rowData,
890
        recentEmojiRowCount
891
    );
892
};