Forked from arbales/handlebars-formatTextForHTML.coffee
Last active
December 19, 2015 16:49
-
-
Save mjumbewu/5986956 to your computer and use it in GitHub Desktop.
Now matches things like "I got this from http://github.com/, and it's great!" as well. The trailing comma would throw it off before.
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
LINK_DETECTION_REGEX = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?).?(\s+|$)/gi | |
EMOJI_DIRECTORY = "/path/to/assets/emoji/20x20" | |
# Handlebars is presumed, but you could swap out | |
ESCAPE_EXPRESSION_FUNCTION = Handlebars.Utils.escapeExpression | |
MARKSAFE_FUNCTION = (str) -> new Handlebars.SafeString(str) | |
# Emoji unicode chars become images. | |
emojify = (safeContent) -> | |
safeContent.replace /([\ue001-\ue537])/g, (emoji) -> | |
filename = emoji.charCodeAt(0).toString(16).toUpperCase() | |
"<img class='emoji' src='#{EMOJI_DIRECTORY}/#{filename}.png'/>" # TODO: alt and title | |
# Replace URLs like https://github.com with <a href='https://github.com'>github.com</a> | |
linkify = (safeContent) -> | |
safeContent.replace LINK_DETECTION_REGEX, (match, url) -> | |
address = if /[a-z]+:\/\//.test url then url else "http://#{url}" | |
match = match.replace /^https?:\/\//, '' | |
"<a href='#{address}' target='_blank'>#{match}</a>" | |
# Helper for formatting strings with links and line breaks for display in HTML | |
formatTextForHTML = (content) -> | |
# Start by escaping expressions in the content to make them safe. | |
safeContent = ESCAPE_EXPRESSION_FUNCTION(content) | |
safeContent = linkify safeContent | |
# Line breaks become <br/>'s | |
safeContent = safeContent.replace /\n/g, '<br/>' | |
safeContent = emojify safeContent | |
MARKSAFE_FUNCTION(safeContent) # Mark our string as safe, since it is. | |
Handlebars.registerHelper 'formatTextForHTML', formatTextForHTML |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment