From 4b22e67c8bc1814133f58bc32f84e42372654abc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Saquetim?= <1108771+megothss@users.noreply.github.com> Date: Thu, 15 Jun 2023 10:52:52 -0300 Subject: [PATCH] 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. --- lib/pretty_text.rb | 3 +++ spec/lib/pretty_text_spec.rb | 39 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/lib/pretty_text.rb b/lib/pretty_text.rb index b711e404576..f3a4b6e4420 100644 --- a/lib/pretty_text.rb +++ b/lib/pretty_text.rb @@ -457,6 +457,9 @@ module PrettyText end end + mentions = + DiscoursePluginRegistry.apply_modifier(:pretty_text_extract_mentions, mentions, cooked) + mentions.compact! mentions.uniq! mentions diff --git a/spec/lib/pretty_text_spec.rb b/spec/lib/pretty_text_spec.rb index 8a117ccc991..41ad0944bc6 100644 --- a/spec/lib/pretty_text_spec.rb +++ b/spec/lib/pretty_text_spec.rb @@ -566,6 +566,45 @@ RSpec.describe PrettyText do ).to match_html '

Hello @狮子

' end end + + context "with pretty_text_extract_mentions modifier" do + it "allows changing the mentions extracted" do + cooked_html = <<~HTML +

+ @test, + @test-group, + @test-custom, + this is a test +

+ 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 describe "code fences" do