Skip to content

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

FEATURE: Highlight watched words found in reviewables. (#32167)

Gary Pendergast33748895a9bc
diff --git a/app/assets/javascripts/discourse-markdown-it/src/index.js b/app/assets/javascripts/discourse-markdown-it/src/index.js
index c7e9cde1ac7..0a42aa117b1 100644
--- a/app/assets/javascripts/discourse-markdown-it/src/index.js
+++ b/app/assets/javascripts/discourse-markdown-it/src/index.js
@@ -51,6 +51,12 @@ export default class DiscourseMarkdownIt {
}
cook(raw) {
+ if (raw === undefined || raw === null) {
+ return "";
+ }
+
+ raw = raw.toString();
+
if (!raw || raw.length === 0) {
return "";
}
diff --git a/app/assets/javascripts/discourse/app/components/reviewable-flagged-post.gjs b/app/assets/javascripts/discourse/app/components/reviewable-flagged-post.gjs
index 277d394d323..77448e36677 100644
--- a/app/assets/javascripts/discourse/app/components/reviewable-flagged-post.gjs
+++ b/app/assets/javascripts/discourse/app/components/reviewable-flagged-post.gjs
@@ -3,7 +3,6 @@ import { tracked } from "@glimmer/tracking";
import { hash } from "@ember/helper";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
-import { htmlSafe } from "@ember/template";
import DButton from "discourse/components/d-button";
import PluginOutlet from "discourse/components/plugin-outlet";
import ReviewableCreatedBy from "discourse/components/reviewable-created-by";
@@ -11,6 +10,7 @@ import ReviewablePostEdits from "discourse/components/reviewable-post-edits";
import ReviewablePostHeader from "discourse/components/reviewable-post-header";
import ReviewableTopicLink from "discourse/components/reviewable-topic-link";
import { bind } from "discourse/lib/decorators";
+import highlightWatchedWords from "discourse/lib/highlight-watched-words";
import { i18n } from "discourse-i18n";
export default class ReviewableFlaggedPost extends Component {
@@ -68,7 +68,7 @@ export default class ReviewableFlaggedPost extends Component {
{{#if @reviewable.blank_post}}
<p>{{i18n "review.deleted_post"}}</p>
{{else}}
- {{htmlSafe @reviewable.cooked}}
+ {{highlightWatchedWords @reviewable.cooked @reviewable}}
{{/if}}
</div>
diff --git a/app/assets/javascripts/discourse/app/components/reviewable-post.gjs b/app/assets/javascripts/discourse/app/components/reviewable-post.gjs
index b344e628373..996a511aeb5 100644
--- a/app/assets/javascripts/discourse/app/components/reviewable-post.gjs
+++ b/app/assets/javascripts/discourse/app/components/reviewable-post.gjs
@@ -1,9 +1,9 @@
import Component from "@ember/component";
-import { htmlSafe } from "@ember/template";
import ReviewableCreatedBy from "discourse/components/reviewable-created-by";
import ReviewablePostEdits from "discourse/components/reviewable-post-edits";
import ReviewablePostHeader from "discourse/components/reviewable-post-header";
import ReviewableTopicLink from "discourse/components/reviewable-topic-link";
+import highlightWatchedWords from "discourse/lib/highlight-watched-words";
import { i18n } from "discourse-i18n";
export default class ReviewablePost extends Component {
@@ -25,7 +25,7 @@ export default class ReviewablePost extends Component {
{{#if this.reviewable.blank_post}}
<p>{{i18n "review.deleted_post"}}</p>
{{else}}
- {{htmlSafe this.reviewable.cooked}}
+ {{highlightWatchedWords this.reviewable.cooked this.reviewable}}
{{/if}}
</div>
{{yield}}
diff --git a/app/assets/javascripts/discourse/app/components/reviewable-queued-post.gjs b/app/assets/javascripts/discourse/app/components/reviewable-queued-post.gjs
index 88723d6fd98..82c5e6d1a27 100644
--- a/app/assets/javascripts/discourse/app/components/reviewable-queued-post.gjs
+++ b/app/assets/javascripts/discourse/app/components/reviewable-queued-post.gjs
@@ -13,6 +13,7 @@ import ReviewableTags from "discourse/components/reviewable-tags";
import ReviewableTopicLink from "discourse/components/reviewable-topic-link";
import categoryBadge from "discourse/helpers/category-badge";
import icon from "discourse/helpers/d-icon";
+import highlightWatchedWords from "discourse/lib/highlight-watched-words";
export default class ReviewableQueuedPost extends Component {
@service modal;
@@ -67,7 +68,7 @@ export default class ReviewableQueuedPost extends Component {
<ReviewableTopicLink @reviewable={{@reviewable}} @tagName="">
<div class="title-text">
{{icon "square-plus" title="review.new_topic"}}
- {{@reviewable.payload.title}}
+ {{highlightWatchedWords @reviewable.payload.title @reviewable}}
</div>
{{categoryBadge @reviewable.category}}
<ReviewableTags @tags={{@reviewable.payload.tags}} @tagName="" />
@@ -90,7 +91,7 @@ export default class ReviewableQueuedPost extends Component {
<CookText
class="post-body {{if this.isCollapsed 'is-collapsed'}}"
- @rawText={{@reviewable.payload.raw}}
+ @rawText={{highlightWatchedWords @reviewable.payload.raw @reviewable}}
@categoryId={{@reviewable.category_id}}
@topicId={{@reviewable.topic_id}}
@paintOneboxes={{true}}
diff --git a/app/assets/javascripts/discourse/app/components/reviewable-topic-link.gjs b/app/assets/javascripts/discourse/app/components/reviewable-topic-link.gjs
index ce5baf859bc..84760a0c8db 100644
--- a/app/assets/javascripts/discourse/app/components/reviewable-topic-link.gjs
+++ b/app/assets/javascripts/discourse/app/components/reviewable-topic-link.gjs
@@ -1,10 +1,10 @@
import Component from "@ember/component";
import { array } from "@ember/helper";
import { LinkTo } from "@ember/routing";
-import { htmlSafe } from "@ember/template";
import ReviewableTags from "discourse/components/reviewable-tags";
import TopicStatus from "discourse/components/topic-status";
import categoryBadge from "discourse/helpers/category-badge";
+import highlightWatchedWords from "discourse/lib/highlight-watched-words";
import { i18n } from "discourse-i18n";
export default class ReviewableTopicLink extends Component {
@@ -15,8 +15,12 @@ export default class ReviewableTopicLink extends Component {
@topic={{this.reviewable.topic}}
@showPrivateMessageIcon={{true}}
/>
- <a href={{this.reviewable.target_url}} class="title-text">{{htmlSafe
+ <a
+ href={{this.reviewable.target_url}}
+ class="title-text"
+ >{{highlightWatchedWords
this.reviewable.topic.fancyTitle
+ this.reviewable
}}</a>
{{categoryBadge this.reviewable.category}}
<ReviewableTags @tags={{this.reviewable.topic_tags}} @tagName="" />
diff --git a/app/assets/javascripts/discourse/app/lib/highlight-html.js b/app/assets/javascripts/discourse/app/lib/highlight-html.js
index 21610eb48b7..7fdbdfdefb6 100644
--- a/app/assets/javascripts/discourse/app/lib/highlight-html.js
+++ b/app/assets/javascripts/discourse/app/lib/highlight-html.js
@@ -25,9 +25,10 @@ function highlight(node, pattern, nodeName, className) {
const element = document.createElement(nodeName);
element.className = className;
- element.innerText = match[0];
- const matchNode = node.splitText(match.index);
- matchNode.splitText(match[0].length);
+ element.innerText = match[2];
+
+ const matchNode = node.splitText(match.index + match[1].length);
+ matchNode.splitText(match[2].length);
matchNode.parentNode.replaceChild(element, matchNode);
return 1;
}
@@ -51,7 +52,7 @@ export default function (node, words, opts = {}) {
return node;
}
- const pattern = `(${words.join(" ")})`;
+ const pattern = `(\\W|^)(${words.join(" ")})(\\W|$)`;
let flag;
if (!settings.matchCase) {
diff --git a/app/assets/javascripts/discourse/app/lib/highlight-watched-words.js b/app/assets/javascripts/discourse/app/lib/highlight-watched-words.js
new file mode 100644
index 00000000000..a944c70b168
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/highlight-watched-words.js
@@ -0,0 +1,35 @@
+import { htmlSafe } from "@ember/template";
+import { decode } from "html-entities";
+import highlightHTML from "discourse/lib/highlight-html";
+
+export default function (text, reviewable) {
+ if (!text) {
+ return text;
+ }
+
+ if (!reviewable || !reviewable.reviewable_scores) {
+ return htmlSafe(text);
+ }
+
+ const words = reviewable.reviewable_scores
+ .map((rs) => {
+ return rs.reason_type === "watched_word" ? rs.reason_data : [];
+ })
+ .flat();
+
+ if (!words.length) {
+ return htmlSafe(text);
+ }
+
+ const elem = document.createElement("span");
+ elem.innerHTML = text;
+
+ words.forEach((word) => {
+ highlightHTML(elem, word, {
+ nodeName: "mark",
+ className: "watched-word-highlight",
+ });
+ });
+
+ return htmlSafe(decode(elem.innerHTML));
+}
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/highlight-watched-words-test.js b/app/assets/javascripts/discourse/tests/unit/lib/highlight-watched-words-test.js
new file mode 100644
index 00000000000..c6e48416dc1
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/unit/lib/highlight-watched-words-test.js
@@ -0,0 +1,104 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import highlightWatchedWords from "discourse/lib/highlight-watched-words";
+
+module("Unit | Utility | highlight-watched-words", function (hooks) {
+ setupTest(hooks);
+
+ test("no text", function (assert) {
+ const text = null;
+ const reviewable = {
+ reviewable_scores: [
+ {
+ reason_type: "watched_word",
+ reason_data: ["some text", "is", "word not in this text"],
+ },
+ ],
+ };
+ const highlighted = highlightWatchedWords(text, reviewable);
+ assert.strictEqual(highlighted, null, "it should return the original text");
+ });
+
+ test("no reviewable", function (assert) {
+ const text = "This is some text to highlight";
+ const reviewable = null;
+ const highlighted = highlightWatchedWords(text, reviewable);
+ assert.strictEqual(
+ highlighted.toString(),
+ "This is some text to highlight",
+ "it should return the original text"
+ );
+ });
+
+ test("no reviewable scores", function (assert) {
+ const text = "This is some text to highlight";
+ const reviewable = {
+ reviewable_scores: null,
+ };
+ const highlighted = highlightWatchedWords(text, reviewable);
+ assert.strictEqual(
+ highlighted.toString(),
+ "This is some text to highlight",
+ "it should return the original text"
+ );
+ });
+
+ test("no watched words", function (assert) {
+ const text = "This is some text to highlight";
+ const reviewable = {
+ reviewable_scores: [
+ {
+ reason_type: "watched_word",
+ reason_data: [],
+ },
+ ],
+ };
+ const highlighted = highlightWatchedWords(text, reviewable);
+ assert.strictEqual(
+ highlighted.toString(),
+ "This is some text to highlight",
+ "it should return the original text"
+ );
+ });
+
+ test("highlighting text", function (assert) {
+ const text = "This is some text to highlight";
+ const reviewable = {
+ reviewable_scores: [
+ {
+ reason_type: "watched_word",
+ reason_data: ["some text", "is", "word not in this text"],
+ },
+ ],
+ };
+
+ const highlighted = highlightWatchedWords(text, reviewable);
+
+ assert.strictEqual(
+ highlighted.toString(),
+ 'This <mark class="watched-word-highlight">is</mark> <mark class="watched-word-highlight">some text</mark> to highlight',
+ "it should highlight the term correctly"
+ );
+ });
+
+ test("highlighting unicode text", function (assert) {
+ const text = "This is some தமிழ் & русский text to highlight";
+
+ const reviewable = {
+ reviewable_scores: [
+ {
+ reason_type: "watched_word",
+ reason_data: ["தமிழ் & русский", "highlight", "this"],
+ },
+ ],
+ };
+
+ const highlighted = highlightWatchedWords(text, reviewable);
+
+ assert.strictEqual(
+ highlighted.toString(),
+ '<mark class="watched-word-highlight">This</mark> is some <mark class="watched-word-highlight">தமிழ் & русский</mark> text to <mark class="watched-word-highlight">highlight</mark>',
+ "it should highlight the term correctly"
+ );
+ });
+});
diff --git a/app/serializers/reviewable_score_serializer.rb b/app/serializers/reviewable_score_serializer.rb
index 1fe7b888e0e..0ee2fbcdc41 100644
--- a/app/serializers/reviewable_score_serializer.rb
+++ b/app/serializers/reviewable_score_serializer.rb
@@ -17,7 +17,14 @@ class ReviewableScoreSerializer < ApplicationSerializer
contains_media: "skip_media_review_groups",
}
- attributes :id, :score, :agree_stats, :reason, :created_at, :reviewed_at
+ attributes :id,
+ :score,
+ :agree_stats,
+ :reason,
+ :reason_type,
+ :reason_data,
+ :created_at,
+ :reviewed_at
attribute :status_for_database, key: :status
@@ -55,6 +62,14 @@ class ReviewableScoreSerializer < ApplicationSerializer
text
end
+ def reason_type
+ object.reason
+ end
+
+ def reason_data
+ watched_words_found if object.reason == "watched_word"
+ end
+
def include_reason?
reason.present?
end
@@ -75,20 +90,7 @@ class ReviewableScoreSerializer < ApplicationSerializer
private
def watched_word_reason(link)
- if object.context.nil?
- # If the words weren't recorded, try to guess them based on current settings.
- if object.reviewable.respond_to?(:post)
- s = object.reviewable.post.raw.clone
- s << " #{object.reviewable.post.topic.title}" if object.reviewable.post.post_number == 1
- elsif object.reviewable.respond_to?(:payload)
- s = object.reviewable.payload["raw"].clone
- s << " #{object.reviewable.payload["title"]}" if object.reviewable.payload.key?("title")
- end
-
- words = WordWatcher.new(s).word_matches_across_all_actions
- else
- words = object.context.split(",")
- end
+ words = watched_words_found
if words.nil? || words.empty?
text =
@@ -107,6 +109,25 @@ class ReviewableScoreSerializer < ApplicationSerializer
text
end
+ def watched_words_found
+ if object.context.nil?
+ # If the words weren't recorded, try to guess them based on current settings.
+ if object.reviewable.respond_to?(:post)
+ s = object.reviewable.post.raw.clone
+ s << " #{object.reviewable.post.topic.title}" if object.reviewable.post.post_number == 1
+ elsif object.reviewable.respond_to?(:payload)
+ s = object.reviewable.payload["raw"].clone
+ s << " #{object.reviewable.payload["title"]}" if object.reviewable.payload.key?("title")
+ end
+
+ words = WordWatcher.new(s).word_matches_across_all_actions
+ else
+ words = object.context.split(",")
+ end
+
+ words.map(&:downcase).uniq
+ end
+
def url_for(reason, text)
case reason
when "watched_word"
diff --git a/spec/serializers/reviewable_score_serializer_spec.rb b/spec/serializers/reviewable_score_serializer_spec.rb
index 3248bc251f5..268007dfc5e 100644
--- a/spec/serializers/reviewable_score_serializer_spec.rb
+++ b/spec/serializers/reviewable_score_serializer_spec.rb
@@ -4,6 +4,21 @@ RSpec.describe ReviewableScoreSerializer do
fab!(:reviewable) { Fabricate(:reviewable_flagged_post) }
fab!(:admin)
+ reasons = %w[
+ post_count
+ trust_level
+ new_topics_unless_trust_level
+ fast_typer
+ auto_silence_regex
+ staged
+ must_approve_users
+ invite_only
+ email_spam
+ suspect_user
+ contains_media
+ watched_word
+ ]
+
describe "#reason" do
context "with regular links" do
it "adds a link for watched words" do
@@ -28,31 +43,19 @@ RSpec.describe ReviewableScoreSerializer do
end
context "with site setting links" do
- reasons = %w[
- post_count
- trust_level
- new_topics_unless_trust_level
- fast_typer
- auto_silence_regex
- staged
- must_approve_users
- invite_only
- email_spam
- suspect_user
- contains_media
- ]
-
- reasons.each do |r|
- it "addd a link to a site setting for the #{r} reason" do
- serialized = serialized_score(r)
- setting_name = described_class::REASONS_AND_SETTINGS[r.to_sym]
- link_url =
- "#{Discourse.base_url}/admin/site_settings/category/all_results?filter=#{setting_name}"
- link = "<a href=\"#{link_url}\">#{setting_name.gsub("_", " ")}</a>"
-
- expect(serialized.reason).to include(link)
+ reasons
+ .reject { |r| r == "watched_word" }
+ .each do |r|
+ it "adds a link to a site setting for the #{r} reason" do
+ serialized = serialized_score(r)
+ setting_name = described_class::REASONS_AND_SETTINGS[r.to_sym]
+ link_url =
+ "#{Discourse.base_url}/admin/site_settings/category/all_results?filter=#{setting_name}"
+ link = "<a href=\"#{link_url}\">#{setting_name.gsub("_", " ")}</a>"
+
+ expect(serialized.reason).to include(link)
+ end
end
- end
end
context "with custom reasons" do
@@ -114,6 +117,38 @@ RSpec.describe ReviewableScoreSerializer do
end
end
+ describe "#reason_type" do
+ reasons.each do |reason|
+ it "returns the correct reason type for #{reason}" do
+ serialized = serialized_score(reason)
+ expect(serialized.reason_type).to eq(reason)
+ end
+ end
+ end
+
+ describe "#reason_data" do
+ reasons
+ .reject { |r| r == "watched_word" }
+ .each do |reason|
+ it "returns nil for #{reason}" do
+ serialized = serialized_score(reason)
+ expect(serialized.reason_data).to be_nil
+ end
+ end
+
+ it "returns the watched words found for the watched_word reason" do
+ raw = "I'm a post with some bad words like 'bad' and 'words'."
+ reviewable.target = Fabricate(:post, raw:)
+
+ score = serialized_score("watched_word")
+
+ Fabricate(:watched_word, action: WatchedWord.actions[:flag], word: "bad")
+ Fabricate(:watched_word, action: WatchedWord.actions[:flag], word: "words")
+
+ expect(score.reason_data).to include("bad", "words")
+ end
+ end
+
describe "#setting_name_for_reason" do
after { DiscoursePluginRegistry.reset_register!(:reviewable_score_links) }