Skip to content

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

FEATURE: allow filtering of tag groups with special chars (#37049)

Samdf1bafeed5a8
diff --git a/app/models/tag_group.rb b/app/models/tag_group.rb
index 07cdab6c6d7..fd33bb4eb8d 100644
--- a/app/models/tag_group.rb
+++ b/app/models/tag_group.rb
@@ -4,6 +4,12 @@ class TagGroup < ActiveRecord::Base
validates :name, length: { maximum: 100 }
validates :name, uniqueness: { case_sensitive: false }
+ scope :where_name,
+ ->(name) do
+ name = Array(name).map(&:downcase)
+ where("lower(tag_groups.name) IN (?)", name)
+ end
+
has_many :tag_group_memberships, dependent: :destroy
has_many :tags, through: :tag_group_memberships
has_many :none_synonym_tags,
diff --git a/frontend/discourse/app/lib/filter-suggestions.js b/frontend/discourse/app/lib/filter-suggestions.js
index aa1bd4245e0..0b71a234440 100644
--- a/frontend/discourse/app/lib/filter-suggestions.js
+++ b/frontend/discourse/app/lib/filter-suggestions.js
@@ -150,6 +150,8 @@ export default class FilterSuggestions {
return await suggester.getCategorySuggestions();
case "tag":
return await suggester.getTagSuggestions();
+ case "tag_group":
+ return await suggester.getTagGroupSuggestions();
case "username":
return await suggester.getUserSuggestions();
case "group":
@@ -176,7 +178,9 @@ class FilterParser {
}
parse() {
- const words = this.text.split(/\s+/).filter(Boolean);
+ // Split on whitespace, but preserve quoted strings
+ const quotedPattern = /"[^"]*"|'[^']*'|[^\s]+/g;
+ const words = (this.text.match(quotedPattern) || []).filter(Boolean);
this.endsWithSpace = this.text.endsWith(" ");
return words.map((word) => this.parseWord(word));
}
@@ -343,6 +347,29 @@ class FilterTypeValueSuggester {
}
}
+ async getTagGroupSuggestions() {
+ try {
+ const response = await ajax("/tag_groups/filter/search.json", {
+ data: { q: this.searchTerm || "", limit: 10 },
+ });
+
+ return response.results.map((tagGroup) => {
+ // Quote the name if it contains special characters
+ const needsQuoting = /[\s&\-()']/.test(tagGroup.name);
+ const quotedName = needsQuoting ? `"${tagGroup.name}"` : tagGroup.name;
+
+ return {
+ name: this.buildSuggestionName(quotedName),
+ description: tagGroup.tag_names?.join(", ") || "",
+ term: quotedName,
+ isSuggestion: true,
+ };
+ });
+ } catch {
+ return [];
+ }
+ }
+
async getUserSuggestions() {
try {
const data = { limit: 10 };
diff --git a/lib/topics_filter.rb b/lib/topics_filter.rb
index 054986b6622..6fc2517d30d 100644
--- a/lib/topics_filter.rb
+++ b/lib/topics_filter.rb
@@ -18,14 +18,27 @@ class TopicsFilter
}
private_constant :FILTER_ALIASES
+ # Shared pattern for matching quoted values (single or double quotes)
+ QUOTED_VALUE_PATTERN = '"[^"]*"|\'[^\']*\''
+ private_constant :QUOTED_VALUE_PATTERN
+
+ # Pattern for extracting filter components: prefix, key, and value (supports quoted values)
+ FILTER_EXTRACTION_PATTERN =
+ /(?<key_prefix>(?:-|=|-=|=-))?(?<key>[\w-]+):(?<value>#{QUOTED_VALUE_PATTERN}|[^\s]+)/
+ private_constant :FILTER_EXTRACTION_PATTERN
+
+ # Pattern for tokenizing query string while preserving quoted values and filter:value pairs
+ # Note: wrap QUOTED_VALUE_PATTERN in non-capturing group to preserve alternation precedence
+ TOKENIZER_PATTERN =
+ /[\w-]+:(?:#{QUOTED_VALUE_PATTERN})|[\w-]+:[^\s]+|(?:#{QUOTED_VALUE_PATTERN})|[^\s]+/
+ private_constant :TOKENIZER_PATTERN
+
def filter_from_query_string(query_string)
return @scope if query_string.blank?
filters = {}
- query_string.scan(
- /(?<key_prefix>(?:-|=|-=|=-))?(?<key>[\w-]+):(?<value>[^\s]+)/,
- ) do |key_prefix, key, value|
+ query_string.scan(FILTER_EXTRACTION_PATTERN) do |key_prefix, key, value|
key = FILTER_ALIASES[key] || key
filters[key] ||= {}
@@ -100,8 +113,13 @@ class TopicsFilter
end
end
+ # Tokenize while preserving quoted values, then extract keywords (non-filter terms)
keywords =
- query_string.split(/\s+/).reject { |word| word.include?(":") }.map(&:strip).reject(&:empty?)
+ query_string
+ .scan(TOKENIZER_PATTERN)
+ .reject { |word| word.include?(":") }
+ .map(&:strip)
+ .reject(&:empty?)
if keywords.present? && keywords.join(" ").length >= SiteSetting.min_search_term_length
ts_query = Search.ts_query(term: keywords.join(" "))
@@ -851,8 +869,9 @@ class TopicsFilter
end
def filter_tag_groups(values:)
- values.each do |key_prefix, tag_groups|
- tag_group_ids = TagGroup.visible(@guardian).where(name: tag_groups).pluck(:id)
+ values.each do |key_prefix, tag_groups_value|
+ tag_group_name = strip_quotes(tag_groups_value)
+ tag_group_ids = TagGroup.visible(@guardian).where_name(tag_group_name).pluck(:id)
exclude_clause = "NOT" if key_prefix == "-"
filter =
"tags.id #{exclude_clause} IN (SELECT tag_id FROM tag_group_memberships WHERE tag_group_id IN (?))"
@@ -871,6 +890,10 @@ class TopicsFilter
end
end
+ def strip_quotes(value)
+ value.gsub(/\A["']|["']\z/, "")
+ end
+
def filter_tags(values:)
return if !SiteSetting.tagging_enabled?
diff --git a/spec/lib/topics_filter_spec.rb b/spec/lib/topics_filter_spec.rb
index 8fc8b1c215f..d9c47b27c5d 100644
--- a/spec/lib/topics_filter_spec.rb
+++ b/spec/lib/topics_filter_spec.rb
@@ -1561,6 +1561,88 @@ RSpec.describe TopicsFilter do
end
end
+ describe "when filtering by tag_groups with special characters" do
+ fab!(:tag) { Fabricate(:tag, name: "special-tag") }
+ fab!(:tag_group_with_spaces) do
+ Fabricate(:tag_group, name: "My Tag Group", tag_names: [tag.name])
+ end
+ fab!(:tag_group_with_ampersand) do
+ Fabricate(:tag_group, name: "News & Updates", tag_names: [tag.name])
+ end
+ fab!(:tag_group_with_parens) do
+ Fabricate(:tag_group, name: "Group (Test)", tag_names: [tag.name])
+ end
+ fab!(:topic_with_tag) { Fabricate(:topic, tags: [tag]) }
+ fab!(:topic_without_tag, :topic)
+
+ it "should filter by tag group name with spaces using double quotes" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string('tag_group:"My Tag Group"')
+ .pluck(:id),
+ ).to contain_exactly(topic_with_tag.id)
+ end
+
+ it "should filter by tag group name with spaces using single quotes" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("tag_group:'My Tag Group'")
+ .pluck(:id),
+ ).to contain_exactly(topic_with_tag.id)
+ end
+
+ it "should filter by tag group name with ampersand" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string('tag_group:"News & Updates"')
+ .pluck(:id),
+ ).to contain_exactly(topic_with_tag.id)
+ end
+
+ it "should filter by tag group name with parentheses" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string('tag_group:"Group (Test)"')
+ .pluck(:id),
+ ).to contain_exactly(topic_with_tag.id)
+ end
+
+ it "should perform case-insensitive tag group lookup" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string('tag_group:"MY TAG GROUP"')
+ .pluck(:id),
+ ).to contain_exactly(topic_with_tag.id)
+ end
+
+ it "should handle exclude prefix with quoted tag group names" do
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string('-tag_group:"My Tag Group"')
+ .pluck(:id),
+ ).to contain_exactly(topic_without_tag.id)
+ end
+
+ it "should maintain backward compatibility with unquoted tag group names" do
+ simple_tag = Fabricate(:tag, name: "simple-tag")
+ _simple_group = Fabricate(:tag_group, name: "simple", tag_names: [simple_tag.name])
+ topic_simple = Fabricate(:topic, tags: [simple_tag])
+
+ expect(
+ TopicsFilter
+ .new(guardian: Guardian.new)
+ .filter_from_query_string("tag_group:simple")
+ .pluck(:id),
+ ).to contain_exactly(topic_simple.id)
+ end
+ end
+
describe "when filtering by locale" do
fab!(:en_topic) { Fabricate(:topic, locale: "en") }
fab!(:ja_topic) { Fabricate(:topic, locale: "ja") }
diff --git a/spec/models/tag_group_spec.rb b/spec/models/tag_group_spec.rb
index c8be4eca242..21a0cd8c511 100644
--- a/spec/models/tag_group_spec.rb
+++ b/spec/models/tag_group_spec.rb
@@ -127,6 +127,29 @@ RSpec.describe TagGroup do
expect(TagGroup.find_by_name_insensitive("TeSt-TaG-GrOuP")).to eq(tag_group)
end
end
+
+ describe ".where_name" do
+ fab!(:tag_group1) { Fabricate(:tag_group, name: "My Group") }
+ fab!(:tag_group2) { Fabricate(:tag_group, name: "Other Group") }
+
+ it "finds tag groups case-insensitively" do
+ expect(TagGroup.where_name("my group")).to contain_exactly(tag_group1)
+ expect(TagGroup.where_name("MY GROUP")).to contain_exactly(tag_group1)
+ expect(TagGroup.where_name("My Group")).to contain_exactly(tag_group1)
+ end
+
+ it "accepts an array of names" do
+ expect(TagGroup.where_name(["my group", "other group"])).to contain_exactly(
+ tag_group1,
+ tag_group2,
+ )
+ end
+
+ it "returns an empty array when no match is found" do
+ expect(TagGroup.where_name("nonexistent")).to be_empty
+ end
+ end
+
describe "tag_names=" do
let(:tag_group) { Fabricate(:tag_group) }
fab!(:tag)
diff --git a/spec/system/filtering_topics_spec.rb b/spec/system/filtering_topics_spec.rb
index 011b6ebf3cd..00a9623b3d0 100644
--- a/spec/system/filtering_topics_spec.rb
+++ b/spec/system/filtering_topics_spec.rb
@@ -108,6 +108,26 @@ describe "Filtering topics", type: :system do
end
end
+ describe "when filtering by tag groups with special characters" do
+ fab!(:tag) { Fabricate(:tag, name: "special-tag") }
+ fab!(:tag_group) { Fabricate(:tag_group, name: "Cat & Dogs", tag_names: [tag.name]) }
+ fab!(:topic_with_tag) { Fabricate(:topic, tags: [tag]) }
+ fab!(:topic_without_tag, :topic)
+
+ it "filters by tag group name with spaces using quoted syntax" do
+ sign_in(user)
+ visit("/filter")
+
+ expect(topic_list).to have_topic(topic_with_tag)
+ expect(topic_list).to have_topic(topic_without_tag)
+
+ topic_query_filter.fill_in('tag_group:"Cat & Dogs"')
+
+ expect(topic_list).to have_topic(topic_with_tag)
+ expect(topic_list).to have_no_topic(topic_without_tag)
+ end
+ end
+
describe "bulk topic selection" do
fab!(:user, :moderator)