Skip to content

Instantly share code, notes, and snippets.

@mohangk
Forked from thomasboyt/emoji.js
Last active August 29, 2015 14:15
Show Gist options
  • Save mohangk/be69058e1a2bf14bec0c to your computer and use it in GitHub Desktop.
Save mohangk/be69058e1a2bf14bec0c to your computer and use it in GitHub Desktop.
/** @jsx React.DOM */
define([
'react',
'modernizr',
'punycode'
], function(React, Modernizr, punycode) {
/**
* Replaces the emojis in a text string with <img> tags
*/
var isEmojiCode = function(charCode) {
return (
( charCode >= 0x1F300 && charCode <= 0x1F5FF ) ||
( charCode >= 0x1F600 && charCode <= 0x1F64F ) ||
( charCode >= 0x1F680 && charCode <= 0x1F6FF ) ||
( charCode >= 0x2600 && charCode <= 0x26FF )
);
};
var emojiTransform = function(text) {
var decoded = punycode.ucs2.decode(text);
var entries = [];
decoded.forEach(function(charCode, idx) {
if ( isEmojiCode(charCode) ) {
// emoji char encountered, insert img tag
var hexCode = charCode.toString(16);
entries.push(
<img src={"/w/images/emoji/" + hexCode + ".png"} key={idx} />
);
} else {
var char = punycode.ucs2.encode([charCode]);
var lastIdx = entries.length - 1;
if ( typeof entries[lastIdx] === 'string' ) {
entries[lastIdx] += char;
} else {
entries.push(char);
}
}
});
return entries;
};
var Emojify = React.createClass({
propTypes: {
text: React.PropTypes.string.isRequired
},
shouldComponentUpdate: function(nextProps) {
return nextProps.text !== this.props.text;
},
render: function() {
var emojifiedText = !Modernizr.emoji ? emojiTransform(this.props.text) : this.props.text;
return (
<span>{emojifiedText}</span>
);
}
});
return Emojify;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment