DEV: Added modifier to change mentions extracted from cooked text (#21654)

Added a new modifier hook to allow plugins to modify the @mentions
extracted from a cooked text.

Use case: Some plugins may change how the mentions are cooked to prevent
them from being confused with user or group mentions and display the user
card.

This modifier hook allows the plugin to filter the mentions detected or add new ways
to add mentions into cooked text.
This commit is contained in:
Sérgio Saquetim 2023-06-15 10:52:52 -03:00 committed by GitHub
parent 5bd09edc2d
commit 4b22e67c8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 0 deletions

View File

@ -457,6 +457,9 @@ module PrettyText
end end
end end
mentions =
DiscoursePluginRegistry.apply_modifier(:pretty_text_extract_mentions, mentions, cooked)
mentions.compact! mentions.compact!
mentions.uniq! mentions.uniq!
mentions mentions

View File

@ -566,6 +566,45 @@ RSpec.describe PrettyText do
).to match_html '<p>Hello <span class="mention">@狮子</span></p>' ).to match_html '<p>Hello <span class="mention">@狮子</span></p>'
end end
end end
context "with pretty_text_extract_mentions modifier" do
it "allows changing the mentions extracted" do
cooked_html = <<~HTML
<p>
<a class="mention" href="/u/test">@test</a>,
<a class="mention-group" href="/g/test-group">@test-group</a>,
<a class="custom-mention" href="/custom-mention">@test-custom</a>,
this is a test
</p>
HTML
extracted_mentions = PrettyText.extract_mentions(Nokogiri::HTML5.fragment(cooked_html))
expect(extracted_mentions).to include("test", "test-group")
expect(extracted_mentions).not_to include("test-custom")
Plugin::Instance
.new
.register_modifier(:pretty_text_extract_mentions) do |mentions, cooked_text|
custom_mentions =
cooked_text
.css(".custom-mention")
.map do |e|
if (name = e.inner_text)
name = name[1..-1]
name = User.normalize_username(name)
name
end
end
mentions + custom_mentions
end
extracted_mentions = PrettyText.extract_mentions(Nokogiri::HTML5.fragment(cooked_html))
expect(extracted_mentions).to include("test", "test-group", "test-custom")
ensure
DiscoursePluginRegistry.clear_modifiers!
end
end
end end
describe "code fences" do describe "code fences" do