Class: Banzai::Filter::EmojiFilter

Inherits:
HTML::Pipeline::Filter
  • Object
show all
Defined in:
lib/banzai/filter/emoji_filter.rb

Overview

HTML filter that replaces :emoji: and unicode with images.

Based on HTML::Pipeline::EmojiFilter

Constant Summary collapse

IGNORED_ANCESTOR_TAGS =
%w[pre code tt].to_set

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.emoji_patternObject

Build a regexp that matches all valid :emoji: names.



55
56
57
# File 'lib/banzai/filter/emoji_filter.rb', line 55

def self.emoji_pattern
  @emoji_pattern ||= TanukiEmoji.index.alpha_code_pattern
end

.emoji_unicode_patternObject

Build a regexp that matches all valid unicode emojis names.



60
61
62
# File 'lib/banzai/filter/emoji_filter.rb', line 60

def self.emoji_unicode_pattern
  @emoji_unicode_pattern ||= TanukiEmoji.index.codepoints_pattern
end

Instance Method Details

#callObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/banzai/filter/emoji_filter.rb', line 12

def call
  doc.xpath('descendant-or-self::text()').each do |node|
    content = node.to_html
    next if has_ancestor?(node, IGNORED_ANCESTOR_TAGS)

    next unless content.include?(':') || node.text.match(emoji_unicode_pattern)

    html = emoji_unicode_element_unicode_filter(content)
    html = emoji_name_element_unicode_filter(html)

    next if html == content

    node.replace(html)
  end
  doc
end

#emoji_name_element_unicode_filter(text) ⇒ Object

Replace :emoji: with corresponding gl-emoji unicode.

text - String text to replace :emoji: in.

Returns a String with :emoji: replaced with gl-emoji unicode.



34
35
36
37
38
39
40
# File 'lib/banzai/filter/emoji_filter.rb', line 34

def emoji_name_element_unicode_filter(text)
  text.gsub(emoji_pattern) do |match|
    name = Regexp.last_match(1)
    emoji = TanukiEmoji.find_by_alpha_code(name)
    Gitlab::Emoji.gl_emoji_tag(emoji)
  end
end

#emoji_unicode_element_unicode_filter(text) ⇒ Object

Replace unicode emoji with corresponding gl-emoji unicode.

text - String text to replace unicode emoji in.

Returns a String with unicode emoji replaced with gl-emoji unicode.



47
48
49
50
51
52
# File 'lib/banzai/filter/emoji_filter.rb', line 47

def emoji_unicode_element_unicode_filter(text)
  text.gsub(emoji_unicode_pattern) do |moji|
    emoji = TanukiEmoji.find_by_codepoints(moji)
    Gitlab::Emoji.gl_emoji_tag(emoji)
  end
end