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.


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

def self.emoji_pattern
  @emoji_pattern ||=
    %r{(?<=[^[:alnum:]:]|\n|^)
    :(#{Gitlab::Emoji.emojis_names.map { |name| Regexp.escape(name) }.join('|')}):
    (?=[^[:alnum:]:]|$)}x
end

.emoji_unicode_patternObject

Build a regexp that matches all valid unicode emojis names.


62
63
64
# File 'lib/banzai/filter/emoji_filter.rb', line 62

def self.emoji_unicode_pattern
  @emoji_unicode_pattern ||= /(#{Gitlab::Emoji.emojis_unicodes.map { |moji| Regexp.escape(moji) }.join('|')})/
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.search(".//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
# 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)
    Gitlab::Emoji.gl_emoji_tag(name)
  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.


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

def emoji_unicode_element_unicode_filter(text)
  text.gsub(emoji_unicode_pattern) do |moji|
    emoji_info = Gitlab::Emoji.emojis_by_moji[moji]
    Gitlab::Emoji.gl_emoji_tag(emoji_info['name'])
  end
end