### Run Local Dev Server Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Start a local development server on localhost:3000. ```bash pnpm dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Install project dependencies using pnpm. ```bash pnpm i ``` -------------------------------- ### Basic Usage Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Demonstrates how to install and use the emoji-picker-element in an HTML document, including listening for emoji click events. ```APIDOC ## Basic Usage ### Description This section shows how to include the emoji-picker-element in your project using npm or a script tag, and how to add it to your HTML. ### Installation (npm) ```bash npm install emoji-picker-element ``` ### Import (JavaScript) ```javascript import 'emoji-picker-element'; ``` ### Script Tag ```html ``` ### HTML Usage ```html ``` ### Event Listener ```javascript document.querySelector('emoji-picker') .addEventListener('emoji-click', event => console.log(event.detail)); ``` ### Event Payload Example ```json { "emoji": { "annotation": "grinning face", "group": 0, "order": 1, "shortcodes": [ "grinning_face", "grinning" ], "tags": [ "face", "grin" ], "unicode": "πŸ˜€", "version": 1, "emoticon": ":D" }, "skinTone": 0, "unicode": "πŸ˜€" } ``` ``` -------------------------------- ### Install emoji-picker-element via npm Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Use npm to install the emoji-picker-element package. This is the standard method for projects using a build process. ```bash npm install emoji-picker-element ``` -------------------------------- ### Initialize Emoji Picker and Event Listeners Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/index.html Select the emoji picker element and set up event listeners for 'emoji-click-sync' and 'emoji-click'. This example demonstrates copying emoji to the clipboard and logging details. ```javascript const picker = $('emoji-picker') const alert = $('[role="alert"]') const pre = $('pre') const summary = $('summary') const copyToClipboard = async e => { try { await navigator.clipboard.write([ new ClipboardItem({ 'text/plain': e.detail.then(({ unicode }) => unicode}), }), ]) summary.textContent = `Copied to clipboard! Details:` } catch (err) { console.log(err) summary.textContent = `Failed to write to the clipboard! Event details:` } } const log = async e => { const detail = await e.detail alert.classList.add('shown') pre.innerHTML = JSON.stringify(detail, null, 2) } picker.addEventListener('emoji-click-sync', async e => { await copyToClipboard(e) await log(e) }) picker.addEventListener('emoji-click', async e => { await log(e) }) ``` -------------------------------- ### Copy Emoji to Clipboard with Sync Event Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Example demonstrating how to use `emoji-click-sync` to copy an emoji to the clipboard, including error handling for the Clipboard API. ```javascript picker.addEventListener('emoji-click-sync', async event => { try { await navigator.clipboard.write([new ClipboardItem({ 'text/plain': e.detail.then(({ unicode }) => unicode), })]); console.log('Copied to clipboard!'); } catch (err) { console.log('Failed to copy to clipboard', err); } }); ``` -------------------------------- ### Set and Get Custom Emoji with Database Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Demonstrates how to add, retrieve, and clear custom emoji from the Database instance. Setting custom emoji triggers an index rebuild, and searching will include them. Invalid data formats will throw an error. ```javascript import { Database } from 'emoji-picker-element'; const db = new Database(); // Set custom emoji (triggers index rebuild) db.customEmoji = [ { name: 'Garfield', shortcodes: ['garfield'], url: '/garfield.png', category: 'Cats' }, { name: 'Heathcliff', shortcodes: ['heathcliff'], url: '/heathcliff.png', category: 'Cats' }, // shortcodes are optional: { name: 'NoShortcode', url: '/no-shortcode.png' } ]; // Read back console.log(db.customEmoji[0].name); // 'Garfield' // Search now includes custom emoji const results = await db.getEmojiBySearchQuery('garfield'); console.log(results[0].name); // 'Garfield' // Clear custom emoji db.customEmoji = []; console.log(db.customEmoji.length); // 0 await db.delete(); ``` -------------------------------- ### Handle emoji-click event Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Listen for the 'emoji-click' event to get details about the selected emoji, including its unicode representation, skin tone, and metadata. This event fires asynchronously. ```javascript import { Picker } from 'emoji-picker-element'; const picker = new Picker(); document.body.appendChild(picker); picker.addEventListener('emoji-click', event => { const { emoji, skinTone, unicode, name } = event.detail; console.log(unicode); // 'πŸ‘πŸΎ' (skin-toned unicode, if applicable) console.log(skinTone); // 4 (0=Default, 1=Light … 5=Dark) console.log(emoji.annotation);// 'thumbs up' console.log(emoji.shortcodes);// ['thumbsup', '+1', 'yes'] console.log(emoji.tags); // ['+1', 'hand', 'thumb', 'up'] console.log(emoji.unicode); // 'πŸ‘οΈ' (base unicode without skin tone) console.log(emoji.version); // 0.6 console.log(emoji.skins); // [{tone:1, unicode:'πŸ‘πŸ»', version:1}, …] // For custom emoji, `name` is present and `unicode` is absent: // { name: 'Garfield', shortcodes: ['garfield'], url: 'http://…/garfield.png' } }); ``` -------------------------------- ### Initialize and Ready Database Instance Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Use this code to manually manage the database instance and ensure it's ready before displaying the picker. Handles potential errors during database initialization, such as offline scenarios. ```javascript const database = new Database(); try { await database.ready(); } catch (err) { // Deal with any errors (e.g. offline) } ``` -------------------------------- ### Picker Constructor and Options Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Demonstrates basic usage of the Picker constructor and explains the available options for customization. ```APIDOC ## Picker Constructor Basic usage: ```js import { Picker } from 'emoji-picker-element'; const picker = new Picker(); document.body.appendChild(picker); ``` The `new Picker(options)` constructor supports several options: | Name | Type | Default | |-------------------------|---------------|------------------------------------------------------------------------------------| | `customCategorySorting` | function | - | | `customEmoji` | CustomEmoji[] | - | | `dataSource` | string | "https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json" | | `emojiVersion` | number | - | | `i18n` | I18n | - | | `locale` | string | "en" | | `skinToneEmoji` | string | "πŸ–οΈ" | ### Description - `customCategorySorting`: Function to sort custom category strings (sorted alphabetically by default). - `customEmoji`: Array of custom emoji. - `dataSource`: URL to fetch the emoji data from (`data-source` when used as an attribute). - `emojiVersion`: Maximum supported emoji version as a number (e.g. `14.0` or `13.1`). Setting this disables the default emoji support detection. - `i18n`: i18n object (see below for details). - `locale`: Locale string. - `skinToneEmoji`: The emoji to use for the skin tone picker (`skin-tone-emoji` when used as an attribute). For instance: ```js const picker = new Picker({ locale: 'fr', dataSource: '/fr-emoji.json' }) ``` These values can also be set at runtime: ```js const picker = new Picker(); picker.dataSource = '/my-emoji.json'; ``` Some values can also be set as declarative attributes: ```html ``` Note that complex properties like `i18n` or `customEmoji` are not supported as attributes, because the DOM only supports string attributes, not complex objects. ``` -------------------------------- ### Database Accessor: customEmoji Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Provides methods to get and set custom emoji associated with the database. ```APIDOC #### Accessors ##### customEmoji β€’ **get customEmoji**(): *CustomEmoji[]* Return the custom emoji associated with this Database, or the empty array if none. **Returns:** *CustomEmoji[]* β€’ **set customEmoji**(`customEmoji`: CustomEmoji[]): *void* 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[] | | **Returns:** *void* ``` -------------------------------- ### Build Docs Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Build the GitHub Pages documentation site. ```bash pnpm docs ``` -------------------------------- ### Get Top Favorite Emoji Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Fetches a list of the most favorited emoji, ordered by count. Returns an empty array if no emoji have been favorited. ```typescript getTopFavoriteEmoji(10) ``` -------------------------------- ### Get Preferred Skin Tone Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Retrieves the user's preferred skin tone setting. Returns 0 if no preference is found. ```typescript getPreferredSkinTone() ``` -------------------------------- ### Run Tests Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Execute the project's test suite. ```bash pnpm test ``` -------------------------------- ### Get Emoji by Group from Database Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Retrieve all native emoji belonging to a specific group, ordered by their 'order' property. Custom emoji are not included. ```javascript await database.getEmojiByGroup(group); ``` -------------------------------- ### Database API - Initialization Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Shows how to initialize the Database class for querying emoji data separately from the picker element. ```APIDOC ### Database You can work with the database API separately, which allows you to query emoji the same way that the picker does: ```js import { Database } from 'emoji-picker-element'; const database = new Database(); await database.getEmojiBySearchPrefix('elephant'); // [{unicode: "🐘", ...}] ``` 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). ``` -------------------------------- ### Initialize Database with Custom Emoji Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Creates a new Database instance, providing custom emoji data upon creation. ```javascript const database = new Database({ customEmoji: [ /* ... */ ] }); ``` -------------------------------- ### Get Emoji by Shortcode Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Retrieve an emoji using its shortcode. Exclude colons and be mindful of case sensitivity. Throws an error for empty or null strings. ```typescript getEmojiByShortcode("slight_smile") ``` -------------------------------- ### Configure Picker with Options Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Initialize the Picker with an options object to customize locale and data source. The constructor accepts various configuration options. ```javascript const picker = new Picker({ locale: 'fr', dataSource: '/fr-emoji.json' }) ``` -------------------------------- ### Get Emoji by Unicode or Name Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Fetch an emoji by its Unicode string (including skin tone variants) or its custom name. Throws an error for empty or null strings. ```typescript getEmojiByUnicodeOrName("πŸ˜€") ``` -------------------------------- ### Initialize Emoji Picker with Database Deletion Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/test/adhoc/index.html Sets up the emoji picker with a data source and adds an event listener to delete the database on button click. It also includes logic to load custom emoji if specified in the URL. ```javascript import { Picker, Database } from '/index.js' (async () => { if (typeof PerformanceObserver !== 'undefined') { const observer = new PerformanceObserver(entries => { const entry = entries.getEntriesByName('initialLoad')[0] if (entry) { const pre = document.createElement('pre') pre.classList.add('load-time') pre.innerHTML = 'initialLoad: ' + entry.duration.toFixed(2) + 'ms' document.body.appendChild(pre) observer.disconnect() } }) observer.observe({ entryTypes: ['measure'] }) } const opts = { dataSource: '/node_modules/emoji-picker-element-data/en/emojibase/data.json' } document.querySelector('.delete').addEventListener('click', () => { new Database(opts).delete() }) const params = new URLSearchParams(location.search) if (params.has('worker')) { const worker = new Worker('/test/adhoc/worker.js', { type: 'module' }) await new Promise((resolve, reject) => { worker.addEventListener('message', () => { worker.terminate() resolve() }) worker.addEventListener('error', reject) worker.postMessage('init') }) } if (new URLSearchParams(location.search).has('custom')) { // enable custom emoji const categoriesToCustomEmoji = (await (await fetch('/docs/custom.json')).json()) const customEmoji = [] for (const [category, names] of Object.entries(categoriesToCustomEmoji)) { for (const name of names) { customEmoji.push({ category: category || undefined, name, shortcodes: [name], url: `/docs/custom/${name}.svg` }) } } opts.customEmoji = customEmoji } const picker = new Picker(opts) picker.addEventListener('emoji-click', e => console.log(e)) document.body.appendChild(picker) })() ``` -------------------------------- ### Database Constructor Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Creates a new Database instance, allowing configuration of custom emoji, data source, and locale. ```APIDOC #### Constructors ##### constructor + **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 | `locale` | string | "en" | Locale string | **Returns:** *Database* ``` -------------------------------- ### Set Custom Emoji Font with CSS Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/demos/custom-font/index.html Use the `--emoji-font-family` CSS custom property to specify a custom font for the emoji picker. This example sets it to 'Noto Color Emoji'. ```css emoji-picker { --emoji-font-family: "Noto Color Emoji"; } ``` -------------------------------- ### Run Memory Benchmark Server Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/test/memory/README.md Execute the server script for memory benchmarking in one terminal. ```bash node ./test/memory/server.js ``` -------------------------------- ### Database.customEmoji Property Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Get or set the array of custom emoji on an existing Database instance. Setting custom emoji triggers a recomputation of the in-memory search index. Setting to null or an invalid format will throw an error. ```APIDOC ## `Database.customEmoji` Property Get or set the array of custom emoji on an existing `Database` instance. Triggers recomputation of the in-memory search index. Setting to `null` or `'foo'` or an array containing invalid objects throws `'Custom emojis are in the wrong format'`. ### Usage ```js import { Database } from 'emoji-picker-element'; const db = new Database(); // Set custom emoji (triggers index rebuild) db.customEmoji = [ { name: 'Garfield', shortcodes: ['garfield'], url: '/garfield.png', category: 'Cats' }, { name: 'Heathcliff', shortcodes: ['heathcliff'], url: '/heathcliff.png', category: 'Cats' }, // shortcodes are optional: { name: 'NoShortcode', url: '/no-shortcode.png' } ]; // Read back console.log(db.customEmoji[0].name); // 'Garfield' // Search now includes custom emoji const results = await db.getEmojiBySearchQuery('garfield'); console.log(results[0].name); // 'Garfield' // Clear custom emoji db.customEmoji = []; console.log(db.customEmoji.length); // 0 await db.delete(); ``` ``` -------------------------------- ### Benchmark Bundle Size Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Measure the bundle size of the project. ```bash pnpm benchmark:bundlesize ``` -------------------------------- ### Get Emoji by Group using Database Class Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Retrieve native emoji belonging to a specific group number using `Database.getEmojiByGroup()`. Custom emoji are not included. Group IDs map to Unicode emoji categories. ```javascript import { Database } from 'emoji-picker-element'; const db = new Database(); // Group IDs: // 0 = smileys-emotion // 1 = people-body // 3 = animals-nature // 4 = food-drink // 5 = travel-places // 6 = activities // 7 = objects // 8 = symbols // 9 = flags const smileys = await db.getEmojiByGroup(0); // Returns: NativeEmoji[] // [{ // annotation: 'grinning face', // group: 0, // order: 1, // shortcodes: ['grinning_face', 'grinning'], // tags: ['face', 'grin'], // unicode: 'πŸ˜€', // version: 1, // emoticon: ':D' // }, …] console.log(smileys[0].unicode); // 'πŸ˜€' console.log(smileys[0].annotation); // 'grinning face' await db.delete(); ``` -------------------------------- ### Instantiate and configure Picker programmatically Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Import the Picker class and instantiate it programmatically. Configure options like locale, data source, and emoji version via constructor arguments or property setters. Attach the picker to a DOM element. ```javascript import { Picker } from 'emoji-picker-element'; // Instantiate programmatically and attach to DOM const picker = new Picker({ locale: 'en', dataSource: 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json', skinToneEmoji: 'πŸ–οΈ', emojiVersion: 15.0, // skip auto-detection; show all emoji up to v15 customCategorySorting: (a, b) => a.localeCompare(b) }); document.querySelector('#emoji-container').appendChild(picker); // Or declaratively in HTML: // // Properties can be updated at runtime picker.dataSource = '/my-emoji.json'; picker.locale = 'de'; ``` -------------------------------- ### Import Emoji Picker and Database Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/index.html Import the necessary JavaScript files for the emoji picker and its database. Ensure these are loaded before initializing the picker. ```javascript import 'https://cdn.jsdelivr.net/npm/emoji-picker-element@^1.27/picker.js' import 'https://cdn.jsdelivr.net/npm/emoji-picker-element@^1.27/database.js' ``` -------------------------------- ### Tree-shaking: Separate Picker and Database Imports Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Illustrates how to import `Picker` and `Database` from separate entry points to enable effective tree-shaking by bundlers. Importing `Picker` from `emoji-picker-element/picker` registers the custom element immediately. ```javascript // Import only the Picker (registers custom element) import Picker from 'emoji-picker-element/picker'; const picker = new Picker({ locale: 'en' }); document.body.appendChild(picker); // Import only the Database (no custom element side effect) import Database from 'emoji-picker-element/database'; const db = new Database({ locale: 'en' }); const results = await db.getEmojiBySearchQuery('cat'); await db.delete(); // Import both from the main entry point: import { Picker, Database } from 'emoji-picker-element'; ``` -------------------------------- ### ready Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Provides a promise that resolves when the emoji database is ready for use. If the database fails to initialize, the promise will reject with an error. Note that other API calls will automatically wait for this promise to resolve. ```APIDOC ## ready ### Description 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. ### Method `ready` ### Returns *Promiseβ€Ήvoidβ€Ί* ``` -------------------------------- ### Ensuring Emoji Database is Ready Before Picker Initialization Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Explicitly wait for the emoji database to be ready using `database.ready()` before attaching the `Picker`. This is crucial for PWA pre-caching or when immediate data access is required. ```javascript // Explicitly ensure data is loaded before showing the picker (e.g. for PWA pre-caching) import { Database, Picker } from 'emoji-picker-element'; const database = new Database(); try { await database.ready(); } catch (err) { console.error('Emoji database failed to load:', err.message); // Handle offline/error state in your UI } // Now attach the picker knowing the DB is ready const picker = new Picker({ database }); document.body.appendChild(picker); ``` -------------------------------- ### Benchmark Runtime Performance Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Measure the runtime performance of the project. ```bash pnpm benchmark:runtime ``` -------------------------------- ### Benchmark Storage Size Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Measure the storage size used by the project. ```bash pnpm benchmark:storage ``` -------------------------------- ### Tree-shaking: Separate Picker and Database Imports Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Import `Picker` and `Database` from separate entry points to enable effective tree-shaking by bundlers. Importing `Picker` from `emoji-picker-element/picker` registers the custom element immediately. ```APIDOC ## Tree-shaking: Separate Picker and Database Imports Import `Picker` and `Database` from separate entry points to ensure bundlers can tree-shake each independently. Importing `Picker` from `emoji-picker-element/picker` registers the custom element immediately as a side effect. ### Example ```js // Import only the Picker (registers custom element) import Picker from 'emoji-picker-element/picker'; const picker = new Picker({ locale: 'en' }); document.body.appendChild(picker); // Import only the Database (no custom element side effect) import Database from 'emoji-picker-element/database'; const db = new Database({ locale: 'en' }); const results = await db.getEmojiBySearchQuery('cat'); await db.delete(); // Import both from the main entry point: import { Picker, Database } from 'emoji-picker-element'; ``` ``` -------------------------------- ### Initialize and Query Emoji Database Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Initialize the Database class and use its methods to query for emoji, such as by search prefix. Note that the database partitions data by locale. ```javascript import { Database } from 'emoji-picker-element'; const database = new Database(); await database.getEmojiBySearchPrefix('elephant'); // [{unicode: "🐘", ...}] ``` -------------------------------- ### Close and Delete Database Connections Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Explains the difference between `close()` and `delete()` methods. `close()` preserves data and allows auto-reopening, while `delete()` destroys the database. Both methods flush pending updates. ```javascript import { Database } from 'emoji-picker-element'; const db = new Database({ dataSource: '/emoji.json', locale: 'en' }); await db.ready(); // Close (data is preserved, DB auto-reopens on next query) await db.close(); const emoji = await db.getEmojiByUnicodeOrName('🐡'); // auto-reopens console.log(emoji.annotation); // 'monkey face' // Delete (destroys and re-creates on next query) await db.delete(); const emoji2 = await db.getEmojiByUnicodeOrName('🐡'); // re-fetches from dataSource console.log(emoji2.annotation); // 'monkey face' // Multiple databases on the same locale share one IDB connection – // closing/deleting one affects all of them: const db1 = new Database({ locale: 'en' }); const db2 = new Database({ locale: 'en' }); // shares db1's IDB connection await db1.close(); // db2 also loses the connection, but auto-reopens await db.delete(); ``` -------------------------------- ### Load Emoji Picker with Data Source Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/test/memory/index.html This snippet demonstrates how to dynamically load the emoji picker element. It checks URL parameters to determine the behavior, loading the picker script and initializing it with a specified data source if the 'picker' parameter is present. ```javascript (async () => { const params = new URLSearchParams(location.search) if (params.has('picker')) { const script = document.createElement('script') script.onload = () => { const picker = new emojiPickerElement.Picker({ dataSource: '/node_modules/emoji-picker-element-data/en/emojibase/data.json' }) document.body.appendChild(picker) } script.src = '/bundle.js' document.body.appendChild(script) } else if (params.has('compact')) { window.json = await (await fetch('https://cdn.jsdelivr.net/npm/emojibase-data@^5/en/compact.json')).json() } else if (params.has('full')) { window.json = await (await fetch('https://cdn.jsdelivr.net/npm/emojibase-data@^5/en/data.json')).json() } })() ``` -------------------------------- ### Check Code Coverage Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Run tests and report on code coverage. ```bash pnpm cover ``` -------------------------------- ### Import Database Separately Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Imports only the Database component, enabling code-splitting and optimizing bundle size by excluding the Picker. ```javascript import Database from 'emoji-picker-element/database'; ``` -------------------------------- ### SvelteKit OnMount for Emoji Picker Integration Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt In SvelteKit, load the emoji picker within the `onMount` lifecycle function to ensure it runs only on the client-side. The picker is appended to a bound DOM element. ```javascript // SvelteKit: load inside onMount
``` -------------------------------- ### Initialize Picker with Custom Emoji Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Instantiates the Picker component, passing custom emoji data during initialization. ```javascript const picker = new Picker({ customEmoji: [ /* ... */ ] }); ``` -------------------------------- ### Styling Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Guidance on styling the emoji picker element using CSS, including CSS variables and dark mode. ```APIDOC ## Styling ### Description This section provides guidance on how to style the emoji-picker-element using CSS, including leveraging CSS variables for customization. ### Styling Options #### Size Control the overall size of the emoji picker. #### Dark mode Apply styles for dark mode appearance. #### CSS variables Utilize CSS variables for flexible theming and customization of various aspects of the picker. #### Focus outline Customize the focus outline for accessibility. #### Small screen sizes Adapt the picker's appearance for smaller screens. #### Custom styling Apply custom CSS rules to further tailor the picker's look and feel. ``` -------------------------------- ### Use Database in a Web Worker Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Shows how to use the `Database` class within a Web Worker to offload emoji data processing from the main thread. This leverages `fetch` and `IndexedDB`, which are available in worker contexts. ```javascript // worker.js import Database from 'emoji-picker-element/database'; self.addEventListener('message', async ({ data: query }) => { const db = new Database({ dataSource: 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json' }); await db.ready(); const results = await db.getEmojiBySearchQuery(query); self.postMessage(results); await db.close(); }); // main.js const worker = new Worker('./worker.js', { type: 'module' }); worker.postMessage('thumbs'); worker.addEventListener('message', ({ data }) => { console.log(data.map(e => e.unicode)); // ['πŸ‘οΈ', 'πŸ‘Ž', …] }); ``` -------------------------------- ### Import emoji-picker-element in SvelteKit Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Use dynamic import() with onMount() for client-side-only imports in SvelteKit to avoid server-side rendering errors. ```javascript import('emoji-picker-element') ``` -------------------------------- ### Configure Picker with Custom Locale and Data Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Configure the picker with a specific locale and data source, useful when using custom translations. ```javascript 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', }); ``` -------------------------------- ### Listen for Skin Tone Changes Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Add an event listener for the `skin-tone-change` event to detect when the user selects a new skin tone. ```javascript picker.addEventListener('skin-tone-change', event => { console.log(event.detail); // will log something like the above }) ``` -------------------------------- ### Initialize Emoji Picker Element Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Basic usage for initializing the emoji picker element and appending it to the document body. Ensure 'emoji-picker-element' is imported. ```javascript import { Picker } from 'emoji-picker-element'; const picker = new Picker(); document.body.appendChild(picker); ``` -------------------------------- ### Database.close() / Database.delete() Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Methods to manage the database connection. `close()` closes the connection without deleting data, allowing it to reopen automatically. `delete()` destroys the entire database, requiring a re-fetch on the next call. Both methods flush pending updates. ```APIDOC ## `Database.close()` / `Database.delete()` `close()` closes the underlying IndexedDB connection without deleting data (automatically reopens on next API call). `delete()` destroys the entire database (reopens and re-fetches on next call). Both methods flush any pending lazy update before acting. ### Usage ```js import { Database } from 'emoji-picker-element'; const db = new Database({ dataSource: '/emoji.json', locale: 'en' }); await db.ready(); // Close (data is preserved, DB auto-reopens on next query) await db.close(); const emoji = await db.getEmojiByUnicodeOrName('🐡'); // auto-reopens console.log(emoji.annotation); // 'monkey face' // Delete (destroys and re-creates on next query) await db.delete(); const emoji2 = await db.getEmojiByUnicodeOrName('🐡'); // re-fetches from dataSource console.log(emoji2.annotation); // 'monkey face' // Multiple databases on the same locale share one IDB connection – // closing/deleting one affects all of them: const db1 = new Database({ locale: 'en' }); const db2 = new Database({ locale: 'en' }); // shares db1's IDB connection await db1.close(); // db2 also loses the connection, but auto-reopens await db.delete(); ``` ``` -------------------------------- ### Benchmark Memory Usage Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/CONTRIBUTING.md Measure the memory usage of the project. ```bash pnpm benchmark:memory ``` -------------------------------- ### Initialize Database Class for Emoji Data Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Instantiate the `Database` class to access IndexedDB emoji data. Supports default English locale or custom locales and data sources. Custom emoji can also be pre-loaded. ```javascript import { Database } from 'emoji-picker-element'; // Default: English, hosted emoji data const db = new Database(); // Custom locale and data source const frDb = new Database({ locale: 'fr', dataSource: 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/fr/emojibase/data.json' }); // With custom emoji pre-loaded const dbWithCustom = new Database({ dataSource: '/emoji-data.json', customEmoji: [ { name: 'Garfield', shortcodes: ['garfield'], url: '/garfield.png', category: 'Cats' } ] }); // Optionally wait for initialization before querying: await db.ready(); // resolves when IndexedDB is populated, throws on network/IDB error ``` -------------------------------- ### JavaScript API - Picker Methods Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Lists and describes the methods available on the emoji picker element instance for programmatic control. ```APIDOC ## JavaScript API - Picker Methods ### Description This section outlines the methods available on the emoji picker element for interacting with its functionality programmatically. ### Methods #### `close()` Closes the emoji picker. #### `getEmojiByGroup(group)` Retrieves emojis by their group. #### `getEmojiBySearchQuery(query)` Retrieves emojis based on a search query. #### `getEmojiByShortcode(shortcode)` Retrieves an emoji using its shortcode. #### `getEmojiByUnicodeOrName(unicodeOrName)` Retrieves an emoji by its Unicode character or name. #### `getPreferredSkinTone()` Gets the currently preferred skin tone. #### `getTopFavoriteEmoji()` Retrieves the top favorite emoji. #### `incrementFavoriteEmojiCount(emoji)` Increments the favorite count for a given emoji. #### `ready()` Returns a promise that resolves when the picker is ready. #### `setPreferredSkinTone(skinTone)` Sets the preferred skin tone. ``` -------------------------------- ### Configure Picker with HTML Attributes Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Set picker properties like locale, data source, and skin tone emoji using declarative HTML attributes. Note that complex properties are not supported as attributes. ```html ``` -------------------------------- ### Polyfilling IndexedDB for Offline/Node.js Environments Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Use `fake-indexeddb` to polyfill `globalThis.indexedDB` for browsers without IndexedDB support (like Firefox private mode) or for Node.js test environments. This allows the `Database` class to function correctly. ```javascript // Polyfill for Firefox private mode / Node.js (Jest / Vitest) import { IDBFactory } from 'fake-indexeddb'; // Replace the global indexedDB before importing the picker globalThis.indexedDB = new IDBFactory(); import { Database } from 'emoji-picker-element'; const db = new Database(); await db.ready(); const results = await db.getEmojiBySearchQuery('elephant'); console.log(results[0].unicode); // '🐘' await db.delete(); ``` -------------------------------- ### Run Memory Benchmark Test Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/test/memory/README.md Execute the test script for memory benchmarking in a separate terminal. ```bash node ./test/memory/test.js ``` -------------------------------- ### Database Ready Promise Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md A promise that resolves when the database is initialized and ready for use. Other API calls will automatically wait for this. ```typescript ready() ``` -------------------------------- ### Listen for skin-tone-change Event Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Add an event listener to the picker to detect when a user selects a new skin tone. The event detail includes the selected skin tone as an integer. ```javascript import { Picker } from 'emoji-picker-element'; const picker = new Picker(); document.body.appendChild(picker); picker.addEventListener('skin-tone-change', event => { const { skinTone } = event.detail; console.log(skinTone); // e.g. 3 (Medium) const labels = ['Default', 'Light', 'Medium-Light', 'Medium', 'Medium-Dark', 'Dark']; console.log(labels[skinTone]); // 'Medium' }); ``` -------------------------------- ### Import JavaScript Module Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Import the emoji-picker-element into your JavaScript project. ```javascript import 'emoji-picker-element'; ``` -------------------------------- ### Handle Skin Tone Change Event Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/index.html Listens for the 'skin-tone-change' event on the emoji picker. Logs event details to the console. ```javascript 'skin-tone-change', async e => { summary.textContent = 'Skin tone changed! Details:' await log(e) } ``` -------------------------------- ### Apply Focus Visible Polyfill Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Import and apply the focus-visible polyfill for accessibility in browsers that do not support :focus-visible. Ensure the polyfill is applied to the picker's shadow root. ```javascript import 'focus-visible'; const picker = new Picker(); applyFocusVisiblePolyfill(picker.shadowRoot); ``` -------------------------------- ### Internationalize Picker with `i18n` and `locale` Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Configure the picker for internationalization by providing an `i18n` object and a `locale` string. Built-in translations are available as importable modules. The `dataSource` should point to the appropriate language data JSON. ```javascript import { Picker } from 'emoji-picker-element'; import fr from 'emoji-picker-element/i18n/fr'; import de from 'emoji-picker-element/i18n/de'; // French picker with French emoji data const frPicker = new Picker({ i18n: fr, locale: 'fr', dataSource: 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/fr/emojibase/data.json' }); document.body.appendChild(frPicker); // Switch language at runtime frPicker.i18n = de; frPicker.locale = 'de'; frPicker.dataSource = 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/de/emojibase/data.json'; // Available built-in locales: // ar, de, en, es, fa, fr, hi, hu, id, it, ja, ms_MY, // nl, pl, pt_BR, pt_PT, ru_RU, tr, vi, zh_CN // Custom i18n object structure: const customI18n = { categoriesLabel: 'Categories', emojiUnsupportedMessage: 'Your browser does not support color emoji.', favoritesLabel: 'Favorites', loadingMessage: 'Loading…', networkErrorMessage: 'Could not load emoji.', regionLabel: 'Emoji picker', searchDescription: 'When search results are available, press up or down to select and enter to choose.', searchLabel: 'Search', searchResultsLabel: 'Search results', skinToneDescription: 'When expanded, press up or down to select and enter to choose.', skinToneLabel: 'Choose a skin tone (currently {skinTone})', skinTonesLabel: 'Skin tones', skinTones: ['Default', 'Light', 'Medium-Light', 'Medium', 'Medium-Dark', 'Dark'], categories: { custom: 'Custom', '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' } }; ``` -------------------------------- ### Picker Internationalization (`i18n`) Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Pass an `i18n` object to translate all visible and screen-reader-accessible strings. Built-in translations are available as importable modules for 20+ languages. ```APIDOC ## Picker Internationalization (`i18n`) Pass an `i18n` object to translate all visible and screen-reader-accessible strings. Built-in translations are available as importable modules for 20+ languages. ### Configuration - **i18n** (Object) - An object containing translation strings for various UI elements and messages. - **locale** (string) - The locale code for the language to use (e.g., 'fr', 'de'). - **dataSource** (string) - The URL to the emoji data JSON file for the specified locale. ### Example Usage ```js import { Picker } from 'emoji-picker-element'; import fr from 'emoji-picker-element/i18n/fr'; import de from 'emoji-picker-element/i18n/de'; // French picker with French emoji data const frPicker = new Picker({ i18n: fr, locale: 'fr', dataSource: 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/fr/emojibase/data.json' }); document.body.appendChild(frPicker); // Switch language at runtime frPicker.i18n = de; frPicker.locale = 'de'; frPicker.dataSource = 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/de/emojibase/data.json'; // Available built-in locales: ar, de, en, es, fa, fr, hi, hu, id, it, ja, ms_MY, nl, pl, pt_BR, pt_PT, ru_RU, tr, vi, zh_CN // Custom i18n object structure: const customI18n = { categoriesLabel: 'Categories', emojiUnsupportedMessage: 'Your browser does not support color emoji.', favoritesLabel: 'Favorites', loadingMessage: 'Loading…', networkErrorMessage: 'Could not load emoji.', regionLabel: 'Emoji picker', searchDescription: 'When search results are available, press up or down to select and enter to choose.', searchLabel: 'Search', searchResultsLabel: 'Search results', skinToneDescription: 'When expanded, press up or down to select and enter to choose.', skinToneLabel: 'Choose a skin tone (currently {skinTone})', skinTonesLabel: 'Skin tones', skinTones: ['Default', 'Light', 'Medium-Light', 'Medium', 'Medium-Dark', 'Dark'], categories: { custom: 'Custom', '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' } }; ``` ``` -------------------------------- ### Tooltip Implementation with Popper.js Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/docs/demos/tooltip/index.html This snippet initializes Popper.js to position a tooltip relative to a button. It also sets up an event listener to toggle the tooltip's visibility when the button is clicked. ```javascript import * as Popper from 'https://cdn.jsdelivr.net/npm/@popperjs/core@^2/dist/esm/index.js' const button = document.querySelector('button') const tooltip = document.querySelector('.tooltip') Popper.createPopper(button, tooltip) document.querySelector('button').onclick = () => { tooltip.classList.toggle('shown') } ``` -------------------------------- ### Self-host emoji data source Source: https://github.com/nolanlawson/emoji-picker-element/blob/master/README.md Configure the picker to use a self-hosted emoji data JSON file by specifying the dataSource option. ```javascript const picker = new Picker({ dataSource: '/path/to/my/webserver/data.json' }); ``` -------------------------------- ### `skin-tone-change` Event Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt Fires whenever the user selects a new skin tone from the picker's skin tone dropdown. Skin tones are integers: 0 (Default), 1 (Light), 2 (Medium-Light), 3 (Medium), 4 (Medium-Dark), 5 (Dark). ```APIDOC ## `skin-tone-change` Event Fires whenever the user selects a new skin tone from the picker's skin tone dropdown. Skin tones are integers: 0 (Default), 1 (Light), 2 (Medium-Light), 3 (Medium), 4 (Medium-Dark), 5 (Dark). ### Example Usage ```js import { Picker } from 'emoji-picker-element'; const picker = new Picker(); document.body.appendChild(picker); picker.addEventListener('skin-tone-change', event => { const { skinTone } = event.detail; console.log(skinTone); // e.g. 3 (Medium) const labels = ['Default', 'Light', 'Medium-Light', 'Medium', 'Medium-Dark', 'Dark']; console.log(labels[skinTone]); // 'Medium' }); ``` ``` -------------------------------- ### Database Class Constructor Source: https://context7.com/nolanlawson/emoji-picker-element/llms.txt The Database class provides direct programmatic access to the IndexedDB emoji store. It supports custom locales and data sources, and allows for pre-loading custom emoji. ```APIDOC ## `Database` Class – Constructor The `Database` class provides direct programmatic access to the IndexedDB emoji store. Multiple `Database` instances sharing the same `locale` share the same underlying IndexedDB connection. Data is fetched on first use and updated lazily (stale-while-revalidate). The database is partitioned by locale, so different locales get separate stores. ```js import { Database } from 'emoji-picker-element'; // Default: English, hosted emoji data const db = new Database(); // Custom locale and data source const frDb = new Database({ locale: 'fr', dataSource: 'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/fr/emojibase/data.json' }); // With custom emoji pre-loaded const dbWithCustom = new Database({ dataSource: '/emoji-data.json', customEmoji: [ { name: 'Garfield', shortcodes: ['garfield'], url: '/garfield.png', category: 'Cats' } ] }); // Optionally wait for initialization before querying: await db.ready(); // resolves when IndexedDB is populated, throws on network/IDB error ``` ```