Skip to content

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

DEV: Expand top_tags, topic.tags, etc, to return an array of tag objects instead of tag names (#36678)

Natalie Tay9e99066b073a
diff --git a/app/controllers/admin/embeddable_hosts_controller.rb b/app/controllers/admin/embeddable_hosts_controller.rb
index 3ef3c1aa1db..193009ec5f1 100644
--- a/app/controllers/admin/embeddable_hosts_controller.rb
+++ b/app/controllers/admin/embeddable_hosts_controller.rb
@@ -38,7 +38,7 @@ class Admin::EmbeddableHostsController < Admin::AdminController
ActiveRecord::Base.transaction do
if host.save
- manage_tags(host, params[:embeddable_host][:tags]&.map(&:strip))
+ manage_tags(host, params[:embeddable_host][:tags])
changes = host.saved_changes if action == :update
StaffActionLogger.new(current_user).log_embeddable_host(
@@ -59,25 +59,7 @@ class Admin::EmbeddableHostsController < Admin::AdminController
end
end
- def manage_tags(host, tags)
- if tags.blank?
- host.tags.clear
- return
- end
-
- existing_tags = Tag.where(name: tags).index_by(&:name)
- tags_to_associate = []
-
- tags.each do |tag_name|
- tag = existing_tags[tag_name] || Tag.create(name: tag_name)
- if tag.persisted?
- tags_to_associate << tag
- else
- host.errors.add(:tags, "Failed to create or find tag: #{tag_name}")
- raise ActiveRecord::Rollback
- end
- end
-
- host.tags = tags_to_associate
+ def manage_tags(host, tag_ids)
+ tag_ids.blank? ? host.tags.clear : host.tags = Tag.where(id: tag_ids)
end
end
diff --git a/app/controllers/admin/staff_action_logs_controller.rb b/app/controllers/admin/staff_action_logs_controller.rb
index f98385ccd2d..d5c74530ae2 100644
--- a/app/controllers/admin/staff_action_logs_controller.rb
+++ b/app/controllers/admin/staff_action_logs_controller.rb
@@ -103,12 +103,25 @@ class Admin::StaffActionLogsController < Admin::StaffController
end
def diff_tag_group(diff_fields, prev, cur)
- %w[parent_tag_name one_per_topic permissions].each do |f|
+ %w[one_per_topic permissions].each do |f|
diff_fields[f] = { prev: prev&.dig(f).to_s, cur: cur&.dig(f).to_s }
end
- diff_fields["tag_names"] = {
- prev: prev&.dig("tag_names")&.join("\n"),
- cur: cur&.dig("tag_names")&.join("\n"),
+ add_tag_diff(diff_fields, prev, cur, "tags", "tag_names")
+ add_tag_diff(diff_fields, prev, cur, "parent_tag", "parent_tag_name")
+ end
+
+ def add_tag_diff(diff_fields, prev, cur, new_key, old_key)
+ prev_key = prev&.key?(new_key) ? new_key : old_key
+ cur_key = cur&.key?(new_key) ? new_key : old_key
+ field_name = cur&.key?(new_key) || prev&.key?(new_key) ? new_key : old_key
+ diff_fields[field_name] = {
+ prev: extract_tag_names(prev&.dig(prev_key)),
+ cur: extract_tag_names(cur&.dig(cur_key)),
}
end
+
+ def extract_tag_names(tags)
+ return nil if tags.blank?
+ tags.map { |t| t.is_a?(Hash) ? t["name"] : t }.join("\n")
+ end
end
diff --git a/app/controllers/drafts_controller.rb b/app/controllers/drafts_controller.rb
index c82b58a2a74..1c920807f07 100644
--- a/app/controllers/drafts_controller.rb
+++ b/app/controllers/drafts_controller.rb
@@ -113,10 +113,16 @@ class DraftsController < ApplicationController
# Since the topic might have hidden tags the current editor can't see,
# we need to check for conflicts even though there might not be any visible tags in the editor
if !conflict
- original_tags = (original_tags || []).map(&:downcase).to_set
- current_tags = post.topic.tags.pluck(:name).to_set
- hidden_tags = DiscourseTagging.hidden_tag_names(@guardian).to_set
- conflict = original_tags != (current_tags - hidden_tags)
+ original_tags ||= []
+ original_tag_ids = original_tags.filter_map { |t| t["id"] if t.is_a?(Hash) }
+ # old draft format is tag names as strings
+ old_format_names = original_tags.select { |t| t.is_a?(String) }
+ original_tag_ids +=
+ Tag.where(name: old_format_names).pluck(:id) if old_format_names.present?
+
+ current_tag_ids = post.topic.tags.pluck(:id).to_set
+ hidden_tag_ids = DiscourseTagging.hidden_tags(@guardian).pluck(:id).to_set
+ conflict = original_tag_ids.to_set != (current_tag_ids - hidden_tag_ids)
end
end
diff --git a/app/controllers/tag_groups_controller.rb b/app/controllers/tag_groups_controller.rb
index 4fda59156e2..497e2683d32 100644
--- a/app/controllers/tag_groups_controller.rb
+++ b/app/controllers/tag_groups_controller.rb
@@ -102,7 +102,12 @@ class TagGroupsController < ApplicationController
render json: {
results:
- matches.map { |x| { name: x.name, tag_names: x.tags.base_tags.pluck(:name).sort } },
+ matches.map do |x|
+ {
+ name: x.name,
+ tags: x.tags.base_tags.pluck(:id, :name).map { |id, name| { id:, name: } },
+ }
+ end,
}
end
@@ -117,10 +122,44 @@ class TagGroupsController < ApplicationController
params.merge!(tag_group.permit!) if tag_group
result =
- params.permit(:id, :name, :one_per_topic, tag_names: [], parent_tag_name: [], permissions: {})
+ params.permit(
+ :id,
+ :name,
+ :one_per_topic,
+ tags: %i[id name slug],
+ tag_names: [],
+ parent_tag: %i[id name slug],
+ parent_tag_name: [],
+ permissions: {
+ },
+ )
+
+ if result[:tags].present?
+ result[:tag_ids] = result[:tags].map { |t| t["id"] }
+ elsif result[:tag_names].present?
+ Discourse.deprecate(
+ "the tag_names param is deprecated, use tags instead",
+ since: "2026.01",
+ drop_from: "2026.07",
+ )
+ else
+ result[:tag_names] = []
+ end
+ result.delete(:tags)
+
+ if result[:parent_tag].present?
+ result[:parent_tag_id] = result[:parent_tag].first&.dig("id")
+ elsif result[:parent_tag_name].present?
+ Discourse.deprecate(
+ "the parent_tag_name param is deprecated, use parent_tag instead",
+ since: "2026.01",
+ drop_from: "2026.07",
+ )
+ else
+ result[:parent_tag_name] = []
+ end
+ result.delete(:parent_tag)
- result[:tag_names] ||= []
- result[:parent_tag_name] ||= []
result[:one_per_topic] = params[:one_per_topic].in?([true, "true"])
result
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index 3e9ad30f538..8092e0dadfd 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -338,9 +338,18 @@ class TagsController < ::ApplicationController
end
def search
+ if params[:selected_tags].present?
+ Discourse.deprecate(
+ "selected_tags param is deprecated, use selected_tag_ids instead",
+ since: "2026.01",
+ drop_from: "2026.07",
+ )
+ end
+
filter_params = {
for_input: params[:filterForInput],
selected_tags: params[:selected_tags],
+ selected_tag_ids: params[:selected_tag_ids],
exclude_synonyms: params[:excludeSynonyms],
exclude_has_synonyms: params[:excludeHasSynonyms],
}
@@ -448,16 +457,24 @@ class TagsController < ::ApplicationController
def create_synonyms
guardian.ensure_can_edit_tag!
- value = DiscourseTagging.add_or_create_synonyms_by_name(@tag, params[:synonyms])
- if value.is_a?(Array)
- render json:
- failed_json.merge(
- failed_tags:
- value.inject({}) do |h, t|
- h[t.name] = t.errors.full_messages.first
- h
- end,
- )
+
+ # frontend uses form data
+ tags_param = params[:tags].try(:values) || params[:tags]
+ synonym_tag_ids = tags_param&.filter_map { |t| t[:id]&.to_i } || []
+ new_synonym_names = tags_param&.select { |t| t[:id].blank? }&.filter_map { |t| t[:name] } || []
+
+ if params[:synonyms].present? && tags_param.blank?
+ Discourse.deprecate(
+ "the synonyms param is deprecated, use tags array instead",
+ since: "2026.01",
+ drop_from: "2026.07",
+ )
+ new_synonym_names = params[:synonyms]
+ end
+
+ value = DiscourseTagging.add_or_create_synonyms(@tag, synonym_tag_ids:, new_synonym_names:)
+ if value.is_a?(Hash)
+ render json: failed_json.merge(failed_tags: value)
else
render json: success_json
end
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rb
index 9b793d52290..0ba284be3ae 100644
--- a/app/controllers/topics_controller.rb
+++ b/app/controllers/topics_controller.rb
@@ -380,8 +380,8 @@ class TopicsController < ApplicationController
return render_json_error(I18n.t("edit_conflict"), status: 409)
end
- original_tags = params[:original_tags]
- if original_tags.present? && original_tags.sort != topic.tags.pluck(:name).sort
+ original_tag_ids = params[:original_tags]&.map { |t| t["id"] }&.sort
+ if original_tag_ids.present? && original_tag_ids != topic.tags.pluck(:id).sort
return render_json_error(I18n.t("edit_conflict"), status: 409)
end
@@ -472,14 +472,26 @@ class TopicsController < ApplicationController
end
def update_tags
- params.require(:tags)
topic = Topic.find_by(id: params[:topic_id])
guardian.ensure_can_edit_tags!(topic)
+ tags =
+ if params[:tag_ids].present?
+ params[:tag_ids].map(&:to_i)
+ else
+ params.require(:tags)
+ Discourse.deprecate(
+ "the tags param is deprecated, use tag_ids instead",
+ since: "2026.01",
+ drop_from: "2026.07",
+ )
+ params[:tags]
+ end
+
success =
PostRevisor.new(topic.first_post, topic).revise!(
current_user,
- { tags: params[:tags] },
+ { tags: },
validate_post: false,
)
@@ -899,6 +911,7 @@ class TopicsController < ApplicationController
post_ids = params.require(:post_ids)
topic_id = params.require(:topic_id)
params.permit(:category_id)
+ params.permit(:tag_ids)
params.permit(:tags)
params.permit(:participants)
params.permit(:chronological_order)
@@ -1060,6 +1073,7 @@ class TopicsController < ApplicationController
:message,
:silent,
*DiscoursePluginRegistry.permitted_bulk_action_parameters,
+ tag_ids: [],
tags: [],
)
.to_h
@@ -1415,7 +1429,16 @@ class TopicsController < ApplicationController
args[:destination_topic_id] = params[:destination_topic_id].to_i if params[
:destination_topic_id
].present?
- args[:tags] = params[:tags] if params[:tags].present?
+ if params[:tag_ids].present?
+ args[:tag_ids] = params[:tag_ids]
+ elsif params[:tags].present?
+ Discourse.deprecate(
+ "the tags param for move_posts is deprecated, use tag_ids instead",
+ since: "2026.01",
+ drop_from: "2026.07",
+ )
+ args[:tags] = params[:tags]
+ end
args[:chronological_order] = params[:chronological_order] == "true"
args[:freeze_original] = true if params[:freeze_original] == "true"
diff --git a/app/models/form_template.rb b/app/models/form_template.rb
index 3fcd8036ca6..07f50e784e6 100644
--- a/app/models/form_template.rb
+++ b/app/models/form_template.rb
@@ -49,7 +49,8 @@ class FormTemplate < ActiveRecord::Base
form_field.each do |key, value|
ordered_field[key] = value
- ordered_field["choices"] = tags.map(&:name) if key == "id"
+ ordered_field["choices"] = tags.map { |t| { "id" => t.id, "name" => t.name } } if key ==
+ "id"
end
ordered_field["attributes"] ||= {}
diff --git a/app/models/post_mover.rb b/app/models/post_mover.rb
index dde0e94b43d..a0beca8093f 100644
--- a/app/models/post_mover.rb
+++ b/app/models/post_mover.rb
@@ -38,7 +38,7 @@ class PostMover
topic
end
- def to_new_topic(title, category_id = nil, tags = nil)
+ def to_new_topic(title, category_id = nil, tag_ids: nil, tags: nil)
@move_type = PostMover.move_types[:new_topic]
@creating_new_topic = true
@@ -56,7 +56,11 @@ class PostMover
created_at: post.created_at,
archetype: archetype,
)
- DiscourseTagging.tag_topic_by_names(new_topic, Guardian.new(user), tags)
+ if tag_ids.present?
+ DiscourseTagging.tag_topic_by_ids(new_topic, Guardian.new(user), tag_ids)
+ elsif tags.present?
+ DiscourseTagging.tag_topic_by_names(new_topic, Guardian.new(user), tags)
+ end
move_posts_to new_topic
watch_new_topic
update_topic_excerpt new_topic
diff --git a/app/models/tag.rb b/app/models/tag.rb
index 288c146687e..50ad53ccda3 100644
--- a/app/models/tag.rb
+++ b/app/models/tag.rb
@@ -154,17 +154,17 @@ class Tag < ActiveRecord::Base
)
tag_names_with_counts = DB.query <<~SQL
- SELECT tags.name as tag_name, SUM(stats.topic_count) AS sum_topic_count
+ SELECT tags.id as tag_id, tags.name as tag_name, tags.slug as tag_slug, SUM(stats.topic_count) AS sum_topic_count
FROM category_tag_stats stats
JOIN tags ON stats.tag_id = tags.id AND stats.topic_count > 0
WHERE stats.category_id in (#{scope_category_ids.join(",")})
#{filter_sql}
- GROUP BY tags.name
- ORDER BY sum_topic_count DESC, tag_name ASC
- LIMIT #{limit}
+ GROUP BY tags.id
+ ORDER BY sum_topic_count DESC, tag_name ASC
+ LIMIT #{limit}
SQL
- tag_names_with_counts.map { |row| row.tag_name }
+ tag_names_with_counts.map { |row| { id: row.tag_id, name: row.tag_name, slug: row.tag_slug } }
end
def self.topic_count_column(guardian)
diff --git a/app/models/tag_group.rb b/app/models/tag_group.rb
index b1443f9bce8..cf7fe27a720 100644
--- a/app/models/tag_group.rb
+++ b/app/models/tag_group.rb
@@ -31,8 +31,18 @@ class TagGroup < ActiveRecord::Base
attr_reader :permissions
- def tag_names=(tag_names_arg)
- DiscourseTagging.add_or_create_tags_by_name(self, tag_names_arg, unlimited: true)
+ def tag_names=(tags_arg)
+ DiscourseTagging.add_or_create_tags_by_name(self, tags_arg, unlimited: true)
+ end
+
+ def tag_ids=(ids)
+ base_tags = Tag.where(id: ids)
+ synonyms = Tag.where(target_tag_id: base_tags.select(:id)).where.not(id: base_tags.select(:id))
+ self.tags = base_tags + synonyms
+ end
+
+ def parent_tag_id=(id)
+ self.parent_tag = id.present? ? Tag.find_by(id: id) : nil
end
def parent_tag_name=(tag_names_arg)
diff --git a/app/models/tag_user.rb b/app/models/tag_user.rb
index f91ad7ffb48..263600fd0c2 100644
--- a/app/models/tag_user.rb
+++ b/app/models/tag_user.rb
@@ -221,25 +221,34 @@ class TagUser < ActiveRecord::Base
# Anonymous users have all default tags set to regular tracking,
# except for default muted tags which stay muted.
if user.blank?
+ default_tag_names = [
+ SiteSetting.default_tags_watching_first_post.split("|"),
+ SiteSetting.default_tags_watching.split("|"),
+ SiteSetting.default_tags_tracking.split("|"),
+ ].flatten
+
+ muted_tag_names = SiteSetting.default_tags_muted.split("|")
+
+ tag_name_to_id = Tag.where(name: default_tag_names + muted_tag_names).pluck(:name, :id).to_h
+
notification_levels =
- [
- SiteSetting.default_tags_watching_first_post.split("|"),
- SiteSetting.default_tags_watching.split("|"),
- SiteSetting.default_tags_tracking.split("|"),
- ].flatten.map { |name| [name, self.notification_levels[:regular]] }
+ default_tag_names.filter_map do |name|
+ id = tag_name_to_id[name]
+ [id, self.notification_levels[:regular]] if id
+ end
notification_levels +=
- SiteSetting
- .default_tags_muted
- .split("|")
- .map { |name| [name, self.notification_levels[:muted]] }
+ muted_tag_names.filter_map do |name|
+ id = tag_name_to_id[name]
+ [id, self.notification_levels[:muted]] if id
+ end
else
notification_levels =
TagUser
.notification_level_visible
.where(user: user)
.joins(:tag)
- .pluck("tags.name", :notification_level)
+ .pluck("tags.id", :notification_level)
end
Hash[*notification_levels.flatten]
diff --git a/app/models/topic.rb b/app/models/topic.rb
index 639e7aaa0d7..a723c64d4ce 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -1359,7 +1359,12 @@ class Topic < ActiveRecord::Base
topic
elsif opts[:title]
- post_mover.to_new_topic(opts[:title], opts[:category_id], opts[:tags])
+ post_mover.to_new_topic(
+ opts[:title],
+ opts[:category_id],
+ tag_ids: opts[:tag_ids],
+ tags: opts[:tags],
+ )
end
end
diff --git a/app/models/topic_tracking_state.rb b/app/models/topic_tracking_state.rb
index 1135e298ba3..d4d5b052e09 100644
--- a/app/models/topic_tracking_state.rb
+++ b/app/models/topic_tracking_state.rb
@@ -42,9 +42,6 @@ class TopicTrackingState
def self.publish_new(topic)
return unless topic.regular?
- tag_ids, tags = nil
- tag_ids, tags = topic.tags.pluck(:id, :name).transpose if include_tags_in_report?
-
payload = {
last_read_post_number: nil,
highest_post_number: 1,
@@ -54,10 +51,7 @@ class TopicTrackingState
created_in_new_period: true,
}
- if tags
- payload[:tags] = tags
- payload[:topic_tag_ids] = tag_ids
- end
+ payload[:tags] = topic.tags.pluck(:id).map { |id| { id: id } } if include_tags_in_report?
message = { topic_id: topic.id, message_type: NEW_TOPIC_MESSAGE_TYPE, payload: payload }
@@ -70,23 +64,15 @@ class TopicTrackingState
def self.publish_latest(topic, whisper = false)
return unless topic.regular?
- tag_ids, tags = nil
- tag_ids, tags = topic.tags.pluck(:id, :name).transpose if include_tags_in_report?
-
- message = {
- topic_id: topic.id,
- message_type: LATEST_MESSAGE_TYPE,
- payload: {
- bumped_at: topic.bumped_at,
- category_id: topic.category_id,
- archetype: topic.archetype,
- },
+ payload = {
+ bumped_at: topic.bumped_at,
+ category_id: topic.category_id,
+ archetype: topic.archetype,
}
- if tags
- message[:payload][:tags] = tags
- message[:payload][:topic_tag_ids] = tag_ids
- end
+ payload[:tags] = topic.tags.pluck(:id).map { |id| { id: id } } if include_tags_in_report?
+
+ message = { topic_id: topic.id, message_type: LATEST_MESSAGE_TYPE, payload: payload }
group_ids =
if whisper
@@ -141,9 +127,6 @@ class TopicTrackingState
return unless post.topic.regular?
# TODO at high scale we are going to have to defer this,
# perhaps cut down to users that are around in the last 7 days as well
- tags = nil
- tag_ids = nil
- tag_ids, tags = post.topic.tags.pluck(:id, :name).transpose if include_tags_in_report?
# We don't need to publish unread to the person who just made the post,
# this is why they are excluded from the initial scope.
@@ -182,10 +165,7 @@ class TopicTrackingState
archetype: post.topic.archetype,
}
- if tags
- payload[:tags] = tags
- payload[:topic_tag_ids] = tag_ids
- end
+ payload[:tags] = post.topic.tags.pluck(:id).map { |id| { id: id } } if include_tags_in_report?
message = { topic_id: post.topic_id, message_type: UNREAD_MESSAGE_TYPE, payload: payload }
@@ -350,9 +330,10 @@ class TopicTrackingState
#{sql}
)
SELECT *, (
- SELECT ARRAY_AGG(name) from topic_tags
- JOIN tags on tags.id = topic_tags.tag_id
- WHERE topic_id = tags_included_cte.topic_id
+ SELECT JSON_AGG(JSON_BUILD_OBJECT('id', tags.id, 'name', tags.name, 'slug', tags.slug))
+ FROM topic_tags
+ JOIN tags ON tags.id = topic_tags.tag_id
+ WHERE topic_id = tags_included_cte.topic_id
) tags
FROM tags_included_cte
SQL
diff --git a/app/serializers/concerns/topic_tags_mixin.rb b/app/serializers/concerns/topic_tags_mixin.rb
index 95cba86602f..5a829824213 100644
--- a/app/serializers/concerns/topic_tags_mixin.rb
+++ b/app/serializers/concerns/topic_tags_mixin.rb
@@ -13,7 +13,7 @@ module TopicTagsMixin
end
def tags
- all_tags.map(&:name)
+ all_tags.map { |tag| { id: tag.id, name: tag.name, slug: tag.slug } }
end
def tags_descriptions
diff --git a/app/serializers/embeddable_host_serializer.rb b/app/serializers/embeddable_host_serializer.rb
index e9da2dd0f7a..185170df995 100644
--- a/app/serializers/embeddable_host_serializer.rb
+++ b/app/serializers/embeddable_host_serializer.rb
@@ -12,6 +12,6 @@ class EmbeddableHostSerializer < ApplicationSerializer
end
def tags
- object.tags.map(&:name)
+ object.tags.map { |t| { id: t.id, name: t.name, slug: t.slug } }
end
end
diff --git a/app/serializers/reviewable_serializer.rb b/app/serializers/reviewable_serializer.rb
index 31ac7e419e7..16ab0e27030 100644
--- a/app/serializers/reviewable_serializer.rb
+++ b/app/serializers/reviewable_serializer.rb
@@ -110,7 +110,7 @@ class ReviewableSerializer < ApplicationSerializer
end
def topic_tags
- object.topic.tags.map(&:name)
+ object.topic.tags.map { |t| { id: t.id, name: t.name, slug: t.slug } }
end
def include_topic_tags?
diff --git a/app/serializers/sidebar_tag_serializer.rb b/app/serializers/sidebar_tag_serializer.rb
index 7433950c423..731ed2e7a5d 100644
--- a/app/serializers/sidebar_tag_serializer.rb
+++ b/app/serializers/sidebar_tag_serializer.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class SidebarTagSerializer < ApplicationSerializer
- attributes :name, :description, :pm_only
+ attributes :id, :name, :slug, :description, :pm_only
def pm_only
topic_count_column = Tag.topic_count_column(scope)
diff --git a/app/serializers/site_category_serializer.rb b/app/serializers/site_category_serializer.rb
index 77e18bc6bc7..d1d3ea6044e 100644
--- a/app/serializers/site_category_serializer.rb
+++ b/app/serializers/site_category_serializer.rb
@@ -18,7 +18,7 @@ class SiteCategorySerializer < BasicCategorySerializer
end
def allowed_tags
- object.tags.pluck(:name)
+ object.tags.pluck(:id, :name, :slug).map { |id, name, slug| { id: id, name: name, slug: slug } }
end
def include_allowed_tag_groups?
diff --git a/app/serializers/site_serializer.rb b/app/serializers/site_serializer.rb
index 18658d88537..48545e0cb9d 100644
--- a/app/serializers/site_serializer.rb
+++ b/app/serializers/site_serializer.rb
@@ -316,7 +316,8 @@ class SiteSerializer < ApplicationSerializer
def navigation_menu_site_top_tags
if top_tags.present?
- tag_names = top_tags[0...SIDEBAR_TOP_TAGS_TO_SHOW]
+ top_tag_objects = top_tags[0...SIDEBAR_TOP_TAGS_TO_SHOW]
+ tag_names = top_tag_objects.map { |t| t[:name] }
serialized = serialize_tags(Tag.where(name: tag_names))
# Ensures order of top tags is preserved
diff --git a/app/serializers/tag_group_serializer.rb b/app/serializers/tag_group_serializer.rb
index d8ff8c74d65..26a33f577c9 100644
--- a/app/serializers/tag_group_serializer.rb
+++ b/app/serializers/tag_group_serializer.rb
@@ -1,14 +1,15 @@
# frozen_string_literal: true
class TagGroupSerializer < ApplicationSerializer
- attributes :id, :name, :tag_names, :parent_tag_name, :one_per_topic, :permissions
+ attributes :id, :name, :tags, :parent_tag, :one_per_topic, :permissions
- def tag_names
- object.tags.base_tags.map(&:name).sort
+ def tags
+ object.tags.base_tags.order(:name).map { |t| { id: t.id, name: t.name, slug: t.slug } }
end
- def parent_tag_name
- [object.parent_tag.try(:name)].compact
+ def parent_tag
+ return [] unless object.parent_tag
+ [{ id: object.parent_tag.id, name: object.parent_tag.name, slug: object.parent_tag.slug }]
end
def permissions
diff --git a/app/serializers/tag_serializer.rb b/app/serializers/tag_serializer.rb
index 1f2b828dda9..ebee81af4f9 100644
--- a/app/serializers/tag_serializer.rb
+++ b/app/serializers/tag_serializer.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class TagSerializer < ApplicationSerializer
- attributes :id, :name, :topic_count, :staff, :description
+ attributes :id, :name, :slug, :topic_count, :staff, :description
has_many :localizations, serializer: TagLocalizationSerializer, embed: :objects
diff --git a/frontend/discourse/admin/components/admin-embedding-host-form.gjs b/frontend/discourse/admin/components/admin-embedding-host-form.gjs
index 82e4ee9d126..5e5cb1aa20a 100644
--- a/frontend/discourse/admin/components/admin-embedding-host-form.gjs
+++ b/frontend/discourse/admin/components/admin-embedding-host-form.gjs
@@ -51,6 +51,7 @@ export default class AdminEmbeddingHostForm extends Component {
...data,
user: data.user?.at(0),
category_id: data.category,
+ tags: data.tags?.map((t) => t.id),
});
if (!this.isEditing) {
this.adminEmbedding.embedding.embeddable_hosts.push(host);
diff --git a/frontend/discourse/admin/components/edit-category-tags.gjs b/frontend/discourse/admin/components/edit-category-tags.gjs
index 1d0e3bf0c83..567fb350822 100644
--- a/frontend/discourse/admin/components/edit-category-tags.gjs
+++ b/frontend/discourse/admin/components/edit-category-tags.gjs
@@ -36,6 +36,11 @@ export default class EditCategoryTags extends buildCategoryPanel("tags") {
removeValueFromArray(this.category.required_tag_groups, rtg);
}
+ @action
+ onAllowedTagsChange(items) {
+ set(this.category, "allowed_tags", items);
+ }
+
<template>
<section class="field minimum-required-tags">
<label for="category-minimum-tags">
@@ -62,7 +67,7 @@ export default class EditCategoryTags extends buildCategoryPanel("tags") {
@everyTag={{true}}
@excludeSynonyms={{true}}
@unlimitedTagCount={{true}}
- @onChange={{fn (mut this.category.allowed_tags)}}
+ @onChange={{this.onAllowedTagsChange}}
@options={{hash filterPlaceholder="category.tags_placeholder"}}
/>
</section>
diff --git a/frontend/discourse/admin/components/embeddable-host.gjs b/frontend/discourse/admin/components/embeddable-host.gjs
index 58e0314d569..f5383639648 100644
--- a/frontend/discourse/admin/components/embeddable-host.gjs
+++ b/frontend/discourse/admin/components/embeddable-host.gjs
@@ -25,7 +25,7 @@ export default class EmbeddableHost extends Component {
const category = Category.findById(categoryId);
this.category = category;
- this.tags = (this.host.tags || []).join(", ");
+ this.tags = (this.host.tags || []).map((t) => t.name).join(", ");
this.user = this.host.user;
}
diff --git a/frontend/discourse/app/components/d-navigation.gjs b/frontend/discourse/app/components/d-navigation.gjs
index 45f7c69837d..e201649aaf4 100644
--- a/frontend/discourse/app/components/d-navigation.gjs
+++ b/frontend/discourse/app/components/d-navigation.gjs
@@ -130,7 +130,7 @@ export default class DNavigation extends Component {
"filterType",
"category",
"noSubcategories",
- "tag.name",
+ "tag",
"router.currentRoute.queryParams",
"skipCategoriesNavItem"
)
@@ -138,7 +138,7 @@ export default class DNavigation extends Component {
filterType,
category,
noSubcategories,
- tagId,
+ tag,
currentRouteQueryParams,
skipCategoriesNavItem
) {
@@ -146,7 +146,7 @@ export default class DNavigation extends Component {
filterType,
noSubcategories,
currentRouteQueryParams,
- tagId,
+ tag,
siteSettings: this.siteSettings,
skipCategoriesNavItem,
});
diff --git a/frontend/discourse/app/components/discovery/topics.gjs b/frontend/discourse/app/components/discovery/topics.gjs
index 740cb2279e2..071a18ff2d9 100644
--- a/frontend/discourse/app/components/discovery/topics.gjs
+++ b/frontend/discourse/app/components/discovery/topics.gjs
@@ -100,7 +100,7 @@ export default class DiscoveryTopics extends Component {
return this.topicTrackingState.countUnread({
categoryId: this.args.category?.id,
noSubcategories: this.args.noSubcategories,
- tagId: this.args.tag?.name,
+ tagId: this.args.tag?.id,
});
} else {
return 0;
@@ -114,7 +114,7 @@ export default class DiscoveryTopics extends Component {
return this.topicTrackingState.countNew({
categoryId: this.args.category?.id,
noSubcategories: this.args.noSubcategories,
- tagId: this.args.tag?.name,
+ tagId: this.args.tag?.id,
});
} else {
return 0;
diff --git a/frontend/discourse/app/components/form-template-field/tag-chooser.gjs b/frontend/discourse/app/components/form-template-field/tag-chooser.gjs
index 9db975c779b..79f6e68350e 100644
--- a/frontend/discourse/app/components/form-template-field/tag-chooser.gjs
+++ b/frontend/discourse/app/components/form-template-field/tag-chooser.gjs
@@ -16,22 +16,29 @@ export default class TagChooserField extends Component {
@service dialog;
get formattedChoices() {
- return this.args.choices.map((choice) => ({
- name: choice,
- display: this.args.attributes.tag_choices[choice]
- ? this.args.attributes.tag_choices[choice]
- : choice.replace(/-/g, " ").toUpperCase(),
+ return this.args.choices.map((tag) => ({
+ id: tag.id,
+ name: tag.name,
+ display: this.args.attributes.tag_choices[tag.name]
+ ? this.args.attributes.tag_choices[tag.name]
+ : tag.name.replace(/-/g, " ").toUpperCase(),
}));
}
+ _tagId(tag) {
+ return typeof tag === "object" ? tag.id : null;
+ }
+
get filteredSelectedValues() {
return this.tags.filter((tag) =>
- this.formattedChoices.some((choice) => choice.name === tag)
+ this.formattedChoices.some((choice) => choice.id === this._tagId(tag))
);
}
get selectedTags() {
- return this.tags.filter((tag) => this.args.choices.includes(tag));
+ return this.tags.filter((tag) =>
+ this.args.choices.some((choice) => choice.id === this._tagId(tag))
+ );
}
@action
@@ -50,14 +57,17 @@ export default class TagChooserField extends Component {
})
);
- const selectedTags = [
- ...this.tags.filter((tag) => !this.selectedTags.includes(tag)),
+ const selectedTagIds = this.selectedTags.map((t) => this._tagId(t));
+ const filteredTags = [
+ ...this.tags.filter(
+ (tag) => !selectedTagIds.includes(this._tagId(tag))
+ ),
];
// the next is needed because we already updated the tags in the same runloop
// when the user selected a tag in the composer directly
next(() => {
- set(this.composer.model, "tags", selectedTags);
+ set(this.composer.model, "tags", filteredTags);
this.args.onChange([]);
});
} else {
@@ -79,50 +89,42 @@ export default class TagChooserField extends Component {
}
@action
- handleSelectedValues(event) {
- const getFallbackValue = (optionValue) =>
- optionValue.toLowerCase().replace(/\s+/g, "-");
- let choiceMap = null;
- const tagChoices = this.args.attributes.tag_choices;
-
- if (tagChoices) {
- choiceMap = new Map(
- Object.entries(tagChoices).map(([key, value]) => [value, key])
- );
- }
-
- const selectedValues = Array.from(event.target.selectedOptions).map(
- (option) => {
- const mappedValue = choiceMap?.get(option.textContent.trim());
- return mappedValue ?? getFallbackValue(option.value);
- }
- );
-
- return selectedValues;
+ handleSelectedTagIds(event) {
+ return Array.from(event.target.selectedOptions)
+ .map((option) => parseInt(option.value, 10))
+ .filter((id) => !isNaN(id));
}
@action
handleInput(event) {
- const selectedValues = this.handleSelectedValues(event);
- const validChoices = this.formattedChoices.map((choice) => choice.name);
- const selectedTags = selectedValues.filter((tag) =>
- validChoices.includes(tag)
+ const selectedTagIds = this.handleSelectedTagIds(event);
+ const validTagIds = this.formattedChoices.map((choice) => choice.id);
+ const filteredTagIds = selectedTagIds.filter((tagId) =>
+ validTagIds.includes(tagId)
+ );
+ const existingSelectedTagIds = this.selectedTags.map((t) => this._tagId(t));
+
+ const selectedTags = filteredTagIds.map((tagId) =>
+ this.formattedChoices.find((choice) => choice.id === tagId)
);
set(
this.composer.model,
"tags",
uniqueItemsFromArray([
- ...this.tags.filter((tag) => !this.selectedTags.includes(tag)),
+ ...this.tags.filter(
+ (tag) => !existingSelectedTagIds.includes(this._tagId(tag))
+ ),
...selectedTags,
])
);
}
@action
- isSelected(option) {
- option = option.toLowerCase().replace(/\s+/g, "-");
- return this.filteredSelectedValues.includes(option);
+ isSelected(tagId) {
+ return this.filteredSelectedValues.some(
+ (tag) => this._tagId(tag) === tagId
+ );
}
<template>
@@ -165,8 +167,8 @@ export default class TagChooserField extends Component {
{{/if}}
{{#each this.formattedChoices as |choice|}}
<option
- value={{choice.display}}
- selected={{this.isSelected choice.name}}
+ value={{choice.id}}
+ selected={{this.isSelected choice.id}}
>{{choice.display}}</option>
{{/each}}
</select>
diff --git a/frontend/discourse/app/components/modal/bulk-topic-actions.gjs b/frontend/discourse/app/components/modal/bulk-topic-actions.gjs
index cb3a6c18e4f..d99e18dac95 100644
--- a/frontend/discourse/app/components/modal/bulk-topic-actions.gjs
+++ b/frontend/discourse/app/components/modal/bulk-topic-actions.gjs
@@ -191,10 +191,16 @@ export default class BulkTopicActions extends Component {
);
break;
case "append-tags":
- this.performAndRefresh({ type: "append_tags", tags: this.tags });
+ this.performAndRefresh({
+ type: "append_tags",
+ tag_ids: this.tags?.map((t) => t.id),
+ });
break;
case "replace-tags":
- this.performAndRefresh({ type: "change_tags", tags: this.tags });
+ this.performAndRefresh({
+ type: "change_tags",
+ tag_ids: this.tags?.map((t) => t.id),
+ });
break;
case "remove-tags":
this.performAndRefresh({ type: "remove_tags" });
diff --git a/frontend/discourse/app/components/modal/move-to-topic.gjs b/frontend/discourse/app/components/modal/move-to-topic.gjs
index 3d3acf3b1d2..d7cf3e6b46b 100644
--- a/frontend/discourse/app/components/modal/move-to-topic.gjs
+++ b/frontend/discourse/app/components/modal/move-to-topic.gjs
@@ -148,14 +148,14 @@ export default class MoveToTopic extends Component {
title: this.topicName,
post_ids: this.args.model.selectedPostIds,
category_id: this.categoryId,
- tags: this.tags,
+ tag_ids: this.tags?.map((t) => t.id),
};
} else {
mergeOptions = {};
moveOptions = {
title: this.topicName,
post_ids: this.args.model.selectedPostIds,
- tags: this.tags,
+ tag_ids: this.tags?.map((t) => t.id),
archetype: "private_message",
};
}
diff --git a/frontend/discourse/app/components/search-advanced-options.gjs b/frontend/discourse/app/components/search-advanced-options.gjs
index 8d36cd62fb6..89bbf1c1fa3 100644
--- a/frontend/discourse/app/components/search-advanced-options.gjs
+++ b/frontend/discourse/app/components/search-advanced-options.gjs
@@ -447,7 +447,8 @@ export default class SearchAdvancedOptions extends Component {
@action
onChangeSearchTermForTags(tags) {
- this.set("searchedTerms.tags", tags.length ? tags : null);
+ const tagNames = tags.map((t) => (typeof t === "object" ? t.name : t));
+ this.set("searchedTerms.tags", tagNames.length ? tagNames : null);
this._updateSearchTermForTags();
}
diff --git a/frontend/discourse/app/components/tag-groups-form.gjs b/frontend/discourse/app/components/tag-groups-form.gjs
index bdca262c39e..610e28fc2eb 100644
--- a/frontend/discourse/app/components/tag-groups-form.gjs
+++ b/frontend/discourse/app/components/tag-groups-form.gjs
@@ -72,8 +72,8 @@ export default class TagGroupsForm extends Component {
save() {
const attrs = this.buffered.getProperties(
"name",
- "tag_names",
- "parent_tag_name",
+ "tags",
+ "parent_tag",
"one_per_topic",
"permissions"
);
@@ -83,7 +83,7 @@ export default class TagGroupsForm extends Component {
return false;
}
- if (isEmpty(attrs.tag_names)) {
+ if (isEmpty(attrs.tags)) {
this.dialog.alert("tagging.groups.cannot_save.no_tags");
return false;
}
@@ -125,7 +125,7 @@ export default class TagGroupsForm extends Component {
<section class="group-tags-list">
<label>{{i18n "tagging.groups.tags_label"}}</label><br />
<TagChooser
- @tags={{this.buffered.tag_names}}
+ @tags={{this.buffered.tags}}
@everyTag={{true}}
@unlimitedTagCount={{true}}
@excludeSynonyms={{true}}
@@ -140,7 +140,7 @@ export default class TagGroupsForm extends Component {
<label>{{i18n "tagging.groups.parent_tag_label"}}</label>
<div>
<TagChooser
- @tags={{this.buffered.parent_tag_name}}
+ @tags={{this.buffered.parent_tag}}
@everyTag={{true}}
@excludeSynonyms={{true}}
@options={{hash
diff --git a/frontend/discourse/app/components/tag-info.gjs b/frontend/discourse/app/components/tag-info.gjs
index bd9f28d3e2e..9fb86fb5420 100644
--- a/frontend/discourse/app/components/tag-info.gjs
+++ b/frontend/discourse/app/components/tag-info.gjs
@@ -166,12 +166,15 @@ export default class TagInfo extends Component {
})
.then((result) => {
this.set("editing", false);
- this.tagInfo.set("description", this.newTagDescription);
-
if (result.responseJson.tag) {
- const newTagName = result.responseJson.tag.name;
- if (oldTagName !== newTagName) {
- this.router.transitionTo("tag.show", newTagName);
+ const updatedTag = result.responseJson.tag;
+ this.tagInfo.setProperties({
+ name: updatedTag.name,
+ slug: updatedTag.slug,
+ description: this.newTagDescription,
+ });
+ if (oldTagName !== updatedTag.name) {
+ this.router.transitionTo("tag.show", updatedTag.name);
}
}
})
@@ -222,7 +225,11 @@ export default class TagInfo extends Component {
return ajax(`/tag/${this.tagInfo.name}/synonyms`, {
type: "POST",
data: {
- synonyms: this.newSynonyms,
+ tags: this.newSynonyms.map((t) =>
+ typeof t.id === "number"
+ ? { id: t.id, name: t.name }
+ : { name: t.name }
+ ),
},
})
.then((response) => {
diff --git a/frontend/discourse/app/components/topic-list/item.gjs b/frontend/discourse/app/components/topic-list/item.gjs
index e3515884a4b..ba9865e1b18 100644
--- a/frontend/discourse/app/components/topic-list/item.gjs
+++ b/frontend/discourse/app/components/topic-list/item.gjs
@@ -61,7 +61,10 @@ export default class Item extends Component {
}
get tagClassNames() {
- return this.args.topic.tags?.map((tagName) => `tag-${tagName}`);
+ return this.args.topic.tags?.map((tag) => {
+ const tagName = typeof tag === "string" ? tag : tag.name;
+ return `tag-${tagName}`;
+ });
}
get expandPinned() {
diff --git a/frontend/discourse/app/components/topic-list/latest-topic-list-item.gjs b/frontend/discourse/app/components/topic-list/latest-topic-list-item.gjs
index c158fe9865b..501524836da 100644
--- a/frontend/discourse/app/components/topic-list/latest-topic-list-item.gjs
+++ b/frontend/discourse/app/components/topic-list/latest-topic-list-item.gjs
@@ -18,7 +18,10 @@ import { applyValueTransformer } from "discourse/lib/transformer";
export default class LatestTopicListItem extends Component {
get tagClassNames() {
- return this.args.topic.tags?.map((tagName) => `tag-${tagName}`);
+ return this.args.topic.tags?.map((tag) => {
+ const tagName = typeof tag === "string" ? tag : tag.name;
+ return `tag-${tagName}`;
+ });
}
get additionalClasses() {
diff --git a/frontend/discourse/app/lib/render-tag.js b/frontend/discourse/app/lib/render-tag.js
index 9d6c1b9f763..5bdb47b074a 100644
--- a/frontend/discourse/app/lib/render-tag.js
+++ b/frontend/discourse/app/lib/render-tag.js
@@ -15,19 +15,22 @@ export function defaultRenderTag(tag, params) {
let siteSettings = helperContext().siteSettings;
params = params || {};
- const visibleName = escapeExpression(tag);
- tag = visibleName.toLowerCase();
+ const tagName = typeof tag === "string" ? tag : tag.name;
+ const visibleName = escapeExpression(tagName);
+ const tagNameLower = visibleName.toLowerCase();
+
const classes = ["discourse-tag"];
- const tagName = params.tagName || "a";
+ const htmlTag = params.tagName || "a";
+
let path;
- if (tagName === "a" && !params.noHref) {
+ if (htmlTag === "a" && !params.noHref) {
if ((params.isPrivateMessage || params.pmOnly) && User.current()) {
const username = params.tagsForUser
? params.tagsForUser
: User.current().username;
- path = `/u/${username}/messages/tags/${tag}`;
+ path = `/u/${username}/messages/tags/${tagNameLower}`;
} else {
- path = `/tag/${tag}`;
+ path = `/tag/${tagNameLower}`;
}
}
const href = path ? ` href='${getURL(path)}' ` : "";
@@ -48,17 +51,17 @@ export function defaultRenderTag(tag, params) {
let val =
"<" +
- tagName +
+ htmlTag +
href +
" data-tag-name=" +
- tag +
+ tagNameLower +
(params.description ? ' title="' + escape(hoverDescription) + '" ' : "") +
" class='" +
classes.join(" ") +
"'>" +
(params.displayName ? escape(params.displayName) : visibleName) +
"</" +
- tagName +
+ htmlTag +
">";
if (params.count) {
diff --git a/frontend/discourse/app/lib/render-tags.js b/frontend/discourse/app/lib/render-tags.js
index 5217dbf8448..cdb3ae627eb 100644
--- a/frontend/discourse/app/lib/render-tags.js
+++ b/frontend/discourse/app/lib/render-tags.js
@@ -84,14 +84,15 @@ export default function (topic, params) {
if (tags && tags.length > 0) {
for (let i = 0; i < tags.length; i++) {
const tag = tags[i];
+ const tagStr = typeof tag === "string" ? tag : tag.name;
const tagParams = params ? { ...params } : {};
- if (params?.tagClasses && params?.tagClasses[tag]) {
- tagParams.extraClass = params.tagClasses[tag];
+ if (params?.tagClasses && params?.tagClasses[tagStr]) {
+ tagParams.extraClass = params.tagClasses[tagStr];
}
buffer += renderTag(tag, {
- description: topic?.tags_descriptions?.[tag],
+ description: topic?.tags_descriptions?.[tagStr],
isPrivateMessage,
tagsForUser,
tagName,
diff --git a/frontend/discourse/app/lib/sidebar/user/tags-section/tag-section-link.js b/frontend/discourse/app/lib/sidebar/user/tags-section/tag-section-link.js
index 71fdac45764..1621478449d 100644
--- a/frontend/discourse/app/lib/sidebar/user/tags-section/tag-section-link.js
+++ b/frontend/discourse/app/lib/sidebar/user/tags-section/tag-section-link.js
@@ -16,12 +16,12 @@ export default class TagSectionLink extends BaseTagSectionLink {
@bind
refreshCounts() {
this.totalUnread = this.topicTrackingState.countUnread({
- tagId: this.tagName,
+ tagId: this.tag.id,
});
if (this.totalUnread === 0 || this.#newNewViewEnabled) {
this.totalNew = this.topicTrackingState.countNew({
- tagId: this.tagName,
+ tagId: this.tag.id,
});
}
}
diff --git a/frontend/discourse/app/lib/topic-list-tracked-filter.js b/frontend/discourse/app/lib/topic-list-tracked-filter.js
index 7e973a9c231..f7c0d14fb4a 100644
--- a/frontend/discourse/app/lib/topic-list-tracked-filter.js
+++ b/frontend/discourse/app/lib/topic-list-tracked-filter.js
@@ -50,10 +50,10 @@ export function isTrackedTopic(topic) {
}
if (topic.tags) {
- const tags = User.current().trackedTags;
+ const tagIds = User.current().trackedTags;
- for (const tag of tags) {
- if (topic.tags.includes(tag)) {
+ for (const tagId of tagIds) {
+ if (topic.tags.some((t) => t.id === tagId)) {
return true;
}
}
diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.js
index 021d4382c45..8e3bb9c6a88 100644
--- a/frontend/discourse/app/models/category.js
+++ b/frontend/discourse/app/models/category.js
@@ -483,6 +483,7 @@ export default class Category extends RestModel {
@tracked localizations = this.category_localizations;
@tracked minimum_required_tags;
@tracked styleType = this.style_type;
+ @tracked allowed_tags;
@trackedArray available_groups;
@trackedArray permissions;
@trackedArray required_tag_groups;
@@ -798,7 +799,9 @@ export default class Category extends RestModel {
all_topics_wiki: this.all_topics_wiki,
allow_unlimited_owner_edits_on_first_post:
this.allow_unlimited_owner_edits_on_first_post,
- allowed_tags: this.allowed_tags,
+ allowed_tags: this.allowed_tags?.map((t) =>
+ typeof t === "object" ? t.name : t
+ ),
allowed_tag_groups: this.allowed_tag_groups,
allow_global_tags: this.allow_global_tags,
required_tag_groups: this.required_tag_groups,
diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.js
index dae7b22702f..2805ac51bd4 100644
--- a/frontend/discourse/app/models/composer.js
+++ b/frontend/discourse/app/models/composer.js
@@ -1154,8 +1154,14 @@ export default class Composer extends RestModel {
serialize(serializer, dest) {
dest = dest || {};
Object.keys(serializer).forEach((f) => {
- const val = this.get(serializer[f]);
+ let val = this.get(serializer[f]);
if (typeof val !== "undefined") {
+ if (f === "tags" && Array.isArray(val)) {
+ // extract tag names from objects for backend compatibility
+ if (val.some((t) => typeof t === "object" && t !== null)) {
+ val = val.map((t) => (typeof t === "object" ? t.name : t));
+ }
+ }
set(dest, f, val);
}
});
diff --git a/frontend/discourse/app/models/nav-item.js b/frontend/discourse/app/models/nav-item.js
index 3d153d1dcd5..a976cc63d0c 100644
--- a/frontend/discourse/app/models/nav-item.js
+++ b/frontend/discourse/app/models/nav-item.js
@@ -33,7 +33,8 @@ export default class NavItem extends EmberObject {
return path;
}
- if (context.tagId && Site.currentProp("filters").includes(filterType)) {
+ const tagName = context.tag?.name;
+ if (tagName && Site.currentProp("filters").includes(filterType)) {
includesTagContext = true;
if (context.category) {
@@ -53,7 +54,7 @@ export default class NavItem extends EmberObject {
}
if (includesTagContext) {
- path += `/${context.tagId}`;
+ path += `/${tagName}`;
}
if (includesTagContext || includesCategoryContext) {
@@ -93,8 +94,8 @@ export default class NavItem extends EmberObject {
if (opts.category) {
args.category = opts.category;
}
- if (opts.tagId) {
- args.tagId = opts.tagId;
+ if (opts.tag) {
+ args.tag = opts.tag;
}
if (opts.currentRouteQueryParams) {
args.currentRouteQueryParams = opts.currentRouteQueryParams;
@@ -158,6 +159,7 @@ export default class NavItem extends EmberObject {
const context = {
category: args.category,
+ tag: args.tag,
tagId: args.tagId,
noSubcategories: args.noSubcategories,
};
@@ -221,6 +223,7 @@ export default class NavItem extends EmberObject {
@service currentUser;
@tracked name;
+ @tracked tag;
@reads("name") filterType;
@tracked _title;
@@ -255,7 +258,7 @@ export default class NavItem extends EmberObject {
if (
this.name === "latest" &&
- (Site.currentProp("desktopView") || this.tagId !== undefined)
+ (Site.currentProp("desktopView") || this.tag !== undefined)
) {
count = 0;
}
@@ -272,8 +275,8 @@ export default class NavItem extends EmberObject {
this._displayName = value;
}
- @discourseComputed("filterType", "category", "noSubcategories", "tagId")
- href(filterType, category, noSubcategories, tagId) {
+ @discourseComputed("filterType", "category", "noSubcategories", "tag")
+ href(filterType, category, noSubcategories, tag) {
let customHref = null;
NavItem.customNavItemHrefs.forEach(function (cb) {
@@ -287,7 +290,7 @@ export default class NavItem extends EmberObject {
return getURL(customHref);
}
- const context = { category, noSubcategories, tagId };
+ const context = { category, noSubcategories, tag };
return NavItem.pathFor(filterType, context);
}
@@ -308,16 +311,16 @@ export default class NavItem extends EmberObject {
@discourseComputed(
"name",
"category",
- "tagId",
+ "tag",
"noSubcategories",
"currentRouteQueryParams",
"topicTrackingState.messageCount"
)
- count(name, category, tagId, noSubcategories, currentRouteQueryParams) {
+ count(name, category, tag, noSubcategories, currentRouteQueryParams) {
return this.topicTrackingState?.lookupCount({
type: name,
category,
- tagId,
+ tagId: tag?.id,
noSubcategories,
customFilterFn: hasTrackedFilter(currentRouteQueryParams)
? isTrackedTopic
diff --git a/frontend/discourse/app/models/topic-tracking-state.js b/frontend/discourse/app/models/topic-tracking-state.js
index a47b8de4314..e6c3afee402 100644
--- a/frontend/discourse/app/models/topic-tracking-state.js
+++ b/frontend/discourse/app/models/topic-tracking-state.js
@@ -37,15 +37,15 @@ function isUnseen(topic) {
return !topic.is_seen;
}
-function hasMutedTags(topicTags, mutedTags, siteSettings) {
- if (!mutedTags || !topicTags) {
+function hasMutedTags(topicTagIds, mutedTagIds, siteSettings) {
+ if (!mutedTagIds || !topicTagIds) {
return false;
}
return (
(siteSettings.remove_muted_tags_from_latest === "always" &&
- topicTags.some((topicTag) => mutedTags.includes(topicTag))) ||
+ topicTagIds.some((tagId) => mutedTagIds.includes(tagId))) ||
(siteSettings.remove_muted_tags_from_latest === "only_muted" &&
- topicTags.every((topicTag) => mutedTags.includes(topicTag)))
+ topicTagIds.every((tagId) => mutedTagIds.includes(tagId)))
);
}
@@ -58,7 +58,8 @@ export default class TopicTrackingState extends EmberObject {
@tracked incomingCount = 0;
@tracked newIncoming;
@tracked filterCategory;
- @tracked filterTag;
+ @tracked filterTagName;
+ @tracked filterTagId;
@tracked filter;
states = new TrackedMap();
stateChangeCallbacks = {};
@@ -263,7 +264,6 @@ export default class TopicTrackingState extends EmberObject {
const filter = this.filter;
const filterCategory = this.filterCategory;
- const filterTag = this.filterTag;
const categoryId = data.payload && data.payload.category_id;
// if we have a filter category currently and it is not the
@@ -279,7 +279,10 @@ export default class TopicTrackingState extends EmberObject {
}
}
- if (filterTag && !data.payload.tags?.includes(filterTag)) {
+ if (
+ this.filterTagId &&
+ !data.payload.tags?.some((t) => t.id === this.filterTagId)
+ ) {
return;
}
@@ -367,11 +370,13 @@ export default class TopicTrackingState extends EmberObject {
* filters e.g. latest, unread, new. As well as this
* specific category and tag URLs like tag/test/l/latest,
* c/cat/sub-cat/6/l/latest or tags/c/cat/sub-cat/6/test/l/latest.
+ * @param {Object} opts
+ * @param {Number} opts.tagId - The ID of the tag to filter by.
*/
- trackIncoming(filter) {
+ trackIncoming(filter, { tagId } = {}) {
this.newIncoming = new TrackedArray();
- let category, tag;
+ let category, tagName;
if (filter.startsWith("c/") || filter.startsWith("tags/c/")) {
const categoryId = filter.match(/\/(\d*)\//);
@@ -379,7 +384,7 @@ export default class TopicTrackingState extends EmberObject {
const split = filter.split("/");
if (filter.startsWith("tags/c/")) {
- tag = split[split.indexOf(categoryId[1]) + 1];
+ tagName = split[split.indexOf(categoryId[1]) + 1];
}
if (split.length >= 4) {
@@ -388,11 +393,12 @@ export default class TopicTrackingState extends EmberObject {
} else if (filter.startsWith("tag/")) {
const split = filter.split("/");
filter = split[split.length - 1];
- tag = split[1];
+ tagName = split[1];
}
this.filterCategory = category;
- this.filterTag = tag;
+ this.filterTagName = tagName;
+ this.filterTagId = tagId;
this.filter = filter;
this.incomingCount = 0;
}
@@ -604,7 +610,7 @@ export default class TopicTrackingState extends EmberObject {
return false;
}
- if (tagId && !topic.tags?.includes(tagId)) {
+ if (tagId && !topic.tags?.some((t) => t.id === tagId)) {
return false;
}
@@ -677,7 +683,7 @@ export default class TopicTrackingState extends EmberObject {
if (
topic.category_id === category_id &&
!topic.deleted &&
- (!tagId || topic.tags?.includes(tagId))
+ (!tagId || topic.tags?.some((t) => t.id === tagId))
) {
sum +=
topic.last_read_post_number === null ||
@@ -955,7 +961,7 @@ export default class TopicTrackingState extends EmberObject {
if (["new_topic", "latest"].includes(data.message_type)) {
if (
hasMutedTags(
- data.payload.tags,
+ data.payload.tags?.map((t) => t.id),
this.currentUser?.muted_tags,
this.siteSettings
)
@@ -968,11 +974,6 @@ export default class TopicTrackingState extends EmberObject {
if (data.message_type === "latest") {
this.notifyIncoming(data);
-
- if (old.tags !== data.payload.tags) {
- this.modifyStateProp(data, "tags", data.payload.tags);
- this.messageCount++;
- }
}
if (data.message_type === "dismiss_new") {
diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.js
index b65a296468b..b91818aaddc 100644
--- a/frontend/discourse/app/models/topic.js
+++ b/frontend/discourse/app/models/topic.js
@@ -94,6 +94,12 @@ export default class Topic extends RestModel {
}
const data = { ...props };
+
+ // SHOULD NOT normalize tags to names - backend expects string array
+ if (Array.isArray(data.tags)) {
+ data.tags = data.tags.map((t) => (typeof t === "string" ? t : t.name));
+ }
+
if (opts.fastEdit) {
data.keep_existing_draft = true;
}
@@ -452,7 +458,8 @@ export default class Topic extends RestModel {
const newTags = [];
tags.forEach(function (tag) {
- if (!title.includes(tag.toLowerCase())) {
+ const tagName = typeof tag === "string" ? tag : tag.name;
+ if (!title.includes(tagName.toLowerCase())) {
newTags.push(tag);
}
});
@@ -952,13 +959,17 @@ export default class Topic extends RestModel {
}
updateTags(tags) {
- if (!tags || tags.length === 0) {
- tags = [""];
+ // send tag_ids when values are objects
+ if (tags?.every((t) => typeof t === "object")) {
+ return ajax(`/t/${this.id}/tags`, {
+ type: "PUT",
+ data: { tag_ids: tags.map((t) => t.id) },
+ });
}
return ajax(`/t/${this.id}/tags`, {
type: "PUT",
- data: { tags },
+ data: { tags: tags || [] },
});
}
}
diff --git a/frontend/discourse/app/models/user.js b/frontend/discourse/app/models/user.js
index 8051c7324e1..511d6933082 100644
--- a/frontend/discourse/app/models/user.js
+++ b/frontend/discourse/app/models/user.js
@@ -572,7 +572,13 @@ export default class User extends RestModel.extend(Evented) {
"watching_first_post_tags",
].forEach((prop) => {
if (fields === undefined || fields.includes(prop)) {
- data[prop] = this.get(prop) ? this.get(prop).join(",") : "";
+ const tags = this.get(prop);
+ if (tags) {
+ const names = tags.map((t) => (typeof t === "object" ? t.name : t));
+ data[prop] = names.join(",");
+ } else {
+ data[prop] = "";
+ }
}
});
diff --git a/frontend/discourse/app/routes/build-topic-route.js b/frontend/discourse/app/routes/build-topic-route.js
index 9a8631b3d82..dee61475790 100644
--- a/frontend/discourse/app/routes/build-topic-route.js
+++ b/frontend/discourse/app/routes/build-topic-route.js
@@ -66,7 +66,8 @@ export async function findTopicList(
if (tracking) {
tracking.sync(list, list.filter, filterParams);
- tracking.trackIncoming(list.filter);
+ const tagId = list.topic_list?.tags?.[0]?.id;
+ tracking.trackIncoming(list.filter, { tagId });
}
Session.currentProp("topicList", list);
diff --git a/frontend/discourse/select-kit/components/mini-tag-chooser.js b/frontend/discourse/select-kit/components/mini-tag-chooser.js
index 205db29da62..60ba6db8f55 100644
--- a/frontend/discourse/select-kit/components/mini-tag-chooser.js
+++ b/frontend/discourse/select-kit/components/mini-tag-chooser.js
@@ -1,4 +1,4 @@
-import { computed } from "@ember/object";
+import { action, computed } from "@ember/object";
import { empty, or } from "@ember/object/computed";
import { service } from "@ember/service";
import {
@@ -34,14 +34,14 @@ import TagRow from "./tag-row";
maximum: "maxTagsPerTopic",
autoInsertNoneItem: false,
useHeaderFilter: false,
- valueProperty: "name",
+ valueProperty: "id",
nameProperty: "name",
})
@pluginApiIdentifiers(["mini-tag-chooser"])
export default class MiniTagChooser extends MultiSelectComponent {
@service tagUtils;
- valueProperty = "name";
+ valueProperty = "id";
nameProperty = "name";
@empty("value") noTags;
@@ -50,6 +50,11 @@ export default class MiniTagChooser extends MultiSelectComponent {
@setting("max_tag_search_results") maxTagSearchResults;
@setting("max_tags_per_topic") maxTagsPerTopic;
+ @computed("value.[]")
+ get tags() {
+ return makeArray(this.value);
+ }
+
modifyComponentForRow(collection, item) {
if (this.getValue(item) === this.selectKit.filter && !item.count) {
return SelectKitRow;
@@ -79,18 +84,40 @@ export default class MiniTagChooser extends MultiSelectComponent {
: "plus";
}
- @computed("value.[]")
+ @computed("tags.[]")
get content() {
- let values = makeArray(this.value);
+ let tags = this.tags;
if (this.selectKit.options.hiddenValues) {
- values = values.filter(
- (val) => !this.selectKit.options.hiddenValues.includes(val)
- );
+ tags = tags.filter((t) => {
+ const id = typeof t === "object" ? t.id : t;
+ return !this.selectKit.options.hiddenValues.some((h) => {
+ const hiddenId = typeof h === "object" ? h.id : h;
+ return hiddenId === id;
+ });
+ });
+ }
+ return tags.map((t) => {
+ if (typeof t === "object" && t !== null) {
+ return this.defaultItem(t.id, t.name);
+ }
+ return this.defaultItem(t, t);
+ });
+ }
+
+ @action
+ _onChange(value, items) {
+ if (this.onChange) {
+ this.onChange(items);
+ } else {
+ this.set("value", items);
}
- return values.map((x) => this.defaultItem(x, x));
}
validateCreate(filter, content) {
+ const selectedTagNames = (this.selectedContent || []).map((t) =>
+ typeof t === "string" ? t : t.name
+ );
+
return this.tagUtils.validateCreate(
filter,
content,
@@ -98,7 +125,7 @@ export default class MiniTagChooser extends MultiSelectComponent {
(e) => this.addError(e),
this.termMatchesForbidden,
(value) => this.getValue(value),
- this.value
+ selectedTagNames
);
}
@@ -120,8 +147,11 @@ export default class MiniTagChooser extends MultiSelectComponent {
categoryId: this.selectKit.options.categoryId,
};
- if (this.value) {
- data.selected_tags = this.value.slice(0, 100);
+ if (this.value?.length) {
+ const ids = this.value.map((v) => v.id);
+ if (ids.length) {
+ data.selected_tag_ids = ids.slice(0, 100);
+ }
}
if (!this.selectKit.options.everyTag) {
@@ -149,7 +179,7 @@ export default class MiniTagChooser extends MultiSelectComponent {
});
if (this.siteSettings.tags_sort_alphabetically) {
- results = results.sort((a, b) => a.text.localeCompare(b.text));
+ results = results.sort((a, b) => a.name.localeCompare(b.name));
}
if (json.required_tag_group) {
@@ -164,6 +194,9 @@ export default class MiniTagChooser extends MultiSelectComponent {
this.set("selectKit.options.translatedFilterPlaceholder", null);
}
- return results.filter((r) => !makeArray(this.tags).includes(r.name));
+ const selectedNames = this.tags.map((t) =>
+ typeof t === "string" ? t : t.name
+ );
+ return results.filter((r) => !selectedNames.includes(r.name));
}
}
diff --git a/frontend/discourse/select-kit/components/multi-select.gjs b/frontend/discourse/select-kit/components/multi-select.gjs
index ae681235528..1d23da2cecd 100644
--- a/frontend/discourse/select-kit/components/multi-select.gjs
+++ b/frontend/discourse/select-kit/components/multi-select.gjs
@@ -149,8 +149,10 @@ export default class MultiSelect extends SelectKitComponent {
value.forEach((v) => {
if (this.selectKit.valueProperty) {
+ // extract ID from object values for comparison
+ const vId = this.getValue(v);
const c = makeArray(this.content).find(
- (item) => item[this.selectKit.valueProperty] === v
+ (item) => item[this.selectKit.valueProperty] === vId
);
if (c) {
content.push(c);
diff --git a/frontend/discourse/select-kit/components/select-kit.js b/frontend/discourse/select-kit/components/select-kit.js
index a8338b3dd23..ed36d68fb4c 100644
--- a/frontend/discourse/select-kit/components/select-kit.js
+++ b/frontend/discourse/select-kit/components/select-kit.js
@@ -684,7 +684,7 @@ export default class SelectKit extends Component {
}
deselectByValue(value) {
- if (!value) {
+ if (isNone(value)) {
return;
}
@@ -895,7 +895,10 @@ export default class SelectKit extends Component {
_deselectLast() {
if (this.selectKit.hasSelection) {
- this.deselectByValue(this.value[this.value.length - 1]);
+ const lastItem = this.value[this.value.length - 1];
+ // handle both raw values and objects with valueProperty
+ const value = this.getValue(lastItem) ?? lastItem;
+ this.deselectByValue(value);
}
}
diff --git a/frontend/discourse/select-kit/components/select-kit/select-kit-header.js b/frontend/discourse/select-kit/components/select-kit/select-kit-header.js
index 5cbf8ba7384..cd67b052c87 100644
--- a/frontend/discourse/select-kit/components/select-kit/select-kit-header.js
+++ b/frontend/discourse/select-kit/components/select-kit/select-kit-header.js
@@ -28,9 +28,12 @@ export default class SelectKitHeader extends Component {
@computed("value")
get selectedValue() {
- return this.value === this.getValue(this.selectKit.noneItem)
- ? null
- : makeArray(this.value).join(",");
+ if (this.value === this.getValue(this.selectKit.noneItem)) {
+ return null;
+ }
+ return makeArray(this.value)
+ .map((v) => this.getValue(v))
+ .join(",");
}
@computed("selectedContent.[]")
diff --git a/frontend/discourse/select-kit/components/tag-chooser-row.gjs b/frontend/discourse/select-kit/components/tag-chooser-row.gjs
index 3941fe488bf..79948eec691 100644
--- a/frontend/discourse/select-kit/components/tag-chooser-row.gjs
+++ b/frontend/discourse/select-kit/components/tag-chooser-row.gjs
@@ -5,6 +5,6 @@ import SelectKitRowComponent from "discourse/select-kit/components/select-kit/se
@classNames("tag-chooser-row")
export default class TagChooserRow extends SelectKitRowComponent {
<template>
- {{discourseTag this.rowValue count=this.item.count noHref=true}}
+ {{discourseTag this.rowName count=this.item.count noHref=true}}
</template>
}
diff --git a/frontend/discourse/select-kit/components/tag-chooser.js b/frontend/discourse/select-kit/components/tag-chooser.js
index d01a577b8af..9249c572fab 100644
--- a/frontend/discourse/select-kit/components/tag-chooser.js
+++ b/frontend/discourse/select-kit/components/tag-chooser.js
@@ -20,13 +20,13 @@ import TagChooserRow from "./tag-chooser-row";
limit: null,
allowAny: "canCreateTag",
maximum: "maximumTagCount",
- valueProperty: "name",
+ valueProperty: "id",
})
@pluginApiIdentifiers("tag-chooser")
export default class TagChooser extends MultiSelectComponent {
@service tagUtils;
- valueProperty = "name";
+ valueProperty = "id";
nameProperty = "name";
blockedTags = null;
@@ -72,26 +72,47 @@ export default class TagChooser extends MultiSelectComponent {
@computed("tags.[]")
get value() {
- return uniqueItemsFromArray(makeArray(this.tags));
+ return uniqueItemsFromArray(
+ makeArray(this.tags).map((t) => {
+ if (typeof t === "string" || typeof t === "number") {
+ return t;
+ }
+ return t.id;
+ })
+ );
}
@computed("tags.[]")
get content() {
- return uniqueItemsFromArray(makeArray(this.tags)).map((t) =>
- this.defaultItem(t, t)
+ return uniqueItemsFromArray(
+ makeArray(this.tags).map((t) => {
+ if (typeof t === "string") {
+ return this.defaultItem(t, t);
+ }
+ if (typeof t === "number") {
+ // numeric ID - use as both id and name until we can look up the actual name
+ return this.defaultItem(t, t);
+ }
+ return this.defaultItem(t.id, t.name);
+ })
);
}
@action
_onChange(value, items) {
if (this.onChange) {
- this.onChange(value, items);
+ this.onChange(items);
} else {
- this.set("tags", value);
+ this.set("tags", items);
}
}
validateCreate(filter, content) {
+ // Get tag names for validation (not IDs)
+ const selectedTagNames = makeArray(this.tags)
+ .filter(Boolean)
+ .map((t) => (typeof t === "string" ? t : t.name));
+
return this.tagUtils.validateCreate(
filter,
content,
@@ -99,7 +120,7 @@ export default class TagChooser extends MultiSelectComponent {
(e) => this.addError(e),
this.termMatchesForbidden,
(value) => this.getValue(value),
- this.value
+ selectedTagNames
);
}
@@ -117,9 +138,22 @@ export default class TagChooser extends MultiSelectComponent {
};
if (selectedTags.length || this.blockedTags.length) {
- data.selected_tags = uniqueItemsFromArray(
+ const allTags = uniqueItemsFromArray(
selectedTags.concat(this.blockedTags)
).slice(0, 100);
+
+ // Extract IDs for objects, keep strings for legacy/blocked tags
+ const ids = allTags
+ .map((t) => (typeof t === "string" ? null : t.id))
+ .filter((id) => id !== null);
+ const names = allTags.filter((t) => typeof t === "string");
+
+ if (ids.length) {
+ data.selected_tag_ids = ids;
+ }
+ if (names.length) {
+ data.selected_tags = names;
+ }
}
if (!this.everyTag) {
@@ -153,8 +187,12 @@ export default class TagChooser extends MultiSelectComponent {
});
if (this.blockedTags) {
+ // extract names from blockedTags (may be strings or objects)
+ const blockedNames = this.blockedTags.map((t) =>
+ typeof t === "string" ? t : t.name
+ );
results = results.filter((result) => {
- return !this.blockedTags.includes(result.name);
+ return !blockedNames.includes(result.name);
});
}
diff --git a/frontend/discourse/select-kit/components/tag-drop.js b/frontend/discourse/select-kit/components/tag-drop.js
index 4a9ab29ce09..139fcf1503f 100644
--- a/frontend/discourse/select-kit/components/tag-drop.js
+++ b/frontend/discourse/select-kit/components/tag-drop.js
@@ -143,7 +143,9 @@ export default class TagDrop extends ComboBoxComponent {
get content() {
const topTags = this.topTags.slice(0, this.maxTagsInFilterList);
if (this.sortTagsAlphabetically && topTags) {
- return this.shortcuts.concat(topTags.sort());
+ return this.shortcuts.concat(
+ topTags.sort((a, b) => a.name.localeCompare(b.name))
+ );
} else {
return this.shortcuts.concat(makeArray(topTags));
}
diff --git a/frontend/discourse/select-kit/components/tags-intersection-chooser.js b/frontend/discourse/select-kit/components/tags-intersection-chooser.js
index b8e4aca37ab..874dfcd6aa0 100644
--- a/frontend/discourse/select-kit/components/tags-intersection-chooser.js
+++ b/frontend/discourse/select-kit/components/tags-intersection-chooser.js
@@ -23,21 +23,24 @@ export default class TagsIntersectionChooser extends MiniTagChooser {
@action
onChange(tags) {
- if (tags.includes(this.mainTag)) {
- const remainingTags = tags.filter((t) => t !== this.mainTag);
+ const mainTagName = this.mainTag?.name ?? this.mainTag;
+ const tagNames = tags.map((t) => t.name ?? t);
+
+ if (mainTagName && tagNames.includes(mainTagName)) {
+ const remainingTags = tagNames.filter((t) => t !== mainTagName);
if (remainingTags.length >= 1) {
DiscourseURL.routeTo(
- `/tags/intersection/${this.mainTag}/${remainingTags.join("/")}`
+ `/tags/intersection/${mainTagName}/${remainingTags.join("/")}`
);
} else {
- DiscourseURL.routeTo(`/tag/${this.mainTag}`);
+ DiscourseURL.routeTo(`/tag/${mainTagName}`);
}
} else {
- if (tags.length >= 2) {
- DiscourseURL.routeTo(`/tags/intersection/${tags.join("/")}`);
- } else if (tags.length === 1) {
- DiscourseURL.routeTo(`/tag/${tags[0]}`);
+ if (tagNames.length >= 2) {
+ DiscourseURL.routeTo(`/tags/intersection/${tagNames.join("/")}`);
+ } else if (tagNames.length === 1) {
+ DiscourseURL.routeTo(`/tag/${tagNames[0]}`);
} else {
DiscourseURL.routeTo("/tags");
}
diff --git a/frontend/discourse/select-kit/components/topic-notifications-button.gjs b/frontend/discourse/select-kit/components/topic-notifications-button.gjs
index 8c118d73a1f..2c80522ad93 100644
--- a/frontend/discourse/select-kit/components/topic-notifications-button.gjs
+++ b/frontend/discourse/select-kit/components/topic-notifications-button.gjs
@@ -83,7 +83,10 @@ export default class TopicNotificationsButton extends Component {
} else if (!isEmpty(this.args.topic.tags)) {
if (level === 3 && reason === 10) {
// 3_10 watching tag
- return !this.args.topic.tags.some((tag) => watchedTags.includes(tag));
+ return !this.args.topic.tags.some((tag) => {
+ const tagName = typeof tag === "string" ? tag : tag.name;
+ return watchedTags.includes(tagName);
+ });
}
}
diff --git a/frontend/discourse/select-kit/lib/select-kit-prop-utils.js b/frontend/discourse/select-kit/lib/select-kit-prop-utils.js
index 2e8969dd234..2c1a402fb65 100644
--- a/frontend/discourse/select-kit/lib/select-kit-prop-utils.js
+++ b/frontend/discourse/select-kit/lib/select-kit-prop-utils.js
@@ -1,4 +1,5 @@
import { get } from "@ember/object";
+import { isNone } from "@ember/utils";
export default function selectKitPropUtils(target) {
target.prototype.defaultItem = function (value, name) {
@@ -26,12 +27,12 @@ export default function selectKitPropUtils(target) {
property,
options = { definedOnly: true }
) {
- if (!item) {
+ if (isNone(item)) {
return null;
}
- if (item && typeof property === "string") {
+ if (typeof property === "string") {
const attempt = get(item, property);
- if (attempt) {
+ if (attempt !== undefined) {
return attempt;
}
}
@@ -40,6 +41,10 @@ export default function selectKitPropUtils(target) {
return options.definedOnly ? null : item;
}
if (typeof property === "string") {
+ // primitives don't have properties, return the value directly
+ if (typeof item !== "object" || item === null) {
+ return item;
+ }
return get(item, property);
}
diff --git a/frontend/discourse/select-kit/services/tag-utils.js b/frontend/discourse/select-kit/services/tag-utils.js
index da6da806826..d132d9ff2fc 100644
--- a/frontend/discourse/select-kit/services/tag-utils.js
+++ b/frontend/discourse/select-kit/services/tag-utils.js
@@ -45,11 +45,14 @@ export default class TagUtils extends Service {
}
const toLowerCaseOrUndefined = (string) => {
- return isEmpty(string) ? undefined : string.toLowerCase();
+ if (isEmpty(string)) {
+ return undefined;
+ }
+ return typeof string === "string" ? string.toLowerCase() : undefined;
};
const inCollection = content
- .map((c) => toLowerCaseOrUndefined(getValue(c)))
+ .map((c) => toLowerCaseOrUndefined(c?.name || getValue(c)))
.filter(Boolean)
.includes(filter);
diff --git a/frontend/discourse/tests/acceptance/category-edit-test.js b/frontend/discourse/tests/acceptance/category-edit-test.js
index 11377538947..f4eb463063b 100644
--- a/frontend/discourse/tests/acceptance/category-edit-test.js
+++ b/frontend/discourse/tests/acceptance/category-edit-test.js
@@ -95,7 +95,7 @@ acceptance("Category Edit", function (needs) {
const allowedTagChooser = selectKit("#category-allowed-tags");
await allowedTagChooser.expand();
- await allowedTagChooser.selectRowByValue("monkey");
+ await allowedTagChooser.selectRowByName("monkey");
await allowedTagChooser.collapse();
const allowedTagGroupChooser = selectKit("#category-allowed-tag-groups");
@@ -113,7 +113,7 @@ acceptance("Category Edit", function (needs) {
await allowedTagGroupChooser.collapse();
await allowedTagChooser.expand();
- await allowedTagChooser.deselectItemByValue("monkey");
+ await allowedTagChooser.deselectItemByName("monkey");
await allowedTagGroupChooser.expand();
await allowedTagGroupChooser.deselectItemByValue("TagGroup1");
diff --git a/frontend/discourse/tests/acceptance/composer-actions-test.js b/frontend/discourse/tests/acceptance/composer-actions-test.js
index 264f7ce3728..9d9e31fcac8 100644
--- a/frontend/discourse/tests/acceptance/composer-actions-test.js
+++ b/frontend/discourse/tests/acceptance/composer-actions-test.js
@@ -408,13 +408,13 @@ acceptance(`Composer Actions With New Topic Draft`, function (needs) {
const tags = selectKit(".mini-tag-chooser");
await tags.expand();
- await tags.selectRowByValue("monkey");
+ await tags.selectRowByName("monkey");
const composerActions = selectKit(".composer-actions");
await composerActions.expand();
await composerActions.selectRowByValue("shared_draft");
- assert.strictEqual(tags.header().value(), "monkey", "tags are not reset");
+ assert.strictEqual(tags.header().name(), "monkey", "tags are not reset");
assert
.dom("#reply-title")
.hasValue("This is the new text for the title using 'quotes'");
diff --git a/frontend/discourse/tests/acceptance/composer-tags-test.js b/frontend/discourse/tests/acceptance/composer-tags-test.js
index 14f3e19d3d8..b5de884cc2d 100644
--- a/frontend/discourse/tests/acceptance/composer-tags-test.js
+++ b/frontend/discourse/tests/acceptance/composer-tags-test.js
@@ -106,7 +106,7 @@ acceptance("Composer - Tags", function (needs) {
const tags = selectKit(".mini-tag-chooser");
await tags.expand();
- await tags.selectRowByValue("monkey");
+ await tags.selectRowByName("monkey");
await click("#reply-control button.create");
assert.notStrictEqual(currentURL(), "/");
@@ -140,7 +140,7 @@ acceptance("Composer - Tags", function (needs) {
const tags = selectKit(".mini-tag-chooser");
await tags.expand();
- await tags.selectRowByValue("monkey");
+ await tags.selectRowByName("monkey");
await click("#reply-control button.create");
assert.notStrictEqual(currentURL(), "/");
diff --git a/frontend/discourse/tests/acceptance/composer-test.js b/frontend/discourse/tests/acceptance/composer-test.js
index f0f49d73e0f..cc1f7014aab 100644
--- a/frontend/discourse/tests/acceptance/composer-test.js
+++ b/frontend/discourse/tests/acceptance/composer-test.js
@@ -1158,10 +1158,11 @@ acceptance(`Composer - Customizations`, function (needs) {
needs.site({ can_tag_topics: true });
function customComposerAction(composer) {
- return (
- (composer.tags || []).includes("monkey") &&
- composer.action === CREATE_TOPIC
+ const tags = composer.tags || [];
+ const hasMonkey = tags.some(
+ (t) => (typeof t === "string" ? t : t.name) === "monkey"
);
+ return hasMonkey && composer.action === CREATE_TOPIC;
}
needs.hooks.beforeEach(() => {
@@ -1189,7 +1190,7 @@ acceptance(`Composer - Customizations`, function (needs) {
assert.dom(".save-or-cancel button").hasText(i18n("composer.create_topic"));
const tags = selectKit(".mini-tag-chooser");
await tags.expand();
- await tags.selectRowByValue("monkey");
+ await tags.selectRowByName("monkey");
assert.dom(".action-title").hasText("custom text");
assert.dom(".save-or-cancel button").hasText(i18n("composer.emoji"));
});
diff --git a/frontend/discourse/tests/acceptance/review-test.js b/frontend/discourse/tests/acceptance/review-test.js
index aea53208d28..24cc7deb94b 100644
--- a/frontend/discourse/tests/acceptance/review-test.js
+++ b/frontend/discourse/tests/acceptance/review-test.js
@@ -180,7 +180,7 @@ acceptance("Review", function (needs) {
assert.strictEqual(requests.length, 1);
assert.strictEqual(requests[0].queryParams.categoryId, "6");
await tags.fillInFilter("monkey");
- await tags.selectRowByValue("monkey");
+ await tags.selectRowByName("monkey");
await fillIn(".editable-field.payload-raw textarea", "new raw contents");
await click(`${topic} .reviewable-action.save-edit`);
diff --git a/frontend/discourse/tests/acceptance/search-full-test.js b/frontend/discourse/tests/acceptance/search-full-test.js
index f13f0284f12..a025c4ef5ac 100644
--- a/frontend/discourse/tests/acceptance/search-full-test.js
+++ b/frontend/discourse/tests/acceptance/search-full-test.js
@@ -515,11 +515,11 @@ acceptance("Search - Full Page", function (needs) {
const tagSelector = selectKit("#search-with-tags");
await tagSelector.expand();
- await tagSelector.selectRowByValue("monkey");
+ await tagSelector.selectRowByName("monkey");
assert.dom("input.all-tags").isNotVisible("all tags checkbox not visible");
- await tagSelector.selectRowByValue("gazelle");
+ await tagSelector.selectRowByName("gazelle");
assert.dom("input.all-tags").isVisible("all tags checkbox is visible");
});
diff --git a/frontend/discourse/tests/acceptance/sidebar-user-tags-section-test.js b/frontend/discourse/tests/acceptance/sidebar-user-tags-section-test.js
index 448b32254e7..714a26ea408 100644
--- a/frontend/discourse/tests/acceptance/sidebar-user-tags-section-test.js
+++ b/frontend/discourse/tests/acceptance/sidebar-user-tags-section-test.js
@@ -17,17 +17,19 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
});
needs.user({
- tracked_tags: ["tag1"],
- watched_tags: ["tag2", "tag3"],
+ tracked_tags: [1],
+ watched_tags: [2, 3],
watching_first_post_tags: [],
sidebar_tags: [
- { name: "tag2", pm_only: false },
- { name: "tag1", pm_only: false },
+ { id: 2, name: "tag2", pm_only: false },
+ { id: 1, name: "tag1", pm_only: false },
{
+ id: 4,
name: "tag4",
pm_only: true,
},
{
+ id: 3,
name: "tag3",
pm_only: false,
},
@@ -168,7 +170,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
]);
@@ -209,7 +211,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: NotificationLevels.TRACKING,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
]);
@@ -328,7 +330,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
{
topic_id: 2,
@@ -339,7 +341,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
{
topic_id: 3,
@@ -350,7 +352,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag2"],
+ tags: [{ id: 2, name: "tag2", slug: "tag2" }],
},
]);
@@ -424,7 +426,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
{
topic_id: 2,
@@ -435,7 +437,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
{
topic_id: 3,
@@ -446,7 +448,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag2"],
+ tags: [{ id: 2, name: "tag2", slug: "tag2" }],
},
{
topic_id: 4,
@@ -457,7 +459,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag4"],
+ tags: [{ id: 4, name: "tag4", slug: "tag4" }],
},
]);
@@ -579,9 +581,9 @@ acceptance(
new_new_view_enabled: true,
display_sidebar_tags: true,
sidebar_tags: [
- { name: "tag2", pm_only: false },
- { name: "tag1", pm_only: false },
- { name: "tag3", pm_only: false },
+ { id: 2, name: "tag2", pm_only: false },
+ { id: 1, name: "tag1", pm_only: false },
+ { id: 3, name: "tag3", pm_only: false },
],
});
@@ -602,7 +604,10 @@ acceptance(
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1", "tag3"],
+ tags: [
+ { id: 1, name: "tag1", slug: "tag1" },
+ { id: 3, name: "tag3", slug: "tag3" },
+ ],
},
{
topic_id: 2,
@@ -613,7 +618,10 @@ acceptance(
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1", "tag2"],
+ tags: [
+ { id: 1, name: "tag1", slug: "tag1" },
+ { id: 2, name: "tag2", slug: "tag2" },
+ ],
},
{
topic_id: 3,
@@ -624,7 +632,7 @@ acceptance(
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
]);
@@ -669,7 +677,7 @@ acceptance(
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
{
topic_id: 2,
@@ -680,7 +688,7 @@ acceptance(
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag2"],
+ tags: [{ id: 2, name: "tag2", slug: "tag2" }],
},
]);
@@ -722,7 +730,7 @@ acceptance(
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
{
topic_id: 2,
@@ -733,7 +741,7 @@ acceptance(
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag2"],
+ tags: [{ id: 2, name: "tag2", slug: "tag2" }],
},
{
topic_id: 3,
@@ -744,7 +752,7 @@ acceptance(
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag3"],
+ tags: [{ id: 3, name: "tag3", slug: "tag3" }],
},
]);
@@ -792,7 +800,7 @@ acceptance(
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag1"],
+ tags: [{ id: 1, name: "tag1", slug: "tag1" }],
},
{
topic_id: 2,
@@ -803,7 +811,7 @@ acceptance(
notification_level: 2,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag2"],
+ tags: [{ id: 2, name: "tag2", slug: "tag2" }],
},
]);
diff --git a/frontend/discourse/tests/acceptance/tag-groups-test.js b/frontend/discourse/tests/acceptance/tag-groups-test.js
index 7f4e9d9566f..3c986714b5c 100644
--- a/frontend/discourse/tests/acceptance/tag-groups-test.js
+++ b/frontend/discourse/tests/acceptance/tag-groups-test.js
@@ -12,8 +12,8 @@ acceptance("Tag Groups", function (needs) {
tag_group: {
id: 42,
name: "test tag group",
- tag_names: ["monkey"],
- parent_tag_name: [],
+ tags: [{ id: 1, name: "monkey", slug: "monkey" }],
+ parent_tag: [],
one_per_topic: false,
permissions: { 0: 1 },
},
@@ -44,12 +44,12 @@ acceptance("Tag Groups", function (needs) {
await fillIn(".tag-group-content .group-name input", "test tag group");
await tags.expand();
- await tags.selectRowByValue("monkey");
+ await tags.selectRowByName("monkey");
await click(".tag-group-content .btn.btn-primary");
await click(".tag-groups-sidebar li:first-child a");
await tags.expand();
- await tags.deselectItemByValue("monkey");
+ await tags.deselectItemByName("monkey");
assert.dom(".tag-group-content .btn.btn-danger").isEnabled();
});
@@ -62,7 +62,7 @@ acceptance("Tag Groups", function (needs) {
await fillIn(".tag-group-content .group-name input", "test tag group");
await tags.expand();
- await tags.selectRowByValue("monkey");
+ await tags.selectRowByName("monkey");
await click("#visible-permission");
await groups.expand();
diff --git a/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js b/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js
index 0df0015236d..59eaa04af95 100644
--- a/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js
+++ b/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js
@@ -12,9 +12,9 @@ import { i18n } from "discourse-i18n";
acceptance("Topic Discovery Tracked", function (needs) {
needs.user({
- tracked_tags: ["tag1"],
- watched_tags: ["tag2"],
- watching_first_post_tags: ["tag3"],
+ tracked_tags: [1],
+ watched_tags: [2],
+ watching_first_post_tags: [3],
});
needs.pretender((server, helper) => {
@@ -31,8 +31,11 @@ acceptance("Topic Discovery Tracked", function (needs) {
});
});
- server.get("/tag/:tag_name/l/latest.json", () => {
- return helper.response(cloneJSON(topicFixtures["/latest.json"]));
+ server.get("/tag/:tag_name/l/latest.json", (request) => {
+ const response = cloneJSON(topicFixtures["/latest.json"]);
+ // add tag with id to response so tracking state gets the tag id
+ response.topic_list.tags = [{ id: 99, name: request.params.tag_name }];
+ return helper.response(response);
});
});
@@ -176,7 +179,7 @@ acceptance("Topic Discovery Tracked", function (needs) {
notification_level: NotificationLevels.TRACKING,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag3"],
+ tags: [{ id: 3 }],
},
]);
@@ -258,7 +261,7 @@ acceptance("Topic Discovery Tracked", function (needs) {
notification_level: null,
created_in_new_period: true,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["some-other-tag"],
+ tags: [{ id: 99 }],
},
]);
@@ -340,7 +343,7 @@ acceptance("Topic Discovery Tracked", function (needs) {
notification_level: NotificationLevels.TRACKING,
created_in_new_period: false,
treat_as_new_topic_start_date: "2022-05-09T03:17:34.286Z",
- tags: ["tag3"],
+ tags: [{ id: 3 }],
},
]);
diff --git a/frontend/discourse/tests/acceptance/user-preferences-tracking-test.js b/frontend/discourse/tests/acceptance/user-preferences-tracking-test.js
index 247d116e613..1f8e34348a8 100644
--- a/frontend/discourse/tests/acceptance/user-preferences-tracking-test.js
+++ b/frontend/discourse/tests/acceptance/user-preferences-tracking-test.js
@@ -39,7 +39,7 @@ acceptance("User Preferences - Tracking", function (needs) {
);
await trackedTagsSelector.expand();
- await trackedTagsSelector.selectRowByValue("monkey");
+ await trackedTagsSelector.selectRowByName("monkey");
const watchedTagsSelector = selectKit(
".tracking-controls__watched-tags .tag-chooser"
@@ -48,11 +48,11 @@ acceptance("User Preferences - Tracking", function (needs) {
await watchedTagsSelector.expand();
assert.false(
- watchedTagsSelector.rowByValue("monkey").exists(),
+ watchedTagsSelector.rowByName("monkey").exists(),
"tag that has already been selected is not available for selection"
);
- await watchedTagsSelector.selectRowByValue("gazelle");
+ await watchedTagsSelector.selectRowByName("gazelle");
const mutedTagsSelector = selectKit(
".tracking-controls__muted-tags .tag-chooser"
@@ -62,12 +62,12 @@ acceptance("User Preferences - Tracking", function (needs) {
["monkey", "gazelle"].forEach((tagName) => {
assert.false(
- mutedTagsSelector.rowByValue(tagName).exists(),
- `tag "${tagName}" has already been selected is not available for selection`
+ mutedTagsSelector.rowByName(tagName).exists(),
+ `tag ${tagName} has already been selected is not available for selection`
);
});
- await mutedTagsSelector.selectRowByValue("dog");
+ await mutedTagsSelector.selectRowByName("dog");
const watchedFirstPostTagsSelector = selectKit(
".tracking-controls__watched-first-post-tags .tag-chooser"
@@ -77,12 +77,12 @@ acceptance("User Preferences - Tracking", function (needs) {
["dog", "gazelle", "monkey"].forEach((tagName) => {
assert.false(
- watchedFirstPostTagsSelector.rowByValue(tagName).exists(),
- "tag `${tagName}` has already been selected is not available for selection"
+ watchedFirstPostTagsSelector.rowByName(tagName).exists(),
+ `tag ${tagName} has already been selected is not available for selection`
);
});
- await watchedFirstPostTagsSelector.selectRowByValue("cat");
+ await watchedFirstPostTagsSelector.selectRowByName("cat");
await click(".save-changes");
@@ -206,7 +206,7 @@ acceptance("User Preferences - Tracking", function (needs) {
assert.dom(".user-preferences__watched-precedence-over-muted").doesNotExist;
await mutedTagsSelector.expand();
- await mutedTagsSelector.selectRowByValue("dog");
+ await mutedTagsSelector.selectRowByName("dog");
assert.dom(".user-preferences__watched-precedence-over-muted").exists();
});
diff --git a/frontend/discourse/tests/acceptance/user-private-messages-test.js b/frontend/discourse/tests/acceptance/user-private-messages-test.js
index 42e5f0cc83d..773fcd1b40a 100644
--- a/frontend/discourse/tests/acceptance/user-private-messages-test.js
+++ b/frontend/discourse/tests/acceptance/user-private-messages-test.js
@@ -908,8 +908,8 @@ acceptance(
const tags = selectKit("#reply-control .mini-tag-chooser");
await tags.expand();
- await tags.selectRowByValue("monkey");
- await tags.selectRowByValue("gazelle");
+ await tags.selectRowByName("monkey");
+ await tags.selectRowByName("gazelle");
await click("#reply-control .save-or-cancel button");
diff --git a/frontend/discourse/tests/fixtures/tag-group-fixtures.js b/frontend/discourse/tests/fixtures/tag-group-fixtures.js
index 07eb46530cc..449665489fe 100644
--- a/frontend/discourse/tests/fixtures/tag-group-fixtures.js
+++ b/frontend/discourse/tests/fixtures/tag-group-fixtures.js
@@ -1,8 +1,5 @@
export default {
"/tag_groups/filter/search": {
- results: [
- { name: "TagGroup1", tag_names: ["alpha", "bravo", "charlie"] },
- { name: "TagGroup2", tag_names: ["delta", "echo"] },
- ],
+ results: [{ name: "TagGroup1" }, { name: "TagGroup2" }],
},
};
diff --git a/frontend/discourse/tests/helpers/create-pretender.js b/frontend/discourse/tests/helpers/create-pretender.js
index ef1a14af034..376f01c5285 100644
--- a/frontend/discourse/tests/helpers/create-pretender.js
+++ b/frontend/discourse/tests/helpers/create-pretender.js
@@ -198,17 +198,17 @@ export function applyDefaultHandlers(pretender) {
pretender.get("/tags/filter/search", (request) => {
const responseBody = {
results: [
- { id: "monkey", name: "monkey", count: 1 },
- { id: "gazelle", name: "gazelle", count: 2 },
- { id: "dog", name: "dog", count: 3 },
- { id: "cat", name: "cat", count: 4 },
+ { id: 1, name: "monkey", slug: "monkey", count: 1 },
+ { id: 2, name: "gazelle", slug: "gazelle", count: 2 },
+ { id: 3, name: "dog", slug: "dog", count: 3 },
+ { id: 4, name: "cat", slug: "cat", count: 4 },
],
};
if (
request.queryParams.categoryId === "1" &&
request.queryParams.q === "" &&
- !request.queryParams.selected_tags.includes("monkey")
+ !request.queryParams.selected_tag_ids?.includes("1")
) {
responseBody["required_tag_group"] = {
name: "monkey group",
diff --git a/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs b/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs
index 68f633a5657..04af7daa1b8 100644
--- a/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs
+++ b/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs
@@ -1067,13 +1067,13 @@ module(
`${inputFields.fields.required_tags_with_validations.selector} .select-kit`
);
- assert.strictEqual(tagSelector.header().value(), "gazelle,cat");
+ assert.strictEqual(tagSelector.header().name(), "gazelle,cat");
await tagSelector.expand();
await tagSelector.selectRowByIndex(2);
await tagSelector.collapse();
- assert.strictEqual(tagSelector.header().value(), "gazelle,cat,dog");
+ assert.strictEqual(tagSelector.header().name(), "gazelle,cat,dog");
await tagSelector.expand();
await tagSelector.deselectItemByName("gazelle");
@@ -1096,7 +1096,7 @@ module(
await tagSelector.expand();
await tagSelector.selectRowByIndex(1);
- assert.strictEqual(tagSelector.header().value(), "gazelle");
+ assert.strictEqual(tagSelector.header().name(), "gazelle");
inputFields.refresh();
@@ -2196,13 +2196,13 @@ module(
`${inputFields.fields.required_tags_with_validations.selector} .select-kit`
);
- assert.strictEqual(tagSelector.header().value(), "gazelle,cat");
+ assert.strictEqual(tagSelector.header().name(), "gazelle,cat");
await tagSelector.expand();
await tagSelector.selectRowByIndex(2);
await tagSelector.collapse();
- assert.strictEqual(tagSelector.header().value(), "gazelle,cat,dog");
+ assert.strictEqual(tagSelector.header().name(), "gazelle,cat,dog");
await tagSelector.expand();
await tagSelector.deselectItemByName("gazelle");
@@ -2225,7 +2225,7 @@ module(
await tagSelector.expand();
await tagSelector.selectRowByIndex(1);
- assert.strictEqual(tagSelector.header().value(), "gazelle");
+ assert.strictEqual(tagSelector.header().name(), "gazelle");
inputFields.refresh();
diff --git a/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjs b/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjs
index caddd5a4ea4..aba968f967d 100644
--- a/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjs
+++ b/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjs
@@ -17,7 +17,10 @@ module(
});
test("displays tags", async function (assert) {
- this.set("value", ["foo", "bar"]);
+ this.set("value", [
+ { id: "foo", name: "foo", slug: "foo" },
+ { id: "bar", name: "bar", slug: "bar" },
+ ]);
await render(
<template><MiniTagChooser @value={{this.value}} /></template>
@@ -27,7 +30,10 @@ module(
});
test("create a tag", async function (assert) {
- this.set("value", ["foo", "bar"]);
+ this.set("value", [
+ { id: "foo", name: "foo", slug: "foo" },
+ { id: "bar", name: "bar", slug: "bar" },
+ ]);
await render(
<template><MiniTagChooser @value={{this.value}} /></template>
@@ -46,13 +52,16 @@ module(
[...queryAll(".select-kit-row")].map((el) => el.textContent.trim()),
["monkey x1", "gazelle x2", "dog x3", "cat x4"]
);
- await this.subject.selectRowByValue("monkey");
+ await this.subject.selectRowByName("monkey");
- assert.strictEqual(this.subject.header().value(), "foo,bar,monkey");
+ assert.strictEqual(this.subject.header().name(), "foo,bar,monkey");
});
test("max_tags_per_topic", async function (assert) {
- this.set("value", ["foo", "bar"]);
+ this.set("value", [
+ { id: "foo", name: "foo", slug: "foo" },
+ { id: "bar", name: "bar", slug: "bar" },
+ ]);
this.siteSettings.max_tags_per_topic = 2;
await render(
@@ -63,7 +72,7 @@ module(
await this.subject.expand();
await this.subject.fillInFilter("baz");
- await this.subject.selectRowByValue("monkey");
+ await this.subject.selectRowByName("monkey");
assert.dom(".select-kit-error").hasText(
i18n("select_kit.max_content_reached", {
@@ -73,7 +82,10 @@ module(
});
test("disables search and shows limit when max_tags_per_topic is zero", async function (assert) {
- this.set("value", ["cat", "kit"]);
+ this.set("value", [
+ { id: "cat", name: "cat", slug: "cat" },
+ { id: "kit", name: "kit", slug: "kit" },
+ ]);
this.siteSettings.max_tags_per_topic = 0;
await render(
@@ -95,7 +107,10 @@ module(
});
test("required_tag_group", async function (assert) {
- this.set("value", ["foo", "bar"]);
+ this.set("value", [
+ { id: "foo", name: "foo", slug: "foo" },
+ { id: "bar", name: "bar", slug: "bar" },
+ ]);
await render(
<template>
@@ -118,7 +133,7 @@ module(
})
);
- await this.subject.selectRowByValue("monkey");
+ await this.subject.selectRowByName("monkey");
assert
.dom("input[name=filter-input-search]")
@@ -159,8 +174,11 @@ module(
});
test("values in hiddenFromPreview will not display in preview", async function (assert) {
- this.set("value", ["foo", "bar"]);
- this.set("hiddenValues", ["foo"]);
+ this.set("value", [
+ { id: 1, name: "foo", slug: "foo" },
+ { id: 2, name: "bar", slug: "bar" },
+ ]);
+ this.set("hiddenValues", [{ id: 1, name: "foo", slug: "foo" }]);
await render(
<template>
@@ -193,7 +211,11 @@ module(
});
test("displays tags and filter in header", async function (assert) {
- this.set("value", ["apple", "orange", "potato"]);
+ this.set("value", [
+ { id: 10, name: "apple", slug: "apple" },
+ { id: 11, name: "orange", slug: "orange" },
+ { id: 12, name: "potato", slug: "potato" },
+ ]);
await render(
<template>
@@ -204,7 +226,7 @@ module(
</template>
);
- assert.strictEqual(this.subject.header().value(), "apple,orange,potato");
+ assert.strictEqual(this.subject.header().name(), "apple,orange,potato");
assert.dom(".select-kit-header--filter").exists();
assert.dom(".select-kit-header button[data-name='apple']").exists();
@@ -232,7 +254,11 @@ module(
});
test("removing a tag does not display the dropdown", async function (assert) {
- this.set("value", ["apple", "orange", "potato"]);
+ this.set("value", [
+ { id: 10, name: "apple", slug: "apple" },
+ { id: 11, name: "orange", slug: "orange" },
+ { id: 12, name: "potato", slug: "potato" },
+ ]);
await render(
<template>
@@ -243,13 +269,13 @@ module(
</template>
);
- assert.strictEqual(this.subject.header().value(), "apple,orange,potato");
+ assert.strictEqual(this.subject.header().name(), "apple,orange,potato");
await click(".select-kit-header button[data-name='apple']");
assert.dom(".select-kit-collection").doesNotExist();
assert.dom(".select-kit-header button[data-name='apple']").doesNotExist();
- assert.strictEqual(this.subject.header().value(), "orange,potato");
+ assert.strictEqual(this.subject.header().name(), "orange,potato");
assert
.dom(".select-kit-header .filter-input")
diff --git a/frontend/discourse/tests/integration/components/select-kit/tag-drop-test.gjs b/frontend/discourse/tests/integration/components/select-kit/tag-drop-test.gjs
index ed27d0af616..195cb4e2c5a 100644
--- a/frontend/discourse/tests/integration/components/select-kit/tag-drop-test.gjs
+++ b/frontend/discourse/tests/integration/components/select-kit/tag-drop-test.gjs
@@ -13,7 +13,12 @@ module("Integration | Component | select-kit/tag-drop", function (hooks) {
hooks.beforeEach(function () {
this.subject = selectKit();
- this.site.top_tags = ["jeff", "neil", "arpit", "régis"];
+ this.site.top_tags = [
+ { id: 1, name: "jeff" },
+ { id: 2, name: "neil" },
+ { id: 3, name: "arpit" },
+ { id: 4, name: "régis" },
+ ];
pretender.get("/tags/filter/search", (params) => {
if (params.queryParams.q === "dav") {
@@ -84,4 +89,40 @@ module("Integration | Component | select-kit/tag-drop", function (hooks) {
.dom(".filter-for-more")
.doesNotExist("does not have the 'filter for more' note");
});
+
+ test("sorts tags alphabetically when setting enabled", async function (assert) {
+ this.siteSettings.tags_sort_alphabetically = true;
+ this.site.top_tags = [
+ { id: 1, name: "zebra" },
+ { id: 2, name: "apple" },
+ { id: 3, name: "banana" },
+ ];
+
+ await render(<template><TagDrop /></template>);
+ await this.subject.expand();
+
+ const content = this.subject.displayedContent();
+ // first item is "no tags" shortcut
+ assert.strictEqual(content[1].name, "apple");
+ assert.strictEqual(content[2].name, "banana");
+ assert.strictEqual(content[3].name, "zebra");
+ });
+
+ test("preserves tag order when alphabetical sorting disabled", async function (assert) {
+ this.siteSettings.tags_sort_alphabetically = false;
+ this.site.top_tags = [
+ { id: 1, name: "zebra" },
+ { id: 2, name: "apple" },
+ { id: 3, name: "banana" },
+ ];
+
+ await render(<template><TagDrop /></template>);
+ await this.subject.expand();
+
+ const content = this.subject.displayedContent();
+ // first item is "no tags" shortcut
+ assert.strictEqual(content[1].name, "zebra");
+ assert.strictEqual(content[2].name, "apple");
+ assert.strictEqual(content[3].name, "banana");
+ });
});
diff --git a/frontend/discourse/tests/unit/models/composer-test.js b/frontend/discourse/tests/unit/models/composer-test.js
index 4c2d8f3c898..f7f87ea2926 100644
--- a/frontend/discourse/tests/unit/models/composer-test.js
+++ b/frontend/discourse/tests/unit/models/composer-test.js
@@ -511,4 +511,36 @@ module("Unit | Model | composer", function (hooks) {
);
assert.strictEqual(composer.composerVersion, 1);
});
+
+ test("serialize normalizes tags to names and keeps original_tags as objects", function (assert) {
+ const composer = createComposer.call(this, {
+ tags: [
+ { id: 1, name: "bug", slug: "bug" },
+ { id: 2, name: "feature", slug: "feature" },
+ ],
+ originalTags: [
+ { id: 1, name: "bug", slug: "bug" },
+ { id: 3, name: "support", slug: "support" },
+ ],
+ });
+
+ const serialized = composer.serialize({
+ tags: "tags",
+ original_tags: "originalTags",
+ });
+
+ assert.deepEqual(
+ serialized.tags,
+ ["bug", "feature"],
+ "tags are normalized to string names"
+ );
+ assert.deepEqual(
+ serialized.original_tags,
+ [
+ { id: 1, name: "bug", slug: "bug" },
+ { id: 3, name: "support", slug: "support" },
+ ],
+ "original_tags are kept as objects for backend to extract IDs"
+ );
+ });
});
diff --git a/frontend/discourse/tests/unit/models/nav-item-test.js b/frontend/discourse/tests/unit/models/nav-item-test.js
index d284ba71850..721b364455c 100644
--- a/frontend/discourse/tests/unit/models/nav-item-test.js
+++ b/frontend/discourse/tests/unit/models/nav-item-test.js
@@ -25,10 +25,18 @@ module("Unit | Model | nav-item", function (hooks) {
href("latest", {}, "/latest", "latest");
href("categories", {}, "/categories", "categories");
- href("latest", { tagId: "bar" }, "/tag/bar/l/latest", "latest with tag");
href(
"latest",
- { tagId: "bar", category: Category.findBySlugPath(["foo"]) },
+ { tag: { id: 1, name: "bar", slug: "bar" } },
+ "/tag/bar/l/latest",
+ "latest with tag"
+ );
+ href(
+ "latest",
+ {
+ tag: { id: 1, name: "bar", slug: "bar" },
+ category: Category.findBySlugPath(["foo"]),
+ },
"/tags/c/foo/123/bar/l/latest",
"latest with tag and category"
);
diff --git a/frontend/discourse/tests/unit/models/topic-tracking-state-test.js b/frontend/discourse/tests/unit/models/topic-tracking-state-test.js
index 69a6fce5d68..bb8f7b83699 100644
--- a/frontend/discourse/tests/unit/models/topic-tracking-state-test.js
+++ b/frontend/discourse/tests/unit/models/topic-tracking-state-test.js
@@ -635,7 +635,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
0
);
assert.strictEqual(
- trackingState.countNew({ categoryId: 1, tagId: "missing-tag" }),
+ trackingState.countNew({ categoryId: 1, tagId: 999 }),
0
);
assert.strictEqual(trackingState.countNew({ categoryId: 2 }), 1);
@@ -646,7 +646,7 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
id: 113,
notification_level: NotificationLevels.TRACKING,
category_id: 3,
- tags: ["amazing"],
+ tags: [{ id: 77, name: "amazing", slug: "amazing" }],
created_in_new_period: true,
});
@@ -656,14 +656,14 @@ module("Unit | Model | topic-tracking-state", function (hooks) {
assert.strictEqual(
trackingState.countNew({
categoryId: 3,
- tagId: "amazing",
+ tagId: 77,
}),
1
);
assert.strictEqual(
trackingState.countNew({
categoryId: 3,
- tagId: "missing",
+ tagId: 888,
}),
0
);
@@ -730,8 +730,7 @@ module("Unit | Model | topic-tracking-state | /unread", function (hooks) {
message_type: "unread",
payload: {
category_id: 123,
- topic_tag_ids: [44],
- tags: ["pending"],
+ tags: [{ id: 44 }],
highest_post_number: 10,
created_at: "2012-11-31 12:00:00 UTC",
archetype: "regular",
@@ -787,8 +786,7 @@ module("Unit | Model | topic-tracking-state | /unread", function (hooks) {
{
topic_id: 111,
category_id: 123,
- topic_tag_ids: [44],
- tags: ["pending"],
+ tags: [{ id: 44 }],
last_read_post_number: 4,
highest_post_number: 10,
notification_level: NotificationLevels.TRACKING,
@@ -856,22 +854,22 @@ module("Unit | Model | topic-tracking-state | /unread", function (hooks) {
test("correct tag and category filters for different lists", function (assert) {
this.trackingState.trackIncoming("unread");
assert.strictEqual(this.trackingState.filterCategory, undefined);
- assert.strictEqual(this.trackingState.filterTag, undefined);
+ assert.strictEqual(this.trackingState.filterTagName, undefined);
assert.strictEqual(this.trackingState.filter, "unread");
this.trackingState.trackIncoming("tag/test/l/latest");
assert.strictEqual(this.trackingState.filterCategory, undefined);
- assert.strictEqual(this.trackingState.filterTag, "test");
+ assert.strictEqual(this.trackingState.filterTagName, "test");
assert.strictEqual(this.trackingState.filter, "latest");
this.trackingState.trackIncoming("c/cat/sub-cat/6/l/latest");
assert.strictEqual(this.trackingState.filterCategory.id, 6);
- assert.strictEqual(this.trackingState.filterTag, undefined);
+ assert.strictEqual(this.trackingState.filterTagName, undefined);
assert.strictEqual(this.trackingState.filter, "latest");
this.trackingState.trackIncoming("tags/c/cat/sub-cat/6/test/l/latest");
assert.strictEqual(this.trackingState.filterCategory.id, 6);
- assert.strictEqual(this.trackingState.filterTag, "test");
+ assert.strictEqual(this.trackingState.filterTagName, "test");
assert.strictEqual(this.trackingState.filter, "latest");
});
@@ -884,8 +882,7 @@ module("Unit | Model | topic-tracking-state | /unread", function (hooks) {
this.trackingState.findState(999),
{
category_id: 123,
- topic_tag_ids: [44],
- tags: ["pending"],
+ tags: [{ id: 44 }],
last_read_post_number: 9,
highest_post_number: 10,
notification_level: NotificationLevels.TRACKING,
@@ -982,8 +979,7 @@ module("Unit | Model | topic-tracking-state | /new", function (hooks) {
message_type: "new_topic",
payload: {
category_id: 123,
- topic_tag_ids: [44],
- tags: ["pending"],
+ tags: [{ id: 44 }],
last_read_post_number: null,
highest_post_number: 1,
created_at: "2012-11-31 12:00:00 UTC",
@@ -1049,8 +1045,7 @@ module("Unit | Model | topic-tracking-state | /new", function (hooks) {
this.trackingState.findState(222),
{
category_id: 123,
- topic_tag_ids: [44],
- tags: ["pending"],
+ tags: [{ id: 44 }],
last_read_post_number: null,
highest_post_number: 1,
created_at: "2012-11-31 12:00:00 UTC",
@@ -1061,7 +1056,7 @@ module("Unit | Model | topic-tracking-state | /new", function (hooks) {
});
test("topics in muted tags do not get added to the state", async function (assert) {
- this.currentUser.set("muted_tags", ["pending"]);
+ this.currentUser.set("muted_tags", [44]);
await publishToMessageBus("/new", newTopicPayload);
@@ -1093,8 +1088,7 @@ module("Unit | Model | topic-tracking-state | /new", function (hooks) {
this.trackingState.findState(222),
{
category_id: 123,
- topic_tag_ids: [44],
- tags: ["pending"],
+ tags: [{ id: 44 }],
last_read_post_number: null,
highest_post_number: 1,
created_at: "2012-11-31 12:00:00 UTC",
diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rb
index 5f1b6c14751..1da2bde0058 100644
--- a/lib/discourse_tagging.rb
+++ b/lib/discourse_tagging.rb
@@ -247,6 +247,11 @@ module DiscourseTagging
end
end
+ def self.tag_topic_by_ids(topic, guardian, tag_ids, append: false)
+ tag_names = Tag.where(id: tag_ids).pluck(:name)
+ tag_topic_by_names(topic, guardian, tag_names, append: append)
+ end
+
def self.validate_category_tags(guardian, model, category, tags = [])
existing_tags = tags.present? ? Tag.where(name: tags) : []
valid_tags = guardian.can_create_tag? ? tags : existing_tags
@@ -439,14 +444,22 @@ module DiscourseTagging
# category: a Category to which the object being tagged belongs
# for_input: result is for an input field, so only show permitted tags
# for_topic: results are for tagging a topic
- # selected_tags: an array of tag names that are in the current selection
+ # selected_tags: an array of tag names that are in the current selection (legacy)
+ # selected_tag_ids: an array of tag ids that are in the current selection
# only_tag_names: limit results to tags with these names
# exclude_synonyms: exclude synonyms from results
# order_search_results: result should be ordered for name search results
# order_popularity: order result by topic_count
# excluded_tag_names: an array of tag names not to include in the results
def self.filter_allowed_tags(guardian, opts = {})
- selected_tag_ids = opts[:selected_tags] ? Tag.where_name(opts[:selected_tags]).pluck(:id) : []
+ selected_tag_ids =
+ if opts[:selected_tag_ids].present?
+ opts[:selected_tag_ids].map(&:to_i)
+ elsif opts[:selected_tags].present?
+ Tag.where_name(opts[:selected_tags]).pluck(:id)
+ else
+ []
+ end
category = opts[:category]
category_has_tag_groups = category && category.tag_groups.count > 0
category_has_restricted_tags = category_has_tag_groups || (category && category.tags.count > 0)
@@ -677,9 +690,9 @@ module DiscourseTagging
guardian&.is_admin? ? query : query.where(id: visible_tags(guardian).select(:id))
end
- def self.hidden_tag_names(guardian = nil)
+ def self.hidden_tags(guardian = nil)
if guardian&.is_admin?
- []
+ Tag.none
else
# Hidden tags have at least one TagGroupPermission but must not have any for permitted groups
Tag
@@ -691,10 +704,13 @@ module DiscourseTagging
.where(group_id: permitted_group_ids_query(guardian))
.select("tag_group_memberships.tag_id"),
)
- .pluck(:name)
end
end
+ def self.hidden_tag_names(guardian = nil)
+ hidden_tags(guardian).pluck(:name)
+ end
+
def self.permitted_group_ids_query(guardian = nil)
if guardian&.authenticated?
Group.from(
@@ -809,35 +825,96 @@ module DiscourseTagging
end
end
- # Returns true if all were added successfully, or an Array of the
- # tags that failed to be added, with errors on each Tag.
- def self.add_or_create_synonyms_by_name(target_tag, synonym_names)
- tag_names =
- DiscourseTagging.tags_for_saving(synonym_names, Guardian.new(Discourse.system_user)) || []
- tag_names -= [target_tag.name]
- existing = Tag.where_name(tag_names).all
- target_tag.synonyms << existing
- (tag_names - target_tag.synonyms.map(&:name)).each do |name|
- target_tag.synonyms << Tag.create(name: name)
- end
- successful = existing.select { |t| !t.errors.present? }
- synonyms_ids = successful.map(&:id)
- TopicTag.where(topic_id: target_tag.topics.with_deleted, tag_id: synonyms_ids).delete_all
- TopicTag.joins(DB.sql_fragment(<<~SQL, synonyms_ids: synonyms_ids)).delete_all
- INNER JOIN (
- SELECT MIN(id) AS id, topic_id
- FROM topic_tags
- WHERE tag_id IN (:synonyms_ids)
- GROUP BY topic_id
- ) AS tt ON tt.id < topic_tags.id
- AND tt.topic_id = topic_tags.topic_id
- AND topic_tags.tag_id IN (:synonyms_ids)
+ # Add synonyms to a target tag.
+ #
+ # - ensures synonym tags do not already have synonyms,
+ # - adds the synonyms to tag groups, categories of the target tag
+ # - moves topic_tags of the synonym to the target tag
+ #
+ # @!attribute target_tag [Tag] the tag to which synonyms will be added
+ # @!attribute synonym_tag_ids [Array<Integer>] existing tag IDs to be added as synonyms
+ # @!attribute new_synonym_names [Array<String>] new tag names to be created as synonyms
+ # @return [true, Hash] true if all synonyms were added successfully or a hash of
+ # failed synonym names with error messages
+ def self.add_or_create_synonyms(target_tag, synonym_tag_ids: [], new_synonym_names: [])
+ return true if synonym_tag_ids.blank? && new_synonym_names.blank?
+
+ # normalize inputs
+ synonym_tag_ids -= [target_tag.id]
+ cleaned_names =
+ (tags_for_saving(new_synonym_names, Guardian.new(Discourse.system_user)) || []) -
+ [target_tag.name]
+
+ # single query: find candidates + check if they have synonyms
+ candidates =
+ DB.query(
+ <<~SQL,
+ SELECT t.id, t.name,
+ EXISTS(SELECT 1 FROM tags s WHERE s.target_tag_id = t.id) AS has_synonyms
+ FROM tags t
+ WHERE (LOWER(t.name) IN (:names) OR t.id IN (:ids))
+ AND t.id != :target_id
SQL
- TopicTag.where(tag_id: synonyms_ids).update_all(tag_id: target_tag.id)
- Scheduler::Defer.later "Update tag topic counts" do
- Tag.ensure_consistency!
+ ids: synonym_tag_ids,
+ names: cleaned_names.map(&:downcase),
+ target_id: target_tag.id,
+ )
+
+ valid_ids = []
+ failed = {}
+ existing_names = Set.new
+
+ candidates.each do |c|
+ existing_names << c.name.downcase
+ if c.has_synonyms
+ failed[c.name] = I18n.t("tags.synonyms_exist")
+ else
+ valid_ids << c.id
+ end
+ end
+ # set target_tag_id on existing tags
+ Tag.where(id: valid_ids).update_all(target_tag_id: target_tag.id)
+
+ # create new tags for names that don't exist
+ names_to_create = cleaned_names.reject { |n| existing_names.include?(n.downcase) }
+ if names_to_create.present?
+ now = Time.current
+ rows =
+ names_to_create.map do |n|
+ { name: n, target_tag_id: target_tag.id, created_at: now, updated_at: now }
+ end
+ valid_ids += Tag.insert_all(rows, returning: :id).pluck("id")
end
- (existing - successful).presence || true
+
+ return failed.presence || true if valid_ids.blank?
+
+ # copy associations and consolidate topic_tags
+ DB.exec(<<~SQL, synonym_ids: valid_ids, target_id: target_tag.id)
+ INSERT INTO tag_group_memberships (tag_id, tag_group_id, created_at, updated_at)
+ SELECT s.id, tgm.tag_group_id, NOW(), NOW()
+ FROM unnest(ARRAY[:synonym_ids]::int[]) s(id)
+ JOIN tag_group_memberships tgm ON tgm.tag_id = :target_id
+ ON CONFLICT DO NOTHING;
+
+ INSERT INTO category_tags (tag_id, category_id, created_at, updated_at)
+ SELECT s.id, ct.category_id, NOW(), NOW()
+ FROM unnest(ARRAY[:synonym_ids]::int[]) s(id)
+ JOIN category_tags ct ON ct.tag_id = :target_id
+ ON CONFLICT DO NOTHING;
+
+ WITH keep AS (
+ SELECT MIN(id) AS id FROM topic_tags
+ WHERE tag_id IN (:synonym_ids)
+ AND topic_id NOT IN (SELECT topic_id FROM topic_tags WHERE tag_id = :target_id)
+ GROUP BY topic_id
+ )
+ DELETE FROM topic_tags WHERE tag_id IN (:synonym_ids) AND id NOT IN (SELECT id FROM keep);
+
+ UPDATE topic_tags SET tag_id = :target_id WHERE tag_id IN (:synonym_ids);
+ SQL
+
+ Scheduler::Defer.later("Update tag topic counts") { Tag.ensure_consistency! }
+ failed.presence || true
end
def self.muted_tags(user)
diff --git a/lib/post_revisor.rb b/lib/post_revisor.rb
index b375d6578a0..5599b19e7d2 100644
--- a/lib/post_revisor.rb
+++ b/lib/post_revisor.rb
@@ -40,6 +40,54 @@ class PostRevisor
def diff
@diff ||= {}
end
+
+ def apply_tag_changes(tag_value)
+ return unless guardian.can_tag_topics?
+
+ prev_tags = topic.tags.map(&:name)
+ return if tag_value.blank? && prev_tags.blank?
+
+ by_ids = tag_value.first.is_a?(Integer)
+ success =
+ if by_ids
+ DiscourseTagging.tag_topic_by_ids(topic, guardian, tag_value)
+ else
+ DiscourseTagging.tag_topic_by_names(topic, guardian, tag_value)
+ end
+
+ unless success
+ check_result(false)
+ return
+ end
+
+ new_tags = topic.tags.map(&:name)
+ return if prev_tags.sort == new_tags.sort
+
+ record_change("tags", prev_tags, new_tags)
+ DB.after_commit do
+ t = topic.reload
+ post = t.ordered_posts.first
+ notified_user_ids = [post.user_id, post.last_editor_id].uniq
+
+ persisted_tag_names = t.tags.pluck(:name)
+ added_tags = persisted_tag_names - prev_tags
+ removed_tags = prev_tags - persisted_tag_names
+ diff_tags = added_tags | removed_tags
+
+ if diff_tags.present?
+ if !SiteSetting.disable_tags_edit_notifications
+ Jobs.enqueue(:notify_tag_change, post_id: post.id, notified_user_ids:, diff_tags:)
+ end
+
+ PostRevisor.create_small_action_for_tag_changes(
+ topic: t,
+ user: user,
+ added_tags:,
+ removed_tags:,
+ )
+ end
+ end
+ end
end
POST_TRACKED_FIELDS = %w[raw cooked edit_reason user_id wiki post_type locale]
@@ -108,46 +156,7 @@ class PostRevisor
end
end
- track_topic_field(:tags) do |tc, tags|
- if tc.guardian.can_tag_topics?
- prev_tags = tc.topic.tags.map(&:name)
- next if tags.blank? && prev_tags.blank?
-
- if !DiscourseTagging.tag_topic_by_names(tc.topic, tc.guardian, tags)
- tc.check_result(false)
- next
- end
-
- new_tags = tc.topic.tags.map(&:name)
-
- if prev_tags.sort != new_tags.sort
- tc.record_change("tags", prev_tags, new_tags)
- DB.after_commit do
- topic = tc.topic.reload
- post = topic.ordered_posts.first
- notified_user_ids = [post.user_id, post.last_editor_id].uniq
-
- persisted_tag_names = topic.tags.pluck(:name)
- added_tags = persisted_tag_names - prev_tags
- removed_tags = prev_tags - persisted_tag_names
- diff_tags = added_tags | removed_tags
-
- if diff_tags.present?
- if !SiteSetting.disable_tags_edit_notifications
- Jobs.enqueue(:notify_tag_change, post_id: post.id, notified_user_ids:, diff_tags:)
- end
-
- create_small_action_for_tag_changes(
- topic: topic,
- user: tc.user,
- added_tags:,
- removed_tags:,
- )
- end
- end
- end
- end
- end
+ track_topic_field(:tags) { |tc, tags| tc.apply_tag_changes(tags) }
track_topic_field(:featured_link) do |topic_changes, featured_link|
if !SiteSetting.topic_featured_link_enabled ||
@@ -381,6 +390,9 @@ class PostRevisor
def should_create_new_version?
return false if @skip_revision
+ # topic-only changes (without post content changes) should always create a new version
+ # since the grace period concept doesn't apply to metadata changes like tags
+ return true if topic_changed? && !post_changed?
edited_by_another_user? || flagged? || !grace_period_edit? || owner_changed? ||
force_new_version? || edit_reason_specified?
end
diff --git a/lib/topic_creator.rb b/lib/topic_creator.rb
index a5bb692c3ae..d13ea6d26ba 100644
--- a/lib/topic_creator.rb
+++ b/lib/topic_creator.rb
@@ -27,7 +27,12 @@ class TopicCreator
category = find_category
if category.present? && guardian.can_tag?(topic)
- tags = @opts[:tags].presence || []
+ tags =
+ if @opts[:tag_ids].present?
+ Tag.where(id: @opts[:tag_ids]).pluck(:name)
+ else
+ @opts[:tags].presence || []
+ end
# adds topic.errors
DiscourseTagging.validate_category_tags(guardian, topic, category, tags)
@@ -190,10 +195,18 @@ class TopicCreator
end
def setup_tags(topic)
- if @opts[:tags].present?
- # We can try the full tagging workflow which does validations and other
- # things like replacing synonyms first, but if this fails then we can try
- # the simple workflow if validations are skipped.
+ if @opts[:tag_ids].present?
+ valid_tags = DiscourseTagging.tag_topic_by_ids(topic, @guardian, @opts[:tag_ids])
+ if !valid_tags
+ if @opts[:skip_validations]
+ tag_names = Tag.where(id: @opts[:tag_ids]).pluck(:name)
+ DiscourseTagging.add_or_create_tags_by_name(topic, tag_names)
+ else
+ topic.errors.add(:base, :unable_to_tag)
+ rollback_from_errors!(topic)
+ end
+ end
+ elsif @opts[:tags].present?
valid_tags = DiscourseTagging.tag_topic_by_names(topic, @guardian, @opts[:tags])
if !valid_tags
if @opts[:skip_validations]
diff --git a/lib/topics_bulk_action.rb b/lib/topics_bulk_action.rb
index 707ade47f06..6198703e39b 100644
--- a/lib/topics_bulk_action.rb
+++ b/lib/topics_bulk_action.rb
@@ -242,13 +242,14 @@ class TopicsBulkAction
end
def change_tags
- tags = @operation[:tags]
- tags = DiscourseTagging.tags_for_saving(tags, guardian) if tags.present?
+ tag_ids, tag_names = extract_tag_params
topics.each do |t|
if guardian.can_edit?(t)
- if tags.present?
- DiscourseTagging.tag_topic_by_names(t, guardian, tags)
+ if tag_ids.present?
+ DiscourseTagging.tag_topic_by_ids(t, guardian, tag_ids)
+ elsif tag_names.present?
+ DiscourseTagging.tag_topic_by_names(t, guardian, tag_names)
else
t.tags = []
end
@@ -258,17 +259,36 @@ class TopicsBulkAction
end
def append_tags
- tags = @operation[:tags]
- tags = DiscourseTagging.tags_for_saving(tags, guardian) if tags.present?
+ tag_ids, tag_names = extract_tag_params
topics.each do |t|
if guardian.can_edit?(t)
- DiscourseTagging.tag_topic_by_names(t, guardian, tags, append: true) if tags.present?
+ if tag_ids.present?
+ DiscourseTagging.tag_topic_by_ids(t, guardian, tag_ids, append: true)
+ elsif tag_names.present?
+ DiscourseTagging.tag_topic_by_names(t, guardian, tag_names, append: true)
+ end
@changed_ids << t.id
end
end
end
+ def extract_tag_params
+ if @operation[:tag_ids].present?
+ [@operation[:tag_ids], nil]
+ elsif @operation[:tags].present?
+ Discourse.deprecate(
+ "the tags param for bulk actions is deprecated, use tag_ids instead",
+ since: "2026.01",
+ drop_from: "2026.07",
+ )
+ tag_names = @operation[:tags]
+ [nil, tag_names]
+ else
+ [nil, nil]
+ end
+ end
+
def remove_tags
topics.each do |t|
if guardian.can_edit?(t)
diff --git a/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs b/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs
index 5be880b6589..f1c5a5d1b8b 100644
--- a/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs
+++ b/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs
@@ -11,6 +11,8 @@ export default class TagsField extends BaseField {
onChangeTags(tags) {
if (isBlank(tags)) {
tags = undefined;
+ } else {
+ tags = tags.map((t) => (typeof t === "string" ? t : t.name));
}
this.mutValue(tags);
diff --git a/plugins/automation/test/javascripts/integration/components/da-tags-field-test.gjs b/plugins/automation/test/javascripts/integration/components/da-tags-field-test.gjs
index 54b3b026014..ab02747943d 100644
--- a/plugins/automation/test/javascripts/integration/components/da-tags-field-test.gjs
+++ b/plugins/automation/test/javascripts/integration/components/da-tags-field-test.gjs
@@ -28,7 +28,7 @@ module("Integration | Component | da-tags-field", function (hooks) {
);
await selectKit().expand();
- await selectKit().selectRowByValue("monkey");
+ await selectKit().selectRowByName("monkey");
assert.deepEqual(this.field.metadata.value, ["monkey"]);
});
@@ -47,11 +47,11 @@ module("Integration | Component | da-tags-field", function (hooks) {
</template>
);
await selectKit().expand();
- await selectKit().selectRowByValue("monkey");
+ await selectKit().selectRowByName("monkey");
assert.deepEqual(this.field.metadata.value, ["monkey"]);
- await selectKit().deselectItemByValue("monkey");
+ await selectKit().deselectItemByName("monkey");
assert.strictEqual(this.field.metadata.value, undefined);
});
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjs
index c8e28ea35fa..184d0c85eef 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjs
@@ -57,6 +57,7 @@ export default class AiSplitTopicSuggester extends Component {
} else if (this.args.mode === this.SUGGESTION_TYPES.tag) {
this.suggestions = result.assistant.map((s) => {
return {
+ id: s.id,
name: s.name,
count: s.count,
};
@@ -148,7 +149,7 @@ export default class AiSplitTopicSuggester extends Component {
<li data-name={{suggestion.name}} data-value={{index}}>
<DButton
@translatedLabel={{suggestion.name}}
- @action={{fn this.applySuggestion suggestion.name menu}}
+ @action={{fn this.applySuggestion suggestion menu}}
>
<span class="topic-count">x{{suggestion.count}}</span>
</DButton>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjs
index 320cd576707..e716b3f0d5f 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjs
@@ -85,7 +85,7 @@ export default class AiTagSuggester extends Component {
if (this.tagSelectorHasValues) {
this.suggestions = this.suggestions.filter(
- (s) => !this.model.get("tags").includes(s.name)
+ (s) => !model.get("tags").some((t) => t.id === s.id)
);
}
@@ -117,7 +117,7 @@ export default class AiTagSuggester extends Component {
const tags = this.model.get("tags");
if (!tags) {
- this.model.set("tags", [suggestion.name]);
+ this.model.set("tags", [suggestion]);
this.#removeAppliedTag(suggestion);
return;
}
@@ -134,7 +134,8 @@ export default class AiTagSuggester extends Component {
});
}
- this.model.set("tags", [...tags, suggestion.name]);
+ tags.push(suggestion);
+ this.model.set("tags", [...tags]);
suggestion.disabled = true;
this.#removeAppliedTag(suggestion);
}
diff --git a/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rb b/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rb
index 488741de83a..81d4197bcf8 100644
--- a/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rb
+++ b/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rb
@@ -91,8 +91,10 @@ module DiscourseAi
.then do |tags|
models = Tag.where(name: tags.map { _1[:name] }).index_by(&:name)
tags.map do |tag|
- tag[:id] = models.dig(tag[:name])&.id
- tag[:count] = models.dig(tag[:name])&.public_send(count_column) || 0
+ model = models.dig(tag[:name])
+ tag[:id] = model&.id
+ tag[:slug] = model&.slug
+ tag[:count] = model&.public_send(count_column) || 0
tag
end
end
diff --git a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
index 6e9401d97a4..a829f35fc0b 100644
--- a/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_helper/ai_composer_helper_spec.rb
@@ -345,9 +345,8 @@ RSpec.describe "AI Composer helper", type: :system do
response =
Tag
.take(7)
- .pluck(:name)
- .map { |s| { name: s, score: rand(0.0...45.0) } }
- .sort { |h| h[:score] }
+ .map { |t| { id: t.id, name: t.name, score: rand(0.0...45.0) } }
+ .sort_by { |h| h[:score] }
DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)
visit("/latest")
@@ -368,9 +367,8 @@ RSpec.describe "AI Composer helper", type: :system do
response =
Tag
.take(7)
- .pluck(:name)
- .map { |s| { name: s, score: rand(0.0...45.0) } }
- .sort { |h| h[:score] }
+ .map { |t| { id: t.id, name: t.name, score: rand(0.0...45.0) } }
+ .sort_by { |h| h[:score] }
DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)
topic_page.visit_topic(topic)
diff --git a/plugins/discourse-ai/spec/system/ai_helper/ai_split_topic_suggestion_spec.rb b/plugins/discourse-ai/spec/system/ai_helper/ai_split_topic_suggestion_spec.rb
index 7141b583895..f748f38a302 100644
--- a/plugins/discourse-ai/spec/system/ai_helper/ai_split_topic_suggestion_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_helper/ai_split_topic_suggestion_spec.rb
@@ -125,9 +125,8 @@ RSpec.describe "AI Post helper", type: :system do
response =
Tag
.take(5)
- .pluck(:name)
- .map { |s| { name: s, score: rand(0.0...45.0) } }
- .sort { |h| h[:score] }
+ .map { |t| { id: t.id, name: t.name, score: rand(0.0...45.0) } }
+ .sort_by { |h| h[:score] }
DiscourseAi::AiHelper::SemanticCategorizer.any_instance.stubs(:tags).returns(response)
open_move_topic_modal
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/category-calendar.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/category-calendar.gjs
index 76777e47eb6..8ad79ee6233 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/category-calendar.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/category-calendar.gjs
@@ -118,7 +118,10 @@ export default class CategoryCalendar extends Component {
if (post.topic.tags) {
const tagColorEntry = this.tagsColorsMap.find(
(entry) =>
- entry.type === "tag" && post.topic.tags.includes(entry.slug)
+ entry.type === "tag" &&
+ post.topic.tags.some(
+ (t) => (typeof t === "string" ? t : t.name) === entry.slug
+ )
);
backgroundColor = tagColorEntry ? tagColorEntry.color : null;
}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/upcoming-events-calendar.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/upcoming-events-calendar.gjs
index 16bdbbe0b6e..2b41f729361 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/upcoming-events-calendar.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/upcoming-events-calendar.gjs
@@ -67,7 +67,10 @@ export default class UpcomingEventsCalendar extends Component {
if (post?.topic?.tags) {
const tagColorEntry = tagsColorsMap.find(
(entry) =>
- entry.type === "tag" && post.topic.tags.includes(entry.slug)
+ entry.type === "tag" &&
+ post.topic.tags.some(
+ (t) => (typeof t === "string" ? t : t.name) === entry.slug
+ )
);
backgroundColor = tagColorEntry?.color;
}
diff --git a/plugins/discourse-rss-polling/app/controllers/discourse_rss_polling/feed_settings_controller.rb b/plugins/discourse-rss-polling/app/controllers/discourse_rss_polling/feed_settings_controller.rb
index 9ffb69e66e9..d556c44e85f 100644
--- a/plugins/discourse-rss-polling/app/controllers/discourse_rss_polling/feed_settings_controller.rb
+++ b/plugins/discourse-rss-polling/app/controllers/discourse_rss_polling/feed_settings_controller.rb
@@ -14,11 +14,12 @@ module DiscourseRssPolling
if feed
rss_feed = RssFeed.find_by_id(feed["id"]) || RssFeed.new
+ tags = feed["discourse_tags"]&.map { |t| t["name"] }&.join(",")
rss_feed.assign_attributes(
url: feed["feed_url"],
author: feed["author_username"],
category_id: feed["discourse_category_id"],
- tags: feed["discourse_tags"]&.join(","),
+ tags:,
category_filter: feed["feed_category_filter"],
)
if rss_feed.save
diff --git a/plugins/discourse-rss-polling/spec/system/admin_spec.rb b/plugins/discourse-rss-polling/spec/system/admin_spec.rb
index a67ae16b08c..31d1fc382b5 100644
--- a/plugins/discourse-rss-polling/spec/system/admin_spec.rb
+++ b/plugins/discourse-rss-polling/spec/system/admin_spec.rb
@@ -26,7 +26,7 @@ RSpec.describe "Rss Polling - admin", type: :system do
category.select_row_by_value(category_1.id)
tag = PageObjects::Components::SelectKit.new(".rss-polling-feed-tag")
tag.search(tag_1.name)
- tag.select_row_by_value(tag_1.name)
+ tag.select_row_by_name(tag_1.name)
find(".save-rss-polling-feed").click
expect(DiscourseRssPolling::RssFeed.last).to have_attributes(
diff --git a/spec/lib/discourse_tagging_spec.rb b/spec/lib/discourse_tagging_spec.rb
index 97c07075be4..cb270271823 100644
--- a/spec/lib/discourse_tagging_spec.rb
+++ b/spec/lib/discourse_tagging_spec.rb
@@ -1680,6 +1680,32 @@ RSpec.describe DiscourseTagging do
end
end
+ describe "tag_topic_by_ids" do
+ fab!(:topic)
+ fab!(:tag1) { Fabricate(:tag, name: "tag1") }
+ fab!(:tag2) { Fabricate(:tag, name: "tag2") }
+
+ it "tags a topic using tag IDs" do
+ valid = DiscourseTagging.tag_topic_by_ids(topic, Guardian.new(admin), [tag1.id, tag2.id])
+ expect(valid).to eq(true)
+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)
+ end
+
+ it "returns false for non-existent IDs" do
+ valid = DiscourseTagging.tag_topic_by_ids(topic, Guardian.new(admin), [-1])
+ expect(valid).to eq(true) # succeeds but with no tags
+ expect(topic.reload.tags).to be_empty
+ end
+
+ it "clears tags when given empty array" do
+ topic.tags = [tag1]
+ topic.save!
+ valid = DiscourseTagging.tag_topic_by_ids(topic, Guardian.new(admin), [])
+ expect(valid).to eq(true)
+ expect(topic.reload.tags).to be_empty
+ end
+ end
+
describe "#tags_for_saving" do
it "returns empty array if input is nil" do
expect(described_class.tags_for_saving(nil, guardian)).to eq([])
@@ -1879,10 +1905,22 @@ RSpec.describe DiscourseTagging do
end
end
- describe "#add_or_create_synonyms_by_name" do
+ describe "#add_or_create_synonyms" do
it "can add an existing tag" do
expect {
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name])).to eq(true)
+ expect(DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag2.name])).to eq(
+ true,
+ )
+ }.to_not change { Tag.count }
+ expect_same_tag_names(tag1.reload.synonyms, [tag2])
+ expect(tag2.reload.target_tag).to eq(tag1)
+ end
+
+ it "can add an existing tag by ID" do
+ expect {
+ expect(DiscourseTagging.add_or_create_synonyms(tag1, synonym_tag_ids: [tag2.id])).to eq(
+ true,
+ )
}.to_not change { Tag.count }
expect_same_tag_names(tag1.reload.synonyms, [tag2])
expect(tag2.reload.target_tag).to eq(tag1)
@@ -1891,7 +1929,9 @@ RSpec.describe DiscourseTagging do
it "can add an existing tag when both tags added to same topic" do
topic = Fabricate(:topic, tags: [tag1, tag2, tag3])
expect {
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name])).to eq(true)
+ expect(DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag2.name])).to eq(
+ true,
+ )
}.to_not change { Tag.count }
expect_same_tag_names(tag1.reload.synonyms, [tag2])
expect_same_tag_names(topic.reload.tags, [tag1, tag3])
@@ -1900,19 +1940,33 @@ RSpec.describe DiscourseTagging do
it "can add existing tag with wrong case" do
expect {
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name.upcase])).to eq(
- true,
- )
+ expect(
+ DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag2.name.upcase]),
+ ).to eq(true)
}.to_not change { Tag.count }
expect_same_tag_names(tag1.reload.synonyms, [tag2])
expect(tag2.reload.target_tag).to eq(tag1)
end
- it "removes target tag name from synonyms if present " do
+ it "removes target tag name from synonyms if present" do
expect {
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag1.name, tag2.name])).to eq(
- true,
- )
+ expect(
+ DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag1.name, tag2.name]),
+ ).to eq(true)
+ }.to_not change { Tag.count }
+ expect_same_tag_names(tag1.reload.synonyms, [tag2])
+ expect(tag2.reload.target_tag).to eq(tag1)
+ end
+
+ it "ignores target tag ID passed in synonym_tag_ids" do
+ expect {
+ expect(
+ DiscourseTagging.add_or_create_synonyms(
+ tag1,
+ synonym_tag_ids: [tag1.id, tag2.id],
+ new_synonym_names: [],
+ ),
+ ).to eq(true)
}.to_not change { Tag.count }
expect_same_tag_names(tag1.reload.synonyms, [tag2])
expect(tag2.reload.target_tag).to eq(tag1)
@@ -1922,9 +1976,9 @@ RSpec.describe DiscourseTagging do
tag4, tag5 = 2.times.collect { Fabricate(:tag) }
topic = Fabricate(:topic, tags: [tag2, tag3, tag4])
expect {
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name, tag3.name])).to eq(
- true,
- )
+ expect(
+ DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag2.name, tag3.name]),
+ ).to eq(true)
}.to_not change { Tag.count }
expect_same_tag_names(tag1.reload.synonyms, [tag2, tag3])
expect_same_tag_names(topic.reload.tags, [tag1, tag4])
@@ -1933,7 +1987,9 @@ RSpec.describe DiscourseTagging do
it "can create new tags" do
expect {
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, ["synonym1"])).to eq(true)
+ expect(
+ DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: ["synonym1"]),
+ ).to eq(true)
}.to change { Tag.count }.by(1)
s = Tag.where_name("synonym1").first
expect_same_tag_names(tag1.reload.synonyms, [s])
@@ -1943,7 +1999,23 @@ RSpec.describe DiscourseTagging do
it "can add existing and new tags" do
expect {
expect(
- DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name, "synonym1"]),
+ DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag2.name, "synonym1"]),
+ ).to eq(true)
+ }.to change { Tag.count }.by(1)
+ s = Tag.where_name("synonym1").first
+ expect_same_tag_names(tag1.reload.synonyms, [tag2, s])
+ expect(s.target_tag).to eq(tag1)
+ expect(tag2.reload.target_tag).to eq(tag1)
+ end
+
+ it "can add existing tags by ID and new tags by name" do
+ expect {
+ expect(
+ DiscourseTagging.add_or_create_synonyms(
+ tag1,
+ synonym_tag_ids: [tag2.id],
+ new_synonym_names: ["synonym1"],
+ ),
).to eq(true)
}.to change { Tag.count }.by(1)
s = Tag.where_name("synonym1").first
@@ -1955,7 +2027,9 @@ RSpec.describe DiscourseTagging do
it "can change a synonym's target tag" do
synonym = Fabricate(:tag, name: "synonym1", target_tag: tag1)
expect {
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag2, [synonym.name])).to eq(true)
+ expect(
+ DiscourseTagging.add_or_create_synonyms(tag2, new_synonym_names: [synonym.name]),
+ ).to eq(true)
}.to_not change { Tag.count }
expect_same_tag_names(tag2.reload.synonyms, [synonym])
expect(tag1.reload.synonyms.count).to eq(0)
@@ -1964,17 +2038,18 @@ RSpec.describe DiscourseTagging do
it "doesn't allow tags that have synonyms to become synonyms" do
tag2.synonyms << Fabricate(:tag)
- value = DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name])
- expect(value).to be_a(Array)
- expect(value.size).to eq(1)
- expect(value.first.errors[:target_tag_id]).to be_present
+ value = DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag2.name])
+ expect(value).to be_a(Hash)
+ expect(value).to have_key(tag2.name)
expect(tag1.reload.synonyms.count).to eq(0)
expect(tag2.reload.synonyms.count).to eq(1)
end
it "changes tag of topics" do
topic = Fabricate(:topic, tags: [tag2])
- expect(DiscourseTagging.add_or_create_synonyms_by_name(tag1, [tag2.name])).to eq(true)
+ expect(DiscourseTagging.add_or_create_synonyms(tag1, new_synonym_names: [tag2.name])).to eq(
+ true,
+ )
expect_same_tag_names(topic.reload.tags, [tag1])
tag1.reload
@@ -1987,5 +2062,27 @@ RSpec.describe DiscourseTagging do
expect(tag2.public_topic_count).to eq(0)
expect(tag2.staff_topic_count).to eq(0)
end
+
+ it "returns true for empty inputs" do
+ expect(DiscourseTagging.add_or_create_synonyms(tag1)).to eq(true)
+ expect(
+ DiscourseTagging.add_or_create_synonyms(tag1, synonym_tag_ids: [], new_synonym_names: []),
+ ).to eq(true)
+ expect(tag1.reload.synonyms.count).to eq(0)
+ end
+
+ it "deduplicates when same tag passed as both ID and name" do
+ expect {
+ expect(
+ DiscourseTagging.add_or_create_synonyms(
+ tag1,
+ synonym_tag_ids: [tag2.id],
+ new_synonym_names: [tag2.name],
+ ),
+ ).to eq(true)
+ }.to_not change { Tag.count }
+ expect_same_tag_names(tag1.reload.synonyms, [tag2])
+ expect(tag2.reload.target_tag).to eq(tag1)
+ end
end
end
diff --git a/spec/lib/post_revisor_spec.rb b/spec/lib/post_revisor_spec.rb
index 031eb634940..e8872576892 100644
--- a/spec/lib/post_revisor_spec.rb
+++ b/spec/lib/post_revisor_spec.rb
@@ -227,6 +227,12 @@ describe PostRevisor do
expect { post_revisor.revise!(admin, tags: ["new-tag"]) }.not_to change { Post.count }
end
+ it "accepts tags as integer IDs" do
+ tag = Fabricate(:tag)
+ post_revisor.revise!(admin, tags: [tag.id])
+ expect(post.topic.reload.tags).to contain_exactly(tag)
+ end
+
describe "when `create_post_for_category_and_tag_changes` site setting is enabled" do
fab!(:tag1) { Fabricate(:tag, name: "First tag") }
fab!(:tag2) { Fabricate(:tag, name: "Second tag") }
@@ -1046,14 +1052,49 @@ describe PostRevisor do
expect(post_revisor.raw_changed?).to eq(false)
post_revisor.revise!(admin, tags: %w[new-tag new-tag-2])
- expect(post.post_revisions.last.modifications).to eq("tags" => [[], %w[new-tag new-tag-2]])
+ expect(post.post_revisions.last.modifications).to eq(
+ "tags" => [["new-tag"], %w[new-tag new-tag-2]],
+ )
expect(post_revisor.raw_changed?).to eq(false)
post_revisor.revise!(admin, tags: ["new-tag-3"])
- expect(post.post_revisions.last.modifications).to eq("tags" => [[], ["new-tag-3"]])
+ expect(post.post_revisions.last.modifications).to eq(
+ "tags" => [%w[new-tag new-tag-2], ["new-tag-3"]],
+ )
expect(post_revisor.raw_changed?).to eq(false)
end
+ it "tracks tag changes by IDs (integers) with revision storing names" do
+ tag1 = Fabricate(:tag, name: "existing-tag")
+ tag2 = Fabricate(:tag, name: "another-tag")
+
+ post.topic.update!(tags: [tag1])
+
+ post_revisor.revise!(admin, tags: [tag2.id])
+
+ modifications = post.post_revisions.last.modifications
+ expect(modifications["tags"]).to eq([["existing-tag"], ["another-tag"]])
+ end
+
+ it "tracks tag changes from empty to tagged using IDs (integers)" do
+ tag = Fabricate(:tag, name: "new-via-id")
+
+ post_revisor.revise!(admin, tags: [tag.id])
+
+ modifications = post.post_revisions.last.modifications
+ expect(modifications["tags"]).to eq([[], ["new-via-id"]])
+ end
+
+ it "tracks tag changes from tagged to empty" do
+ tag = Fabricate(:tag, name: "will-remove")
+ post.topic.update!(tags: [tag])
+
+ post_revisor.revise!(admin, tags: [])
+
+ modifications = post.post_revisions.last.modifications
+ expect(modifications["tags"]).to eq([["will-remove"], []])
+ end
+
describe "#publish_changes" do
let!(:post) { Fabricate(:post, topic: topic) }
diff --git a/spec/lib/topic_creator_spec.rb b/spec/lib/topic_creator_spec.rb
index cf5fdc178b4..ac321300610 100644
--- a/spec/lib/topic_creator_spec.rb
+++ b/spec/lib/topic_creator_spec.rb
@@ -128,6 +128,17 @@ RSpec.describe TopicCreator do
expect(topic).to be_valid
expect(topic.tags.length).to eq(1)
end
+
+ it "user can add tags to topic using tag_ids" do
+ topic =
+ TopicCreator.create(
+ user,
+ Guardian.new(user),
+ valid_attrs.merge(tag_ids: [tag1.id, tag2.id]),
+ )
+ expect(topic).to be_valid
+ expect(topic.tags).to contain_exactly(tag1, tag2)
+ end
end
context "when assigned via matched watched words" do
diff --git a/spec/lib/topics_bulk_action_spec.rb b/spec/lib/topics_bulk_action_spec.rb
index d0a11ac6931..dedd026abe2 100644
--- a/spec/lib/topics_bulk_action_spec.rb
+++ b/spec/lib/topics_bulk_action_spec.rb
@@ -456,43 +456,24 @@ RSpec.describe TopicsBulkAction do
end
context "when the user can edit the topic" do
- context "when permitted to create new tags" do
- before { SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0] }
+ fab!(:tag3, :tag)
- it "changes tags and creates new ones" do
- topic_ids =
- TopicsBulkAction.new(
- topic.user,
- [topic.id],
- type: "change_tags",
- tags: ["newtag", tag1.name],
- ).perform!
-
- expect(topic_ids).to eq([topic.id])
- expect(topic.reload.tags.map(&:name)).to contain_exactly("newtag", tag1.name)
- end
- end
-
- context "when not permitted to create new tags" do
- before { SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_4] }
-
- it "changes to existing tags only" do
- topic_ids =
- TopicsBulkAction.new(
- topic.user,
- [topic.id],
- type: "change_tags",
- tags: ["newtag", tag1.name],
- ).perform!
+ it "changes tags to specified tags" do
+ topic_ids =
+ TopicsBulkAction.new(
+ topic.user,
+ [topic.id],
+ type: "change_tags",
+ tag_ids: [tag1.id, tag3.id],
+ ).perform!
- expect(topic_ids).to eq([topic.id])
- expect(topic.reload.tags.map(&:name)).to contain_exactly(tag1.name)
- end
+ expect(topic_ids).to eq([topic.id])
+ expect(topic.reload.tags).to contain_exactly(tag1, tag3)
end
it "removes all tags with empty array" do
topic_ids =
- TopicsBulkAction.new(topic.user, [topic.id], type: "change_tags", tags: []).perform!
+ TopicsBulkAction.new(topic.user, [topic.id], type: "change_tags", tag_ids: []).perform!
expect(topic_ids).to eq([topic.id])
expect(topic.reload.tags).to be_empty
@@ -500,6 +481,8 @@ RSpec.describe TopicsBulkAction do
end
context "when the user can't edit the topic" do
+ fab!(:tag3, :tag)
+
it "doesn't change the tags" do
Guardian.any_instance.expects(:can_edit?).returns(false)
@@ -508,11 +491,11 @@ RSpec.describe TopicsBulkAction do
topic.user,
[topic.id],
type: "change_tags",
- tags: ["newtag", tag1.name],
+ tag_ids: [tag3.id],
).perform!
expect(topic_ids).to eq([])
- expect(topic.reload.tags.map(&:name)).to contain_exactly(tag1.name, tag2.name)
+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)
end
end
end
@@ -529,51 +512,25 @@ RSpec.describe TopicsBulkAction do
end
context "when the user can edit the topic" do
- context "when permitted to create new tags" do
- before { SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_0] }
-
- it "appends new and existing tags" do
- topic_ids =
- TopicsBulkAction.new(
- topic.user,
- [topic.id],
- type: "append_tags",
- tags: [tag1.name, tag3.name, "newtag"],
- ).perform!
-
- expect(topic_ids).to eq([topic.id])
- expect(topic.reload.tags.map(&:name)).to contain_exactly(
- tag1.name,
- tag2.name,
- tag3.name,
- "newtag",
- )
- end
- end
-
- context "when not permitted to create new tags" do
- before { SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:trust_level_4] }
-
- it "appends only existing tags" do
- topic_ids =
- TopicsBulkAction.new(
- topic.user,
- [topic.id],
- type: "append_tags",
- tags: [tag3.name, "newtag"],
- ).perform!
+ it "appends existing tags" do
+ topic_ids =
+ TopicsBulkAction.new(
+ topic.user,
+ [topic.id],
+ type: "append_tags",
+ tag_ids: [tag3.id],
+ ).perform!
- expect(topic_ids).to eq([topic.id])
- expect(topic.reload.tags.map(&:name)).to contain_exactly(tag1.name, tag2.name, tag3.name)
- end
+ expect(topic_ids).to eq([topic.id])
+ expect(topic.reload.tags).to contain_exactly(tag1, tag2, tag3)
end
it "keeps existing tags when appending empty array" do
topic_ids =
- TopicsBulkAction.new(topic.user, [topic.id], type: "append_tags", tags: []).perform!
+ TopicsBulkAction.new(topic.user, [topic.id], type: "append_tags", tag_ids: []).perform!
expect(topic_ids).to eq([topic.id])
- expect(topic.reload.tags.map(&:name)).to contain_exactly(tag1.name, tag2.name)
+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)
end
end
@@ -586,11 +543,11 @@ RSpec.describe TopicsBulkAction do
topic.user,
[topic.id],
type: "append_tags",
- tags: ["newtag", tag3.name],
+ tag_ids: [tag3.id],
).perform!
expect(topic_ids).to eq([])
- expect(topic.reload.tags.map(&:name)).to contain_exactly(tag1.name, tag2.name)
+ expect(topic.reload.tags).to contain_exactly(tag1, tag2)
end
end
end
diff --git a/spec/models/form_template_spec.rb b/spec/models/form_template_spec.rb
index b71434cd93f..aace300434a 100644
--- a/spec/models/form_template_spec.rb
+++ b/spec/models/form_template_spec.rb
@@ -116,7 +116,11 @@ RSpec.describe FormTemplate, type: :model do
g1, g2 = YAML.safe_load(form_template.template)
- expect(g1["choices"]).to eq([tag1.name, tag2.name, tag3.name].sort)
+ expect(g1["choices"]).to contain_exactly(
+ { "id" => tag1.id, "name" => tag1.name },
+ { "id" => tag2.id, "name" => tag2.name },
+ { "id" => tag3.id, "name" => tag3.name },
+ )
expect(g2["attributes"]["tag_group"]).to eq(tag_group2.name)
expect(g2["attributes"]["multiple"]).to eq(true)
end
diff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rb
index 9eb69f224c1..18475626432 100644
--- a/spec/models/tag_spec.rb
+++ b/spec/models/tag_spec.rb
@@ -95,7 +95,9 @@ RSpec.describe Tag do
let!(:tags) { make_some_tags(tag_a_topic: true) }
it "returns all tags" do
- expect(Tag.top_tags.sort).to eq(tags.map(&:name).sort)
+ expect(Tag.top_tags).to contain_exactly(
+ *tags.map { |t| { id: t.id, name: t.name, slug: t.slug } },
+ )
end
end
@@ -117,20 +119,30 @@ RSpec.describe Tag do
end
it "works correctly" do
- expect(Tag.top_tags(category: category1).sort).to eq([tags[0].name].sort)
- expect(Tag.top_tags(guardian: Guardian.new(Fabricate(:admin))).sort).to eq(
- [tags[0].name, tags[1].name, tags[2].name].sort,
+ expect(Tag.top_tags(category: category1)).to eq(
+ [{ id: tags[0].id, name: tags[0].name, slug: tags[0].slug }],
+ )
+ expect(Tag.top_tags(guardian: Guardian.new(Fabricate(:admin)))).to contain_exactly(
+ { id: tags[0].id, name: tags[0].name, slug: tags[0].slug },
+ { id: tags[1].id, name: tags[1].name, slug: tags[1].slug },
+ { id: tags[2].id, name: tags[2].name, slug: tags[2].slug },
)
expect(
- Tag.top_tags(category: private_category, guardian: Guardian.new(Fabricate(:admin))).sort,
- ).to eq([tags[2].name].sort)
+ Tag.top_tags(category: private_category, guardian: Guardian.new(Fabricate(:admin))),
+ ).to eq([{ id: tags[2].id, name: tags[2].name, slug: tags[2].slug }])
- expect(Tag.top_tags.sort).to eq([tags[0].name, tags[1].name].sort)
+ expect(Tag.top_tags).to contain_exactly(
+ { id: tags[0].id, name: tags[0].name, slug: tags[0].slug },
+ { id: tags[1].id, name: tags[1].name, slug: tags[1].slug },
+ )
expect(Tag.top_tags(category: private_category)).to be_empty
sub_category = Fabricate(:category, parent_category_id: category1.id)
Fabricate(:topic, category: sub_category, tags: [tags[1]])
- expect(Tag.top_tags(category: category1).sort).to eq([tags[0].name, tags[1].name].sort)
+ expect(Tag.top_tags(category: category1)).to contain_exactly(
+ { id: tags[0].id, name: tags[0].name, slug: tags[0].slug },
+ { id: tags[1].id, name: tags[1].name, slug: tags[1].slug },
+ )
end
end
@@ -147,15 +159,24 @@ RSpec.describe Tag do
end
it "for category with restricted tags, lists those tags" do
- expect(Tag.top_tags(category: category1)).to eq([tags[0].name])
+ expect(Tag.top_tags(category: category1)).to eq(
+ [{ id: tags[0].id, name: tags[0].name, slug: tags[0].slug }],
+ )
end
it "for category without tags, lists allowed tags" do
- expect(Tag.top_tags(category: category2).sort).to eq([tags[1].name, tags[2].name].sort)
+ expect(Tag.top_tags(category: category2)).to contain_exactly(
+ { id: tags[1].id, name: tags[1].name, slug: tags[1].slug },
+ { id: tags[2].id, name: tags[2].name, slug: tags[2].slug },
+ )
end
it "for no category arg, lists all tags" do
- expect(Tag.top_tags.sort).to eq([tags[0].name, tags[1].name, tags[2].name].sort)
+ expect(Tag.top_tags).to contain_exactly(
+ { id: tags[2].id, name: tags[2].name, slug: tags[2].slug },
+ { id: tags[0].id, name: tags[0].name, slug: tags[0].slug },
+ { id: tags[1].id, name: tags[1].name, slug: tags[1].slug },
+ )
end
end
@@ -167,16 +188,20 @@ RSpec.describe Tag do
let!(:topic2) { Fabricate(:topic, tags: [tag, hidden_tag]) }
it "returns all tags to staff" do
- expect(Tag.top_tags(guardian: Guardian.new(Fabricate(:admin)))).to include(hidden_tag.name)
+ expect(Tag.top_tags(guardian: Guardian.new(Fabricate(:admin)))).to include(
+ { id: hidden_tag.id, name: hidden_tag.name, slug: hidden_tag.slug },
+ )
end
it "doesn't return hidden tags to anon" do
- expect(Tag.top_tags).to_not include(hidden_tag.name)
+ expect(Tag.top_tags).to_not include(
+ { id: hidden_tag.id, name: hidden_tag.name, slug: hidden_tag.slug },
+ )
end
it "doesn't return hidden tags to non-staff" do
expect(Tag.top_tags(guardian: Guardian.new(Fabricate(:user)))).to_not include(
- hidden_tag.name,
+ { id: hidden_tag.id, name: hidden_tag.name, slug: hidden_tag.slug },
)
end
end
diff --git a/spec/models/tag_user_spec.rb b/spec/models/tag_user_spec.rb
index d12edbd7394..370beb8ec49 100644
--- a/spec/models/tag_user_spec.rb
+++ b/spec/models/tag_user_spec.rb
@@ -366,10 +366,10 @@ RSpec.describe TagUser do
end
it "every tag from the default_tags_* site settings get overridden to watching_first_post, except for muted" do
levels = TagUser.notification_levels_for(user)
- expect(levels[tag1.name]).to eq(TagUser.notification_levels[:regular])
- expect(levels[tag2.name]).to eq(TagUser.notification_levels[:regular])
- expect(levels[tag3.name]).to eq(TagUser.notification_levels[:regular])
- expect(levels[tag4.name]).to eq(TagUser.notification_levels[:muted])
+ expect(levels[tag1.id]).to eq(TagUser.notification_levels[:regular])
+ expect(levels[tag2.id]).to eq(TagUser.notification_levels[:regular])
+ expect(levels[tag3.id]).to eq(TagUser.notification_levels[:regular])
+ expect(levels[tag4.id]).to eq(TagUser.notification_levels[:muted])
end
end
@@ -402,11 +402,11 @@ RSpec.describe TagUser do
include tags the user is not tracking at all" do
tag5 = Fabricate(:tag)
levels = TagUser.notification_levels_for(user)
- expect(levels[tag1.name]).to eq(TagUser.notification_levels[:watching])
- expect(levels[tag2.name]).to eq(TagUser.notification_levels[:tracking])
- expect(levels[tag3.name]).to eq(TagUser.notification_levels[:watching_first_post])
- expect(levels[tag4.name]).to eq(TagUser.notification_levels[:muted])
- expect(levels.key?(tag5.name)).to eq(false)
+ expect(levels[tag1.id]).to eq(TagUser.notification_levels[:watching])
+ expect(levels[tag2.id]).to eq(TagUser.notification_levels[:tracking])
+ expect(levels[tag3.id]).to eq(TagUser.notification_levels[:watching_first_post])
+ expect(levels[tag4.id]).to eq(TagUser.notification_levels[:muted])
+ expect(levels.key?(tag5.id)).to eq(false)
end
it "does not show a tag is tracked if the user does not belong to the tag group with permissions" do
@@ -414,7 +414,7 @@ RSpec.describe TagUser do
tag_group = Fabricate(:tag_group, tags: [tag2], permissions: { group.name => 1 })
expect(TagUser.notification_levels_for(user).keys).to match_array(
- [tag1.name, tag3.name, tag4.name],
+ [tag1.id, tag3.id, tag4.id],
)
end
end
diff --git a/spec/models/topic_list_spec.rb b/spec/models/topic_list_spec.rb
index fde5e45c35c..f7f533c2fde 100644
--- a/spec/models/topic_list_spec.rb
+++ b/spec/models/topic_list_spec.rb
@@ -72,8 +72,12 @@ RSpec.describe TopicList do
it "should return the right tags" do
tag = Fabricate(:tag, topics: [topic])
other_tag = Fabricate(:tag, topics: [topic], name: "use-anywhere")
- output = [tag.name, other_tag.name]
- expect(topic_list.top_tags.sort).to eq(output.sort)
+ expect(topic_list.top_tags).to eq(
+ [
+ { id: tag.id, name: tag.name, slug: tag.slug },
+ { id: other_tag.id, name: other_tag.name, slug: other_tag.slug },
+ ],
+ )
end
describe "when there are tags restricted to a category" do
@@ -93,12 +97,20 @@ RSpec.describe TopicList do
end
it "should return tags used in the category" do
- expect(topic_list.top_tags).to eq([tag.name, other_tag.name].sort)
+ expect(topic_list.top_tags).to eq(
+ [
+ { id: tag.id, name: tag.name, slug: tag.slug },
+ { id: other_tag.id, name: other_tag.name, slug: other_tag.slug },
+ ],
+ )
end
it "with no category, should return all tags" do
- expect(TopicList.new("latest", other_topic.user, [other_topic]).top_tags.sort).to eq(
- [tag.name, other_tag.name].sort,
+ expect(TopicList.new("latest", other_topic.user, [other_topic]).top_tags).to eq(
+ [
+ { id: tag.id, name: tag.name, slug: tag.slug },
+ { id: other_tag.id, name: other_tag.name, slug: other_tag.slug },
+ ],
)
end
diff --git a/spec/models/topic_tracking_state_spec.rb b/spec/models/topic_tracking_state_spec.rb
index b95f7dd0554..a549775bfa3 100644
--- a/spec/models/topic_tracking_state_spec.rb
+++ b/spec/models/topic_tracking_state_spec.rb
@@ -82,6 +82,32 @@ RSpec.describe TopicTrackingState do
describe ".publish_new" do
include_examples("publishes message to right groups and users", "/new", :publish_new)
include_examples("does not publish message for private topics", :publish_new)
+
+ it "includes tags as objects with id when tagging is enabled" do
+ SiteSetting.tagging_enabled = true
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
+ topic.tags = [tag1, tag2]
+ topic.save!
+
+ message = MessageBus.track_publish("/new") { described_class.publish_new(topic) }.first
+
+ expect(message.data["payload"]["tags"]).to contain_exactly(
+ { "id" => tag1.id },
+ { "id" => tag2.id },
+ )
+ end
+
+ it "does not include tags when tagging is disabled" do
+ SiteSetting.tagging_enabled = false
+ tag = Fabricate(:tag)
+ topic.tags = [tag]
+ topic.save!
+
+ message = MessageBus.track_publish("/new") { described_class.publish_new(topic) }.first
+
+ expect(message.data["payload"]["tags"]).to be_nil
+ end
end
describe ".publish_latest" do
@@ -100,6 +126,21 @@ RSpec.describe TopicTrackingState do
expect(message.user_ids).to eq(nil)
end
+ it "includes tags as objects with id when tagging is enabled" do
+ SiteSetting.tagging_enabled = true
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
+ topic.tags = [tag1, tag2]
+ topic.save!
+
+ message = MessageBus.track_publish("/latest") { described_class.publish_latest(topic) }.first
+
+ expect(message.data["payload"]["tags"]).to contain_exactly(
+ { "id" => tag1.id },
+ { "id" => tag2.id },
+ )
+ end
+
it "publishes whisper post to staff users and members of whisperers group" do
whisperers_group = Fabricate(:group)
Fabricate(:user, groups: [whisperers_group])
@@ -178,6 +219,22 @@ RSpec.describe TopicTrackingState do
expect(data["payload"]["archetype"]).to eq(Archetype.default)
end
+ it "includes tags as objects with id when tagging is enabled" do
+ SiteSetting.tagging_enabled = true
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
+ topic.tags = [tag1, tag2]
+ topic.save!
+
+ message =
+ MessageBus.track_publish("/unread") { TopicTrackingState.publish_unread(post) }.first
+
+ expect(message.data["payload"]["tags"]).to contain_exactly(
+ { "id" => tag1.id },
+ { "id" => tag2.id },
+ )
+ end
+
it "does not publish unread to the user who created the post" do
message =
MessageBus.track_publish("/unread") { TopicTrackingState.publish_unread(post) }.first
@@ -708,7 +765,7 @@ RSpec.describe TopicTrackingState do
report = TopicTrackingState.report(user)
expect(report.length).to eq(1)
row = report[0]
- expect(row.tags).to contain_exactly("apples", "bananas")
+ expect(row.tags.map { |t| t["name"] }).to contain_exactly("apples", "bananas")
end
end
diff --git a/spec/models/web_hook_spec.rb b/spec/models/web_hook_spec.rb
index 19c68c1de67..a5a87b9230a 100644
--- a/spec/models/web_hook_spec.rb
+++ b/spec/models/web_hook_spec.rb
@@ -236,7 +236,9 @@ RSpec.describe WebHook do
expect(job_args["event_name"]).to eq("topic_edited")
payload = JSON.parse(job_args["payload"])
expect(payload["id"]).to eq(topic_id)
- expect(payload["tags"]).to contain_exactly(tag.name)
+ expect(payload["tags"]).to contain_exactly(
+ { "id" => tag.id, "name" => tag.name, "slug" => tag.slug },
+ )
end
it "should enqueue granular hooks for topic" do
diff --git a/spec/requests/admin/embeddable_hosts_controller_spec.rb b/spec/requests/admin/embeddable_hosts_controller_spec.rb
index 9df7ef634ca..a4854288e53 100644
--- a/spec/requests/admin/embeddable_hosts_controller_spec.rb
+++ b/spec/requests/admin/embeddable_hosts_controller_spec.rb
@@ -23,14 +23,14 @@ RSpec.describe Admin::EmbeddableHostsController do
end
it "creates an embeddable host with associated tags" do
- tag1 = Fabricate(:tag, name: "tag1")
- tag2 = Fabricate(:tag, name: "tag2")
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
post "/admin/embeddable_hosts.json",
params: {
embeddable_host: {
host: "example.com",
- tags: %w[tag1 tag2],
+ tags: [tag1.id, tag2.id],
},
}
@@ -39,14 +39,14 @@ RSpec.describe Admin::EmbeddableHostsController do
end
it "updates an embeddable host with associated tags" do
- tag1 = Fabricate(:tag, name: "newTag1")
- tag2 = Fabricate(:tag, name: "newTag2")
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
put "/admin/embeddable_hosts/#{embeddable_host.id}.json",
params: {
embeddable_host: {
host: "updated-example.com",
- tags: %w[newTag1 newTag2],
+ tags: [tag1.id, tag2.id],
},
}
diff --git a/spec/requests/admin/form_templates_controller_spec.rb b/spec/requests/admin/form_templates_controller_spec.rb
index 382c12bd1cd..bf376d4a53f 100644
--- a/spec/requests/admin/form_templates_controller_spec.rb
+++ b/spec/requests/admin/form_templates_controller_spec.rb
@@ -204,7 +204,11 @@ RSpec.describe Admin::FormTemplatesController do
expect(response.status).to eq(200)
processed_tag_group =
YAML.safe_load(response.parsed_body["form_template"]["template"]).first
- expect(processed_tag_group["choices"]).to eq([tag1.name, tag2.name, tag3.name].sort)
+ expect(processed_tag_group["choices"]).to contain_exactly(
+ { "id" => tag1.id, "name" => tag1.name },
+ { "id" => tag2.id, "name" => tag2.name },
+ { "id" => tag3.id, "name" => tag3.name },
+ )
end
it "rejects invalid templates" do
diff --git a/spec/requests/admin/staff_action_logs_controller_spec.rb b/spec/requests/admin/staff_action_logs_controller_spec.rb
index 056e482491c..f55c7f7014c 100644
--- a/spec/requests/admin/staff_action_logs_controller_spec.rb
+++ b/spec/requests/admin/staff_action_logs_controller_spec.rb
@@ -333,6 +333,47 @@ RSpec.describe Admin::StaffActionLogsController do
expect(parsed["side_by_side"]).to include("<del>#{tag1.name}</del>")
expect(parsed["side_by_side"]).to include("<ins>#{tag3.name}</ins>")
end
+
+ it "generates diffs for old tag_group format with tag_names" do
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
+ tag3 = Fabricate(:tag)
+
+ old_json = {
+ name: "old_group",
+ tag_names: [tag1.name, tag2.name],
+ parent_tag_name: [],
+ one_per_topic: false,
+ permissions: {
+ "0" => 1,
+ },
+ }.to_json
+
+ new_json = {
+ name: "new_group",
+ tag_names: [tag2.name, tag3.name],
+ parent_tag_name: [],
+ one_per_topic: false,
+ permissions: {
+ "0" => 1,
+ },
+ }.to_json
+
+ record =
+ StaffActionLogger.new(Discourse.system_user).log_tag_group_change(
+ "new_group",
+ old_json,
+ new_json,
+ )
+
+ get "/admin/logs/staff_action_logs/#{record.id}/diff.json"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expect(parsed["side_by_side"]).to include("<h3>tag_names</h3>")
+ expect(parsed["side_by_side"]).to include("<del>#{tag1.name}</del>")
+ expect(parsed["side_by_side"]).to include("<ins>#{tag3.name}</ins>")
+ end
end
context "when logged in as an admin" do
diff --git a/spec/requests/api/schemas/json/category_topics_response.json b/spec/requests/api/schemas/json/category_topics_response.json
index 8f15282e8ad..3b38142d00e 100644
--- a/spec/requests/api/schemas/json/category_topics_response.json
+++ b/spec/requests/api/schemas/json/category_topics_response.json
@@ -47,7 +47,21 @@
},
"top_tags": {
"type": "array",
- "items": {}
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "name", "slug"]
+ }
},
"topics": {
"type": "array",
diff --git a/spec/requests/api/schemas/json/search_response.json b/spec/requests/api/schemas/json/search_response.json
index 12a87342136..2385318180d 100644
--- a/spec/requests/api/schemas/json/search_response.json
+++ b/spec/requests/api/schemas/json/search_response.json
@@ -22,7 +22,19 @@
"tags": {
"type": "array",
"items": {
-
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "name", "slug"]
}
},
"groups": {
diff --git a/spec/requests/api/schemas/json/site_response.json b/spec/requests/api/schemas/json/site_response.json
index 801f956f13f..2406de6e04e 100644
--- a/spec/requests/api/schemas/json/site_response.json
+++ b/spec/requests/api/schemas/json/site_response.json
@@ -480,7 +480,19 @@
"top_tags": {
"type": "array",
"items": {
-
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "name", "slug"]
}
},
"wizard_required": {
diff --git a/spec/requests/api/schemas/json/tag_group_create_response.json b/spec/requests/api/schemas/json/tag_group_create_response.json
index 4be34b4204b..03982cceb0f 100644
--- a/spec/requests/api/schemas/json/tag_group_create_response.json
+++ b/spec/requests/api/schemas/json/tag_group_create_response.json
@@ -11,16 +11,28 @@
"name": {
"type": "string"
},
- "tag_names": {
+ "tags": {
"type": "array",
"items": {
-
+ "type": "object",
+ "properties": {
+ "id": { "type": "integer" },
+ "name": { "type": "string" },
+ "slug": { "type": "string" }
+ },
+ "required": ["id", "name", "slug"]
}
},
- "parent_tag_name": {
+ "parent_tag": {
"type": "array",
"items": {
-
+ "type": "object",
+ "properties": {
+ "id": { "type": "integer" },
+ "name": { "type": "string" },
+ "slug": { "type": "string" }
+ },
+ "required": ["id", "name", "slug"]
}
},
"one_per_topic": {
@@ -33,8 +45,8 @@
"required": [
"id",
"name",
- "tag_names",
- "parent_tag_name",
+ "tags",
+ "parent_tag",
"one_per_topic",
"permissions"
]
diff --git a/spec/requests/api/schemas/json/tag_groups_list_response.json b/spec/requests/api/schemas/json/tag_groups_list_response.json
index 22e85a7e6da..382c1d8102b 100644
--- a/spec/requests/api/schemas/json/tag_groups_list_response.json
+++ b/spec/requests/api/schemas/json/tag_groups_list_response.json
@@ -13,16 +13,30 @@
"name": {
"type": "string"
},
- "tag_names": {
+ "tags": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "id": { "type": "integer" },
+ "name": { "type": "string" },
+ "slug": { "type": "string" }
+ },
+ "required": ["id", "name", "slug"]
}
},
- "parent_tag_name": {
+ "parent_tag": {
"type": "array",
"items": {
- "type": "string"
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "id": { "type": "integer" },
+ "name": { "type": "string" },
+ "slug": { "type": "string" }
+ },
+ "required": ["id", "name", "slug"]
}
},
"one_per_topic": {
@@ -38,8 +52,8 @@
"required": [
"id",
"name",
- "tag_names",
- "parent_tag_name",
+ "tags",
+ "parent_tag",
"one_per_topic",
"permissions"
]
diff --git a/spec/requests/api/schemas/json/topic_show_response.json b/spec/requests/api/schemas/json/topic_show_response.json
index 1286d4a1089..bbaa657533d 100644
--- a/spec/requests/api/schemas/json/topic_show_response.json
+++ b/spec/requests/api/schemas/json/topic_show_response.json
@@ -389,7 +389,21 @@
},
"tags": {
"type": "array",
- "items": {}
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "name", "slug"]
+ }
},
"tags_descriptions": {
"type": "object",
@@ -491,7 +505,21 @@
},
"tags": {
"type": "array",
- "items": {}
+ "items": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string"
+ }
+ },
+ "required": ["id", "name", "slug"]
+ }
},
"tags_descriptions": {
"type": "object",
diff --git a/spec/requests/drafts_controller_spec.rb b/spec/requests/drafts_controller_spec.rb
index b5fac339d71..35a28c59272 100644
--- a/spec/requests/drafts_controller_spec.rb
+++ b/spec/requests/drafts_controller_spec.rb
@@ -146,7 +146,11 @@ RSpec.describe DraftsController do
it "checks for a tag conflict on update" do
sign_in(user)
+ tag1 = Fabricate(:tag, name: "tag1")
+ tag2 = Fabricate(:tag, name: "tag2")
post = Fabricate(:post, user:)
+ # topic has different tags than original_tags in draft
+ post.topic.tags = [tag1]
post "/drafts.json",
params: {
@@ -197,6 +201,32 @@ RSpec.describe DraftsController do
expect(response.parsed_body["conflict_user"]).to eq(nil)
end
+ it "handles tag objects format when checking for tag conflict" do
+ sign_in(user)
+ tag1 = Fabricate(:tag)
+ tag2 = Fabricate(:tag)
+ post = Fabricate(:post, user:)
+ post.topic.tags = [tag1, tag2]
+
+ post "/drafts.json",
+ params: {
+ draft_key: "topic",
+ sequence: 0,
+ data: {
+ postId: post.id,
+ original_text: post.raw,
+ original_tags: [
+ { "id" => tag1.id, "name" => tag1.name, "slug" => tag1.name },
+ { "id" => tag2.id, "name" => tag2.name, "slug" => tag2.name },
+ ],
+ action: "edit",
+ }.to_json,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["conflict_user"]).to eq(nil)
+ end
+
it "cant trivially resolve conflicts without interaction" do
sign_in(user)
diff --git a/spec/requests/form_templates_controller_spec.rb b/spec/requests/form_templates_controller_spec.rb
index d2b9a432517..e029ac9cdae 100644
--- a/spec/requests/form_templates_controller_spec.rb
+++ b/spec/requests/form_templates_controller_spec.rb
@@ -134,8 +134,14 @@ RSpec.describe FormTemplatesController do
# It excludes synonyms
expect(parsed_template[0]["choices"].count).to eq(2)
- expect(parsed_template[0]["choices"]).to eq([tag1.name, tag3.name])
- expect(parsed_template[1]["choices"]).to eq([tag2.name, tag4.name])
+ expect(parsed_template[0]["choices"]).to contain_exactly(
+ { "id" => tag1.id, "name" => tag1.name },
+ { "id" => tag3.id, "name" => tag3.name },
+ )
+ expect(parsed_template[1]["choices"]).to contain_exactly(
+ { "id" => tag2.id, "name" => tag2.name },
+ { "id" => tag4.id, "name" => tag4.name },
+ )
end
it "should return a single template with the correct data in order" do
@@ -149,7 +155,13 @@ RSpec.describe FormTemplatesController do
current_template = json["form_template"]
parsed_template = YAML.safe_load(current_template["template"])
- expect(parsed_template[0]["choices"]).to eq([tag1.name, new_tag.name, tag3.name])
+ expect(parsed_template[0]["choices"]).to eq(
+ [
+ { "id" => tag1.id, "name" => tag1.name },
+ { "id" => new_tag.id, "name" => new_tag.name },
+ { "id" => tag3.id, "name" => tag3.name },
+ ],
+ )
end
end
end
diff --git a/spec/requests/list_controller_spec.rb b/spec/requests/list_controller_spec.rb
index e4f27f5364c..213a8312652 100644
--- a/spec/requests/list_controller_spec.rb
+++ b/spec/requests/list_controller_spec.rb
@@ -231,7 +231,9 @@ RSpec.describe ListController do
body = response.parsed_body
expect(body["topic_list"]["topics"].map { |t| t["id"] }).to contain_exactly(topic.id)
- expect(body["topic_list"]["topics"][0]["tags"]).to contain_exactly(tag.name)
+ expect(body["topic_list"]["topics"][0]["tags"]).to contain_exactly(
+ { "id" => tag.id, "name" => tag.name, "slug" => tag.slug },
+ )
end.count
tag2 = Fabricate(:tag)
@@ -250,8 +252,12 @@ RSpec.describe ListController do
topic2.id,
)
- expect(body["topic_list"]["topics"][0]["tags"]).to contain_exactly(tag2.name)
- expect(body["topic_list"]["topics"][1]["tags"]).to contain_exactly(tag.name)
+ expect(body["topic_list"]["topics"][0]["tags"]).to contain_exactly(
+ { "id" => tag2.id, "name" => tag2.name, "slug" => tag2.slug },
+ )
+ expect(body["topic_list"]["topics"][1]["tags"]).to contain_exactly(
+ { "id" => tag.id, "name" => tag.name, "slug" => tag.slug },
+ )
end.count
expect(new_sql_queries_count).to eq(initial_sql_queries_count)
diff --git a/spec/requests/tag_groups_controller_spec.rb b/spec/requests/tag_groups_controller_spec.rb
index e39abc7ca2a..02c7efa06ac 100644
--- a/spec/requests/tag_groups_controller_spec.rb
+++ b/spec/requests/tag_groups_controller_spec.rb
@@ -66,7 +66,7 @@ RSpec.describe TagGroupsController do
end
context "for anons" do
- it "returns the tag group with the associated tag names" do
+ it "returns the tag group with the associated tags" do
tag_group = tag_group_with_permission(everyone, readonly)
tag_group2 = tag_group_with_permission(everyone, readonly)
@@ -76,8 +76,8 @@ RSpec.describe TagGroupsController do
results = JSON.parse(response.body, symbolize_names: true).fetch(:results)
expect(results).to contain_exactly(
- { name: tag_group.name, tag_names: [tag.name] },
- { name: tag_group2.name, tag_names: [tag.name] },
+ { name: tag_group.name, tags: [{ id: tag.id, name: tag.name }] },
+ { name: tag_group2.name, tags: [{ id: tag.id, name: tag.name }] },
)
end
@@ -96,7 +96,7 @@ RSpec.describe TagGroupsController do
context "for regular users" do
before { sign_in(user) }
- it "returns the tag group with the associated tag names" do
+ it "returns the tag group" do
tag_group = tag_group_with_permission(everyone, readonly)
get "/tag_groups/filter/search.json"
@@ -105,7 +105,6 @@ RSpec.describe TagGroupsController do
results = JSON.parse(response.body, symbolize_names: true).fetch(:results)
expect(results.first[:name]).to eq(tag_group.name)
- expect(results.first[:tag_names]).to contain_exactly(tag.name)
end
it "returns an empty array if the tag group is private" do
@@ -173,7 +172,10 @@ RSpec.describe TagGroupsController do
params: {
tag_group: {
name: "test_tag_group_log",
- tag_names: [tag1.name, tag2.name],
+ tags: [
+ { id: tag1.id, name: tag1.name, slug: tag1.slug },
+ { id: tag2.id, name: tag2.name, slug: tag2.slug },
+ ],
},
}
@@ -200,7 +202,9 @@ RSpec.describe TagGroupsController do
}
expect(response.status).to eq(200)
- expect(response.parsed_body["tag_group"]["parent_tag_name"]).to eq([parent_tag.name])
+ expect(response.parsed_body["tag_group"]["parent_tag"]).to eq(
+ [{ "id" => parent_tag.id, "name" => parent_tag.name, "slug" => parent_tag.slug }],
+ )
expect(TagGroup.last.parent_tag).to eq(parent_tag)
end
end
@@ -250,7 +254,10 @@ RSpec.describe TagGroupsController do
params: {
tag_group: {
name: "test_tag_group_new_name",
- tag_names: [tag2.name, tag3.name],
+ tags: [
+ { id: tag2.id, name: tag2.name, slug: tag2.slug },
+ { id: tag3.id, name: tag3.name, slug: tag3.slug },
+ ],
},
}
@@ -275,7 +282,9 @@ RSpec.describe TagGroupsController do
}
expect(response.status).to eq(200)
- expect(response.parsed_body["tag_group"]["parent_tag_name"]).to eq([parent_tag.name])
+ expect(response.parsed_body["tag_group"]["parent_tag"]).to eq(
+ [{ "id" => parent_tag.id, "name" => parent_tag.name, "slug" => parent_tag.slug }],
+ )
expect(tag_group.reload.parent_tag).to eq(parent_tag)
end
end
diff --git a/spec/requests/tags_controller_spec.rb b/spec/requests/tags_controller_spec.rb
index 1c2bc813446..3ff09e08466 100644
--- a/spec/requests/tags_controller_spec.rb
+++ b/spec/requests/tags_controller_spec.rb
@@ -1261,6 +1261,16 @@ RSpec.describe TagsController do
expect(response.status).to eq(200)
expect(response.parsed_body["results"].map { |t| t["name"] }).to contain_exactly(tag2.name)
expect(response.parsed_body["required_tag_group"]).to eq(nil)
+
+ get "/tags/filter/search.json",
+ params: {
+ q: "",
+ categoryId: category.id,
+ filterForInput: true,
+ selected_tag_ids: [tag1.id],
+ }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["results"].map { |t| t["name"] }).to contain_exactly(tag2.name)
end
end
end
@@ -1473,7 +1483,40 @@ RSpec.describe TagsController do
context "when signed in as admin" do
before { sign_in(admin) }
- it "can make a tag a synonym of another tag" do
+ it "can make an existing tag a synonym using tags array with id" do
+ tag2 = Fabricate(:tag)
+ expect {
+ post "/tag/#{tag.name}/synonyms.json",
+ params: {
+ tags: [{ id: tag2.id, name: tag2.name }],
+ }
+ }.to_not change { Tag.count }
+ expect(response.status).to eq(200)
+ expect(tag2.reload.target_tag).to eq(tag)
+ end
+
+ it "can create new tags using tags array without id" do
+ expect {
+ post "/tag/#{tag.name}/synonyms.json", params: { tags: [{ name: "new-synonym" }] }
+ }.to change { Tag.count }.by(1)
+ expect(response.status).to eq(200)
+ expect(Tag.find_by_name("new-synonym")&.target_tag).to eq(tag)
+ end
+
+ it "can use both existing and new tags together in tags array" do
+ tag2 = Fabricate(:tag)
+ expect {
+ post "/tag/#{tag.name}/synonyms.json",
+ params: {
+ tags: [{ id: tag2.id, name: tag2.name }, { name: "new-synonym" }],
+ }
+ }.to change { Tag.count }.by(1)
+ expect(response.status).to eq(200)
+ expect(tag2.reload.target_tag).to eq(tag)
+ expect(Tag.find_by_name("new-synonym")&.target_tag).to eq(tag)
+ end
+
+ it "can make a tag a synonym of another tag (deprecated synonyms param)" do
tag2 = Fabricate(:tag)
expect {
post "/tag/#{tag.name}/synonyms.json", params: { synonyms: [tag2.name] }
@@ -1482,7 +1525,7 @@ RSpec.describe TagsController do
expect(tag2.reload.target_tag).to eq(tag)
end
- it "can create new tags at the same time" do
+ it "can create new tags at the same time (deprecated synonyms param)" do
expect {
post "/tag/#{tag.name}/synonyms.json", params: { synonyms: ["synonym"] }
}.to change { Tag.count }.by(1)
@@ -1493,7 +1536,7 @@ RSpec.describe TagsController do
it "can return errors" do
_tag2 = Fabricate(:tag, target_tag: tag)
tag3 = Fabricate(:tag)
- post "/tag/#{tag3.name}/synonyms.json", params: { synonyms: [tag.name] }
+ post "/tag/#{tag3.name}/synonyms.json", params: { tags: [{ id: tag.id, name: tag.name }] }
expect(response.status).to eq(200)
expect(response.parsed_body["failed"]).to be_present
expect(response.parsed_body.dig("failed_tags", tag.name)).to be_present
@@ -1566,7 +1609,7 @@ RSpec.describe TagsController do
expect(response.status).to eq(200)
expect(response.parsed_body["watched_tags"]).to eq([])
expect(response.parsed_body["watching_first_post_tags"]).to eq([])
- expect(response.parsed_body["tracked_tags"]).to eq([tag.name])
+ expect(response.parsed_body["tracked_tags"]).to eq([tag.id])
expect(response.parsed_body["muted_tags"]).to eq([])
expect(response.parsed_body["regular_tags"]).to eq([])
@@ -1587,7 +1630,7 @@ RSpec.describe TagsController do
expect(response.parsed_body["watched_tags"]).to eq([])
expect(response.parsed_body["watching_first_post_tags"]).to eq([])
expect(response.parsed_body["tracked_tags"]).to eq([])
- expect(response.parsed_body["muted_tags"]).to eq([tag.name])
+ expect(response.parsed_body["muted_tags"]).to eq([tag.id])
expect(response.parsed_body["regular_tags"]).to eq([])
end.to change { user.tag_users.count }.by(1)
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index 71da064ad27..3fd5a82dd1f 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -200,6 +200,26 @@ RSpec.describe TopicsController do
expect(Tag.all.pluck(:name)).to include("foo", "bar")
end
+ it "moves posts to new topic with existing tags" do
+ tag1 = Fabricate(:tag, name: "existing-tag")
+ tag2 = Fabricate(:tag, name: "another-tag")
+
+ post "/t/#{topic.id}/move-posts.json",
+ params: {
+ title: "Topic with tags",
+ post_ids: [p2.id],
+ category_id: category.id,
+ tag_ids: [tag1.id, tag2.id],
+ }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result["success"]).to eq(true)
+
+ new_topic = Topic.last
+ expect(new_topic.tags).to contain_exactly(tag1, tag2)
+ end
+
describe "with freeze_original param" do
it "duplicates post to new topic and keeps original post in place" do
expect do
@@ -2120,6 +2140,15 @@ RSpec.describe TopicsController do
expect(topic.tags.pluck(:id)).to contain_exactly(tag.id)
end
+ it "can update tags using tag_ids" do
+ expect do put "/t/#{topic.id}/tags.json", params: { tag_ids: [tag.id] } end.to change {
+ topic.reload.first_post.revisions.count
+ }.by(1)
+
+ expect(response.status).to eq(200)
+ expect(topic.tags.pluck(:id)).to contain_exactly(tag.id)
+ end
+
it "does not remove tag if no params is given" do
topic.tags << tag
@@ -4073,6 +4102,44 @@ RSpec.describe TopicsController do
expect(TopicUser.get(post1.topic, post1.user).last_read_post_number).to eq(2)
end
+ it "can append tags" do
+ SiteSetting.tagging_enabled = true
+ SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]
+ tag1 = Fabricate(:tag)
+ topic.update!(user:)
+
+ put "/topics/bulk.json",
+ params: {
+ topic_ids: [topic.id],
+ operation: {
+ type: "append_tags",
+ tag_ids: [tag1.id],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(topic.reload.tags).to include(tag1)
+ end
+
+ it "can append tags with tag names for backward compatibility" do
+ SiteSetting.tagging_enabled = true
+ SiteSetting.tag_topic_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]
+ tag1 = Fabricate(:tag)
+ topic.update!(user:)
+
+ put "/topics/bulk.json",
+ params: {
+ topic_ids: [topic.id],
+ operation: {
+ type: "append_tags",
+ tags: [tag1.name],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(topic.reload.tags).to include(tag1)
+ end
+
context "with private message" do
fab!(:group) do
Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone]).tap do |g|
diff --git a/spec/serializers/current_user_serializer_spec.rb b/spec/serializers/current_user_serializer_spec.rb
index 490134f4783..456d6116c72 100644
--- a/spec/serializers/current_user_serializer_spec.rb
+++ b/spec/serializers/current_user_serializer_spec.rb
@@ -75,9 +75,9 @@ RSpec.describe CurrentUserSerializer do
)
end
- it "includes muted tag names" do
+ it "includes muted tag ids" do
payload = serializer.as_json
- expect(payload[:muted_tags]).to eq([tag.name])
+ expect(payload[:muted_tags]).to eq([tag.id])
end
end
diff --git a/spec/serializers/reviewable_serializer_spec.rb b/spec/serializers/reviewable_serializer_spec.rb
index 4d29fe1dadf..18be85a4c09 100644
--- a/spec/serializers/reviewable_serializer_spec.rb
+++ b/spec/serializers/reviewable_serializer_spec.rb
@@ -96,4 +96,14 @@ RSpec.describe ReviewableSerializer do
end
end
end
+
+ describe "topic_tags" do
+ it "returns tag objects with id, name, and slug" do
+ SiteSetting.tagging_enabled = true
+ tag = Fabricate(:tag)
+ reviewable.topic.tags = [tag]
+ json = described_class.new(reviewable, scope: Guardian.new(admin), root: nil).as_json
+ expect(json[:topic_tags]).to eq([{ id: tag.id, name: tag.name, slug: tag.slug }])
+ end
+ end
end
diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rb
index f7de1d9d276..2b1e089c068 100644
--- a/spec/serializers/site_serializer_spec.rb
+++ b/spec/serializers/site_serializer_spec.rb
@@ -58,7 +58,7 @@ RSpec.describe SiteSerializer do
serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
c1 = serialized[:categories].find { |c| c[:id] == category.id }
- expect(c1[:allowed_tags]).to contain_exactly(tag.name)
+ expect(c1[:allowed_tags]).to contain_exactly({ id: tag.id, name: tag.name, slug: tag.slug })
expect(c1[:allowed_tag_groups]).to contain_exactly(tag_group.name)
expect(c1[:required_tag_groups]).to eq([{ name: tag_group_2.name, min_count: 1 }])
end
@@ -188,8 +188,14 @@ RSpec.describe SiteSerializer do
expect(serialized[:anonymous_default_navigation_menu_tags]).to eq(
[
- { name: "dev", description: "some description", pm_only: false },
- { name: "random", description: tag2.description, pm_only: false },
+ { id: tag.id, name: "dev", slug: "dev", description: "some description", pm_only: false },
+ {
+ id: tag2.id,
+ name: "random",
+ slug: "random",
+ description: tag2.description,
+ pm_only: false,
+ },
],
)
end
@@ -308,7 +314,12 @@ RSpec.describe SiteSerializer do
serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
- expect(serialized[:top_tags]).to eq([tag3.name, tag2.name])
+ expect(serialized[:top_tags]).to eq(
+ [
+ { id: tag3.id, name: tag3.name, slug: tag3.slug },
+ { id: tag2.id, name: tag2.name, slug: tag2.slug },
+ ],
+ )
end
end
end
@@ -339,9 +350,27 @@ RSpec.describe SiteSerializer do
expect(serialized[:navigation_menu_site_top_tags]).to eq(
[
- { name: tag3.name, description: tag2.description, pm_only: false },
- { name: tag1.name, description: tag1.description, pm_only: false },
- { name: tag2.name, description: tag3.description, pm_only: false },
+ {
+ id: tag3.id,
+ name: tag3.name,
+ slug: tag3.slug,
+ description: tag2.description,
+ pm_only: false,
+ },
+ {
+ id: tag1.id,
+ name: tag1.name,
+ slug: tag1.slug,
+ description: tag1.description,
+ pm_only: false,
+ },
+ {
+ id: tag2.id,
+ name: tag2.name,
+ slug: tag2.slug,
+ description: tag3.description,
+ pm_only: false,
+ },
],
)
end
diff --git a/spec/serializers/suggested_topic_serializer_spec.rb b/spec/serializers/suggested_topic_serializer_spec.rb
index e5f6885caf5..7c9a8d8ba5b 100644
--- a/spec/serializers/suggested_topic_serializer_spec.rb
+++ b/spec/serializers/suggested_topic_serializer_spec.rb
@@ -56,7 +56,9 @@ RSpec.describe SuggestedTopicSerializer do
it "returns hidden tag to staff" do
json = SuggestedTopicSerializer.new(topic, scope: Guardian.new(admin), root: false).as_json
- expect(json[:tags]).to eq([hidden_tag.name])
+ expect(json[:tags]).to eq(
+ [{ id: hidden_tag.id, name: hidden_tag.name, slug: hidden_tag.slug }],
+ )
end
it "does not return hidden tag to non-staff" do
diff --git a/spec/serializers/tag_group_serializer_spec.rb b/spec/serializers/tag_group_serializer_spec.rb
index 1165583371f..51bb49a3853 100644
--- a/spec/serializers/tag_group_serializer_spec.rb
+++ b/spec/serializers/tag_group_serializer_spec.rb
@@ -21,6 +21,6 @@ RSpec.describe TagGroupSerializer do
synonym = Fabricate(:tag, target_tag: tag)
tag_group = Fabricate(:tag_group, tags: [tag, synonym])
serialized = TagGroupSerializer.new(tag_group, root: false).as_json
- expect(serialized[:tag_names]).to contain_exactly(tag.name)
+ expect(serialized[:tags]).to contain_exactly({ id: tag.id, name: tag.name, slug: tag.slug })
end
end
diff --git a/spec/serializers/tag_serializer_spec.rb b/spec/serializers/tag_serializer_spec.rb
index ea976c0580d..80297a2ec75 100644
--- a/spec/serializers/tag_serializer_spec.rb
+++ b/spec/serializers/tag_serializer_spec.rb
@@ -9,6 +9,13 @@ RSpec.describe TagSerializer do
fab!(:topic_in_public_category) { Fabricate(:topic, tags: [tag]) }
fab!(:topic_in_private_category) { Fabricate(:topic, category: private_category, tags: [tag]) }
+ describe "#slug" do
+ it "includes the slug attribute" do
+ serialized = described_class.new(tag, scope: Guardian.new(user), root: false).as_json
+ expect(serialized[:slug]).to eq(tag.slug)
+ end
+ end
+
describe "#topic_count" do
it "should return the value of `Tag#public_topic_count` for a non-staff user" do
serialized = described_class.new(tag, scope: Guardian.new(user), root: false).as_json
diff --git a/spec/serializers/topic_list_item_serializer_spec.rb b/spec/serializers/topic_list_item_serializer_spec.rb
index 75fc09613d4..1f16100cfb6 100644
--- a/spec/serializers/topic_list_item_serializer_spec.rb
+++ b/spec/serializers/topic_list_item_serializer_spec.rb
@@ -58,7 +58,9 @@ RSpec.describe TopicListItemSerializer do
it "returns hidden tag to staff" do
json = TopicListItemSerializer.new(topic, scope: Guardian.new(admin), root: false).as_json
- expect(json[:tags]).to eq([hidden_tag.name])
+ expect(json[:tags]).to eq(
+ [{ id: hidden_tag.id, name: hidden_tag.name, slug: hidden_tag.slug }],
+ )
end
it "trucates description" do
diff --git a/spec/serializers/topic_tracking_state_item_serializer_spec.rb b/spec/serializers/topic_tracking_state_item_serializer_spec.rb
index b64a99df1f7..9546884700f 100644
--- a/spec/serializers/topic_tracking_state_item_serializer_spec.rb
+++ b/spec/serializers/topic_tracking_state_item_serializer_spec.rb
@@ -31,6 +31,6 @@ RSpec.describe TopicTrackingStateItemSerializer do
report = TopicTrackingState.report(user)
serialized = described_class.new(report[0], scope: Guardian.new(user), root: false).as_json
- expect(serialized[:tags]).to contain_exactly("bananas", "apples")
+ expect(serialized[:tags].map { |t| t["name"] }).to contain_exactly("bananas", "apples")
end
end
diff --git a/spec/serializers/topic_view_serializer_spec.rb b/spec/serializers/topic_view_serializer_spec.rb
index aa621f5adce..e436d313d71 100644
--- a/spec/serializers/topic_view_serializer_spec.rb
+++ b/spec/serializers/topic_view_serializer_spec.rb
@@ -217,7 +217,7 @@ RSpec.describe TopicViewSerializer do
it "should include the tag for staff users" do
[moderator, admin].each do |user|
json = serialize_topic(pm, user)
- expect(json[:tags]).to eq([tag.name])
+ expect(json[:tags]).to eq([{ id: tag.id, name: tag.name, slug: tag.slug }])
end
end
@@ -226,7 +226,7 @@ RSpec.describe TopicViewSerializer do
user.group_users << Fabricate(:group_user, group: group, user: user)
json = serialize_topic(pm_between_reg_users, user)
- expect(json[:tags]).to eq([tag.name])
+ expect(json[:tags]).to eq([{ id: tag.id, name: tag.name, slug: tag.slug }])
json = serialize_topic(pm_between_reg_users, user_2)
expect(json[:tags]).to eq(nil)
@@ -252,7 +252,9 @@ RSpec.describe TopicViewSerializer do
it "returns hidden tag to staff" do
json = serialize_topic(topic, admin)
- expect(json[:tags]).to eq([hidden_tag.name])
+ expect(json[:tags]).to eq(
+ [{ id: hidden_tag.id, name: hidden_tag.name, slug: hidden_tag.slug }],
+ )
end
it "does not return hidden tag to non-staff" do
@@ -298,7 +300,13 @@ RSpec.describe TopicViewSerializer do
it "tags are automatically sorted by tag popularity" do
json = serialize_topic(topic, user)
- expect(json[:tags]).to eq(%w[btag ctag atag])
+ expect(json[:tags]).to eq(
+ [
+ { id: tag2.id, name: "btag", slug: "btag" },
+ { id: tag1.id, name: "ctag", slug: "ctag" },
+ { id: tag3.id, name: "atag", slug: "atag" },
+ ],
+ )
expect(json[:tags_descriptions]).to eq(
{ btag: "b description", ctag: "c description", atag: "a description" },
)
@@ -307,7 +315,13 @@ RSpec.describe TopicViewSerializer do
it "tags can be sorted alphabetically" do
SiteSetting.tags_sort_alphabetically = true
json = serialize_topic(topic, user)
- expect(json[:tags]).to eq(%w[atag btag ctag])
+ expect(json[:tags]).to eq(
+ [
+ { id: tag3.id, name: "atag", slug: "atag" },
+ { id: tag2.id, name: "btag", slug: "btag" },
+ { id: tag1.id, name: "ctag", slug: "ctag" },
+ ],
+ )
end
end
diff --git a/spec/serializers/user_serializer_spec.rb b/spec/serializers/user_serializer_spec.rb
index 3037362db4a..5859d9b7c5e 100644
--- a/spec/serializers/user_serializer_spec.rb
+++ b/spec/serializers/user_serializer_spec.rb
@@ -173,10 +173,10 @@ RSpec.describe UserSerializer do
notification_level: TagUser.notification_levels[:watching_first_post],
)
- expect(json[:muted_tags]).to eq([tag1.name])
- expect(json[:tracked_tags]).to eq([tag2.name])
- expect(json[:watched_tags]).to eq([tag3.name])
- expect(json[:watching_first_post_tags]).to eq([tag4.name])
+ expect(json[:muted_tags]).to eq([tag1.id])
+ expect(json[:tracked_tags]).to eq([tag2.id])
+ expect(json[:watched_tags]).to eq([tag3.id])
+ expect(json[:watching_first_post_tags]).to eq([tag4.id])
end
end
diff --git a/spec/support/shared_examples/user_sidebar_serializer_attributes.rb b/spec/support/shared_examples/user_sidebar_serializer_attributes.rb
index 6713466cf6c..becce818edf 100644
--- a/spec/support/shared_examples/user_sidebar_serializer_attributes.rb
+++ b/spec/support/shared_examples/user_sidebar_serializer_attributes.rb
@@ -81,8 +81,14 @@ RSpec.shared_examples "User Sidebar Serializer Attributes" do |serializer_klass|
json = serializer.as_json
expect(json[:sidebar_tags]).to contain_exactly(
- { name: tag.name, pm_only: false, description: tag.description },
- { name: pm_tag.name, pm_only: true, description: nil },
+ {
+ id: tag.id,
+ name: tag.name,
+ slug: tag.slug,
+ pm_only: false,
+ description: tag.description,
+ },
+ { id: pm_tag.id, name: pm_tag.name, slug: pm_tag.slug, pm_only: true, description: nil },
)
user.update!(admin: true)
@@ -90,9 +96,21 @@ RSpec.shared_examples "User Sidebar Serializer Attributes" do |serializer_klass|
json = serializer.as_json
expect(json[:sidebar_tags]).to contain_exactly(
- { name: tag.name, pm_only: false, description: tag.description },
- { name: pm_tag.name, pm_only: true, description: nil },
- { name: hidden_tag.name, pm_only: false, description: nil },
+ {
+ id: tag.id,
+ name: tag.name,
+ slug: tag.slug,
+ pm_only: false,
+ description: tag.description,
+ },
+ { id: pm_tag.id, name: pm_tag.name, slug: pm_tag.slug, pm_only: true, description: nil },
+ {
+ id: hidden_tag.id,
+ name: hidden_tag.name,
+ slug: hidden_tag.slug,
+ pm_only: false,
+ description: nil,
+ },
)
end
end
diff --git a/spec/system/composer_spec.rb b/spec/system/composer_spec.rb
index fd58b26267f..c3e5bf1968f 100644
--- a/spec/system/composer_spec.rb
+++ b/spec/system/composer_spec.rb
@@ -90,4 +90,36 @@ describe "Composer", type: :system do
expect(composer.reply_button_focused?).to eq(true)
end
+
+ context "with tagging enabled" do
+ fab!(:tag) { Fabricate(:tag, name: "test-tag") }
+ fab!(:category)
+ let(:mini_tag_chooser) { PageObjects::Components::SelectKit.new(".mini-tag-chooser") }
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ category.set_permissions(everyone: :full)
+ category.save!
+ end
+
+ it "creates a topic with tags" do
+ page.visit "/new-topic"
+ expect(composer).to be_opened
+
+ composer.fill_title("Test topic with tags")
+ composer.fill_content("This is a test topic with tags")
+ composer.switch_category(category.name)
+
+ mini_tag_chooser.expand
+ mini_tag_chooser.search(tag.name)
+ mini_tag_chooser.select_row_by_name(tag.name)
+ mini_tag_chooser.collapse
+
+ composer.create
+
+ expect(topic_page).to have_topic_title("Test topic with tags")
+ expect(topic_page.topic_tags).to include(tag.name)
+ end
+ end
end
diff --git a/spec/system/discovery_breadcrumb_navigation_spec.rb b/spec/system/discovery_breadcrumb_navigation_spec.rb
index b1c7b882ccb..afe5564e76f 100644
--- a/spec/system/discovery_breadcrumb_navigation_spec.rb
+++ b/spec/system/discovery_breadcrumb_navigation_spec.rb
@@ -62,7 +62,7 @@ describe "Navigating with breadcrumbs", type: :system do
expect(discovery.topic_list).to have_topics(count: 2)
expect(discovery.tag_drop).to have_selected_name("tags")
- discovery.tag_drop.select_row_by_value(tag.name)
+ discovery.tag_drop.select_row_by_name(tag.name)
expect(discovery.topic_list).to have_topics(count: 1)
expect(discovery.topic_list).to have_topic(c1_topic_tagged)
@@ -76,7 +76,7 @@ describe "Navigating with breadcrumbs", type: :system do
expect(discovery.subcategory_drop).to have_selected_name("no subcategories")
expect(discovery.tag_drop).to have_selected_name("tags")
- discovery.tag_drop.select_row_by_value(tag.name)
+ discovery.tag_drop.select_row_by_name(tag.name)
expect(page).to have_current_path(
"/tags/c/#{category3.slug}/#{category3.id}/none/#{tag.name}",
diff --git a/spec/system/page_objects/pages/admin_embedding_host_form.rb b/spec/system/page_objects/pages/admin_embedding_host_form.rb
index ca91e7e1cae..45c9b246731 100644
--- a/spec/system/page_objects/pages/admin_embedding_host_form.rb
+++ b/spec/system/page_objects/pages/admin_embedding_host_form.rb
@@ -26,7 +26,7 @@ module PageObjects
dropdown = PageObjects::Components::SelectKit.new(".admin-embedding-host-form__tags")
dropdown.expand
dropdown.search(tag.name)
- dropdown.select_row_by_value(tag.name)
+ dropdown.select_row_by_name(tag.name)
dropdown.collapse
self
end
diff --git a/spec/system/page_objects/pages/form_template.rb b/spec/system/page_objects/pages/form_template.rb
index 9ce754b8f07..f371bab2a15 100644
--- a/spec/system/page_objects/pages/form_template.rb
+++ b/spec/system/page_objects/pages/form_template.rb
@@ -84,7 +84,7 @@ module PageObjects
end
def has_tag_chooser_tag?(tag)
- find("option[value=#{tag.name} i]", visible: :all).present?
+ find("option[value='#{tag.id}']", visible: :all).present?
end
def has_preview_modal?
diff --git a/spec/system/search_spec.rb b/spec/system/search_spec.rb
index 589350a718b..953c80a2eed 100644
--- a/spec/system/search_spec.rb
+++ b/spec/system/search_spec.rb
@@ -260,7 +260,7 @@ describe "Search", type: :system do
expect(topic_bulk_actions_modal).to be_open
tag_selector = PageObjects::Components::SelectKit.new(".tag-chooser")
tag_selector.search(tag1.name)
- tag_selector.select_row_by_value(tag1.name)
+ tag_selector.select_row_by_name(tag1.name)
tag_selector.collapse
topic_bulk_actions_modal.click_bulk_topics_confirm
expect(
diff --git a/spec/system/tag_synonyms_spec.rb b/spec/system/tag_synonyms_spec.rb
index 8a0e2d07d9c..5661260fbbf 100644
--- a/spec/system/tag_synonyms_spec.rb
+++ b/spec/system/tag_synonyms_spec.rb
@@ -29,7 +29,7 @@ describe "Tag synonyms", type: :system do
tags_page.edit_synonyms_btn.click
# searched tag doesn't exist but will show option to create tag
tags_page.search_tags("graphics")
- tags_page.select_tag(value: "graphics")
+ tags_page.select_tag(name: "graphics")
tags_page.add_synonym_btn.click
tags_page.confirm_synonym_btn.click
diff --git a/spec/system/tag_view_spec.rb b/spec/system/tag_view_spec.rb
index 945bb9a65c8..7c729e2c4a8 100644
--- a/spec/system/tag_view_spec.rb
+++ b/spec/system/tag_view_spec.rb
@@ -21,7 +21,7 @@ describe "Tag view", type: :system do
tags_page.tags_dropdown.expand
tags_page.tags_dropdown.search(tag_2.name)
- tags_page.tags_dropdown.select_row_by_value(tag_2.name)
+ tags_page.tags_dropdown.select_row_by_name(tag_2.name)
expect(topic_list).to have_topic(topic)
expect(tags_page.tag_name_within_tag_info).to eq(tag_2.name)
diff --git a/spec/system/tags/tags_spec.rb b/spec/system/tags/tags_spec.rb
index b56aa927930..d51c8977f71 100644
--- a/spec/system/tags/tags_spec.rb
+++ b/spec/system/tags/tags_spec.rb
@@ -234,5 +234,34 @@ describe "Tags", type: :system do
expect(topic_page.topic_tags).to include("tag-one", "tag-three")
expect(topic_page.topic_tags).not_to include("tag-two")
end
+
+ it "saves draft correctly when editing topic with tags" do
+ topic = Fabricate(:topic, user: admin, tags: [tag_one, tag_two])
+ Fabricate(:post, topic: topic, user: admin)
+ toasts = PageObjects::Components::Toasts.new
+
+ sign_in(admin)
+ visit topic.url
+
+ find("#post_1 .post-controls .edit").click
+ expect(composer).to be_opened
+
+ # wait for composer to load topic data including tags
+ # this ensures originalTags is set from topic.tags
+ expect(page).to have_css(".mini-tag-chooser", text: "tag-one")
+
+ composer.fill_content("Updated content for draft test")
+
+ draft = nil
+ try_until_success(reason: "saving a draft") do
+ draft = Draft.find_by(user: admin)
+ expect(draft).to be_present
+ end
+
+ # check that original_tags is in the draft data as tag objects
+ draft_data = JSON.parse(draft.data)
+ original_tag_ids = draft_data["original_tags"].map { |t| t["id"] }
+ expect(original_tag_ids).to contain_exactly(tag_one.id, tag_two.id)
+ end
end
end
diff --git a/spec/system/tags_intersection_spec.rb b/spec/system/tags_intersection_spec.rb
index 987a8f9627c..64031bf3a53 100644
--- a/spec/system/tags_intersection_spec.rb
+++ b/spec/system/tags_intersection_spec.rb
@@ -4,13 +4,13 @@ describe "Tags intersection", type: :system do
let(:discovery) { PageObjects::Pages::Discovery.new }
fab!(:category) { Fabricate(:category, name: "fruits") }
- fab!(:some_topic) { Fabricate(:topic, category: category) }
fab!(:tag) { Fabricate(:tag, name: "sour") }
fab!(:tag2) { Fabricate(:tag, name: "tangy") }
- fab!(:some_topic) { Fabricate(:topic, tags: [tag, tag2]) }
+ fab!(:tag3) { Fabricate(:tag, name: "sweet") }
- fab!(:the_topic) { Fabricate(:topic, category: category, tags: [tag, tag2]) }
+ fab!(:tagged_topic) { Fabricate(:topic, tags: [tag, tag2, tag3]) }
+ fab!(:the_topic) { Fabricate(:topic, category:, tags: [tag, tag2, tag3]) }
it "filters by category" do
visit("/tags/intersection/sour/tangy?category=fruits")
@@ -50,4 +50,19 @@ describe "Tags intersection", type: :system do
visit("/tags/intersection/sour/tangy/tangy/tangy")
expect(page).to have_current_path("/tags/intersection/sour/tangy")
end
+
+ it "navigates correctly when adding and removing tags from the intersection chooser" do
+ visit("/tags/intersection/sour/tangy")
+
+ chooser = PageObjects::Components::SelectKit.new(".tags-intersection-chooser")
+ chooser.expand
+ chooser.select_row_by_name("sweet")
+
+ expect(page).to have_current_path("/tags/intersection/sour/tangy/sweet")
+ expect(discovery.topic_list).to have_topics(count: 2)
+
+ chooser.unselect_by_name("tangy")
+
+ expect(page).to have_current_path("/tags/intersection/sour/sweet")
+ end
end
diff --git a/spec/system/topic_bulk_select_spec.rb b/spec/system/topic_bulk_select_spec.rb
index 1b54911421e..453dcb9e334 100644
--- a/spec/system/topic_bulk_select_spec.rb
+++ b/spec/system/topic_bulk_select_spec.rb
@@ -97,9 +97,9 @@ describe "Topic bulk select", type: :system do
topic_bulk_actions_modal.tag_selector.expand
topic_bulk_actions_modal.tag_selector.search(tag1.name)
- topic_bulk_actions_modal.tag_selector.select_row_by_value(tag1.name)
+ topic_bulk_actions_modal.tag_selector.select_row_by_name(tag1.name)
topic_bulk_actions_modal.tag_selector.search(tag2.name)
- topic_bulk_actions_modal.tag_selector.select_row_by_value(tag2.name)
+ topic_bulk_actions_modal.tag_selector.select_row_by_name(tag2.name)
topic_bulk_actions_modal.click_bulk_topics_confirm
@@ -149,9 +149,9 @@ describe "Topic bulk select", type: :system do
topic_bulk_actions_modal.tag_selector.expand
topic_bulk_actions_modal.tag_selector.search(restricted_tag.name)
- topic_bulk_actions_modal.tag_selector.select_row_by_value(restricted_tag.name)
+ topic_bulk_actions_modal.tag_selector.select_row_by_name(restricted_tag.name)
topic_bulk_actions_modal.tag_selector.search(tag1.name)
- topic_bulk_actions_modal.tag_selector.select_row_by_value(tag1.name)
+ topic_bulk_actions_modal.tag_selector.select_row_by_name(tag1.name)
topic_bulk_actions_modal.click_bulk_topics_confirm