GithubHelp home page GithubHelp logo

js-emoji's Introduction

js-emoji - Display emoji in the browser, everywhere

NPM version NPM downloads Build Status Coverage Status

Modern computers and phones allow the display and input of emoji, but you often want to display them on older devices, or in the browser. This library converts emoji (either from character codes or colon-sequences like :smile:) into something that will work on the host computer - either native character codes, a CSS styled span or a text representation.

Installation

Either clone the git repo, or npm install emoji-js

Browser Usage

<link href="emoji.css" rel="stylesheet" type="text/css" />
<script src="emoji.js" type="text/javascript"></script>
<script type="text/javascript">

var emoji = new EmojiConvertor();

// replaces \u{1F604} with platform appropriate content
var output1 = emoji.replace_unified(input);

// replaces :smile: with platform appropriate content
var output2 = emoji.replace_colons(input);

// convert colons explicitly to unicode
emoji.replace_mode = 'unified';
emoji.allow_native = true;
var output3 = emoji.replace_colons(input);

</script>

You can view a live demo here.

Node Usage

After installing the package via npm install emoji-js:

var EmojiConvertor = require('emoji-js');

var emoji = new EmojiConvertor();

console.log(emoji.replace_colons("Hello :smile:"));

Output control

There are many options to control the format of the replacement, although the defaults should work well on all platforms. There are two overrides which ignore all other replacement-mode preferences:

  • emoji.text_mode = true - force text output mode, e.g. smile (default false)
  • emoji.colons_mode = true - force colon output mode, e.g. :smile: (default: false)

After that, the mode is determined automatically by examining the environment and determining capabilities. You can introspect the auto-detected mode by checking emoji.replace_mode, which can have the following values:

  • unified - Output Unicode code points
  • softbank - Output legacy Softbank/iOS code points
  • google - Output legacy Android code points
  • css - Output HTML images, using <span> elements with CSS background images
  • img - Output HTML images, using <img> elements

You can explicitly override the emoji.replace_mode to any of the above values. There are a few options which determine how the emoji.replace_mode value is used at run-time:

  • emoji.allow_native = true - Allow output of code points (default: true, otherwise falls back to css or img mode)
  • emoji.use_sheet = true - Use spritesheets with CSS positioning, instead of individual images (default: false, only applies in css mode)
  • emoji.use_css_imgs = true - Use individual CSS classes for each emoji, rather than inlining the positioning (default: false, only applies in css mode, requires the CSS file to be loaded)
  • emoji.avoid_ms_emoji = true - For browsers on Windows, don't allow native code points (because they look awful) (default: true)

There are also some further options that change the nature of the output under various modes:

  • emoji.wrap_native = true - Wrap native code points in <span class="emoji-native"></span> to allow styling (default: false, only applies in native, google and softbank modes)
  • emoji.include_title = true - Set the "title" property on the <span> or <img> tag to the short-name, e.g. :smile: (default: false, only applies in css and img modes)
  • emoji.include_text = true - Set the text inside the <span> tag to the short-name, e.g. :smile: (default: false, only applies in css mode)

Images

The library supports using multiple image sets, which can be selected using the emoji.img_set property. Valid values are:

  • apple (default)
  • google
  • twitter
  • facebook
  • messenger

This value is used as a lookup in the emoji.img_sets property, which defines each set. By default, it assumes your images are under the path /emoji-data/, but you can override these values:

emoji.img_sets.apple.path = 'http://my-cdn.com/emoji-apple-64/';
emoji.img_sets.apple.sheet = 'http://my-cdn.com/emoji-apple-sheet-64.png';

The .path property, the directory containing individual images, must end in a trailing slash. The .sheet property points directly to a spritesheet. The images can be found in the emoji-data repository: https://github.com/iamcal/emoji-data

Make sure you use the same version of the images that this library was built with, otherwise spritesheets will not work, and some images may be wrong or missing!

If you need to cache-bust your images, you can use the following property:

emoji.img_suffix = '?foo';

This will cause the generated URLs to have ?foo appended (default: '').

Further options

If you wish to allow :SMILE: to work the same as :smile:, you can set emoji.allow_caps = true (default: false)

You can add your own emoji aliases, even overriding built-in emoji:

emoji.addAliases({
  'doge' : '1f415',
  'cat'  : '1f346'
});

You can then remove your custom aliases, which will also reset built-in emoji back to their original state:

emoji.removeAliases([
  'doge',
  'cat',
]);

Upgrading from 1.x or 2.x

Prior to version 3.0, the emoji.js library would instantiate a global object called emoji, which you would call methods on. In versions 3.0 and later, the library exposes a single class called EmojiConvertor which needs to be instantiated manually. To upgrade old code, simply add this line in a global context:

var emoji = new EmojiConvertor();

Lifecycle

The library is designed to be used with the following flow:

  1. User enters text on a modern device, containing native emoji
  2. Data is stored by application, optionally translated to :colon: style
  3. When data is viewed by users on iPhone, Mac or Android phone, emoji appear natively
  4. When data is viewed on older devices, emoji are replaced with inline <span> elements with background images or simple images.

While the JS library can replace native emoji codepoints, it's significantly slower than replacing colon sequences. By translating to and storing colon sequences on the backend, you are able to:

  • Support older Android phones (Google emoji codepoints)
  • Support older iPhones (Softbank emoji codepoints)
  • Allow users to enter :smile: and have it appear as an emoji everywhere

Using MySQL for storage

You don't need to worry about this if you translate to colon syntax before storage.

Some special care may be needed to store emoji in your database. While some characters (e.g. Cloud, U+2601) are within the Basic Multilingual Plane (BMP), others (e.g. Close Umbrella, U+1F302) are not. As such, they require 4 bytes of storage to encode each character. Inside MySQL, this requires switching from utf8 storage to utf8mb4.

You can modify a database and table using a statement like:

ALTER DATABASE my_database DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE my_table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

You will also need to modify your connection character set.

Version History

See CHANGES.md

js-emoji's People

Contributors

charliehess avatar dependabot[bot] avatar eramdam avatar ericost avatar etrobert avatar gera2ld avatar ggozad avatar iamcal avatar jamesplease avatar jfcere avatar justintulloss avatar jwheare avatar mroth avatar realworldedits376w avatar serzhenko avatar snicker avatar streeter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-emoji's Issues

What circumstances cause the emojis to be rendered as an image rather than a span when use_sheet = true?

I used your excellent library to build an emoji picker of my own here https://github.com/RobertMenke/rm-emoji-picker.

I've run into an issue when testing in IE11. On certain web pages I'll get the expected output of a span with sprite sheets using the background-position css properties, but on other pages the library will attempt to render emojis as images. My code basically looks like this:

const converter = new EmojiConvertor();
converter.init_env();

converter.img_sets.apple.sheet    = sheets.apple;
converter.img_sets.google.sheet   = sheets.google;
converter.img_sets.twitter.sheet  = sheets.twitter;
converter.img_sets.emojione.sheet = sheets.emojione;

converter.use_sheet               = true;

some_input.innerHTML = converter.replace_unified(some_string);

Is there a way I can force replace_unified and replace_colons to render as spans instead of images?
Could you shed some light on what causes js-emoji to use images rather than styled spans in this circumstance?

Thanks!!

Smaller download size for image sheet?

While trying out this library in a desktop browser, I was surprised by a 12MB download for the apple_64 image sheet.

Is there any straightforward way to support use cases that could do with smaller icons than the current 64x64 representations? In my own project, 16x16 would be more than enough.

Ideally, users could be able to specify a subset of emoji to support, but this would imply using single images instead of sheets -- and I suppose that would make this into a full-fledged feature request. It's just that the huge size of the sheet can make this library a tough choice to consider given the significant download size.

(I fully understand that this shortcoming is probably due to a design choice to be able to support the full set of emoji.)

Did v3 break everything?

I used this lib in v2 and it was working great, I tried v3 and even on the demo the substitution seems wrong...

screen shot 2016-05-15 at 8 59 15 pm

☔ converting problem

When converting ☔, EmojiConvertor converts it to :umbrella_with_rain_drops: however it should be :umbrella:

Add ability to force replace_mode

Hi. I stuck on replacing emoji to unified sign.
When i set emoji.replace_mode = 'unified' before replace, it always changed in emoji.init_env
Any help will be appreciated.

Some emoji not being converted properly

I'm capturing user input from a textarea. Before I throw that text to the server I'm converting emoji to colon syntax using:

var content = $('#post_reply_box textarea[name="reply_text"]').val()
emoji.text_mode = true;
content = emoji.replace_unified(content);

// send to server

Most of them are being converted properly from my iPhone, but several are not:

  • heart
  • relaxed
  • point_up
  • v
  • etc...

When I output to the resulting string to the console the heart is displaying as :heart" and then when they are converted back it shows the heart but it also appends the invalid character rectangle as well. Am I converting them wrong or is it something else? I'm on iOS 7.

EDIT:
screenshot from iPhone
image

License

Maybe I've missed it, but I can't see a license file for the js and css. Was hoping you could add one in or clarify what the license is.

Include emoji.css in the package and document it

as pointed out in PR #58:

the usage guide includes emoji.css, which made me believe that the project might export a CSS file that needs to be imported, but I can only find the one used by the example. Should that be removed, or is the css file in /demo intended to always be required?

How to replace to colons?

Hi, I need replace from unified to colons, like this: Hello world 😁 -> Hello world :grin:, how do it?

Update emoji-data build as out of date

I looked through the sub-module setup a bit, but for some reason js-emoji pulls an older version of your emoji-data repo. It pulls the version that has an SSH submodule reference which causes builds to fail for this module. If you can update it to pull master (or at least since that issue has been fixed) that would be great.

emoji version

which emoji version is used?
I'm missing some.
e.g. ping_pong, woman_playing_water_polo
life doesn't make any sense without WOMAN_PLAYING_WATER_POLO! :)

can not convert some emoji to colon style string, for example 🤣

I followed the instruction of your demo at demo

When I test In iphone 6, it works just fine if I convert emojis that are very common. But there are still some emojis I can't convert to colon style, their output are still emojis.

For example

  • 🤣
  • 🤡
  • 🤠

my code:

var emoji = new EmojiConvertor();

emoji.img_sets = {
	'apple'    : {'path' : '/js-emoji/build/emoji-data/img-apple-64/'   , 'sheet' : '/js-emoji/build/emoji-data/sheet_apple_64.png',    'mask' : 1 },
	'google'   : {'path' : '/js-emoji/build/emoji-data/img-google-64/'  , 'sheet' : '/js-emoji/build/emoji-data/sheet_google_64.png',   'mask' : 2 },
	'twitter'  : {'path' : '/js-emoji/build/emoji-data/img-twitter-64/' , 'sheet' : '/js-emoji/build/emoji-data/sheet_twitter_64.png',  'mask' : 4 },
	'emojione' : {'path' : '/js-emoji/build/emoji-data/img-emojione-64/', 'sheet' : '/js-emoji/build/emoji-data/sheet_emojione_64.png', 'mask' : 8 }
};

emoji.use_sheet = true;
emoji.init_env();
emoji.img_set = 'apple';
emoji.replace_mode = 'unified';
emoji.text_mode = false;
emoji.colons_mode = true;
var str_out = emoji.replace_unified(str_in);

replace_unified doesn't work with a few emoji's when converted from colons

When I convert emoji's like :man-kiss-man: / :man-man-girl-girl: : etc to Unified/Unicode (:man-man-girl-girl: -> 👨‍👨‍👧‍👧) that works fine.

But if I then execute replace_unified on 👨‍👨‍👧‍👧 it doesn't work.
It shows Example-Broken

instead of

Example-Working

(it does work when I paste that Unicode on Slack though).

Is this a bug in the code or am I doing it wrong?

npm support

Could you put js-emoji on npm as well? It'd be cool if we could keep track of js-emoji versions the same way we do with our other packages. (we'd prefer not to add bower just for js-emoji).

Add category info

The category is available in the initial json from emoji-data. Do you think it would be interesting to add the information in the js library as well?

Updated docs

It looks like the docs could use some sprucing up. The options documented seem incomplete, and feature like jquery.emoji.js aren't mentioned at all atm.

I'd be down to help get this library fully documented if you think I could help out, @iamcal!

Different color variations of emoji not appearing

Hello @iamcal,
First of all, its a amazing plugin. Thanks.

I've been using this plugin and it shows all the emoji's perfectly except the new Apple color emoji variations

Basically, I'm looping it through a series of strings containing the Unicode for the emoji. It converts almost all the Unicode strings except the new Apple color variations.

Here's the code which is generating the emoji's

emoji.img_path = '../emoji/img-apple-64/';
emoji.sheet_path = '../emoji/sheet_apple_64.png';
emoji.use_sheet = true;
emoji.init_env();
var auto_mode = emoji.replace_mode;

var thoughtString = jsonTextWithMarkup;
thoughtString = emoji.replace_unified(thoughtString);

Here's a screenshot of what is being replaced:
screenshot

Keep original unicode emoji

Hi there,
I need a feature to keep the original unicode emoji after a replace.
I'm using replace_unified to replace my unicode emojis. But after clicking on one smiley I need to add this smiley to a chat-text-input.

For this I changed the function emoji.prototype.replacement:

if (self.supports_css) { if (self.use_sheet && px != null && py != null){ var mul = 100 / (self.sheet_size - 1); var style = 'background: url('+self.img_sets[img_set].sheet+');background-position:'+(mul*px)+'% '+(mul*py)+'%;background-size:'+self.sheet_size+'00%'; return '<span class="emoji-outer emoji-sizer" data-unicode-smiley="' + self.data[idx][0][0] + '"><span class="emoji-inner" style="' + style + '"' + title + '>' + text + '</span></span>' + extra; }else if (self.use_css_imgs){ return '<span class="emoji emoji-' + idx + '"' + title + ' data-unicode-smiley="' + self.data[idx][0][0] + '">' + text + '</span>' + extra; }else{ return '<span class="emoji emoji-sizer" data-unicode-smiley="' + self.data[idx][0][0] + '" style="background-image:url(' + img + ')"' + title + '>' + text + '</span>' + extra; } } return '<img src="' + img + '" class="emoji" ' + title + ' data-unicode-smiley="' + self.data[idx][0][0] + '"/>' + extra;

In the data-unicode-smiley attribute I can now catch the original unicode smiley and add in to the text box. Of cource it will not work, if I call the replace_unified function again. Right now the with the emoji will be inserted into the attribute, which destroys the html - I think that such cases should be catched by this library, too!?

text-mode seems to be a bit inconsistent

lib.text_mode = true;
emoji.replace_emoticons(':)') returns :slightly_smiling_face:
emoji.replace_unified("😊") returns :)
emoji.replace_unified("😊💾📽") returns :)floppy_diskfilm_projector

I personally was expecting all 3 methods to return only colon names, but maybe I'm missing something something.

How can I use the cloned emoji-data repo to map a codepoint to an individual image?

I understand that the sprite sheets are probably a more optimized approach to delivering emoji images, but I have a situation where I need to inject the emoji images into a contenteditable div and the nested structure of the spans returned by replace_colons has proven difficult.

If I wanted to use the individual images what would be the best way to do so?

It seemed like they were named according to their codepoints 1f171.png, but some appeared to be named according to surrogate pairs like 0032-20e3.png.

Pin versions with bower.

Please include a bower.json making it easy to pin versions. I was bitten by img_path being replaced by the new img_sets.

Unicode emoji doesn't work for Windows 7+

OS X and iOS aren't the only 2 OSs that ship with an Emoji font, Windows 8+ does as well (And it was backported to Windows 7), as it stands the script unnecessarily converts the emoji to images for these platforms when they're capable of displaying them.

Multiple encodings for the same emoji

Hello, an example, I have a feeling there are plenty of others:

I notice the current shipped emoji.js has a mapping for '0023' to #️⃣ but if I rebuild all the data afresh from all the submodules I end up with a mapping for '0023-fe0f-20e3'. The three byte version seems to be what OS X sends, while iOS7 sends a 2-byte version ''0023-20e3'.

Older versions of iOS send yet further versions, e.g. this page suggests iOS2-4 used 'e210', and I see that's covered by the softbank lookup in emoji.js (gets lost when I rebuild), though I have much less interest in supporting pre-iOS5 than I do current OS X 10.9.2 and iOS7

The images from the latest gemoji have both 2 and 3-byte versions (0023-20e3.png is a symlink to 0023-fe0f-20e3.png, but there's no 0023.png) and I'd like to support both versions, but not sure how I can get a mapping that includes them both in emoji.js.

A separate example that breaks in a different way is ☺️

iOS 5-6: 263a
iOS 7 and OSX 10.9.2: 263a-fe0f
emoji.js mapping (current and rebuilt): 263a, results in ☺️[]
gemoji: 263a.png and 263a-fe0f.png

Thanks!

emoji.img_path doesn't change path

$(function() {
                emoji.img_path = "https://server.com/assets/emoji";
                alert(emoji.replace_colons(':smile:'));
            });

Should return

<span class="emoji emoji-sizer" style="background-image:url('https://server.com/assets/emoji/img-apple-64/1f604.png')"></span>

But instead returns:

<span class="emoji emoji-sizer" style="background-image:url(/emoji-data/img-apple-64/1f604.png)"</span>

Also the filenames (img-apple-64) etc. don't seem to match up with the suggested emoji set:

https://github.com/github/gemoji/tree/master/images/emoji/unicode

which has hex-type filenames like 1f19a.png.

I'm probably doing some things completely wrong.

Uncaught ReferenceError: EmojiConvertor is not defined

I'm using AngularJS with RequireJS.
I tried every possible way to load the EmojiConvertor but without success...

require.config({
    paths: {
        'angular': 'bower_components/angular/angular.min',
        'jquery': 'bower_components/jquery/dist/jquery.min',
        'underscore': 'bower_components/underscore/underscore-min',
        'emoji': 'bower_components/js-emoji/lib/emoji.min'
    },
    shim: {
        'angular': {
            deps: ['jquery'],
            exports: 'angular'
        },
        'jquery': {
            exports: '$'
        },
        'underscore': {
            exports: '_'
        },
        'emoji': {
            exports: 'EmojiConvertor'
        }
    },
    waitSeconds: 0,
    deps: [
        'jquery',
        'angular',
        'underscore',
        'emoji'
    ]
});

My Controller:

define(['common/controllers'], function(controllers) {
    'use strict';

    controllers.controller('feedController', ['$scope', '$config', function($scope, $config) {
            var self = this;
            var emoji = EmojiConvertor();
    }])
});

And I'm getting Uncaught ReferenceError: EmojiConvertor is not defined in my controller.

Any thoughts?

Failing to convert Unicode < 9 characters from the IOS emoji keyboard (chrome & safari)

Hey,

I've been having issues converting several emojis on IOS 10 from the emoji keyboard. Some of these include:

  • SMILING FACE WITH HALO 😇
  • SMILING FACE WITH SUNGLASSES 😎
  • CONFUSED FACE 😕

and many others.

I've confirmed the following aspects of this issue:

  1. Emojis are able to be input and stored in unicode format.
  2. The result of replace_unified works as expected on a desktop web browser running Mac OSX or Windows.
  3. The result of replace_unified is completely blank on both Chrome and Safari on IOS 10 for certain emojis.

Is this a known issue, or is there a way around this? I can create a JSFiddle if that would be helpful.

Import emoji from 'emoji-js'

Hello,

I tried to import in a Angular 2 / Typescript project.

import * as emoji from 'emoji-js';

There is no error.

// console.log(emoji);
    ƒ (){

		var self = this;

		/**
		 * The set of images to use for graphical emoji.
		 *
		 * @memberof emoji
		 * @type {string}
		 */
		self.img_set = 'apple';

		/**
		 * Configuration details for d…

But when I do a emoji.init_env() for example I got this error :

TypeError: __WEBPACK_IMPORTED_MODULE_7_emoji_js__.init_env is not a function

Can you help me please ? Thank you

Minified file does not display proper emoji's

Hi @iamcal,

I updated my emoji sheets and images to the latest files. Since then when I try to use the minified version of emoji.js, it will not show the correct emoji.

I'm using it with requirejs. First I thought it must be some issue caused by r.js optimizer but I tested it with both optimized and unoptimized versions.

Here are 2 screenshots of with and without minified js

Minified:
emoji_minified

No minification:
emoji_no_minification

variant-encoded emoji not being properly detected in replace_unified

The 107 emoji with variant encoding are not being properly detected in replace_unified when they are encoded using the variant version of their encoding.

For examples, you can view the following in Chrome on my staging server which I have upgraded to output variant encoded emoji from internal API methods:

http://staging.emojitracker.com/details/2B50
In the header/title, I am exporting unicode char with variant encoding 2B50-fe0f. js-emoji is matching and replacing the first codepoint only (since it's the non-variant version of the same emoji glyph), leaving the naked fe0f which renders as a broken box. If you look at the streaming tweets you can see that ones from people using iOS6 are replaced properly, but those sending tweets from iOS7 with variant encoding this problem occurs.

http://staging.emojitracker.com/details/0031-20E3
In the new version of js-emoji the keycaps0-9 characters all migrated from being bare 003* to 003*-20E3 format. However, for some reason, the replace_unified method doesn't seem to catch these at all anymore. (On this one, look in the header to see this, since the ones I am feeding into the live tweets are currently only ones that match the old format.)

Not quite sure what's going on here, I tried to figure it out in the source but didn't have any luck. Halp?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.