Last active
March 14, 2019 12:24
-
-
Save thomasboyt/b5ef9ed8606ce6d93982 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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
Thanks, it was helpful.
For the reference, here is code for GitHub's hosted set of emoji:
Example https://assets-cdn.github.com/images/icons/emoji/unicode/1f42f.png