emoji-picker-element/src/picker/components/Picker/Picker.js

598 lines
18 KiB
JavaScript
Raw Normal View History

/* eslint-disable prefer-const,no-labels,no-inner-declarations */
import { onMount, tick } from 'svelte'
2020-06-17 05:17:42 +02:00
import { groups as defaultGroups, customGroup } from '../../groups'
import { MIN_SEARCH_TEXT_LENGTH, NUM_SKIN_TONES } from '../../../shared/constants'
2020-05-18 04:08:00 +02:00
import { requestIdleCallback } from '../../utils/requestIdleCallback'
import { hasZwj } from '../../utils/hasZwj'
import { detectEmojiSupportLevel, supportedZwjEmojis } from '../../utils/emojiSupport'
2020-06-08 04:48:38 +02:00
import { applySkinTone } from '../../utils/applySkinTone'
2020-06-08 16:49:01 +02:00
import { halt } from '../../utils/halt'
import { incrementOrDecrement } from '../../utils/incrementOrDecrement'
2020-06-13 05:14:47 +02:00
import {
DEFAULT_NUM_COLUMNS,
MOST_COMMONLY_USED_EMOJI,
TIMEOUT_BEFORE_LOADING_MESSAGE
} from '../../constants'
import { uniqBy } from '../../../shared/uniqBy'
2020-06-14 23:42:05 +02:00
import { summarizeEmojisForUI } from '../../utils/summarizeEmojisForUI'
import * as widthCalculator from '../../utils/widthCalculator'
2020-06-15 19:38:39 +02:00
import { checkZwjSupport } from '../../utils/checkZwjSupport'
import { requestPostAnimationFrame } from '../../utils/requestPostAnimationFrame'
2020-06-25 15:59:02 +02:00
import { requestAnimationFrame } from '../../utils/requestAnimationFrame'
import { uniq } from '../../../shared/uniq'
import { resetScrollTopIfPossible } from '../../utils/resetScrollTopIfPossible.js'
2020-05-18 04:08:00 +02:00
2020-06-15 19:07:33 +02:00
// public
export let skinToneEmoji
export let i18n
export let database
export let customEmoji
export let customCategorySorting
export let emojiVersion
2020-06-15 19:07:33 +02:00
// private
let initialLoad = true
2020-05-18 04:08:00 +02:00
let currentEmojis = []
2020-06-17 05:17:42 +02:00
let currentEmojisWithCategories = [] // eslint-disable-line no-unused-vars
2020-05-18 04:08:00 +02:00
let rawSearchText = ''
let searchText = ''
let rootElement
let baselineEmoji
2020-06-25 15:59:02 +02:00
let tabpanelElement
2020-06-02 17:42:33 +02:00
let searchMode = false // eslint-disable-line no-unused-vars
let activeSearchItem = -1
let message // eslint-disable-line no-unused-vars
2020-06-09 05:48:41 +02:00
let skinTonePickerExpanded = false
let skinTonePickerExpandedAfterAnimation = false // eslint-disable-line no-unused-vars
let skinToneDropdown
2020-06-08 04:48:38 +02:00
let currentSkinTone = 0
let activeSkinTone = 0
2020-06-17 16:52:25 +02:00
let skinToneButtonText // eslint-disable-line no-unused-vars
let pickerStyle // eslint-disable-line no-unused-vars
let skinToneButtonLabel = '' // eslint-disable-line no-unused-vars
let skinTones = []
2020-06-13 05:14:47 +02:00
let currentFavorites = [] // eslint-disable-line no-unused-vars
2020-06-15 02:30:32 +02:00
let defaultFavoriteEmojis
2020-06-13 05:14:47 +02:00
let numColumns = DEFAULT_NUM_COLUMNS
let isRtl = false // eslint-disable-line no-unused-vars
2020-06-13 05:14:47 +02:00
let scrollbarWidth = 0 // eslint-disable-line no-unused-vars
2020-06-17 05:17:42 +02:00
let currentGroupIndex = 0
let groups = defaultGroups
let currentGroup
let databaseLoaded = false // eslint-disable-line no-unused-vars
let activeSearchItemId // eslint-disable-line no-unused-vars
2020-05-31 22:57:07 +02:00
2020-06-15 19:38:39 +02:00
//
// Utils/helpers
//
const focus = id => {
2020-06-15 19:38:39 +02:00
rootElement.getRootNode().getElementById(id).focus()
}
// fire a custom event that crosses the shadow boundary
const fireEvent = (name, detail) => {
2020-06-15 19:38:39 +02:00
rootElement.dispatchEvent(new CustomEvent(name, {
detail,
bubbles: true,
composed: true
}))
}
// eslint-disable-next-line no-unused-vars
const unicodeWithSkin = (emoji, currentSkinTone) => (
(currentSkinTone && emoji.skins && emoji.skins[currentSkinTone]) || emoji.unicode
)
2020-06-15 19:38:39 +02:00
// eslint-disable-next-line no-unused-vars
const labelWithSkin = (emoji, currentSkinTone) => (
uniq([(emoji.name || unicodeWithSkin(emoji, currentSkinTone)), ...(emoji.shortcodes || [])]).join(', ')
)
// Detect a skintone option button
const isSkinToneOption = element => /^skintone-/.test(element.id)
2020-06-15 19:38:39 +02:00
//
// Determine the emoji support level (in requestIdleCallback)
//
onMount(() => {
if (!emojiVersion) {
detectEmojiSupportLevel().then(level => {
// Can't actually test emoji support in Jest/JSDom, emoji never render in color in Cairo
/* istanbul ignore next */
if (!level) {
message = i18n.emojiUnsupportedMessage
}
})
}
})
2020-06-15 19:38:39 +02:00
//
// Set or update the database object
//
2020-05-18 04:08:00 +02:00
$: {
// show a Loading message if it takes a long time, or show an error if there's a network/IDB error
async function handleDatabaseLoading () {
let showingLoadingMessage = false
const timeoutHandle = setTimeout(() => {
showingLoadingMessage = true
message = i18n.loadingMessage
}, TIMEOUT_BEFORE_LOADING_MESSAGE)
try {
await database.ready()
databaseLoaded = true // eslint-disable-line no-unused-vars
} catch (err) {
console.error(err)
message = i18n.networkErrorMessage
} finally {
clearTimeout(timeoutHandle)
if (showingLoadingMessage) { // Seems safer than checking the i18n string, which may change
showingLoadingMessage = false
message = '' // eslint-disable-line no-unused-vars
}
}
}
if (database) {
/* no await */ handleDatabaseLoading()
}
}
2020-06-15 19:38:39 +02:00
//
// Global styles for the entire picker
//
2020-12-24 22:52:41 +01:00
/* eslint-disable no-unused-vars */
$: pickerStyle = `
2020-06-17 05:17:42 +02:00
--num-groups: ${groups.length};
2020-06-15 19:38:39 +02:00
--indicator-opacity: ${searchMode ? 0 : 1};
--num-skintones: ${NUM_SKIN_TONES};`
2020-12-24 22:52:41 +01:00
/* eslint-enable no-unused-vars */
2020-06-15 19:38:39 +02:00
//
// Set or update the customEmoji
//
2020-06-15 19:38:39 +02:00
$: {
if (customEmoji && database) {
console.log('updating custom emoji')
2020-06-15 19:38:39 +02:00
database.customEmoji = customEmoji
}
}
2020-06-08 04:48:38 +02:00
2020-06-15 02:30:32 +02:00
$: {
if (customEmoji && customEmoji.length) {
2020-06-17 05:17:42 +02:00
groups = [customGroup, ...defaultGroups]
} else if (groups !== defaultGroups) {
if (currentGroupIndex) {
// If the current group is anything other than "custom" (which is first), decrement.
// This fixes the odd case where you set customEmoji, then pick a category, then unset customEmoji
currentGroupIndex--
}
2020-06-17 05:17:42 +02:00
groups = defaultGroups
2020-06-15 02:30:32 +02:00
}
}
2020-06-15 19:38:39 +02:00
//
// Set or update the preferred skin tone
//
2020-06-06 21:38:08 +02:00
2020-06-13 05:14:47 +02:00
$: {
async function updatePreferredSkinTone () {
if (databaseLoaded) {
2020-06-13 05:14:47 +02:00
currentSkinTone = await database.getPreferredSkinTone()
}
}
2020-06-13 18:31:11 +02:00
/* no await */ updatePreferredSkinTone()
2020-06-13 05:14:47 +02:00
}
2020-06-17 16:52:25 +02:00
$: skinTones = Array(NUM_SKIN_TONES).fill().map((_, i) => applySkinTone(skinToneEmoji, i))
2020-12-24 22:52:41 +01:00
/* eslint-disable no-unused-vars */
2020-06-17 16:52:25 +02:00
$: skinToneButtonText = skinTones[currentSkinTone]
2020-06-15 19:38:39 +02:00
$: skinToneButtonLabel = i18n.skinToneLabel.replace('{skinTone}', i18n.skinTones[currentSkinTone])
2020-12-24 22:52:41 +01:00
/* eslint-enable no-unused-vars */
2020-06-15 19:38:39 +02:00
//
// Set or update the favorites emojis
//
2020-06-13 05:14:47 +02:00
$: {
async function updateDefaultFavoriteEmojis () {
2020-06-17 16:52:25 +02:00
defaultFavoriteEmojis = (await Promise.all(MOST_COMMONLY_USED_EMOJI.map(unicode => (
database.getEmojiByUnicodeOrName(unicode)
)))).filter(Boolean) // filter because in Jest tests we don't have all the emoji in the DB
}
if (databaseLoaded) {
2020-06-17 16:52:25 +02:00
/* no await */ updateDefaultFavoriteEmojis()
2020-06-13 05:14:47 +02:00
}
}
$: {
2020-06-17 16:52:25 +02:00
async function updateFavorites () {
console.log('updateFavorites')
2020-06-13 05:14:47 +02:00
const dbFavorites = await database.getTopFavoriteEmoji(numColumns)
2020-06-17 16:52:25 +02:00
const favorites = await summarizeEmojis(uniqBy([
2020-06-13 05:14:47 +02:00
...dbFavorites,
2020-06-15 02:30:32 +02:00
...defaultFavoriteEmojis
2020-06-17 16:52:25 +02:00
], _ => (_.unicode || _.name)).slice(0, numColumns))
currentFavorites = favorites
2020-06-13 05:14:47 +02:00
}
if (databaseLoaded && defaultFavoriteEmojis) {
2020-06-13 18:31:11 +02:00
/* no await */ updateFavorites()
2020-06-13 05:14:47 +02:00
}
}
2020-06-15 19:38:39 +02:00
//
// Calculate the width of the emoji grid. This serves two purposes:
// 1) Re-calculate the --num-columns var because it may have changed
// 2) Re-calculate the scrollbar width because it may have changed
// (i.e. because the number of items changed)
// 3) Re-calculate whether we're in RTL mode or not.
//
// The benefit of doing this in one place is to align with rAF/ResizeObserver
// and do all the calculations in one go. RTL vs LTR is not strictly width-related,
// but since we're already reading the style here, and since it's already aligned with
// the rAF loop, this is the most appropriate place to do it perf-wise.
2020-06-15 19:38:39 +02:00
//
2020-06-13 05:14:47 +02:00
// eslint-disable-next-line no-unused-vars
function calculateEmojiGridStyle (node) {
return widthCalculator.calculateWidth(node, width => {
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'test') { // jsdom throws errors for this kind of fancy stuff
// read all the style/layout calculations we need to make
const style = getComputedStyle(rootElement)
const newNumColumns = parseInt(style.getPropertyValue('--num-columns'), 10)
const newIsRtl = style.getPropertyValue('direction') === 'rtl'
const parentWidth = node.parentElement.getBoundingClientRect().width
const newScrollbarWidth = parentWidth - width
// write to Svelte variables
numColumns = newNumColumns
scrollbarWidth = newScrollbarWidth // eslint-disable-line no-unused-vars
isRtl = newIsRtl // eslint-disable-line no-unused-vars
}
2020-06-13 05:14:47 +02:00
})
}
2020-06-15 19:38:39 +02:00
//
2020-06-17 05:17:42 +02:00
// Update the current group based on the currentGroupIndex
2020-06-15 19:38:39 +02:00
//
2020-06-17 05:17:42 +02:00
$: currentGroup = groups[currentGroupIndex]
2020-06-15 19:38:39 +02:00
//
// Set or update the currentEmojis. Check for invalid ZWJ renderings
// (i.e. double emoji).
//
$: {
2020-06-02 17:42:33 +02:00
async function updateEmojis () {
console.log('updateEmojis')
if (!databaseLoaded) {
currentEmojis = []
searchMode = false
} else if (searchText.length >= MIN_SEARCH_TEXT_LENGTH) {
const currentSearchText = searchText
const newEmojis = await getEmojisBySearchQuery(currentSearchText)
if (currentSearchText === searchText) { // if the situation changes asynchronously, do not update
currentEmojis = newEmojis
searchMode = true
}
2020-06-17 05:17:42 +02:00
} else if (currentGroup) {
const currentGroupId = currentGroup.id
const newEmojis = await getEmojisByGroup(currentGroupId)
if (currentGroupId === currentGroup.id) { // if the situation changes asynchronously, do not update
currentEmojis = newEmojis
searchMode = false
}
2020-05-18 04:08:00 +02:00
}
2020-06-02 17:42:33 +02:00
}
2020-06-13 18:31:11 +02:00
/* no await */ updateEmojis()
2020-05-18 04:08:00 +02:00
}
// Some emojis have their ligatures rendered as two or more consecutive emojis
// We want to treat these the same as unsupported emojis, so we compare their
// widths against the baseline widths and remove them as necessary
$: {
2020-06-15 02:30:32 +02:00
const zwjEmojisToCheck = currentEmojis
.filter(emoji => emoji.unicode) // filter custom emoji
.filter(emoji => hasZwj(emoji) && !supportedZwjEmojis.has(emoji.unicode))
if (!emojiVersion && zwjEmojisToCheck.length) {
2020-05-18 04:08:00 +02:00
// render now, check their length later
2020-06-15 19:38:39 +02:00
requestAnimationFrame(() => checkZwjSupportAndUpdate(zwjEmojisToCheck))
2020-05-18 04:08:00 +02:00
} else {
currentEmojis = emojiVersion ? currentEmojis : currentEmojis.filter(isZwjSupported)
// Reset scroll top to 0 when emojis change
requestAnimationFrame(() => resetScrollTopIfPossible(tabpanelElement))
2020-05-18 04:08:00 +02:00
}
}
2020-06-15 19:38:39 +02:00
function checkZwjSupportAndUpdate (zwjEmojisToCheck) {
const rootNode = rootElement.getRootNode()
const emojiToDomNode = emoji => rootNode.getElementById(`emo-${emoji.id}`)
checkZwjSupport(zwjEmojisToCheck, baselineEmoji, emojiToDomNode)
2020-05-18 04:08:00 +02:00
// force update
currentEmojis = currentEmojis // eslint-disable-line no-self-assign
}
function isZwjSupported (emoji) {
2020-06-15 02:30:32 +02:00
return !emoji.unicode || !hasZwj(emoji) || supportedZwjEmojis.get(emoji.unicode)
2020-05-18 04:08:00 +02:00
}
async function filterEmojisByVersion (emojis) {
const emojiSupportLevel = emojiVersion || await detectEmojiSupportLevel()
2020-06-21 23:25:14 +02:00
// !version corresponds to custom emoji
return emojis.filter(({ version }) => !version || version <= emojiSupportLevel)
2020-05-18 04:08:00 +02:00
}
2020-06-08 17:32:04 +02:00
async function summarizeEmojis (emojis) {
return summarizeEmojisForUI(emojis, emojiVersion || await detectEmojiSupportLevel())
2020-06-08 17:32:04 +02:00
}
2020-05-18 04:08:00 +02:00
async function getEmojisByGroup (group) {
console.log('getEmojiByGroup', group)
2020-06-21 23:25:14 +02:00
// -1 is custom emoji
const emoji = group === -1 ? customEmoji : await database.getEmojiByGroup(group)
return summarizeEmojis(await filterEmojisByVersion(emoji))
2020-05-18 04:08:00 +02:00
}
2020-06-06 02:41:38 +02:00
async function getEmojisBySearchQuery (query) {
2020-06-08 17:32:04 +02:00
return summarizeEmojis(await filterEmojisByVersion(await database.getEmojiBySearchQuery(query)))
2020-05-18 04:08:00 +02:00
}
2020-06-22 02:12:14 +02:00
$: {
// consider initialLoad to be complete when the first tabpanel and favorites are rendered
2020-12-29 02:14:23 +01:00
/* istanbul ignore next */
2020-06-22 02:12:14 +02:00
if (process.env.NODE_ENV !== 'production' || process.env.PERF) {
if (currentEmojis.length && currentFavorites.length && initialLoad) {
initialLoad = false
requestPostAnimationFrame(() => performance.measure('initialLoad', 'initialLoad'))
2020-06-22 02:12:14 +02:00
}
}
}
2020-06-17 04:20:47 +02:00
//
// Derive currentEmojisWithCategories from currentEmojis. This is always done even if there
// are no categories, because it's just easier to code the HTML this way.
//
$: {
2020-06-17 05:17:42 +02:00
function calculateCurrentEmojisWithCategories () {
if (searchMode) {
return [
{
category: '',
emojis: currentEmojis
}
]
}
2020-06-17 05:17:42 +02:00
const categoriesToEmoji = new Map()
for (const emoji of currentEmojis) {
const category = emoji.category || ''
let emojis = categoriesToEmoji.get(category)
if (!emojis) {
emojis = []
categoriesToEmoji.set(category, emojis)
2020-06-17 04:20:47 +02:00
}
2020-06-17 05:17:42 +02:00
emojis.push(emoji)
2020-06-17 04:20:47 +02:00
}
2020-06-17 05:17:42 +02:00
return [...categoriesToEmoji.entries()]
.map(([category, emojis]) => ({ category, emojis }))
.sort((a, b) => customCategorySorting(a.category, b.category))
2020-06-17 04:20:47 +02:00
}
2020-12-24 22:52:41 +01:00
// eslint-disable-next-line no-unused-vars
2020-06-17 04:20:47 +02:00
currentEmojisWithCategories = calculateCurrentEmojisWithCategories()
}
//
// Handle active search item (i.e. pressing up or down while searching)
//
2020-12-24 22:52:41 +01:00
/* eslint-disable no-unused-vars */
$: activeSearchItemId = activeSearchItem !== -1 && currentEmojis[activeSearchItem].id
2020-12-24 22:52:41 +01:00
/* eslint-enable no-unused-vars */
2020-06-15 19:38:39 +02:00
//
// Handle user input on the search input
//
$: {
requestIdleCallback(() => {
2020-06-23 03:59:22 +02:00
searchText = (rawSearchText || '').trim() // defer to avoid input delays, plus we can trim here
2020-06-15 19:38:39 +02:00
activeSearchItem = -1
})
}
2020-06-02 17:42:33 +02:00
// eslint-disable-next-line no-unused-vars
function onSearchKeydown (event) {
if (!searchMode || !currentEmojis.length) {
return
}
2020-06-04 04:12:33 +02:00
const goToNextOrPrevious = (previous) => {
2020-06-08 16:49:01 +02:00
halt(event)
activeSearchItem = incrementOrDecrement(previous, activeSearchItem, currentEmojis)
2020-06-04 04:12:33 +02:00
}
2020-06-02 17:42:33 +02:00
switch (event.key) {
case 'ArrowDown':
2020-06-04 04:12:33 +02:00
return goToNextOrPrevious(false)
2020-06-02 17:42:33 +02:00
case 'ArrowUp':
2020-06-04 04:12:33 +02:00
return goToNextOrPrevious(true)
2020-06-08 16:49:01 +02:00
case 'Enter':
if (activeSearchItem !== -1) {
halt(event)
return clickEmoji(currentEmojis[activeSearchItem].id)
} else if (currentEmojis.length) {
activeSearchItem = 0
2020-06-08 16:49:01 +02:00
}
2020-06-02 17:42:33 +02:00
}
}
2020-06-15 19:38:39 +02:00
//
// Handle user input on nav
//
2020-06-15 22:20:32 +02:00
// eslint-disable-next-line no-unused-vars
2020-06-17 05:17:42 +02:00
function onNavClick (group) {
2020-06-15 22:20:32 +02:00
rawSearchText = ''
searchText = ''
activeSearchItem = -1
2020-06-17 05:17:42 +02:00
currentGroupIndex = groups.findIndex(_ => _.id === group.id)
2020-06-15 22:20:32 +02:00
}
2020-06-04 03:42:27 +02:00
// eslint-disable-next-line no-unused-vars
function onNavKeydown (event) {
const { target, key } = event
const doFocus = el => {
if (el) {
halt(event)
el.focus()
}
}
2020-06-04 03:42:27 +02:00
switch (key) {
case 'ArrowLeft':
return doFocus(target.previousSibling)
2020-06-04 03:42:27 +02:00
case 'ArrowRight':
return doFocus(target.nextSibling)
case 'Home':
return doFocus(target.parentElement.firstChild)
case 'End':
return doFocus(target.parentElement.lastChild)
2020-06-04 03:42:27 +02:00
}
}
2020-06-15 19:38:39 +02:00
//
// Handle user input on an emoji
//
2020-06-15 02:30:32 +02:00
async function clickEmoji (unicodeOrName) {
2020-06-15 08:38:43 +02:00
const emoji = await database.getEmojiByUnicodeOrName(unicodeOrName)
2020-06-15 02:30:32 +02:00
const emojiSummary = [...currentEmojis, ...currentFavorites]
.find(_ => (_.id === unicodeOrName))
2020-06-15 02:30:32 +02:00
const skinTonedUnicode = emojiSummary.unicode && unicodeWithSkin(emojiSummary, currentSkinTone)
await database.incrementFavoriteEmojiCount(unicodeOrName)
fireEvent('emoji-click', {
emoji,
skinTone: currentSkinTone,
2020-06-15 02:39:52 +02:00
...(skinTonedUnicode && { unicode: skinTonedUnicode }),
...(emojiSummary.name && { name: emojiSummary.name })
})
2020-06-08 16:49:01 +02:00
}
2020-06-06 18:54:23 +02:00
// eslint-disable-next-line no-unused-vars
async function onEmojiClick (event) {
const { target } = event
if (!target.classList.contains('emoji')) {
2020-06-06 18:54:23 +02:00
return
}
2020-06-08 16:49:01 +02:00
halt(event)
const id = target.id.substring(4) // replace 'emo-' or 'fav-' prefix
2020-06-06 18:54:23 +02:00
2020-06-15 02:30:32 +02:00
/* no await */ clickEmoji(id)
2020-06-06 18:54:23 +02:00
}
2020-06-15 19:38:39 +02:00
//
// Handle user input on the skintone picker
//
2020-06-09 05:48:41 +02:00
2020-06-08 04:48:38 +02:00
// eslint-disable-next-line no-unused-vars
async function onSkinToneOptionsClick (event) {
2020-06-09 05:48:41 +02:00
const { target } = event
if (!isSkinToneOption(target)) {
2020-06-09 05:48:41 +02:00
return
}
halt(event)
const skinTone = parseInt(target.id.slice(9), 10) // remove 'skintone-' prefix
currentSkinTone = skinTone
skinTonePickerExpanded = false
focus('skintone-button')
fireEvent('skin-tone-change', { skinTone })
2020-06-12 05:04:42 +02:00
/* no await */ database.setPreferredSkinTone(skinTone)
2020-06-08 04:48:38 +02:00
}
// eslint-disable-next-line no-unused-vars
2020-06-09 05:48:41 +02:00
async function onClickSkinToneButton (event) {
skinTonePickerExpanded = !skinTonePickerExpanded
2020-06-08 04:48:38 +02:00
activeSkinTone = currentSkinTone
2020-06-09 05:48:41 +02:00
if (skinTonePickerExpanded) {
halt(event)
requestAnimationFrame(() => focus(`skintone-${activeSkinTone}`))
2020-06-09 05:48:41 +02:00
}
2020-06-08 04:48:38 +02:00
}
// To make the animation nicer, change the z-index of the skintone picker button
// *after* the animation has played. This makes it appear that the picker box
// is expanding "below" the button
$: {
if (skinTonePickerExpanded) {
skinToneDropdown.addEventListener('transitionend', () => {
2020-12-24 22:52:41 +01:00
skinTonePickerExpandedAfterAnimation = true // eslint-disable-line no-unused-vars
}, { once: true })
} else {
2020-12-24 22:52:41 +01:00
skinTonePickerExpandedAfterAnimation = false // eslint-disable-line no-unused-vars
}
}
2020-06-08 04:48:38 +02:00
// eslint-disable-next-line no-unused-vars
function onSkinToneOptionsKeydown (event) {
2020-06-09 05:48:41 +02:00
if (!skinTonePickerExpanded) {
2020-06-08 05:49:21 +02:00
return
}
const changeActiveSkinTone = async nextSkinTone => {
2020-06-08 16:49:01 +02:00
halt(event)
activeSkinTone = nextSkinTone
2020-06-09 05:48:41 +02:00
await tick()
focus(`skintone-${activeSkinTone}`)
2020-06-08 04:48:38 +02:00
}
switch (event.key) {
2020-06-08 04:48:38 +02:00
case 'ArrowUp':
return changeActiveSkinTone(incrementOrDecrement(true, activeSkinTone, skinTones))
2020-06-08 04:48:38 +02:00
case 'ArrowDown':
return changeActiveSkinTone(incrementOrDecrement(false, activeSkinTone, skinTones))
case 'Home':
return changeActiveSkinTone(0)
case 'End':
return changeActiveSkinTone(skinTones.length - 1)
case 'Enter':
// enter on keydown, space on keyup. this is just how browsers work for buttons
// https://lists.w3.org/Archives/Public/w3c-wai-ig/2019JanMar/0086.html
return onSkinToneOptionsClick(event)
case 'Escape':
halt(event)
skinTonePickerExpanded = false
return focus('skintone-button')
}
}
// eslint-disable-next-line no-unused-vars
function onSkinToneOptionsKeyup (event) {
if (!skinTonePickerExpanded) {
return
}
switch (event.key) {
case ' ':
// enter on keydown, space on keyup. this is just how browsers work for buttons
// https://lists.w3.org/Archives/Public/w3c-wai-ig/2019JanMar/0086.html
return onSkinToneOptionsClick(event)
}
}
// eslint-disable-next-line no-unused-vars
async function onSkinToneOptionsFocusOut (event) {
// On blur outside of the skintone options, collapse the skintone picker.
// Except if focus is just moving to another skintone option, e.g. pressing up/down to change focus
const { relatedTarget } = event
if (!relatedTarget || !isSkinToneOption(relatedTarget)) {
skinTonePickerExpanded = false
2020-06-09 05:48:41 +02:00
}
}