emoji-picker-element/README.md

988 lines
43 KiB
Markdown
Raw Permalink Normal View History

emoji-picker-element
2020-05-07 05:17:27 +02:00
====
2020-06-24 16:56:40 +02:00
![Screenshot of emoji-picker-element in light and dark modes](https://nolanwlawson.files.wordpress.com/2020/06/out.png)
2020-06-21 20:55:27 +02:00
```html
<emoji-picker></emoji-picker>
```
2020-06-22 17:16:06 +02:00
A lightweight emoji picker, distributed as a web component.
2020-05-07 05:17:27 +02:00
2020-10-18 00:16:06 +02:00
**Features:**
2020-05-07 05:17:27 +02:00
- Supports [Emoji v15.1](https://emojipedia.org/emoji-15.1/) (depending on OS) and custom emoji
2020-10-18 00:16:06 +02:00
- Uses IndexedDB, so it consumes [far less memory](https://nolanlawson.com/2020/06/28/introducing-emoji-picker-element-a-memory-efficient-emoji-picker-for-the-web/) than other emoji pickers
- [Small bundle size](https://bundlephobia.com/result?p=emoji-picker-element) (<15kB min+gz)
- Renders native emoji by default, with support for custom fonts
- [Accessible by default](https://nolanlawson.com/2020/07/01/building-an-accessible-emoji-picker/)
2020-10-18 00:16:06 +02:00
- Framework and bundler not required, just add a `<script>` tag and use it
2020-05-18 00:42:13 +02:00
2020-06-21 20:55:27 +02:00
**Table of contents:**
<!-- toc start -->
2020-06-25 03:03:24 +02:00
- [emoji-picker-element](#emoji-picker-element-)
2020-06-21 20:55:27 +02:00
* [Usage](#usage)
2020-10-19 16:46:59 +02:00
+ [Examples](#examples)
+ [Emoji support](#emoji-support)
- [Custom emoji font](#custom-emoji-font)
- [Polyfilling flag emoji on Windows](#polyfilling-flag-emoji-on-windows)
2020-06-21 20:55:27 +02:00
* [Styling](#styling)
+ [Size](#size)
+ [Dark mode](#dark-mode)
+ [CSS variables](#css-variables)
+ [Focus outline](#focus-outline)
+ [Small screen sizes](#small-screen-sizes)
2020-06-22 17:16:22 +02:00
+ [Custom styling](#custom-styling)
2020-06-21 20:55:27 +02:00
* [JavaScript API](#javascript-api)
+ [Picker](#picker)
2021-08-06 19:27:54 +02:00
- [Events](#events)
* [`emoji-click`](#emoji-click)
* [`skin-tone-change`](#skin-tone-change)
- [Internationalization](#internationalization)
* [Built-in translations](#built-in-translations)
- [Custom category order](#custom-category-order)
2020-06-21 20:55:27 +02:00
+ [Database](#database)
- [Constructors](#constructors)
* [constructor](#constructor)
- [Accessors](#accessors)
* [customEmoji](#customemoji)
- [Methods](#methods)
* [close](#close)
* [delete](#delete)
* [getEmojiByGroup](#getemojibygroup)
* [getEmojiBySearchQuery](#getemojibysearchquery)
* [getEmojiByShortcode](#getemojibyshortcode)
* [getEmojiByUnicodeOrName](#getemojibyunicodeorname)
* [getPreferredSkinTone](#getpreferredskintone)
* [getTopFavoriteEmoji](#gettopfavoriteemoji)
* [incrementFavoriteEmojiCount](#incrementfavoriteemojicount)
* [ready](#ready)
* [setPreferredSkinTone](#setpreferredskintone)
+ [Custom emoji](#custom-emoji)
+ [Tree-shaking](#tree-shaking)
+ [Within a meta-framework (Next.js, SvelteKit, etc.)](#within-a-meta-framework-nextjs-sveltekit-etc)
2020-06-21 20:55:27 +02:00
+ [Within a Svelte project](#within-a-svelte-project)
* [Data and offline](#data-and-offline)
+ [Data source and JSON format](#data-source-and-json-format)
+ [Shortcodes](#shortcodes)
+ [Cache performance](#cache-performance)
+ [emojibase-data compatibility (deprecated)](#emojibase-data-compatibility-deprecated)
+ [Trimming the emoji data (deprecated)](#trimming-the-emoji-data-deprecated)
2020-06-21 20:55:27 +02:00
+ [Offline-first](#offline-first)
+ [Environments without IndexedDB](#environments-without-indexeddb)
2020-06-21 20:55:27 +02:00
* [Design decisions](#design-decisions)
+ [IndexedDB](#indexeddb)
+ [Native emoji](#native-emoji)
+ [JSON loading](#json-loading)
+ [Browser support](#browser-support)
* [Contributing](#contributing)
<!-- toc end -->
## Usage
2020-05-18 00:42:13 +02:00
Via npm:
2020-05-18 00:42:13 +02:00
npm install emoji-picker-element
2020-05-18 00:42:13 +02:00
```js
2020-06-06 06:02:53 +02:00
import 'emoji-picker-element';
2020-05-18 00:42:13 +02:00
```
Or as a `<script>` tag:
```html
<script type="module" src="https://cdn.jsdelivr.net/npm/emoji-picker-element@^1/index.js"></script>
```
Then use the HTML:
2020-06-22 17:16:06 +02:00
```html
<emoji-picker></emoji-picker>
```
And listen for `emoji-click` events:
2020-06-06 17:43:38 +02:00
```js
2020-06-07 05:47:49 +02:00
document.querySelector('emoji-picker')
.addEventListener('emoji-click', event => console.log(event.detail));
2020-06-06 18:54:23 +02:00
```
This will log:
```json
{
2020-06-22 17:16:06 +02:00
"emoji": {
"annotation": "grinning face",
"group": 0,
"order": 1,
"shortcodes": [ "grinning_face", "grinning" ],
2020-06-22 17:16:06 +02:00
"tags": [ "face", "grin" ],
"unicode": "😀",
"version": 1,
"emoticon": ":D"
},
"skinTone": 0,
"unicode": "😀"
2020-06-06 18:54:23 +02:00
}
```
2020-10-19 16:46:59 +02:00
### Examples
- [Demo](https://nolanlawson.github.io/emoji-picker-element) ([source](https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/index.html))
2022-12-28 23:53:55 +01:00
- [Button with tooltip/popover](https://nolanlawson.github.io/emoji-picker-element/demos/tooltip/index.html) ([source](https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/demos/tooltip/index.html))
- [Inserting emoji into a text input](https://nolanlawson.github.io/emoji-picker-element/demos/input/index.html) ([source](https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/demos/input/index.html))
- [In a React app](https://nolanlawson.github.io/emoji-picker-element/demos/react/index.html) ([source](https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/demos/react/index.html))
- [Custom emoji font](https://nolanlawson.github.io/emoji-picker-element/demos/twemoji-mozilla/index.html) ([source](https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/demos/twemoji-mozilla/index.html))
2022-12-28 23:53:55 +01:00
- [Fallback for missing flag emoji on Windows](https://nolanlawson.github.io/emoji-picker-element/demos/flags/index.html) ([source](https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/demos/flags/index.html))
2020-10-19 16:46:59 +02:00
### Emoji support
[Emoji support varies](https://nolanlawson.com/2022/04/08/the-struggle-of-using-native-emoji-on-the-web/) across browsers and operating systems. By default, `emoji-picker-element` will hide unsupported emoji from the picker.
To work around this, you can use [a custom emoji font](#custom-emoji-font) or [polyfill flag emoji on Windows](#polyfilling-flag-emoji-on-windows).
#### Custom emoji font
To use a custom emoji font, first set the `--emoji-font-family` CSS property:
```css
emoji-picker {
--emoji-font-family: MyCustomFont;
}
```
Then, specify the maximum emoji version supported by the font (see [Emojipedia](https://emojipedia.org/emoji-versions/) for a list of versions).
In HTML:
```html
2023-06-11 06:15:57 +02:00
<emoji-picker emoji-version="15.0"></emoji-picker>
```
Or JavaScript:
```js
const picker = new Picker({
2023-06-11 06:15:57 +02:00
emojiVersion: 15.0
});
```
If the `emoji-version`/`emojiVersion` option is set, then `emoji-picker-element` will not attempt to detect unsupported emoji or hide them.
Also note that support for color fonts [varies across browsers and OSes](https://caniuse.com/colr), and some browsers may have <a href="https://github.com/nolanlawson/emoji-picker-element/pull/308#issuecomment-1367491149">bugs</a> or not render the font at all. Be careful to test your supported browsers when using this approach.
#### Polyfilling flag emoji on Windows
As of this writing, [Windows does not support country flag emoji](https://answers.microsoft.com/en-us/windows/forum/all/where-are-the-flag-emoji-in-windows-10/93daa6e8-880a-48b1-9891-ab5bfbfbce98). This is only a problem in Chromium-based browsers, because Firefox ships with its own emoji font.
To work around this, you can use [country-flag-emoji-polyfill](https://www.npmjs.com/package/country-flag-emoji-polyfill):
```js
import { polyfillCountryFlagEmojis } from 'country-flag-emoji-polyfill';
// emoji-picker-element will use "Twemoji Mozilla" and fall back to other fonts for non-flag emoji
polyfillCountryFlagEmojis('Twemoji Mozilla');
```
Note that you do not need to do this if you are using [a custom emoji font](#custom-emoji-font).
2020-06-06 23:35:53 +02:00
## Styling
2020-05-18 00:42:13 +02:00
2020-06-22 17:16:06 +02:00
`emoji-picker-element` uses [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM), so its inner styling cannot be (easily) changed with arbitrary CSS. Refer to the API below for style customization.
2020-06-06 23:35:53 +02:00
### Size
2020-06-06 17:43:38 +02:00
2020-06-09 17:00:48 +02:00
`emoji-picker-element` has a default size, but you can change it to whatever you want:
2020-06-06 17:43:38 +02:00
```css
emoji-picker {
width: 400px;
height: 300px;
}
```
For instance, to make it expand to fit whatever container you give it:
```css
emoji-picker {
width: 100%;
height: 100%;
}
```
2020-06-06 23:35:53 +02:00
### Dark mode
2020-06-03 04:02:26 +02:00
2020-06-06 17:43:38 +02:00
By default, `emoji-picker-element` will automatically switch to dark mode based on
[`prefers-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme).
2020-06-07 05:48:29 +02:00
Or you can add the class `dark` or `light` to force dark/light mode:
2020-06-03 04:02:26 +02:00
```html
2020-06-06 06:02:53 +02:00
<emoji-picker class="dark"></emoji-picker>
<emoji-picker class="light"></emoji-picker>
2020-06-03 04:02:26 +02:00
```
2020-06-06 23:35:53 +02:00
### CSS variables
2020-06-03 04:02:26 +02:00
2020-06-06 23:18:57 +02:00
Most colors and sizes can be styled with CSS variables. For example:
2020-06-03 04:23:07 +02:00
```css
2020-06-06 06:02:53 +02:00
emoji-picker {
--num-columns: 6;
--emoji-size: 3rem;
--background: gray;
2020-06-03 04:23:07 +02:00
}
```
2020-06-03 04:02:26 +02:00
Here is a full list of options:
<!-- CSS variable options start -->
| Variable | Default | Default (dark) | Description |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------- |
| `--background` | `#fff` | `#222` | Background of the entire `<emoji-picker>` |
| `--border-color` | `#e0e0e0` | `#444` | |
| `--border-size` | `1px` | | Width of border used in most of the picker |
| `--button-active-background` | `#e6e6e6` | `#555555` | Background of an active button |
| `--button-hover-background` | `#d9d9d9` | `#484848` | Background of a hovered button |
| `--category-emoji-padding` | `var(--emoji-padding)` | | Vertical/horizontal padding on category emoji, if you want it to be different from `--emoji-padding` |
| `--category-emoji-size` | `var(--emoji-size)` | | Width/height of category emoji, if you want it to be different from `--emoji-size` |
| `--category-font-color` | `#111` | `#efefef` | Font color of custom emoji category headings |
| `--category-font-size` | `1rem` | | Font size of custom emoji category headings |
| `--emoji-font-family` | `"Twemoji Mozilla","Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji","EmojiOne Color","Android Emoji",sans-serif` | | Font family for a custom emoji font (as opposed to native emoji) |
| `--emoji-padding` | `0.5rem` | | Vertical and horizontal padding on emoji |
| `--emoji-size` | `1.375rem` | | Width and height of all emoji |
| `--indicator-color` | `#385ac1` | `#5373ec` | Color of the nav indicator |
| `--indicator-height` | `3px` | | Height of the nav indicator |
| `--input-border-color` | `#999` | `#ccc` | |
| `--input-border-radius` | `0.5rem` | | |
| `--input-border-size` | `1px` | | |
| `--input-font-color` | `#111` | `#efefef` | |
| `--input-font-size` | `1rem` | | |
| `--input-line-height` | `1.5` | | |
| `--input-padding` | `0.25rem` | | |
| `--input-placeholder-color` | `#999` | `#ccc` | |
| `--num-columns` | `8` | | How many columns to display in the emoji grid |
| `--outline-color` | `#999` | `#fff` | Focus outline color |
| `--outline-size` | `2px` | | Focus outline width |
| `--skintone-border-radius` | `1rem` | | Border radius of the skintone dropdown |
<!-- CSS variable options end -->
2020-06-06 23:35:53 +02:00
### Focus outline
For accessibility reasons, `emoji-picker-element` displays a prominent focus ring for keyboard users. This uses [`:focus-visible`](https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-visible) under the hood. To properly support [browsers that do not support `:focus-visible`](https://caniuse.com/css-focus-visible), you can use the [focus-visible](https://github.com/WICG/focus-visible) polyfill, e.g.:
2020-06-06 23:35:53 +02:00
```js
2020-06-17 06:42:41 +02:00
import 'focus-visible';
2020-06-06 23:35:53 +02:00
const picker = new Picker();
applyFocusVisiblePolyfill(picker.shadowRoot);
```
2020-06-09 17:01:36 +02:00
`emoji-picker-element` already ships with the proper CSS for both the `:focus-visible` standard and the polyfill.
2020-06-06 23:35:53 +02:00
### Small screen sizes
For small screen sizes, you should probably add some CSS like the following:
```css
@media screen and (max-width: 320px) {
emoji-picker {
--num-columns: 6;
--category-emoji-size: 1.125rem;
}
}
```
`emoji-picker-element` does not ship with any CSS to explicitly handle small screen sizes. The right CSS depends on which screen sizes your app supports, and the size of the picker within your app. Perhaps in the future [container queries](https://caniuse.com/css-container-queries) can solve this problem.
2020-06-22 17:16:06 +02:00
### Custom styling
If you absolutely must go beyond the styling API above, you can do something like this:
```js
const style = document.createElement('style');
style.textContent = `/* custom shadow dom styles here */`
picker.shadowRoot.appendChild(style);
```
2020-06-06 23:35:53 +02:00
## JavaScript API
### Picker
2020-06-21 20:55:27 +02:00
Basic usage:
2020-06-06 23:35:53 +02:00
```js
import { Picker } from 'emoji-picker-element';
const picker = new Picker();
document.body.appendChild(picker);
```
2020-06-07 02:36:03 +02:00
The `new Picker(options)` constructor supports several options:
2020-06-06 23:35:53 +02:00
| Name | Type | Default | Description |
|-------------------------|---------------|------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
| `customCategorySorting` | function | - | Function to sort custom category strings (sorted alphabetically by default) |
| `customEmoji` | CustomEmoji[] | - | Array of custom emoji |
| `dataSource` | string | "https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json" | URL to fetch the emoji data from (`data-source` when used as an attribute) |
| `emojiVersion` | number | - | Maximum supported emoji version as a number (e.g. `14.0` or `13.1`). Setting this disables the default emoji support detection. |
| `i18n` | I18n | - | i18n object (see below for details) |
| `locale` | string | "en" | Locale string |
| `skinToneEmoji` | string | "🖐️" | The emoji to use for the skin tone picker (`skin-tone-emoji` when used as an attribute) |
2020-06-07 02:36:03 +02:00
2020-06-21 20:55:27 +02:00
For instance:
```js
const picker = new Picker({
locale: 'fr',
dataSource: '/fr-emoji.json'
})
```
These values can also be set at runtime:
2020-06-06 23:35:53 +02:00
```js
const picker = new Picker();
picker.dataSource = '/my-emoji.json';
```
Some values can also be set as declarative attributes:
```html
<emoji-picker
locale="fr"
data-source="/fr-emoji.json"
skin-tone-emoji="✌"
></emoji-picker>
```
Note that complex properties like `i18n` or `customEmoji` are not supported as attributes, because the DOM only
supports string attributes, not complex objects.
2021-08-06 19:27:54 +02:00
#### Events
##### `emoji-click`
The `emoji-click` event is fired when an emoji is selected by the user. Example format:
```javascript
{
emoji: {
annotation: 'thumbs up',
group: 1,
order: 280,
shortcodes: ['thumbsup', '+1', 'yes'],
tags: ['+1', 'hand', 'thumb', 'up'],
unicode: '👍️',
version: 0.6,
skins: [
{ tone: 1, unicode: '👍🏻', version: 1 },
{ tone: 2, unicode: '👍🏼', version: 1 },
{ tone: 3, unicode: '👍🏽', version: 1 },
{ tone: 4, unicode: '👍🏾', version: 1 },
{ tone: 5, unicode: '👍🏿', version: 1 }
]
},
skinTone: 4,
unicode: '👍🏾'
}
```
And usage:
```js
picker.addEventListener('emoji-click', event => {
console.log(event.detail); // will log something like the above
});
```
Note that `unicode` will represent whatever the emoji should look like
with the given `skinTone`. If the `skinTone` is 0, or if the emoji has
no skin tones, then no skin tone is applied to `unicode`.
##### `skin-tone-change`
This event is fired whenever the user selects a new skin tone. Example format:
```js
{
skinTone: 5
}
```
And usage:
```js
picker.addEventListener('skin-tone-change', event => {
console.log(event.detail); // will log something like the above
})
```
Note that skin tones are an integer from 0 (default) to 1 (light) through 5 (dark).
#### Internationalization
2020-06-06 23:35:53 +02:00
The `i18n` parameter specifies translations for the picker interface. Here is the default English `i18n` object:
2020-06-06 23:35:53 +02:00
<!-- i18n options start -->
```json
{
"categories": {
2020-06-15 02:41:03 +02:00
"custom": "Custom",
2020-06-06 23:35:53 +02:00
"smileys-emotion": "Smileys and emoticons",
"people-body": "People and body",
"animals-nature": "Animals and nature",
"food-drink": "Food and drink",
"travel-places": "Travel and places",
"activities": "Activities",
"objects": "Objects",
"symbols": "Symbols",
"flags": "Flags"
},
"categoriesLabel": "Categories",
"emojiUnsupportedMessage": "Your browser does not support color emoji.",
2020-06-13 05:16:56 +02:00
"favoritesLabel": "Favorites",
"loadingMessage": "Loading…",
"networkErrorMessage": "Could not load emoji.",
2020-06-06 23:35:53 +02:00
"regionLabel": "Emoji picker",
2020-06-09 05:56:10 +02:00
"searchDescription": "When search results are available, press up or down to select and enter to choose.",
"searchLabel": "Search",
2020-06-06 23:35:53 +02:00
"searchResultsLabel": "Search results",
2020-06-09 05:56:10 +02:00
"skinToneDescription": "When expanded, press up or down to select and enter to choose.",
2020-06-11 05:14:26 +02:00
"skinToneLabel": "Choose a skin tone (currently {skinTone})",
2020-06-08 04:50:31 +02:00
"skinTones": [
"Default",
"Light",
"Medium-Light",
"Medium",
"Medium-Dark",
"Dark"
],
"skinTonesLabel": "Skin tones"
2020-06-06 23:35:53 +02:00
}
```
<!-- i18n options end -->
Note that some of these strings are only visible to users of screen readers. They are still important for accessibility!
##### Built-in translations
2021-08-06 19:21:56 +02:00
Community-provided translations for some languages [are available](https://github.com/nolanlawson/emoji-picker-element/tree/master/src/picker/i18n). You can use them like so:
```js
import fr from 'emoji-picker-element/i18n/fr';
import de from 'emoji-picker-element/i18n/de';
// French
picker.i18n = fr;
// German
picker.i18n = de;
```
Note that translations for the interface (`i18n`) are not the same as translations for the emoji data (`dataSource` and `locale`). To support both, you should do something like:
```js
import fr from 'emoji-picker-element/i18n/fr';
const picker = new Picker({
i18n: fr,
locale: 'fr',
dataSource: 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/fr/emojibase/data.json',
});
```
2021-08-06 19:21:56 +02:00
If a built-in translation for your target language is not available, you can also write your own translation and pass it in as `i18n`. Please feel free to contribute your translation [here](https://github.com/nolanlawson/emoji-picker-element/tree/master/src/picker/i18n).
2020-06-06 23:35:53 +02:00
#### Custom category order
By default, custom categories are sorted alphabetically. To change this, pass in your own `customCategorySorting`:
```js
picker.customCategorySorting = (category1, category2) => { /* your sorting code */ };
```
This function should accept two strings and return a number.
Custom emoji with no category will pass in `undefined`. By default, these are shown first, with the label `"Custom"`
(determined by `i18n.categories.custom`).
### Database
2020-06-06 23:35:53 +02:00
You can work with the database API separately, which allows you to query emoji the same
way that the picker does:
```js
2020-06-06 06:02:53 +02:00
import { Database } from 'emoji-picker-element';
const database = new Database();
await database.getEmojiBySearchPrefix('elephant'); // [{unicode: "🐘", ...}]
```
2020-06-09 17:07:50 +02:00
Note that under the hood, IndexedDB data is partitioned based on the `locale`. So if you create two `Database`s with two different `locale`s, it will store twice as much data.
Also note that, unlike the picker, the database does not filter emoji based on whether they are supported by the current browser/OS or not. To detect emoji support, you can use a library like [is-emoji-supported](https://github.com/koala-interactive/is-emoji-supported).
2020-06-07 02:36:03 +02:00
Full API:
2020-06-21 20:55:27 +02:00
#### Constructors
##### constructor
2020-06-07 02:36:03 +02:00
\+ **new Database**(`__namedParameters`: object): *Database*
Create a new Database.
Note that multiple Databases pointing to the same locale will share the
same underlying IndexedDB connection and database.
**Parameters:**
▪`Default value` **__namedParameters**: *object*= {}
Name | Type | Default | Description |
------ | ------ | ------ | ------ |
`customEmoji` | CustomEmoji[] | [] | Array of custom emoji |
`dataSource` | string | "https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json" | URL to fetch the emoji data from |
2020-06-14 21:09:11 +02:00
`locale` | string | "en" | Locale string |
**Returns:** *Database*
2020-06-14 21:09:11 +02:00
2020-06-21 20:55:27 +02:00
#### Accessors
2020-06-14 21:09:11 +02:00
2020-06-21 20:55:27 +02:00
##### customEmoji
2020-06-14 21:09:11 +02:00
**get customEmoji**(): *CustomEmoji[]*
2020-06-14 21:09:11 +02:00
Return the custom emoji associated with this Database, or the empty array if none.
**Returns:** *CustomEmoji[]*
2020-06-14 21:09:11 +02:00
**set customEmoji**(`customEmoji`: CustomEmoji[]): *void*
2020-06-07 02:36:03 +02:00
2020-06-14 21:09:11 +02:00
Set the custom emoji for this database. Throws an error if custom emoji are not in the correct format.
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
`customEmoji` | CustomEmoji[] | |
2020-06-14 21:09:11 +02:00
**Returns:** *void*
2020-06-07 02:36:03 +02:00
2020-06-21 20:55:27 +02:00
#### Methods
2020-06-07 02:36:03 +02:00
2020-06-21 20:55:27 +02:00
##### close
2020-06-07 02:36:03 +02:00
**close**(): *Promisevoid*
Closes the underlying IndexedDB connection. The Database is not usable after that (or any other Databases
with the same locale).
2020-06-14 03:23:50 +02:00
Note that as soon as any other non-close/delete method is called, the database will automatically reopen.
2020-06-07 02:36:03 +02:00
**Returns:** *Promisevoid*
___
2020-06-21 20:55:27 +02:00
##### delete
2020-06-07 02:36:03 +02:00
**delete**(): *Promisevoid*
Deletes the underlying IndexedDB database. The Database is not usable after that (or any other Databases
with the same locale).
2020-06-14 03:23:50 +02:00
Note that as soon as any other non-close/delete method is called, the database will be recreated.
2020-06-07 02:36:03 +02:00
**Returns:** *Promisevoid*
___
2020-06-21 20:55:27 +02:00
##### getEmojiByGroup
2020-06-07 02:36:03 +02:00
**getEmojiByGroup**(`group`: number): *PromiseNativeEmoji[]*
2020-06-07 02:36:03 +02:00
2020-06-14 21:09:11 +02:00
Returns all emoji belonging to a group, ordered by `order`. Only returns native emoji;
custom emoji don't belong to a group.
2020-06-07 02:36:03 +02:00
2020-06-07 05:46:03 +02:00
Non-numbers throw an error.
2020-06-07 02:36:03 +02:00
**Parameters:**
2020-06-07 02:36:03 +02:00
Name | Type | Description |
------ | ------ | ------ |
`group` | number | the group number |
**Returns:** *PromiseNativeEmoji[]*
2020-06-07 02:36:03 +02:00
___
2020-06-21 20:55:27 +02:00
##### getEmojiBySearchQuery
2020-06-07 02:36:03 +02:00
**getEmojiBySearchQuery**(`query`: string): *PromiseEmoji[]*
2020-06-07 02:36:03 +02:00
Returns all emoji matching the given search query, ordered by `order`.
2020-06-07 05:46:03 +02:00
Empty/null strings throw an error.
2020-06-07 02:36:03 +02:00
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
`query` | string | search query string |
**Returns:** *PromiseEmoji[]*
2020-06-07 02:36:03 +02:00
___
2020-06-21 20:55:27 +02:00
##### getEmojiByShortcode
2020-06-07 02:36:03 +02:00
**getEmojiByShortcode**(`shortcode`: string): *PromiseEmoji | null*
2020-06-07 02:36:03 +02:00
Return a single emoji matching the shortcode, or null if not found.
2020-06-07 05:46:03 +02:00
The colons around the shortcode should not be included when querying, e.g.
use "slight_smile", not ":slight_smile:". Uppercase versus lowercase
does not matter. Empty/null strings throw an error.
2020-06-07 02:36:03 +02:00
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
`shortcode` | string | |
**Returns:** *PromiseEmoji | null*
___
2020-06-21 20:55:27 +02:00
##### getEmojiByUnicodeOrName
2020-06-07 02:36:03 +02:00
2020-06-15 08:38:43 +02:00
**getEmojiByUnicodeOrName**(`unicodeOrName`: string): *PromiseEmoji | null*
2020-06-07 02:36:03 +02:00
2020-06-15 08:38:43 +02:00
Return a single native emoji matching the unicode string, or
a custom emoji matching the name, or null if not found.
2020-06-07 02:36:03 +02:00
2020-06-27 22:28:15 +02:00
In the case of native emoji, the unicode string can be either the
main unicode string, or the unicode of one of the skin tone variants.
2020-06-07 05:46:03 +02:00
Empty/null strings throw an error.
2020-06-07 02:36:03 +02:00
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
2020-06-15 08:38:43 +02:00
`unicodeOrName` | string | unicode (native emoji) or name (custom emoji) |
2020-06-07 02:36:03 +02:00
2020-06-15 08:38:43 +02:00
**Returns:** *PromiseEmoji | null*
2020-06-07 02:36:03 +02:00
___
2020-06-21 20:55:27 +02:00
##### getPreferredSkinTone
**getPreferredSkinTone**(): *PromiseSkinTone*
Get the user's preferred skin tone. Returns 0 if not found.
**Returns:** *PromiseSkinTone*
___
2020-06-21 20:55:27 +02:00
##### getTopFavoriteEmoji
2020-06-12 17:08:57 +02:00
**getTopFavoriteEmoji**(`limit`: number): *PromiseEmoji[]*
2020-06-12 17:08:57 +02:00
Get the top favorite emoji in descending order. If there are no favorite emoji yet, returns an empty array.
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
2020-06-14 21:09:11 +02:00
`limit` | number | maximum number of results to return |
2020-06-12 17:08:57 +02:00
**Returns:** *PromiseEmoji[]*
2020-06-12 17:08:57 +02:00
___
2020-06-21 20:55:27 +02:00
##### incrementFavoriteEmojiCount
2020-06-12 17:08:57 +02:00
2020-06-15 02:41:03 +02:00
**incrementFavoriteEmojiCount**(`unicodeOrName`: string): *Promisevoid*
2020-06-12 17:08:57 +02:00
Increment the favorite count for an emoji by one. The unicode string must be non-empty. It should
2020-06-14 21:09:11 +02:00
correspond to the base (non-skin-tone) unicode string from the emoji object, or in the case of
2020-06-15 02:41:03 +02:00
custom emoji, it should be the name.
2020-06-12 17:08:57 +02:00
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
2020-06-15 02:41:03 +02:00
`unicodeOrName` | string | unicode of a native emoji, or name of a custom emoji |
2020-06-12 17:08:57 +02:00
**Returns:** *Promisevoid*
___
2020-06-21 20:55:27 +02:00
##### ready
2020-06-07 02:36:03 +02:00
**ready**(): *Promisevoid*
Resolves when the Database is ready, or throws an error if
the Database could not initialize.
Note that you don't need to do this before calling other APIs they will
all wait for this promise to resolve before doing anything.
**Returns:** *Promisevoid*
___
2020-06-21 20:55:27 +02:00
##### setPreferredSkinTone
**setPreferredSkinTone**(`skinTone`: SkinTone): *Promisevoid*
Set the user's preferred skin tone. Non-numbers throw an error.
**Parameters:**
Name | Type | Description |
------ | ------ | ------ |
`skinTone` | SkinTone | preferred skin tone |
**Returns:** *Promisevoid*
2020-06-14 20:30:38 +02:00
### Custom emoji
Both the Picker and the Database support custom emoji. Unlike regular emoji, custom emoji
are kept in-memory. (It's assumed that they're small, and they might frequently change, so
there's not much point in storing them in IndexedDB.)
Custom emoji should follow the format:
```js
[
{
2020-06-17 05:21:40 +02:00
name: 'Garfield',
shortcodes: ['garfield'],
url: 'http://example.com/garfield.png',
category: 'Cats'
2020-06-14 20:30:38 +02:00
},
{
2020-06-17 05:21:40 +02:00
name: 'Heathcliff',
shortcodes: ['heathcliff'],
url: 'http://example.com/heathcliff.png',
category: 'Cats'
},
{
name: 'Scooby-Doo',
shortcodes: ['scooby'],
url: 'http://example.com/scooby.png',
category: 'Dogs'
2020-06-14 20:30:38 +02:00
}
]
```
2020-06-14 23:42:05 +02:00
Note that names are assumed to be unique (case-insensitive), and it's assumed that the `shortcodes` have at least one entry.
2020-06-17 05:21:40 +02:00
The `category` is optional. If you don't provide it, then the custom emoji will appear in a
single category called "Custom".
2020-06-14 20:30:38 +02:00
To pass custom emoji into the `Picker`:
```js
const picker = new Picker({
customEmoji: [ /* ... */ ]
});
2020-06-14 20:30:38 +02:00
```
Or the `Database`:
```js
const database = new Database({
customEmoji: [ /* ... */ ]
});
2020-06-14 20:30:38 +02:00
```
2020-06-17 05:21:40 +02:00
Custom emoji can also be set at runtime:
2020-06-14 20:30:38 +02:00
```js
picker.customEmoji = [ /* ... */ ];
database.customEmoji = [ /* ... */ ];
2020-06-14 20:30:38 +02:00
```
### Tree-shaking
2020-06-06 23:18:57 +02:00
If you want to import the `Database` without the `Picker`, or you want to code-split them separately, then do:
```js
2020-06-06 06:02:53 +02:00
import Picker from 'emoji-picker-element/picker';
import Database from 'emoji-picker-element/database';
```
2020-06-06 23:18:57 +02:00
The reason for this is that `Picker` automatically registers itself as a custom element, following [web component best practices](https://justinfagnani.com/2019/11/01/how-to-publish-web-components-to-npm/). But this adds side effects, so bundlers like Webpack and Rollup do not tree-shake as well, unless the modules are imported from completely separate files.
### Within a meta-framework (Next.js, SvelteKit, etc.)
Some meta-frameworks will attempt to server-side render (SSR) any dependencies you `import`. However, `emoji-picker-element` only supports client-side rendering it does not work on the server side. If you attempt to import it on the server side, you will see an error like `requestAnimationFrame is not defined`.
To load `emoji-picker-element` only on the client side, use your meta-framework's technique for client-side-only imports. For example, you can use [dynamic `import()`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) with [`next/dynamic` in Next.js](https://stackoverflow.com/a/61881528/680742) or [`onMount()` in SvelteKit](https://www.banjocode.com/post/svelte/client-side-library).
`emoji-picker-element` is not designed for SSR. In most apps, an emoji picker should be lazy-loaded upon user interaction (for example, when the user clicks a button).
2020-06-21 20:55:27 +02:00
### Within a Svelte project
> [!WARNING]
> `emoji-picker-element` is no longer based on Svelte, so importing from `emoji-picker-element/svelte` is now deprecated.
Previously, `emoji-picker-element` was based on Svelte v3/v4, and you could do:
2020-06-21 20:55:27 +02:00
```js
import Picker from 'emoji-picker-element/svelte';
2020-06-21 20:55:27 +02:00
```
The goal was to slightly reduce the bundle size by sharing common `svelte` imports.
This is still supported for backwards compatibility, but it is deprecated and just re-exports the Picker. Instead, do:
2020-06-21 20:55:27 +02:00
```js
import Picker from 'emoji-picker-element/picker';
```
## Data and offline
### Data source and JSON format
If you'd like to host the emoji data (`dataSource`) yourself, you can do:
npm install emoji-picker-element-data@^1
2020-06-26 15:03:50 +02:00
Then host `node_modules/emoji-picker-element-data/en/emojibase/data.json` (or other JSON files) on your web server.
2020-06-26 15:03:50 +02:00
```js
const picker = new Picker({
dataSource: '/path/to/my/webserver/data.json'
});
```
See [`emoji-picker-element-data`](https://www.npmjs.com/package/emoji-picker-element-data) for details.
### Shortcodes
2020-06-26 15:03:50 +02:00
There is no standard for shortcodes, so unlike other emoji data, there is some disagreement as to what a "shortcode" actually is.
2020-06-04 04:08:15 +02:00
`emoji-picker-element-data` is based on `emojibase-data`, which offers several shortcode packs per language. For instance,
you may choose shortcodes from GitHub, Slack, Discord, or Emojibase (the default). You
can browse the available data files [on jsdelivr](https://www.jsdelivr.com/package/npm/emoji-picker-element-data) and see
more details on shortcodes [in the Emojibase docs](https://emojibase.dev/docs/shortcodes).
2020-06-04 04:08:15 +02:00
### Cache performance
2020-06-04 04:08:15 +02:00
For optimal cache performance, it's recommended that your server expose an `ETag` header. If so, `emoji-picker-element` can avoid re-downloading the entire JSON file over and over again. Instead, it will do a `HEAD` request and just check the `ETag`.
2020-06-20 23:06:19 +02:00
If the server hosting the JSON file is not the same as the one containing the emoji picker, then the cross-origin server will also need to expose `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: ETag` (or `Access-Control-Allow-Headers: *` ). `jsdelivr` already does this, which is partly why it is the default.
Note that [Safari does not currently support `Access-Control-Allow-Headers: *`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers#Browser_compatibility), but it does support `Access-Control-Allow-Headers: ETag`.
If `emoji-picker-element` cannot use the `ETag` for any reason, it will fall back to the less performant option, doing a full `GET` request on every page load.
### emojibase-data compatibility (deprecated)
_**Deprecated:** in v1.3.0, `emoji-picker-element` switched from [`emojibase-data`](https://github.com/milesj/emojibase) to
[`emoji-picker-element-data`](https://npmjs.com/package/emoji-picker-element-data) as its default data source. You can still use `emojibase-data`, but only v5 is supported, not v6. Support may be removed in a later release._
When using `emojibase-data`, you must use the _full_ [`emojibase-data`](https://github.com/milesj/emojibase) JSON file, not the "compact" one (i.e. `data.json`, not `compact.json`).
### Trimming the emoji data (deprecated)
_**Deprecated:** in v1.3.0, `emoji-picker-element` switched from [`emojibase-data`](https://github.com/milesj/emojibase) to
[`emoji-picker-element-data`](https://npmjs.com/package/emoji-picker-element-data) as its default data source. With the new `emoji-picker-element-data`, there is no need to trim the emoji down to size. This function is deprecated and may be removed eventually._
If you are hosting the `emojibase-data` JSON file yourself and would like it to be as small as possible, then you can use the utility `trimEmojiData` function:
2020-06-20 23:06:19 +02:00
```js
import trimEmojiData from 'emoji-picker-element/trimEmojiData.js';
import emojiBaseData from 'emojibase-data/en/data.json';
const trimmedData = trimEmojiData(emojiBaseData);
```
Or if your version of Node doesn't support ES modules:
```js
const trimEmojiData = require('emoji-picker-element/trimEmojiData.cjs');
```
### Offline-first
2020-06-06 23:18:57 +02:00
`emoji-picker-element` uses a "stale while revalidate" strategy to update emoji data. In other words, it will use any existing data it finds in IndexedDB, and lazily update via the `dataSource` in case that data has changed. This means it will work [offline-first](http://offlinefirst.org/) the second time it runs.
If you would like to manage the database yourself (e.g. to ensure that it's correctly populated before displaying the `Picker`), then create a new `Database` instance and wait for its `ready()` promise to resolve:
```js
2020-06-26 15:03:50 +02:00
const database = new Database();
try {
2020-06-26 15:03:50 +02:00
await database.ready();
} catch (err) {
// Deal with any errors (e.g. offline)
}
```
2020-06-06 23:18:57 +02:00
If `emoji-picker-element` fails to fetch the JSON data the first time it loads, then it will display an error message.
2020-05-18 00:42:13 +02:00
### Environments without IndexedDB
`emoji-picker-element` has a hard requirement on [IndexedDB](https://developer.mozilla.org/en-US/docs/Glossary/IndexedDB), and will not work without it.
For browsers that don't support IndexedDB, such as [Firefox in private browsing mode](https://bugzilla.mozilla.org/show_bug.cgi?id=1639542), you can polyfill it using [fake-indexeddb](https://github.com/dumbmatter/fakeIndexedDB). Here is [a working example](https://bl.ocks.org/nolanlawson/651e6fbe4356ff098f505e6cc5fb8cd8) and [more details](https://github.com/nolanlawson/emoji-picker-element/issues/9).
2021-07-11 21:33:40 +02:00
For Node.js environments such as [Jest](https://jestjs.io/) or [JSDom](https://github.com/jsdom/jsdom), you can also use fake-indexeddb. A [working example](https://github.com/nolanlawson/emoji-picker-element/blob/39c50c3ce4c4c4d2cd8a15f337a722ad86c739e9/config/jest.setup.js#L28-L29) can be found in the tests for this very project.
2020-05-18 00:42:13 +02:00
## Design decisions
2020-06-22 17:16:06 +02:00
Some of the reasoning behind why `emoji-picker-element` is built the way it is.
2020-05-18 00:42:13 +02:00
### IndexedDB
2020-06-22 17:16:06 +02:00
The [`emojibase-data`](https://github.com/milesj/emojibase) English JSON file is [854kB](https://unpkg.com/browse/emojibase-data@5.0.1/en/), and the "compact" version is still 543kB. That's a lot of data to keep in memory just for an emoji picker. And it's not as if that number is ever going down; the Unicode Consortium keeps adding more emoji every year.
2020-05-08 23:59:22 +02:00
Using IndexedDB has a few advantages:
2020-06-22 17:16:06 +02:00
1. We don't need to keep the full emoji data in memory at all times.
2. After the first load, there is no need to download, parse, and index the JSON file again, because it's already available in IndexedDB.
2020-06-25 03:05:00 +02:00
3. If you want, you can even [load the IndexedDB data in a web worker](https://github.com/nolanlawson/emoji-picker-element/blob/ff86a42/test/adhoc/worker.js), keeping the main thread free from non-UI data processing.
2020-05-07 05:17:27 +02:00
2020-05-18 00:42:13 +02:00
### Native emoji
2020-05-07 05:17:27 +02:00
To avoid downloading a large sprite sheet or font file which may look out-of-place on different platforms, or may have [IP issues](https://blog.emojipedia.org/apples-emoji-crackdown/) `emoji-picker-element` only renders native emoji by default. This means it is limited to the emoji font actually installed on the user's device.
2020-06-22 17:16:06 +02:00
To avoid rendering ugly unsupported or half-supported emoji, `emoji-picker-element` will automatically detect emoji support and only render the supported characters. (So no empty boxes or awkward double emoji.) If no color emoji are supported by the browser/OS, then an error message is displayed (e.g. older browsers, some odd Linux configurations).
That said, `emoji-picker-element` does support [custom emoji fonts](#custom-emoji-font) if you really want.
2020-06-06 06:43:13 +02:00
### JSON loading
2020-06-22 17:16:06 +02:00
Browsers deal with JSON more efficiently when it's loaded via `fetch()` rather than embedded in JavaScript. It's
2020-06-06 06:43:13 +02:00
[faster for the browser to parse JSON than JavaScript](https://joreteg.com/blog/improving-redux-state-transfer-performance),
2020-06-22 17:16:06 +02:00
becuase the data is being parsed in the more tightly-constrained JSON format than the generic JavaScript format.
2020-06-26 15:03:50 +02:00
Plus, embedding the JSON directly would mean re-parsing the entire object on second load, which is something we want to avoid since the data is already in IndexedDB.
2020-06-06 06:43:13 +02:00
### Browser support
2020-06-26 15:03:50 +02:00
`emoji-picker-element` only supports the latest versions of Chrome, Firefox, and Safari, as well as equivalent browsers (Edge, Opera, etc.). If you need support for older browsers, you will need polyfills for the following things (non-exhaustive list):
2020-06-22 17:16:06 +02:00
- Custom elements
- Shadow DOM
- ES2019+
That said, older browsers may not have a color emoji font installed at all, so `emoji-picker-element` will not work in those cases.
## Contributing
2020-06-28 17:46:50 +02:00
See [CONTRIBUTING.md](https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md).