Skip to content

A platform for community discussion. Free, open, simple.

FIX: Emoji.exists? should be consistent with Emoji[] (#36347)

Régis Hanolf453463cfbd2
diff --git a/app/models/emoji.rb b/app/models/emoji.rb
index e83d2ec9352..d17a994ceb1 100644
--- a/app/models/emoji.rb
+++ b/app/models/emoji.rb
@@ -6,6 +6,9 @@ class Emoji
FITZPATRICK_SCALE = %w[1f3fb 1f3fc 1f3fd 1f3fe 1f3ff]
+ # matches emoji codes in text, e.g. :smile: or :wave:t2:
+ EMOJI_CODE_REGEXP = /:([\w\-+]+(?::t\d)?):/.freeze
+
DEFAULT_GROUP = "default"
include ActiveModel::SerializerSupport
@@ -56,29 +59,37 @@ class Emoji
tonable_emojis_db
end
+ def self.normalize_name(name)
+ match = name.match(/\A:?(.+?)(?::t([1-6]))?:?\z/)
+ [match[1], match[2]&.to_i]
+ end
+ private_class_method :normalize_name
+
def self.custom?(name)
- name = name.delete_prefix(":").delete_suffix(":")
+ name, _ = normalize_name(name)
Emoji.custom.detect { |e| e.name == name }.present?
end
def self.exists?(name)
- Emoji[name].present? || Emoji.aliases_values.include?(name)
+ Emoji[name].present?
end
def self.[](name)
- name = name.delete_prefix(":").delete_suffix(":")
- is_toned = name.match?(/\A.+:t[1-6]\z/)
- normalized_name = name.gsub(/\A(.+):t[1-6]\z/, '\1')
+ name, tone = normalize_name(name)
+ is_toned = tone.present?
+ find_emoji(name, is_toned) || find_emoji(resolve_alias(name), is_toned)
+ end
+ def self.find_emoji(name, is_toned)
found_emoji = nil
[[global_emoji_cache, :standard], [site_emoji_cache, :custom]].each do |cache, list_key|
found_emoji =
- cache.defer_get_set(normalized_name) do
+ cache.defer_get_set(name) do
[
Emoji
.public_send(list_key)
- .detect { |e| e.name == normalized_name && (!is_toned || (is_toned && e.tonable)) },
+ .detect { |e| e.name == name && (!is_toned || (is_toned && e.tonable)) },
]
end[
0
@@ -89,6 +100,7 @@ class Emoji
found_emoji
end
+ private_class_method :find_emoji
def self.create_from_db_item(emoji)
name = emoji["name"]
@@ -105,7 +117,8 @@ class Emoji
end
def self.url_for(name)
- name = name.delete_prefix(":").delete_suffix(":").gsub(/(.+):t([1-6])/, '\1/\2')
+ name, tone = normalize_name(name)
+ name = "#{name}/#{tone}" if tone
if SiteSetting.external_emoji_url.blank?
"#{Discourse.base_path}/images/emoji/#{SiteSetting.emoji_set}/#{name}.png?v=#{EMOJI_VERSION}"
else
@@ -182,6 +195,17 @@ class Emoji
@aliases_values ||= Set.new(Emoji.aliases_db.values.flatten)
end
+ def self.reverse_aliases
+ @reverse_aliases ||=
+ aliases_db.each_with_object({}) do |(original, alias_names), map|
+ alias_names.each { |alias_name| map[alias_name] = original }
+ end
+ end
+
+ def self.resolve_alias(name)
+ reverse_aliases[name] || name
+ end
+
def self.search_aliases_db_file
@search_aliases_db_file ||= DiscourseEmojis.paths[:search_aliases]
end
@@ -304,7 +328,7 @@ class Emoji
end
def self.gsub_emoji_to_unicode(str)
- str.gsub(/:([\w\-+]*(?::t\d)?):/) { |name| Emoji.lookup_unicode($1) || name } if str
+ str.gsub(EMOJI_CODE_REGEXP) { |name| Emoji.lookup_unicode($1) || name } if str
end
def self.lookup_unicode(name)
@@ -348,7 +372,7 @@ class Emoji
return if str.blank?
str =
- str.gsub(/:([\w\-+]*(?::t\d)?):/) do |name|
+ str.gsub(EMOJI_CODE_REGEXP) do |name|
code = $1
if code && Emoji.custom?(code)
diff --git a/lib/slug.rb b/lib/slug.rb
index 1fb1c3ecac9..16215a7445a 100644
--- a/lib/slug.rb
+++ b/lib/slug.rb
@@ -5,7 +5,7 @@ module Slug
MAX_LENGTH = 255
def self.for(string, default = "topic", max_length = MAX_LENGTH, method: nil)
- string = string.gsub(/:([\w\-+]+(?::t\d)?):/, "") if string.present? # strip emoji strings
+ string = string.gsub(Emoji::EMOJI_CODE_REGEXP, "") if string.present?
method = (method || SiteSetting.slug_generation_method || :ascii).to_sym
max_length = 9999 if method == :encoded # do not truncate encoded slugs
diff --git a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb
index 1e3b9766eac..e9d64cd7f55 100644
--- a/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb
+++ b/plugins/discourse-narrative-bot/lib/discourse_narrative_bot/new_user_narrative.rb
@@ -208,7 +208,7 @@ module DiscourseNarrativeBot
MD
title = I18n.t("#{I18N_KEY}.hello.title", title: SiteSetting.title)
- title = title.gsub(/:([\w\-+]+(?::t\d)?):/, "").strip if SiteSetting.max_emojis_in_title == 0
+ title = title.gsub(Emoji::EMOJI_CODE_REGEXP, "").strip if SiteSetting.max_emojis_in_title == 0
opts = {
title: title,
diff --git a/spec/models/emoji_spec.rb b/spec/models/emoji_spec.rb
index f1dbe082882..364b63dec26 100644
--- a/spec/models/emoji_spec.rb
+++ b/spec/models/emoji_spec.rb
@@ -1,114 +1,111 @@
# frozen_string_literal: true
RSpec.describe Emoji do
- it "returns the correct codepoints" do
- expect(Emoji.replacement_code("1f47d").codepoints).to eq([128_125])
- end
-
- it "handles multiple codepoints" do
- expect(Emoji.replacement_code("1f1e9-1f1ea").codepoints).to eq([127_465, 127_466])
+ describe ".replacement_code" do
+ it "returns correct codepoints" do
+ expect(Emoji.replacement_code("1f47d").codepoints).to eq([128_125])
+ expect(Emoji.replacement_code("1f1e9-1f1ea").codepoints).to eq([127_465, 127_466])
+ end
end
describe ".load_custom" do
- describe "when a custom emoji has an invalid upload_id" do
- it "should return the custom emoji without a URL" do
- CustomEmoji.create!(name: "test", upload_id: 9999)
-
- emoji = Emoji.load_custom.first
-
- expect(emoji.name).to eq("test")
- expect(emoji.url).to eq(nil)
- end
+ it "returns custom emoji without URL when upload_id is invalid" do
+ CustomEmoji.create!(name: "test", upload_id: 9999)
+ emoji = Emoji.load_custom.first
+ expect(emoji.name).to eq("test")
+ expect(emoji.url).to be_nil
end
end
describe ".lookup_unicode" do
- before do
- SiteSetting.emoji_deny_list = "peach"
- Emoji.clear_cache
- end
-
- it "doesnt convert (TM) and (tm) do an emoji" do
+ it "returns unicode for emoji, aliases, and skin tones" do
expect(Emoji.lookup_unicode("trade_mark")).to eq("™")
- end
-
- it "should return the emoji" do
expect(Emoji.lookup_unicode("blonde_man")).to eq("👱‍♂️")
- end
-
- it "should return an aliased emoji" do
expect(Emoji.lookup_unicode("anger_right")).to eq("🗯")
- end
-
- it "should return a skin toned emoji" do
expect(Emoji.lookup_unicode("blonde_woman:t6")).to eq("👱🏿‍♀️")
end
- it "should not return a fu emoji when emoji is in emoji deny list site setting" do
+ it "respects emoji deny list" do
+ SiteSetting.emoji_deny_list = "peach"
+ Emoji.clear_cache
expect(Emoji.lookup_unicode("peach")).not_to eq("🍑")
end
end
describe ".url_for" do
- expected_url = "/images/emoji/twitter/blonde_woman.png?v=#{Emoji::EMOJI_VERSION}"
- expected_toned_url = "/images/emoji/twitter/blonde_woman/6.png?v=#{Emoji::EMOJI_VERSION}"
+ it "returns correct url for all input formats" do
+ url = "/images/emoji/twitter/blonde_woman.png?v=#{Emoji::EMOJI_VERSION}"
+ toned_url = "/images/emoji/twitter/blonde_woman/6.png?v=#{Emoji::EMOJI_VERSION}"
- it "should return url with filename" do
- expect(Emoji.url_for("blonde_woman")).to eq(expected_url)
+ expect(Emoji.url_for("blonde_woman")).to eq(url)
+ expect(Emoji.url_for(":blonde_woman:")).to eq(url)
+ expect(Emoji.url_for("blonde_woman:t6")).to eq(toned_url)
+ expect(Emoji.url_for(":blonde_woman:t6:")).to eq(toned_url)
end
+ end
- it "should return url with skin toned filename" do
- expect(Emoji.url_for("blonde_woman/6")).to eq(expected_toned_url)
+ describe ".resolve_alias" do
+ it "resolves aliases to canonical names" do
+ expect(Emoji.resolve_alias("xray")).to eq("x_ray")
+ expect(Emoji.resolve_alias("blonde_woman")).to eq("blonde_woman")
end
+ end
- it "should return url with code" do
- expect(Emoji.url_for(":blonde_woman:")).to eq(expected_url)
+ describe "emoji lookup" do
+ it "finds emoji by name" do
+ expect(Emoji["blonde_woman"].name).to eq("blonde_woman")
+ expect(Emoji[":blonde_woman:"].name).to eq("blonde_woman")
+ expect(Emoji.exists?("blonde_woman")).to be(true)
+ expect(Emoji.exists?(":blonde_woman:")).to be(true)
end
- it "should return url with skin toned code" do
- expect(Emoji.url_for(":blonde_woman:t6:")).to eq(expected_toned_url)
- expect(Emoji.url_for("blonde_woman:t6")).to eq(expected_toned_url)
+ it "finds emoji by alias" do
+ expect(Emoji["xray"].name).to eq("x_ray")
+ expect(Emoji[":xray:"].name).to eq("x_ray")
+ expect(Emoji.exists?("xray")).to be(true)
+ expect(Emoji.exists?(":xray:")).to be(true)
end
- end
- describe ".exists?" do
- it "finds existing emoji" do
- expect(Emoji.exists?(":blonde_woman:")).to be(true)
- expect(Emoji.exists?("blonde_woman")).to be(true)
+ it "finds tonable emoji with skin tone" do
+ expect(Emoji["blonde_woman:t6"].name).to eq("blonde_woman")
+ expect(Emoji[":blonde_woman:t6:"].name).to eq("blonde_woman")
+ expect(Emoji.exists?("blonde_woman:t6")).to be(true)
+ expect(Emoji.exists?(":blonde_woman:t1:")).to be(true)
end
- it "finds existing skin toned emoji" do
- expect(Emoji.exists?(":blonde_woman:t1:")).to be(true)
- expect(Emoji.exists?("blonde_woman:t6")).to be(true)
+ it "finds tonable emoji by alias with skin tone" do
+ expect(Emoji["basketball_man:t4"].name).to eq("man_bouncing_ball")
+ expect(Emoji[":basketball_man:t4:"].name).to eq("man_bouncing_ball")
+ expect(Emoji.exists?("basketball_man:t4")).to be(true)
+ expect(Emoji.exists?(":basketball_man:t4:")).to be(true)
end
- it "finds existing custom emoji" do
+ it "finds custom emoji" do
CustomEmoji.create!(name: "test", upload_id: 9999)
Emoji.clear_cache
- expect(Emoji.exists?(":test:")).to be(true)
expect(Emoji.exists?("test")).to be(true)
+ expect(Emoji.exists?(":test:")).to be(true)
end
- it "finds a custom emoji with a name with :t1 in the middle" do
+ it "finds custom emoji with skin tone pattern in name" do
CustomEmoji.create!(name: "test:t1:foo", upload_id: 9999)
Emoji.clear_cache
- expect(Emoji.exists?(":test:t1:foo:")).to be(true)
expect(Emoji.exists?("test:t1:foo")).to be(true)
+ expect(Emoji.exists?(":test:t1:foo:")).to be(true)
end
- it "doesn’t find non-existing emoji" do
+ it "returns nil/false for non-existing emoji" do
+ expect(Emoji["foo_bar_baz"]).to be_nil
+ expect(Emoji[":foo_bar_baz:"]).to be_nil
expect(Emoji.exists?(":foo-bar:")).to be(false)
+ end
+
+ it "returns nil/false for invalid skin tones" do
+ expect(Emoji["apple:t4"]).to be_nil
expect(Emoji.exists?(":blonde_woman:t7:")).to be(false)
expect(Emoji.exists?("blonde_woman:t0")).to be(false)
expect(Emoji.exists?("blonde_woman:t")).to be(false)
end
-
- it "finds aliases" do
- aliases_list = Emoji.aliases_db.values
- expect(Emoji.exists?(aliases_list[0][0])).to be(true)
- expect(Emoji.exists?(aliases_list[1][0])).to be(true)
- expect(Emoji.exists?(aliases_list[2][0])).to be(true)
- end
end
describe ".codes_to_img" do
@@ -117,46 +114,41 @@ RSpec.describe Emoji do
it "replaces emoji codes by images" do
Plugin::CustomEmoji.register("xxxxxx", "/public/xxxxxx.png")
-
- str = "This is a good day :xxxxxx: :woman: :man:t4:"
- replaced_str = described_class.codes_to_img(str)
-
- expect(replaced_str).to eq(
- "This is a good day <img src=\"/public/xxxxxx.png\" title=\"xxxxxx\" class=\"emoji\" alt=\"xxxxxx\" loading=\"lazy\" width=\"20\" height=\"20\"> <img src=\"/images/emoji/twitter/woman.png?v=#{Emoji::EMOJI_VERSION}\" title=\"woman\" class=\"emoji\" alt=\"woman\" loading=\"lazy\" width=\"20\" height=\"20\"> <img src=\"/images/emoji/twitter/man/4.png?v=#{Emoji::EMOJI_VERSION}\" title=\"man:t4\" class=\"emoji\" alt=\"man:t4\" loading=\"lazy\" width=\"20\" height=\"20\">",
- )
+ replaced_str = described_class.codes_to_img("This is a good day :xxxxxx: :woman: :man:t4:")
+ expect(replaced_str).to eq(<<~HTML.chomp)
+ This is a good day <img src="/public/xxxxxx.png" title="xxxxxx" class="emoji" alt="xxxxxx" loading="lazy" width="20" height="20"> <img src="/images/emoji/twitter/woman.png?v=#{Emoji::EMOJI_VERSION}" title="woman" class="emoji" alt="woman" loading="lazy" width="20" height="20"> <img src="/images/emoji/twitter/man/4.png?v=#{Emoji::EMOJI_VERSION}" title="man:t4" class="emoji" alt="man:t4" loading="lazy" width="20" height="20">
+ HTML
end
- it "doesn't replace if code doesn't exist" do
- str = "This is a good day :woman: :foo: :bar:t4: :man:t8:"
- replaced_str = described_class.codes_to_img(str)
-
- expect(replaced_str).to eq(
- "This is a good day <img src=\"/images/emoji/twitter/woman.png?v=#{Emoji::EMOJI_VERSION}\" title=\"woman\" class=\"emoji\" alt=\"woman\" loading=\"lazy\" width=\"20\" height=\"20\"> :foo: :bar:t4: :man:t8:",
- )
+ it "doesn't replace non-existing codes" do
+ replaced_str =
+ described_class.codes_to_img("This is a good day :woman: :foo: :bar:t4: :man:t8:")
+ expect(replaced_str).to eq(<<~HTML.chomp)
+ This is a good day <img src="/images/emoji/twitter/woman.png?v=#{Emoji::EMOJI_VERSION}" title="woman" class="emoji" alt="woman" loading="lazy" width="20" height="20"> :foo: :bar:t4: :man:t8:
+ HTML
end
end
describe ".groups" do
- it "returns an optimized emoji name -> group name datastructure" do
+ it "returns emoji name to group name mapping" do
expect(Emoji.groups["scotland"]).to eq("flags")
end
end
describe ".load_standard" do
it "removes nil emojis" do
- expect(Emoji.load_standard.any? { |element| element.nil? }).to be false
+ expect(Emoji.load_standard.any?(&:nil?)).to be(false)
end
end
describe "#create_from_db_item" do
- it "sets the group of the emoji" do
+ it "creates emoji with group when known" do
emoji = Emoji.create_from_db_item("name" => "scotland")
expect(emoji.group).to eq("flags")
end
- it "doesn’t create emoji when group is unknown" do
- emoji = Emoji.create_from_db_item("name" => "white_hair")
- expect(emoji).to be_nil
+ it "returns nil when group is unknown" do
+ expect(Emoji.create_from_db_item("name" => "white_hair")).to be_nil
end
end
end