Skip to content

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

DEV: Move canonical tag routes to /tag/slug/id keeping /tag/name support (#37055)

Natalie Tay737577e8b47f
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index 8092e0dadfd..acd38334ee0 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -30,7 +30,17 @@ class TagsController < ::ApplicationController
list
]
- before_action :fetch_tag, only: %i[info create_synonyms destroy_synonym]
+ before_action :fetch_tag,
+ only: %i[
+ info
+ update
+ destroy
+ tag_feed
+ notifications
+ update_notifications
+ create_synonyms
+ destroy_synonym
+ ]
after_action :add_noindex_header, except: %i[index show]
@@ -142,21 +152,19 @@ class TagsController < ::ApplicationController
Discourse.filters.each do |filter|
define_method("show_#{filter}") do
- parent_tag_name =
- Tag
- .where_name(params[:tag_name])
- .where.not(target_tag_id: nil)
- .joins(
- "JOIN tags parent_tags ON parent_tags.id = tags.target_tag_id AND tags.target_tag_id != tags.id",
- )
- .pick("parent_tags.name")
+ fetch_tag(raise_not_found: false)
+
+ if @tag
+ if @tag.target_tag_id.present? && @tag.target_tag_id != @tag.id
+ return redirect_to_correct_tag(@tag.target_tag, filter: filter == :latest ? nil : filter)
+ end
- if parent_tag_name
- params[:tag_name] = parent_tag_name
- return redirect_to url_for(params.to_unsafe_hash)
+ if should_redirect_tag?(@tag)
+ return redirect_to_correct_tag(@tag, filter: filter == :latest ? nil : filter)
+ end
end
- @tag_name = params[:tag_name].force_encoding("UTF-8")
+ @tag_name = @tag&.name || params[:tag_name]&.force_encoding("UTF-8")
@additional_tags =
params[:additional_tag_names].to_s.split("/").map { |t| t.force_encoding("UTF-8") }
@@ -195,11 +203,11 @@ class TagsController < ::ApplicationController
@title = I18n.t("rss_by_tag", tag: tag_params.join(" & "))
@description_meta = Tag.where(name: @tag_name).pick(:description) || @title
- canonical_params = params.slice(:category_slug_path_with_id, :tag_name)
+ canonical_params = params.slice(:category_slug_path_with_id, :tag_slug, :tag_id)
canonical_method = url_method(canonical_params)
canonical_url "#{Discourse.base_url_no_prefix}#{public_send(canonical_method, *(canonical_params.values.map { |t| t.force_encoding("UTF-8") }))}"
- if @list.topics.size == 0 && params[:tag_name] != "none" && !Tag.where_name(@tag_name).exists?
+ if @list.topics.size == 0 && @tag_name != "none" && !Tag.where_name(@tag_name).exists?
raise Discourse::NotFound.new("tag not found", check_permalinks: true)
else
respond_with_list(@list)
@@ -222,31 +230,35 @@ class TagsController < ::ApplicationController
Discourse.deprecate(warning, since: "2025.12.0-latest", drop_from: "2026.2.0-latest")
return render_json_error(warning)
end
- tag_name_param = params[:tag_name]
new_tag = params[:tag]
new_tag_name = new_tag[:name]
new_tag_description = new_tag[:description]
- tag = Tag.find_by_name(tag_name_param)
- raise Discourse::NotFound if tag.nil?
-
- guardian.ensure_can_edit_tag!(tag)
+ guardian.ensure_can_edit_tag!(@tag)
- tag.name = DiscourseTagging.clean_tag(new_tag_name) if new_tag_name.present?
- tag.description = new_tag_description if new_tag_description.present?
+ previous_tag_name = @tag.name
+ @tag.name = DiscourseTagging.clean_tag(new_tag_name) if new_tag_name.present?
+ @tag.description = new_tag_description if new_tag_description.present?
- if tag.save
- if tag.name != tag_name_param
+ if @tag.save
+ if @tag.name != previous_tag_name
StaffActionLogger.new(current_user).log_custom(
"renamed_tag",
- previous_value: tag_name_param,
- new_value: tag.name,
+ previous_value: previous_tag_name,
+ new_value: @tag.name,
)
end
- render json: { tag: { id: tag.id, name: tag.name, description: tag.description } }
+ render json: {
+ tag: {
+ id: @tag.id,
+ name: @tag.name,
+ slug: @tag.slug,
+ description: @tag.description,
+ },
+ }
else
- render_json_error tag.errors.full_messages
+ render_json_error @tag.errors.full_messages
end
end
@@ -310,12 +322,10 @@ class TagsController < ::ApplicationController
def destroy
guardian.ensure_can_admin_tags!
- tag_name = params[:tag_name]
- tag = Tag.find_by_name(tag_name)
- raise Discourse::NotFound if tag.nil?
+ tag_name = @tag.name
TopicCustomField.transaction do
- tag.destroy
+ @tag.destroy
StaffActionLogger.new(current_user).log_custom("deleted_tag", subject: tag_name)
end
render json: success_json
@@ -324,13 +334,12 @@ class TagsController < ::ApplicationController
def tag_feed
discourse_expires_in 1.minute
- tag_name = params[:tag_name]
- @link = "#{Discourse.base_url}/tag/#{tag_name}"
- @description = I18n.t("rss_by_tag", tag: tag_name)
+ @link = @tag.full_url
+ @description = I18n.t("rss_by_tag", tag: @tag.name)
@title = "#{SiteSetting.title} - #{@description}"
- @atom_link = "#{Discourse.base_url}/tag/#{tag_name}.rss"
+ @atom_link = "#{@tag.full_url}.rss"
- query = TopicQuery.new(current_user, tags: [tag_name])
+ query = TopicQuery.new(current_user, tags: [@tag.name])
latest_results = query.latest_results
@topic_list = query.create_list(:by_tag, {}, latest_results)
@@ -423,25 +432,27 @@ class TagsController < ::ApplicationController
end
def notifications
- tag = Tag.where_name(params[:tag_name]).first
- raise Discourse::NotFound unless tag
+ if should_redirect_tag?(@tag)
+ url = "#{@tag.url}/notifications"
+ url += ".json" if request.format.json?
+ return redirect_to url, status: :moved_permanently
+ end
+
level =
- tag.tag_users.where(user: current_user).first.try(:notification_level) ||
+ @tag.tag_users.where(user: current_user).first.try(:notification_level) ||
TagUser.notification_levels[:regular]
render json: {
tag_notification: {
- id: tag.id,
- name: tag.name,
+ id: @tag.id,
+ name: @tag.name,
notification_level: level.to_i,
},
}
end
def update_notifications
- tag = Tag.find_by_name(params[:tag_name])
- raise Discourse::NotFound unless tag
level = params[:tag_notification][:notification_level].to_i
- TagUser.change(current_user.id, tag.id, level)
+ TagUser.change(current_user.id, @tag.id, level)
render_serialized(current_user, UserTagNotificationsSerializer, root: false)
end
@@ -481,7 +492,7 @@ class TagsController < ::ApplicationController
end
def destroy_synonym
- synonym = Tag.where_name(params[:synonym_id]).first
+ synonym = Tag.find_by(id: params[:synonym_id])
raise Discourse::NotFound unless synonym
guardian.ensure_can_edit_tag!(synonym)
@@ -496,9 +507,54 @@ class TagsController < ::ApplicationController
private
- def fetch_tag
- @tag = Tag.find_by_name(params[:tag_name].force_encoding("UTF-8"))
- raise Discourse::NotFound unless @tag
+ def fetch_tag(raise_not_found: true)
+ @tag =
+ if params[:tag_id].present?
+ Tag.find_by(id: params[:tag_id])
+ elsif params[:tag_name].present?
+ Tag.find_by_name(params[:tag_name].force_encoding("UTF-8"))
+ end
+ raise Discourse::NotFound if raise_not_found && @tag.nil?
+ @tag
+ end
+
+ def redirect_to_correct_tag(tag, filter: nil)
+ # handle synonyms - redirect to parent
+ tag = tag.target_tag if tag.target_tag_id.present?
+
+ url = tag.url
+ url += "/l/#{filter}" if filter.present?
+
+ if @filter_on_category
+ slug_path = @filter_on_category.slug_path
+ category_path = (slug_path + [@filter_on_category.id.to_s]).join("/")
+ subcategory_mode = params[:no_subcategories] == true ? "none" : nil
+ if subcategory_mode
+ url =
+ "#{Discourse.base_path}/tags/c/#{category_path}/#{subcategory_mode}/#{tag.slug_for_url}/#{tag.id}"
+ else
+ url = "#{Discourse.base_path}/tags/c/#{category_path}/#{tag.slug_for_url}/#{tag.id}"
+ end
+ url += "/l/#{filter}" if filter.present?
+ end
+
+ url += ".json" if request.format.json?
+ url += "?#{request.query_string}" if request.query_string.present?
+ redirect_to url, status: :moved_permanently
+ end
+
+ def should_redirect_tag?(tag)
+ return false if request.format.json?
+ # intersection routes use tag_name, not tag_slug/tag_id - don't redirect
+ return false if params[:additional_tag_names].present?
+
+ if params[:tag_id].present?
+ # new format - redirect if slug doesn't match
+ params[:tag_slug] != tag.slug_for_url
+ else
+ # legacy format - always redirect browser requests
+ true
+ end
end
def ensure_tags_enabled
@@ -525,6 +581,7 @@ class TagsController < ::ApplicationController
id: t.id,
text: t.name,
name: t.name,
+ slug: t.slug.presence || "#{t.id}-tag",
description: t.description,
count: topic_count,
pm_only: topic_count == 0 && t.pm_topic_count > 0,
@@ -570,6 +627,14 @@ class TagsController < ::ApplicationController
def page_params
route_params = { format: "json" }
+ # include tag params
+ if params[:tag_id].present?
+ route_params[:tag_slug] = params[:tag_slug]
+ route_params[:tag_id] = params[:tag_id]
+ elsif params[:tag_name].present?
+ route_params[:tag_name] = params[:tag_name]
+ end
+
if @filter_on_category
if request.path_parameters.include?(:category_slug_path_with_id)
slug_path = @filter_on_category.slug_path
@@ -600,9 +665,20 @@ class TagsController < ::ApplicationController
def url_method(opts = {})
if opts[:category_slug_path_with_id]
- "tag_category_#{action_name}_path"
+ if opts[:tag_id]
+ "tag_category_#{action_name}_path"
+ else
+ "tag_category_#{action_name}_by_name_path"
+ end
else
- "tag_#{action_name}_path"
+ if opts[:tag_slug] && opts[:tag_id]
+ # user-facing canonical URLs use slug/id format
+ "tag_#{action_name}_with_slug_path"
+ elsif opts[:tag_id]
+ "tag_#{action_name}_path"
+ else
+ "tag_#{action_name}_by_name_path"
+ end
end
end
@@ -651,7 +727,8 @@ class TagsController < ::ApplicationController
params[:no_subcategories] == "true"
options[:per_page] = params[:per_page].to_i.clamp(1, 30) if params[:per_page].present?
- if params[:tag_name] == "none"
+ tag_name_param = @tag_name || params[:tag_name]
+ if tag_name_param == "none"
options.delete(:tags)
options[:no_tags] = true
else
@@ -663,6 +740,15 @@ class TagsController < ::ApplicationController
end
def tag_params
- Array(params[:tags]).map(&:to_s).concat(Array(@additional_tags))
+ # params[:tags] is from query string for intersection filtering
+ # @additional_tags is from URL path for /tags/intersection routes
+ # if neither is set, use the primary tag name from URL
+ if params[:tags].present?
+ Array(params[:tags]).map(&:to_s).concat(Array(@additional_tags))
+ elsif @additional_tags.present?
+ [@tag_name].concat(Array(@additional_tags)).compact
+ else
+ [@tag_name].compact
+ end
end
end
diff --git a/app/models/tag.rb b/app/models/tag.rb
index 6020f5b7596..3afdb970fa9 100644
--- a/app/models/tag.rb
+++ b/app/models/tag.rb
@@ -164,7 +164,10 @@ class Tag < ActiveRecord::Base
LIMIT #{limit}
SQL
- tag_names_with_counts.map { |row| { id: row.tag_id, name: row.tag_name, slug: row.tag_slug } }
+ tag_names_with_counts.map do |row|
+ slug = row.tag_slug.presence || "#{row.tag_id}-tag"
+ { id: row.tag_id, name: row.tag_name, slug: slug }
+ end
end
def self.topic_count_column(guardian)
@@ -207,13 +210,13 @@ class Tag < ActiveRecord::Base
end
def url
- "#{Discourse.base_path}/tag/#{UrlHelper.encode_component(self.name)}"
+ "#{Discourse.base_path}/tag/#{slug_for_url}/#{id}"
end
alias_method :relative_url, :url
def full_url
- "#{Discourse.base_url}/tag/#{UrlHelper.encode_component(self.name)}"
+ "#{Discourse.base_url}/tag/#{slug_for_url}/#{id}"
end
def slug_for_url
diff --git a/app/serializers/concerns/topic_tags_mixin.rb b/app/serializers/concerns/topic_tags_mixin.rb
index 5a829824213..3ff0ff2bdd9 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 { |tag| { id: tag.id, name: tag.name, slug: tag.slug } }
+ all_tags.map { |tag| { id: tag.id, name: tag.name, slug: tag.slug_for_url } }
end
def tags_descriptions
diff --git a/app/serializers/sidebar_tag_serializer.rb b/app/serializers/sidebar_tag_serializer.rb
index 731ed2e7a5d..99a71396bfc 100644
--- a/app/serializers/sidebar_tag_serializer.rb
+++ b/app/serializers/sidebar_tag_serializer.rb
@@ -3,6 +3,10 @@
class SidebarTagSerializer < ApplicationSerializer
attributes :id, :name, :slug, :description, :pm_only
+ def slug
+ object.slug_for_url
+ end
+
def pm_only
topic_count_column = Tag.topic_count_column(scope)
object.public_send(topic_count_column) == 0 && object.pm_topic_count > 0
diff --git a/app/serializers/tag_group_serializer.rb b/app/serializers/tag_group_serializer.rb
index 26a33f577c9..b22f1855eb0 100644
--- a/app/serializers/tag_group_serializer.rb
+++ b/app/serializers/tag_group_serializer.rb
@@ -4,12 +4,18 @@ class TagGroupSerializer < ApplicationSerializer
attributes :id, :name, :tags, :parent_tag, :one_per_topic, :permissions
def tags
- object.tags.base_tags.order(:name).map { |t| { id: t.id, name: t.name, slug: t.slug } }
+ object.tags.base_tags.order(:name).map { |t| { id: t.id, name: t.name, slug: t.slug_for_url } }
end
def parent_tag
return [] unless object.parent_tag
- [{ id: object.parent_tag.id, name: object.parent_tag.name, slug: object.parent_tag.slug }]
+ [
+ {
+ id: object.parent_tag.id,
+ name: object.parent_tag.name,
+ slug: object.parent_tag.slug_for_url,
+ },
+ ]
end
def permissions
diff --git a/app/serializers/tag_serializer.rb b/app/serializers/tag_serializer.rb
index ebee81af4f9..71d0c75681d 100644
--- a/app/serializers/tag_serializer.rb
+++ b/app/serializers/tag_serializer.rb
@@ -5,6 +5,10 @@ class TagSerializer < ApplicationSerializer
has_many :localizations, serializer: TagLocalizationSerializer, embed: :objects
+ def slug
+ object.slug_for_url
+ end
+
def topic_count
object.public_send(Tag.topic_count_column(scope))
end
diff --git a/app/services/tag_hashtag_data_source.rb b/app/services/tag_hashtag_data_source.rb
index b674f73bcd2..d713273dc78 100644
--- a/app/services/tag_hashtag_data_source.rb
+++ b/app/services/tag_hashtag_data_source.rb
@@ -25,7 +25,7 @@ class TagHashtagDataSource
tag =
Tag.new(
- tag.slice(:id, :name, :description).merge(topic_count_column => tag[:count]),
+ tag.slice(:id, :name, :slug, :description).merge(topic_count_column => tag[:count]),
) if tag.is_a?(Hash)
HashtagAutocompleteService::HashtagItem.new.tap do |item|
diff --git a/config/routes.rb b/config/routes.rb
index 9e8a7a77df2..8bea4939ea7 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1660,9 +1660,47 @@ Discourse::Application.routes.draw do
get ".well-known/apple-app-site-association" => "metadata#app_association_ios", :format => false
get "opensearch" => "metadata#opensearch", :constraints => { format: :xml }
+ # Tag Routes - Canonical vs Legacy
+ #
+ # Canonical:
+ # - /tag/:slug/:id - for user-facing endpoints with SEO-friendly URLs
+ # - /tag/:id - for APIs
+ # Legacy: /tag/:name - for backward compat, redirects browsers to canonical
+ #
+
+ scope "/tag/:tag_id", constraints: { tag_id: /\d+/, format: :json } do
+ get "/" => "tags#show", :as => "tag_show"
+ get "/info" => "tags#info", :as => "tag_info"
+ get "/notifications" => "tags#notifications", :as => "tag_notifications"
+ put "/notifications" => "tags#update_notifications"
+ put "/" => "tags#update", :as => "tag_update"
+ delete "/" => "tags#destroy", :as => "tag_destroy"
+ post "/synonyms" => "tags#create_synonyms", :as => "tag_synonyms"
+ delete "/synonyms/:synonym_id" => "tags#destroy_synonym"
+
+ Discourse.filters.each do |filter|
+ get "/l/#{filter}" => "tags#show_#{filter}", :as => "tag_show_#{filter}"
+ end
+ end
+
+ scope "/tag/:tag_slug/:tag_id", constraints: { tag_id: /\d+/, format: :json } do
+ get "/" => "tags#show", :as => "tag_show_with_slug"
+
+ Discourse.filters.each do |filter|
+ get "/l/#{filter}" => "tags#show_#{filter}", :as => "tag_show_#{filter}_with_slug"
+ end
+ end
+
+ get "/tag/:tag_slug/:tag_id" => "tags#tag_feed",
+ :constraints => {
+ tag_id: /\d+/,
+ format: :rss,
+ },
+ :as => "tag_feed_with_id"
+
scope "/tag/:tag_name" do
constraints format: :json do
- get "/" => "tags#show", :as => "tag_show"
+ get "/" => "tags#show", :as => "tag_show_by_name"
get "/info" => "tags#info"
get "/notifications" => "tags#notifications"
put "/notifications" => "tags#update_notifications"
@@ -1672,7 +1710,7 @@ Discourse::Application.routes.draw do
delete "/synonyms/:synonym_id" => "tags#destroy_synonym"
Discourse.filters.each do |filter|
- get "/l/#{filter}" => "tags#show_#{filter}", :as => "tag_show_#{filter}"
+ get "/l/#{filter}" => "tags#show_#{filter}", :as => "tag_show_#{filter}_by_name"
end
end
@@ -1681,6 +1719,9 @@ Discourse::Application.routes.draw do
end
end
+ # Tag listings & category+tag combinations:
+ # /tags - index, search, management endpoints
+ # /tags/c/:category/:slug/:id - topics filtered by category AND tag
scope "/tags" do
get "/" => "tags#index"
get "/filter/list" => "tags#index"
@@ -1695,38 +1736,75 @@ Discourse::Application.routes.draw do
get "/unused" => "tags#list_unused"
delete "/unused" => "tags#destroy_unused"
+ # canonical slug/id format for category+tag routes
+ constraints(tag_id: /\d+/, format: /json|rss/) do
+ scope path: "/c/*category_slug_path_with_id" do
+ Discourse.filters.each do |filter|
+ get "/none/:tag_slug/:tag_id/l/#{filter}" => "tags#show_#{filter}",
+ :as => "tag_category_none_show_#{filter}",
+ :defaults => {
+ no_subcategories: true,
+ }
+ get "/all/:tag_slug/:tag_id/l/#{filter}" => "tags#show_#{filter}",
+ :as => "tag_category_all_show_#{filter}",
+ :defaults => {
+ no_subcategories: false,
+ }
+ end
+
+ get "/none/:tag_slug/:tag_id" => "tags#show",
+ :as => "tag_category_none_show",
+ :defaults => {
+ no_subcategories: true,
+ }
+ get "/all/:tag_slug/:tag_id" => "tags#show",
+ :as => "tag_category_all_show",
+ :defaults => {
+ no_subcategories: false,
+ }
+
+ Discourse.filters.each do |filter|
+ get "/:tag_slug/:tag_id/l/#{filter}" => "tags#show_#{filter}",
+ :as => "tag_category_show_#{filter}"
+ end
+
+ get "/:tag_slug/:tag_id" => "tags#show", :as => "tag_category_show"
+ end
+ end
+
+ # legacy name-based format for category+tag routes
constraints(tag_name: %r{[^/]+?}, format: /json|rss/) do
scope path: "/c/*category_slug_path_with_id" do
Discourse.filters.each do |filter|
get "/none/:tag_name/l/#{filter}" => "tags#show_#{filter}",
- :as => "tag_category_none_show_#{filter}",
+ :as => "tag_category_none_show_#{filter}_by_name",
:defaults => {
no_subcategories: true,
}
get "/all/:tag_name/l/#{filter}" => "tags#show_#{filter}",
- :as => "tag_category_all_show_#{filter}",
+ :as => "tag_category_all_show_#{filter}_by_name",
:defaults => {
no_subcategories: false,
}
end
get "/none/:tag_name" => "tags#show",
- :as => "tag_category_none_show",
+ :as => "tag_category_none_show_by_name",
:defaults => {
no_subcategories: true,
}
get "/all/:tag_name" => "tags#show",
- :as => "tag_category_all_show",
+ :as => "tag_category_all_show_by_name",
:defaults => {
no_subcategories: false,
}
Discourse.filters.each do |filter|
get "/:tag_name/l/#{filter}" => "tags#show_#{filter}",
- :as => "tag_category_show_#{filter}"
+ :as => "tag_category_show_#{filter}_by_name"
end
- get "/:tag_name" => "tags#show", :as => "tag_category_show"
+ get "/:tag_name" => "tags#show", :as => "tag_category_show_by_name"
end
get "/intersection/:tag_name/*additional_tag_names" => "tags#show",
diff --git a/frontend/discourse/app/adapters/tag-info.js b/frontend/discourse/app/adapters/tag-info.js
index 545f3ca1d1a..0e8659342dd 100644
--- a/frontend/discourse/app/adapters/tag-info.js
+++ b/frontend/discourse/app/adapters/tag-info.js
@@ -2,6 +2,6 @@ import RESTAdapter from "discourse/adapters/rest";
export default class TagInfoAdapter extends RESTAdapter {
pathFor(store, type, id) {
- return "/tag/" + id + "/info";
+ return `/tag/${id}/info.json`;
}
}
diff --git a/frontend/discourse/app/adapters/tag-notification.js b/frontend/discourse/app/adapters/tag-notification.js
index 9b5e986ff5d..a06e07ee17d 100644
--- a/frontend/discourse/app/adapters/tag-notification.js
+++ b/frontend/discourse/app/adapters/tag-notification.js
@@ -2,6 +2,6 @@ import RESTAdapter from "discourse/adapters/rest";
export default class TagNotificationAdapter extends RESTAdapter {
pathFor(store, type, id) {
- return "/tag/" + id + "/notifications";
+ return `/tag/${id}/notifications.json`;
}
}
diff --git a/frontend/discourse/app/adapters/tag.js b/frontend/discourse/app/adapters/tag.js
index d8570817c29..4082edaf679 100644
--- a/frontend/discourse/app/adapters/tag.js
+++ b/frontend/discourse/app/adapters/tag.js
@@ -1,9 +1,7 @@
import RESTAdapter from "discourse/adapters/rest";
export default class TagAdapter extends RESTAdapter {
- primaryKey = "name";
-
- pathFor(store, type, tagName) {
- return tagName ? `/tag/${tagName}` : `/tags`;
+ pathFor(store, type, findArgs) {
+ return findArgs ? `/tag/${findArgs}.json` : `/tags.json`;
}
}
diff --git a/frontend/discourse/app/components/bread-crumbs.gjs b/frontend/discourse/app/components/bread-crumbs.gjs
index 82ad6021460..0a4a4c5203b 100644
--- a/frontend/discourse/app/components/bread-crumbs.gjs
+++ b/frontend/discourse/app/components/bread-crumbs.gjs
@@ -200,7 +200,7 @@ export default class BreadCrumbs extends Component {
<li>
<TagsIntersectionChooser
@currentCategory={{this.category}}
- @mainTag={{this.tag.name}}
+ @mainTag={{this.tag}}
@additionalTags={{this.additionalTags}}
@options={{hash categoryId=this.category.id}}
/>
diff --git a/frontend/discourse/app/components/discourse-tag-bound.gjs b/frontend/discourse/app/components/discourse-tag-bound.gjs
index 365d0527c6d..65a218c73c1 100644
--- a/frontend/discourse/app/components/discourse-tag-bound.gjs
+++ b/frontend/discourse/app/components/discourse-tag-bound.gjs
@@ -7,14 +7,19 @@ import getURL from "discourse/lib/get-url";
@tagName("")
export default class DiscourseTagBound extends Component {
- @discourseComputed("tagRecord.id")
- tagClass(tagRecordId) {
- return "tag-" + tagRecordId;
+ @discourseComputed("tagRecord.name")
+ tagClass(name) {
+ return "tag-" + name;
}
- @discourseComputed("tagRecord.id")
- href(tagRecordId) {
- return getURL("/tag/" + tagRecordId);
+ @discourseComputed("tagRecord.slug", "tagRecord.id")
+ href(slug, id) {
+ if (id) {
+ const slugForUrl = slug || `${id}-tag`;
+ return getURL(`/tag/${slugForUrl}/${id}`);
+ }
+ // fallback for tags without id
+ return getURL("/tag/" + this.tagRecord.name);
}
<template>
@@ -22,6 +27,6 @@ export default class DiscourseTagBound extends Component {
href={{this.href}}
class={{concatClass "discourse-tag" this.style this.tagClass}}
...attributes
- >{{this.tagRecord.id}}</a>
+ >{{this.tagRecord.name}}</a>
</template>
}
diff --git a/frontend/discourse/app/components/tag-info.gjs b/frontend/discourse/app/components/tag-info.gjs
index 9fb86fb5420..73f9aeffa14 100644
--- a/frontend/discourse/app/components/tag-info.gjs
+++ b/frontend/discourse/app/components/tag-info.gjs
@@ -89,8 +89,9 @@ export default class TagInfo extends Component {
return;
}
this.set("loading", true);
+ const findArgs = this.tag.id || this.tag.name;
return this.store
- .find("tag-info", this.tag.name)
+ .find("tag-info", findArgs)
.then((result) => {
this.set("tagInfo", result);
this.set(
@@ -119,12 +120,13 @@ export default class TagInfo extends Component {
}
@action
- unlinkSynonym(tag, event) {
+ unlinkSynonym(synonym, event) {
event?.preventDefault();
- ajax(`/tag/${this.tagInfo.name}/synonyms/${tag.name}`, {
+ const id = this.tagInfo.id;
+ ajax(`/tag/${id}/synonyms/${synonym.id}.json`, {
type: "DELETE",
})
- .then(() => removeValueFromArray(this.tagInfo.synonyms, tag))
+ .then(() => removeValueFromArray(this.tagInfo.synonyms, synonym))
.catch(popupAjaxError);
}
@@ -161,6 +163,7 @@ export default class TagInfo extends Component {
this.newTagDescription = this.newTagDescription?.replaceAll("\n", "<br>");
this.tag
.update({
+ slug: this.tag.slug,
name: this.newTagName,
description: this.newTagDescription,
})
@@ -174,7 +177,8 @@ export default class TagInfo extends Component {
description: this.newTagDescription,
});
if (oldTagName !== updatedTag.name) {
- this.router.transitionTo("tag.show", updatedTag.name);
+ const slugForUrl = updatedTag.slug || `${updatedTag.id}-tag`;
+ this.router.transitionTo("tag.show", slugForUrl, updatedTag.id);
}
}
})
@@ -222,7 +226,8 @@ export default class TagInfo extends Component {
})
),
didConfirm: () => {
- return ajax(`/tag/${this.tagInfo.name}/synonyms`, {
+ const id = this.tagInfo.id;
+ return ajax(`/tag/${id}/synonyms.json`, {
type: "POST",
data: {
tags: this.newSynonyms.map((t) =>
diff --git a/frontend/discourse/app/components/tag-list.gjs b/frontend/discourse/app/components/tag-list.gjs
index ff76e82c6ef..ceb87255c91 100644
--- a/frontend/discourse/app/components/tag-list.gjs
+++ b/frontend/discourse/app/components/tag-list.gjs
@@ -64,7 +64,7 @@ export default class TagList extends Component {
{{#each this.sortedTags as |tag|}}
<div class="tag-box">
{{discourseTag
- tag.name
+ tag
description=tag.description
isPrivateMessage=this.isPrivateMessage
pmOnly=tag.pmOnly
diff --git a/frontend/discourse/app/initializers/dynamic-route-builders.js b/frontend/discourse/app/initializers/dynamic-route-builders.js
index 75b78c3e59f..ed1d2744e73 100644
--- a/frontend/discourse/app/initializers/dynamic-route-builders.js
+++ b/frontend/discourse/app/initializers/dynamic-route-builders.js
@@ -73,6 +73,18 @@ export default {
);
app.register("controller:tags.show-category-all", DiscoveryListController);
+ // untagged category routes (no tag selected, shows category with tag=none)
+ app.register("route:tags.untagged-category", buildTagRoute());
+ app.register("controller:tags.untagged-category", DiscoveryListController);
+ app.register(
+ "route:tags.untagged-category-all",
+ buildTagRoute({ noSubcategories: false })
+ );
+ app.register(
+ "controller:tags.untagged-category-all",
+ DiscoveryListController
+ );
+
site.get("filters").forEach(function (filter) {
const filterDasherized = dasherize(filter);
@@ -110,6 +122,24 @@ export default {
`controller:tags.show-category-all-${filterDasherized}`,
DiscoveryListController
);
+
+ // category filter routes with no tag selected (tag=none)
+ app.register(
+ `route:tags.untagged-category-${filterDasherized}`,
+ buildTagRoute({ navMode: filter })
+ );
+ app.register(
+ `controller:tags.untagged-category-${filterDasherized}`,
+ DiscoveryListController
+ );
+ app.register(
+ `route:tags.untagged-category-all-${filterDasherized}`,
+ buildTagRoute({ navMode: filter, noSubcategories: false })
+ );
+ app.register(
+ `controller:tags.untagged-category-all-${filterDasherized}`,
+ DiscoveryListController
+ );
});
},
};
diff --git a/frontend/discourse/app/lib/render-tag.js b/frontend/discourse/app/lib/render-tag.js
index 5bdb47b074a..0b8d6d935ef 100644
--- a/frontend/discourse/app/lib/render-tag.js
+++ b/frontend/discourse/app/lib/render-tag.js
@@ -29,6 +29,9 @@ export function defaultRenderTag(tag, params) {
? params.tagsForUser
: User.current().username;
path = `/u/${username}/messages/tags/${tagNameLower}`;
+ } else if (typeof tag === "object" && tag.id) {
+ const slugForUrl = tag.slug || `${tag.id}-tag`;
+ path = `/tag/${slugForUrl}/${tag.id}`;
} else {
path = `/tag/${tagNameLower}`;
}
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 1621478449d..c377bbb071c 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
@@ -31,7 +31,7 @@ export default class TagSectionLink extends BaseTagSectionLink {
}
get models() {
- return [this.tagName];
+ return [this.tag.slug, this.tag.id];
}
get route() {
diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.js
index 4c02045db81..9122c517318 100644
--- a/frontend/discourse/app/lib/url.js
+++ b/frontend/discourse/app/lib/url.js
@@ -515,7 +515,7 @@ export function prefixProtocol(url) {
return `https://${url}`;
}
-export function getCategoryAndTagUrl(category, subcategories, tagName) {
+export function getCategoryAndTagUrl(category, subcategories, tag) {
let url;
if (category) {
@@ -531,10 +531,18 @@ export function getCategoryAndTagUrl(category, subcategories, tagName) {
}
}
- if (tagName) {
- url = url
- ? "/tags" + url + "/" + tagName.toLowerCase()
- : "/tag/" + tagName.toLowerCase();
+ if (tag) {
+ // tag can be string "none" (special filter) or object with {id, name, slug}
+ if (typeof tag === "string") {
+ // special case: "none" filter
+ url = url ? "/tags" + url + "/" + tag : "/tag/" + tag;
+ } else {
+ if (url) {
+ url = "/tags" + url + "/" + tag.slug + "/" + tag.id;
+ } else {
+ url = "/tag/" + tag.slug + "/" + tag.id;
+ }
+ }
}
return getURL(url || "/");
diff --git a/frontend/discourse/app/models/nav-item.js b/frontend/discourse/app/models/nav-item.js
index a976cc63d0c..50eddc77fff 100644
--- a/frontend/discourse/app/models/nav-item.js
+++ b/frontend/discourse/app/models/nav-item.js
@@ -33,8 +33,8 @@ export default class NavItem extends EmberObject {
return path;
}
- const tagName = context.tag?.name;
- if (tagName && Site.currentProp("filters").includes(filterType)) {
+ const tag = context.tag;
+ if (tag?.slug && Site.currentProp("filters").includes(filterType)) {
includesTagContext = true;
if (context.category) {
@@ -54,7 +54,8 @@ export default class NavItem extends EmberObject {
}
if (includesTagContext) {
- path += `/${tagName}`;
+ // use canonical URL format with slug/id when id is available
+ path += tag.id ? `/${tag.slug}/${tag.id}` : `/${tag.slug}`;
}
if (includesTagContext || includesCategoryContext) {
diff --git a/frontend/discourse/app/models/tag.js b/frontend/discourse/app/models/tag.js
index 1149948c1f0..1ac1522080a 100644
--- a/frontend/discourse/app/models/tag.js
+++ b/frontend/discourse/app/models/tag.js
@@ -1,14 +1,21 @@
import { readOnly } from "@ember/object/computed";
import discourseComputed from "discourse/lib/decorators";
+import getURL from "discourse/lib/get-url";
import RestModel from "discourse/models/rest";
export default class Tag extends RestModel {
- // Use tag name instead of numeric id as the primary key
- // since backend tag routes use tag name in the URL path
- primaryKey = "name";
-
@readOnly("pm_only") pmOnly;
+ @discourseComputed("slug", "id")
+ url(slug, id) {
+ if (id) {
+ const slugForUrl = slug || `${id}-tag`;
+ return getURL(`/tag/${slugForUrl}/${id}`);
+ }
+ // fallback for tags without id (legacy)
+ return getURL(`/tag/${this.name}`);
+ }
+
@discourseComputed("count", "pm_count")
totalCount(count, pmCount) {
return pmCount ? count + pmCount : count;
diff --git a/frontend/discourse/app/routes/app-route-map.js b/frontend/discourse/app/routes/app-route-map.js
index 6d1f8571bb0..02de9a03fa0 100644
--- a/frontend/discourse/app/routes/app-route-map.js
+++ b/frontend/discourse/app/routes/app-route-map.js
@@ -220,42 +220,74 @@ export default function () {
this.route("full-page-search", { path: "/search" });
this.route("tag", function () {
- this.route("show", { path: "/:tag_name" });
+ // untagged route (special case for "none")
+ this.route("none");
+ Site.currentProp("filters").forEach((filter) => {
+ this.route("none" + capitalize(filter), { path: "/none/l/" + filter });
+ });
+ // canonical tag route with slug/id
+ this.route("show", { path: "/:tag_slug/:tag_id" });
Site.currentProp("filters").forEach((filter) => {
this.route("show" + capitalize(filter), {
- path: "/:tag_name/l/" + filter,
+ path: "/:tag_slug/:tag_id/l/" + filter,
});
});
+
+ // legacy route: /tag/:tag_name -> redirects to /tag/:slug/:id
+ this.route("legacyRedirect", { path: "/:tag_name" });
});
this.route("tags", function () {
+ // untagged routes (no tag selected) - must come BEFORE showCategory routes
+ // these handle URLs like /tags/c/feature/2/none meaning "category with no tag"
+ this.route("untaggedCategory", {
+ path: "/c/*category_slug_path_with_id/none",
+ });
+ this.route("untaggedCategoryAll", {
+ path: "/c/*category_slug_path_with_id/all/none",
+ });
+
+ // category + tag routes (with tag_slug/tag_id)
this.route("showCategory", {
- path: "/c/*category_slug_path_with_id/:tag_name",
+ path: "/c/*category_slug_path_with_id/:tag_slug/:tag_id",
});
this.route("showCategoryAll", {
- path: "/c/*category_slug_path_with_id/all/:tag_name",
+ path: "/c/*category_slug_path_with_id/all/:tag_slug/:tag_id",
});
this.route("showCategoryNone", {
- path: "/c/*category_slug_path_with_id/none/:tag_name",
+ path: "/c/*category_slug_path_with_id/none/:tag_slug/:tag_id",
});
Site.currentProp("filters").forEach((filter) => {
+ // untagged with filter
+ this.route("untaggedCategory" + capitalize(filter), {
+ path: "/c/*category_slug_path_with_id/none/l/" + filter,
+ });
+ this.route("untaggedCategoryAll" + capitalize(filter), {
+ path: "/c/*category_slug_path_with_id/all/none/l/" + filter,
+ });
+
+ // category + tag with filter
this.route("showCategory" + capitalize(filter), {
- path: "/c/*category_slug_path_with_id/:tag_name/l/" + filter,
+ path: "/c/*category_slug_path_with_id/:tag_slug/:tag_id/l/" + filter,
});
this.route("showCategoryAll" + capitalize(filter), {
- path: "/c/*category_slug_path_with_id/all/:tag_name/l/" + filter,
+ path:
+ "/c/*category_slug_path_with_id/all/:tag_slug/:tag_id/l/" + filter,
});
this.route("showCategoryNone" + capitalize(filter), {
- path: "/c/*category_slug_path_with_id/none/:tag_name/l/" + filter,
+ path:
+ "/c/*category_slug_path_with_id/none/:tag_slug/:tag_id/l/" + filter,
});
});
+
this.route("intersection", {
path: "intersection/:tag_name/*additional_tags",
});
// legacy route
+ // handles /tags/:tag_name -> redirects to /tag/:slug/:id
this.route("legacyRedirect", { path: "/:tag_name" });
});
diff --git a/frontend/discourse/app/routes/tag/legacy-redirect.js b/frontend/discourse/app/routes/tag/legacy-redirect.js
new file mode 100644
index 00000000000..f6bdf7fdbcf
--- /dev/null
+++ b/frontend/discourse/app/routes/tag/legacy-redirect.js
@@ -0,0 +1,16 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+// handles legacy /tag/:tag_name URLs
+// by redirecting to the canonical /tag/:slug/:id format
+export default class TagLegacyRedirect extends DiscourseRoute {
+ @service router;
+
+ async beforeModel() {
+ const tagName = this.paramsFor("tag.legacyRedirect").tag_name;
+ const result = await ajax(`/tag/${tagName}/info.json`);
+ const tag = result.tag_info;
+ this.router.replaceWith("tag.show", tag.slug, tag.id);
+ }
+}
diff --git a/frontend/discourse/app/routes/tag/none.js b/frontend/discourse/app/routes/tag/none.js
new file mode 100644
index 00000000000..2334c809091
--- /dev/null
+++ b/frontend/discourse/app/routes/tag/none.js
@@ -0,0 +1,6 @@
+import { buildTagRoute } from "discourse/routes/tag/show";
+
+// Route for /tag/none - shows topics without any tags
+export default class extends buildTagRoute() {
+ controllerName = "discovery/list";
+}
diff --git a/frontend/discourse/app/routes/tag/show.js b/frontend/discourse/app/routes/tag/show.js
index a344b653911..6c10983fe7d 100644
--- a/frontend/discourse/app/routes/tag/show.js
+++ b/frontend/discourse/app/routes/tag/show.js
@@ -1,6 +1,7 @@
import { action } from "@ember/object";
import { service } from "@ember/service";
import { queryParams, resetParams } from "discourse/controllers/discovery/list";
+import { ajax } from "discourse/lib/ajax";
import { filterTypeForMode } from "discourse/lib/filter-mode";
import { disableImplicitInjections } from "discourse/lib/implicit-injections";
import PreloadStore from "discourse/lib/preload-store";
@@ -40,11 +41,39 @@ export default class TagShowRoute extends DiscourseRoute {
}
async model(params, transition) {
- const name = escapeExpression(params.tag_name);
- const id = params.tag_id;
+ // support both canonical (tag_slug/tag_id) and legacy (tag_name) params
+ let slug = params.tag_slug || params.tag_name;
+ let id = parseInt(params.tag_id, 10);
+
+ if (!slug) {
+ slug = NONE;
+ id = null;
+ }
+
+ // handle legacy URLs without tag_id - fetch tag info to get the ID
+ // e.g., /tags/c/category/1/my-tag -> need to lookup my-tag to get its ID
+ // skip redirect for intersection routes (they use tag_name, not tag_slug/tag_id)
+ const isIntersectionRoute = params.additional_tags !== undefined;
+ if (slug && slug !== NONE && !id && !isIntersectionRoute) {
+ try {
+ const result = await ajax(`/tag/${slug}/info.json`);
+ if (result.tag_info) {
+ id = result.tag_info.id;
+ // redirect to canonical URL with ID
+ const routeName = transition.to.name;
+ const newParams = { ...params, tag_slug: slug, tag_id: id };
+ return this.router.replaceWith(routeName, newParams);
+ }
+ } catch {
+ // tag not found, continue with slug only
+ }
+ }
+
+ // use slug as initial name until API returns actual name
const tag = this.store.createRecord("tag", {
id,
- name,
+ name: slug,
+ slug,
});
let additionalTags;
@@ -60,11 +89,8 @@ export default class TagShowRoute extends DiscourseRoute {
const filterType = filterTypeForMode(this.navMode);
let tagNotification;
- if (tag && name !== NONE && this.currentUser && !additionalTags) {
- tagNotification = await this.store.find(
- "tagNotification",
- name.toLowerCase()
- );
+ if (tag && slug !== NONE && this.currentUser && !additionalTags) {
+ tagNotification = await this.store.find("tagNotification", id);
}
let category = params.category_slug_path_with_id
@@ -75,7 +101,6 @@ export default class TagShowRoute extends DiscourseRoute {
{}
);
const topicFilter = this.navMode;
- const tagName = name ? name.toLowerCase() : NONE;
let filter;
if (category) {
@@ -86,9 +111,15 @@ export default class TagShowRoute extends DiscourseRoute {
filter += this.noSubcategories ? `/${NONE}` : `/${ALL}`;
}
- filter += `/${tagName}/l/${topicFilter}`;
+ if (slug === NONE) {
+ // untagged category route - use "none" without ID
+ filter += `/${NONE}/l/${topicFilter}`;
+ } else {
+ // category+tag routes still use slug/id format
+ filter += `/${slug}/${id}/l/${topicFilter}`;
+ }
} else if (additionalTags) {
- filter = `tags/intersection/${tagName}/${additionalTags.join("/")}`;
+ filter = `tags/intersection/${slug}/${additionalTags.join("/")}`;
if (transition.to.queryParams["category"]) {
filteredQueryParams["category"] = transition.to.queryParams["category"];
@@ -97,7 +128,8 @@ export default class TagShowRoute extends DiscourseRoute {
);
}
} else {
- filter = `tag/${tagName}/l/${topicFilter}`;
+ // use ID-only format for API calls
+ filter = `tag/${id}/l/${topicFilter}`;
}
if (
@@ -110,7 +142,8 @@ export default class TagShowRoute extends DiscourseRoute {
return this.router.replaceWith(
"tags.showCategoryNone",
params.category_slug_path_with_id,
- tagName
+ slug,
+ id
);
}
@@ -124,13 +157,29 @@ export default class TagShowRoute extends DiscourseRoute {
}
);
- if (list.topic_list.tags && list.topic_list.tags.length === 1) {
- // Update name of tag (case might be different)
- tag.setProperties({
- id: list.topic_list.tags[0].id,
- name: list.topic_list.tags[0].name,
- staff: list.topic_list.tags[0].staff,
- });
+ if (list.topic_list.tags && list.topic_list.tags.length >= 1) {
+ const mainTagData = list.topic_list.tags.find(
+ (t) => t.name.toLowerCase() === slug.toLowerCase() || t.slug === slug
+ );
+ if (mainTagData) {
+ tag.setProperties({
+ id: mainTagData.id,
+ name: mainTagData.name,
+ slug: mainTagData.slug,
+ staff: mainTagData.staff,
+ });
+ }
+
+ if (additionalTags) {
+ additionalTags = additionalTags.map((additionalSlug) => {
+ const tagData = list.topic_list.tags.find(
+ (t) =>
+ t.name.toLowerCase() === additionalSlug.toLowerCase() ||
+ t.slug === additionalSlug
+ );
+ return tagData ? tagData.name : additionalSlug;
+ });
+ }
}
return {
diff --git a/frontend/discourse/app/routes/tags/legacy-redirect.js b/frontend/discourse/app/routes/tags/legacy-redirect.js
index 2fc35b4970c..36303247359 100644
--- a/frontend/discourse/app/routes/tags/legacy-redirect.js
+++ b/frontend/discourse/app/routes/tags/legacy-redirect.js
@@ -1,13 +1,16 @@
-import Route from "@ember/routing/route";
import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
-export default class TagsLegacyRedirect extends Route {
+// handles super legacy /tags/:tag_name (note plural) URLs
+// by redirecting to the canonical /tag/:slug/:id format
+export default class TagsLegacyRedirect extends DiscourseRoute {
@service router;
- beforeModel() {
- this.router.transitionTo(
- "tag.show",
- this.paramsFor("tags.legacyRedirect").tag_name
- );
+ async beforeModel() {
+ const tagName = this.paramsFor("tags.legacyRedirect").tag_name;
+ const result = await ajax(`/tag/${tagName}/info.json`);
+ const tag = result.tag_info;
+ this.router.replaceWith("tag.show", tag.slug, tag.id);
}
}
diff --git a/frontend/discourse/select-kit/components/category-drop.js b/frontend/discourse/select-kit/components/category-drop.js
index fe90497f0db..de9bb55c2cc 100644
--- a/frontend/discourse/select-kit/components/category-drop.js
+++ b/frontend/discourse/select-kit/components/category-drop.js
@@ -253,7 +253,7 @@ export default class CategoryDrop extends ComboBoxComponent {
route = getCategoryAndTagUrl(
category,
categoryId !== NO_CATEGORIES_ID,
- this.tag?.name
+ this.tag
);
}
diff --git a/frontend/discourse/select-kit/components/tag-drop.js b/frontend/discourse/select-kit/components/tag-drop.js
index 3f751ede00c..3cf2cb085c0 100644
--- a/frontend/discourse/select-kit/components/tag-drop.js
+++ b/frontend/discourse/select-kit/components/tag-drop.js
@@ -199,6 +199,7 @@ export default class TagDrop extends ComboBoxComponent {
.sort((a, b) => a.name > b.name)
.map((r) => {
const content = this.defaultItem(r.id, r.name);
+ content.slug = r.slug;
if (!this.currentCategory) {
content.count = r.count;
}
@@ -209,18 +210,18 @@ export default class TagDrop extends ComboBoxComponent {
@action
onChange(value, tag) {
- let tagName;
+ let tagArg;
if (value === NO_TAG_ID) {
- tagName = NONE_TAG;
+ tagArg = NONE_TAG;
} else if (value === ALL_TAGS_ID) {
- tagName = null;
- } else if (tag && tag.name) {
- tagName = tag.name;
+ tagArg = null;
+ } else if (tag) {
+ tagArg = tag;
}
DiscourseURL.routeToUrl(
- getCategoryAndTagUrl(this.currentCategory, !this.noSubcategories, tagName)
+ getCategoryAndTagUrl(this.currentCategory, !this.noSubcategories, tagArg)
);
}
}
diff --git a/frontend/discourse/select-kit/components/tags-intersection-chooser.js b/frontend/discourse/select-kit/components/tags-intersection-chooser.js
index 874dfcd6aa0..61033705486 100644
--- a/frontend/discourse/select-kit/components/tags-intersection-chooser.js
+++ b/frontend/discourse/select-kit/components/tags-intersection-chooser.js
@@ -23,7 +23,8 @@ export default class TagsIntersectionChooser extends MiniTagChooser {
@action
onChange(tags) {
- const mainTagName = this.mainTag?.name ?? this.mainTag;
+ const mainTag = this.mainTag;
+ const mainTagName = mainTag?.name;
const tagNames = tags.map((t) => t.name ?? t);
if (mainTagName && tagNames.includes(mainTagName)) {
@@ -33,6 +34,9 @@ export default class TagsIntersectionChooser extends MiniTagChooser {
DiscourseURL.routeTo(
`/tags/intersection/${mainTagName}/${remainingTags.join("/")}`
);
+ } else if (mainTag.id) {
+ const slug = mainTag.slug || `${mainTag.id}-tag`;
+ DiscourseURL.routeTo(`/tag/${slug}/${mainTag.id}`);
} else {
DiscourseURL.routeTo(`/tag/${mainTagName}`);
}
diff --git a/frontend/discourse/tests/acceptance/search-test.js b/frontend/discourse/tests/acceptance/search-test.js
index a2dd2ad5a95..77d1b69ef31 100644
--- a/frontend/discourse/tests/acceptance/search-test.js
+++ b/frontend/discourse/tests/acceptance/search-test.js
@@ -50,11 +50,34 @@ acceptance("Search - Anonymous", function (needs) {
});
});
- server.get("/tag/important/notifications", () => {
+ server.get("/tag/:tag_id/notifications.json", () => {
return helper.response({
tag_notification: { id: 1, name: "important", notification_level: 2 },
});
});
+
+ server.get("/tag/:tag_id/l/latest.json", (request) => {
+ return helper.response({
+ users: [],
+ primary_groups: [],
+ topic_list: {
+ can_create_topic: true,
+ draft: null,
+ draft_key: "new_topic",
+ draft_sequence: 1,
+ per_page: 30,
+ tags: [
+ {
+ id: parseInt(request.params.tag_id, 10),
+ name: "important",
+ slug: "important",
+ topic_count: 1,
+ },
+ ],
+ topics: [],
+ },
+ });
+ });
});
test("presence of elements", async function (assert) {
@@ -146,7 +169,8 @@ acceptance("Search - Anonymous", function (needs) {
test("initial options - tag search scope", async function (assert) {
const contextSelector = ".search-menu .results .search-menu-assistant-item";
- await visit("/tag/important");
+ // canonical URL format: /tag/:tag_slug/:tag_id
+ await visit("/tag/important/1");
await click("#search-button");
assert
@@ -807,13 +831,15 @@ acceptance("Search - with tagging enabled", function (needs) {
return helper.response(searchFixtures["search/query"]);
});
- server.get("/tag/dev/notifications", () => {
+ // canonical format: /tag/:tag_id
+ server.get("/tag/:tag_id/notifications.json", () => {
return helper.response({
tag_notification: { id: 1, name: "dev", notification_level: 2 },
});
});
- server.get("/tags/c/bug/1/dev/l/latest.json", () => {
+ // canonical format: /tags/c/:category/:category_id/:tag_slug/:tag_id
+ server.get("/tags/c/bug/1/dev/1/l/latest.json", () => {
return helper.response({
users: [],
primary_groups: [],
@@ -827,6 +853,7 @@ acceptance("Search - with tagging enabled", function (needs) {
{
id: 1,
name: "dev",
+ slug: "dev",
topic_count: 1,
},
],
@@ -895,7 +922,7 @@ acceptance("Search - with tagging enabled", function (needs) {
});
test("initial options - search history - tag context", async function (assert) {
- await visit("/tags/c/bug/dev");
+ await visit("/tags/c/bug/1/dev/1");
await click("#search-button");
assert
@@ -904,7 +931,7 @@ acceptance("Search - with tagging enabled", function (needs) {
});
test("initial options - tag search scope - shows category / tag combination shortcut when both are present", async function (assert) {
- await visit("/tags/c/bug/dev");
+ await visit("/tags/c/bug/1/dev/1");
await click("#search-button");
assert
@@ -919,7 +946,7 @@ acceptance("Search - with tagging enabled", function (needs) {
});
test("initial options - tag and category search scope - updates tag / category combination search suggestion when typing", async function (assert) {
- await visit("/tags/c/bug/dev");
+ await visit("/tags/c/bug/1/dev/1");
await click("#search-button");
await fillIn("#icon-search-input", "foo bar");
diff --git a/frontend/discourse/tests/acceptance/sidebar-plugin-api-test.gjs b/frontend/discourse/tests/acceptance/sidebar-plugin-api-test.gjs
index 2f12f9c2546..20806f4d128 100644
--- a/frontend/discourse/tests/acceptance/sidebar-plugin-api-test.gjs
+++ b/frontend/discourse/tests/acceptance/sidebar-plugin-api-test.gjs
@@ -581,9 +581,9 @@ acceptance("Sidebar - Plugin API", function (needs) {
updateCurrentUser({
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", slug: "tag2", pm_only: false },
+ { id: 1, name: "tag1", slug: "tag1", pm_only: false },
+ { id: 3, name: "tag3", slug: "tag3", pm_only: false },
],
});
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 714a26ea408..fb037b135e6 100644
--- a/frontend/discourse/tests/acceptance/sidebar-user-tags-section-test.js
+++ b/frontend/discourse/tests/acceptance/sidebar-user-tags-section-test.js
@@ -21,27 +21,22 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
watched_tags: [2, 3],
watching_first_post_tags: [],
sidebar_tags: [
- { 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,
- },
+ { id: 2, name: "tag2", slug: "tag2", pm_only: false },
+ { id: 1, name: "tag1", slug: "tag1", pm_only: false },
+ { id: 4, name: "tag4", slug: "tag4", pm_only: true },
+ { id: 3, name: "tag3", slug: "tag3", pm_only: false },
],
display_sidebar_tags: true,
admin: false,
});
needs.pretender((server, helper) => {
- server.get("/tag/:tagId/notifications", (request) => {
+ server.get("/tag/:tagId/notifications.json", (request) => {
return helper.response({
- tag_notification: { id: 1, name: request.params.tagId },
+ tag_notification: {
+ id: request.params.tagId,
+ name: `tag-${request.params.tagId}`,
+ },
});
});
@@ -93,7 +88,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
assert.strictEqual(
currentURL(),
- "/tag/tag1",
+ "/tag/tag1/1",
"it should transition to tag1's topics discovery page"
);
@@ -111,7 +106,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
assert.strictEqual(
currentURL(),
- "/tag/tag2",
+ "/tag/tag2/2",
"it should transition to tag2's topics discovery page"
);
@@ -138,7 +133,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
assert.strictEqual(
currentURL(),
- "/tag/tag1",
+ "/tag/tag1/1",
"it should transition to tag1's topics discovery page"
);
@@ -179,7 +174,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
assert.strictEqual(
currentURL(),
- "/tag/tag1/l/new",
+ "/tag/tag1/1/l/new",
"it should transition to tag1's topics new page"
);
@@ -220,7 +215,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
assert.strictEqual(
currentURL(),
- "/tag/tag1/l/unread",
+ "/tag/tag1/1/l/unread",
"it should transition to tag1's topics unread page"
);
@@ -258,7 +253,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
});
test("visiting tag discovery top route", async function (assert) {
- await visit(`/tag/tag1/l/top`);
+ await visit(`/tag/tag1/1/l/top`);
assert
.dom(
@@ -272,7 +267,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
});
test("visiting tag discovery new route", async function (assert) {
- await visit(`/tag/tag1/l/new`);
+ await visit(`/tag/tag1/1/l/new`);
assert
.dom(
@@ -286,7 +281,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
});
test("visiting tag discovery unread route", async function (assert) {
- await visit(`/tag/tag1/l/unread`);
+ await visit(`/tag/tag1/1/l/unread`);
assert
.dom(
@@ -300,7 +295,7 @@ acceptance("Sidebar - Logged on user - Tags section", function (needs) {
});
test("visiting tag discovery hot route", async function (assert) {
- await visit(`/tag/tag1/l/hot`);
+ await visit(`/tag/tag1/1/l/hot`);
assert
.dom(
@@ -581,9 +576,9 @@ acceptance(
new_new_view_enabled: true,
display_sidebar_tags: true,
sidebar_tags: [
- { id: 2, name: "tag2", pm_only: false },
- { id: 1, name: "tag1", pm_only: false },
- { id: 3, name: "tag3", pm_only: false },
+ { id: 2, name: "tag2", slug: "tag2", pm_only: false },
+ { id: 1, name: "tag1", slug: "tag1", pm_only: false },
+ { id: 3, name: "tag3", slug: "tag3", pm_only: false },
],
});
@@ -762,7 +757,7 @@ acceptance(
.dom('.sidebar-section-link-wrapper[data-tag-name="tag1"] a')
.hasAttribute(
"href",
- "/tag/tag1/l/new",
+ "/tag/tag1/1/l/new",
"links to the new topics list for the tag because there's 1 new topic"
);
@@ -770,7 +765,7 @@ acceptance(
.dom('.sidebar-section-link-wrapper[data-tag-name="tag2"] a')
.hasAttribute(
"href",
- "/tag/tag2/l/new",
+ "/tag/tag2/2/l/new",
"links to the new topics list for the tag because there's 1 unread topic"
);
@@ -778,7 +773,7 @@ acceptance(
.dom('.sidebar-section-link-wrapper[data-tag-name="tag3"] a')
.hasAttribute(
"href",
- "/tag/tag3",
+ "/tag/tag3/3",
"links to the latest topics list for the tag because there are no unread or new topics"
);
});
@@ -821,7 +816,7 @@ acceptance(
.dom('.sidebar-section-link-wrapper[data-tag-name="tag1"] a')
.hasAttribute(
"href",
- "/tag/tag1",
+ "/tag/tag1/1",
"tag1 links to the latest topics list for the tag"
);
@@ -829,7 +824,7 @@ acceptance(
.dom('.sidebar-section-link-wrapper[data-tag-name="tag2"] a')
.hasAttribute(
"href",
- "/tag/tag2",
+ "/tag/tag2/2",
"tag2 links to the latest topics list for the tag"
);
@@ -837,7 +832,7 @@ acceptance(
.dom('.sidebar-section-link-wrapper[data-tag-name="tag3"] a')
.hasAttribute(
"href",
- "/tag/tag3",
+ "/tag/tag3/3",
"tag3 links to the latest topics list for the tag"
);
});
diff --git a/frontend/discourse/tests/acceptance/tags-intersection-test.js b/frontend/discourse/tests/acceptance/tags-intersection-test.js
index 27aa6a795e0..2b3d9f6d207 100644
--- a/frontend/discourse/tests/acceptance/tags-intersection-test.js
+++ b/frontend/discourse/tests/acceptance/tags-intersection-test.js
@@ -34,6 +34,43 @@ acceptance("Tags intersection", function (needs) {
.hasText("first, second", "populates the tags when clicking 'New topic'");
});
+ test("displays tag names from API, not URL slugs", async function (assert) {
+ pretender.get("/tags/intersection/my-slug/other-slug.json", () => {
+ return response({
+ users: [],
+ primary_groups: [],
+ topic_list: {
+ can_create_topic: true,
+ draft_key: "new_topic",
+ topics: [{ id: 16, posters: [] }],
+ tags: [
+ {
+ id: 10,
+ name: "My Tag Name",
+ slug: "my-slug",
+ topic_count: 1,
+ },
+ {
+ id: 11,
+ name: "Other Tag Name",
+ slug: "other-slug",
+ topic_count: 1,
+ },
+ ],
+ },
+ });
+ });
+
+ await visit("/tags/intersection/my-slug/other-slug");
+
+ assert
+ .dom(".tags-intersection-chooser .formatted-selection")
+ .hasText(
+ "My Tag Name, Other Tag Name",
+ "displays API tag names, not URL slugs"
+ );
+ });
+
test("correctly passes the category filter", async function (assert) {
pretender.get("/tags/intersection/sour/tangy.json", (request) => {
assert.deepEqual(request.queryParams, { category: "fruits" });
diff --git a/frontend/discourse/tests/acceptance/tags-test.js b/frontend/discourse/tests/acceptance/tags-test.js
index d796e57510a..dad67721274 100644
--- a/frontend/discourse/tests/acceptance/tags-test.js
+++ b/frontend/discourse/tests/acceptance/tags-test.js
@@ -13,13 +13,13 @@ acceptance("Tags", function (needs) {
needs.user();
needs.pretender((server, helper) => {
- server.get("/tag/test/notifications", () =>
+ server.get("/tag/42/notifications.json", () =>
helper.response({
tag_notification: { id: 42, name: "test", notification_level: 2 },
})
);
- server.get("/tag/test/l/unread.json", () =>
+ server.get("/tag/42/l/unread.json", () =>
helper.response({
users: [
{
@@ -79,7 +79,7 @@ acceptance("Tags", function (needs) {
server.put("/topics/bulk", () => helper.response({}));
- server.get("/tags/c/faq/4/test/l/latest.json", () => {
+ server.get("/tags/c/faq/4/test/42/l/latest.json", () => {
return helper.response({
users: [],
primary_groups: [],
@@ -91,8 +91,9 @@ acceptance("Tags", function (needs) {
per_page: 30,
tags: [
{
- id: 1,
- name: "planters",
+ id: 42,
+ name: "test",
+ slug: "test",
topic_count: 1,
},
],
@@ -110,14 +111,14 @@ acceptance("Tags", function (needs) {
});
test("dismiss notifications", async function (assert) {
- await visit("/tag/test/l/unread");
+ await visit("/tag/test/42/l/unread");
await click("button.dismiss-read");
await click(".dismiss-read-modal button.btn-primary");
assert.dom(".dismiss-read-modal").doesNotExist();
});
test("hide tag notifications menu", async function (assert) {
- await visit("/tags/c/faq/4/test");
+ await visit("/tags/c/faq/4/test/42");
assert.dom(".tag-notifications-tracking").doesNotExist();
});
});
@@ -128,13 +129,13 @@ acceptance("Tags listed by group", function (needs) {
tags_listed_by_group: true,
});
needs.pretender((server, helper) => {
- server.get("/tag/regular-tag/notifications", () =>
+ server.get("/tag/1/notifications.json", () =>
helper.response({
tag_notification: { id: 1, name: "regular-tag", notification_level: 1 },
})
);
- server.get("/tag/regular-tag/l/latest.json", () =>
+ server.get("/tag/1/l/latest.json", () =>
helper.response({
users: [],
primary_groups: [],
@@ -156,17 +157,17 @@ acceptance("Tags listed by group", function (needs) {
})
);
- server.get("/tag/staff-only-tag/notifications", () =>
+ server.get("/tag/2/notifications.json", () =>
helper.response({
tag_notification: {
- id: 1,
+ id: 2,
name: "staff-only-tag",
notification_level: 1,
},
})
);
- server.get("/tag/staff-only-tag/l/latest.json", () =>
+ server.get("/tag/2/l/latest.json", () =>
helper.response({
users: [],
primary_groups: [],
@@ -178,7 +179,7 @@ acceptance("Tags listed by group", function (needs) {
per_page: 30,
tags: [
{
- id: 1,
+ id: 2,
name: "staff-only-tag",
topic_count: 1,
staff: true,
@@ -214,13 +215,13 @@ acceptance("Tags listed by group", function (needs) {
assert
.dom(".tag-list .tag-box:nth-of-type(1) .discourse-tag")
- .hasAttribute("href", "/tag/focus");
+ .hasAttribute("href", "/tag/focus/457");
assert
.dom(".tag-list .tag-box:nth-of-type(2) .discourse-tag")
.hasAttribute(
"href",
- "/tag/escort",
- "uses a lowercase URL for a mixed case tag"
+ "/tag/escort/456",
+ "uses the canonical slug/id URL"
);
assert
@@ -279,18 +280,18 @@ acceptance("Tags listed by group", function (needs) {
test("new topic button works when viewing staff-only tags", async function (assert) {
updateCurrentUser({ moderator: false, admin: false });
- await visit("/tag/regular-tag");
+ await visit("/tag/regular-tag/1");
assert.dom("#create-topic").isEnabled();
- await visit("/tag/staff-only-tag");
+ await visit("/tag/staff-only-tag/2");
assert.dom("#create-topic").isEnabled();
updateCurrentUser({ moderator: true });
- await visit("/tag/regular-tag");
+ await visit("/tag/regular-tag/1");
assert.dom("#create-topic").isEnabled();
- await visit("/tag/staff-only-tag");
+ await visit("/tag/staff-only-tag/2");
assert.dom("#create-topic").isEnabled();
});
});
@@ -327,18 +328,18 @@ acceptance("Tag info", function (needs) {
tags_listed_by_group: true,
});
needs.pretender((server, helper) => {
- server.get("/tag/:tag_name/notifications", (request) => {
- return helper.response({
+ server.get("/tag/12/notifications.json", () =>
+ helper.response({
tag_notification: {
- id: 1,
- name: request.params.tag_name,
+ id: 12,
+ name: "planters",
notification_level: 1,
},
- });
- });
+ })
+ );
- server.get("/tag/:tag_name/l/latest.json", (request) => {
- return helper.response({
+ server.get("/tag/12/l/latest.json", () =>
+ helper.response({
users: [],
primary_groups: [],
topic_list: {
@@ -349,21 +350,88 @@ acceptance("Tag info", function (needs) {
per_page: 30,
tags: [
{
- id: 1,
- name: request.params.tag_name,
+ id: 12,
+ name: "planters",
+ slug: "planters",
topic_count: 1,
},
],
topics: [],
},
- });
- });
+ })
+ );
+
+ server.get("/tag/13/notifications.json", () =>
+ helper.response({
+ tag_notification: {
+ id: 13,
+ name: "happy-monkey",
+ notification_level: 1,
+ },
+ })
+ );
+
+ server.get("/tag/13/l/latest.json", () =>
+ helper.response({
+ users: [],
+ primary_groups: [],
+ topic_list: {
+ can_create_topic: true,
+ draft: null,
+ draft_key: "new_topic",
+ draft_sequence: 1,
+ per_page: 30,
+ tags: [
+ {
+ id: 13,
+ name: "happy-monkey",
+ slug: "happy-monkey",
+ topic_count: 1,
+ },
+ ],
+ topics: [],
+ },
+ })
+ );
+
+ server.get("/tag/14/notifications.json", () =>
+ helper.response({
+ tag_notification: {
+ id: 14,
+ name: "happy-monkey2",
+ notification_level: 1,
+ },
+ })
+ );
+
+ server.get("/tag/14/l/latest.json", () =>
+ helper.response({
+ users: [],
+ primary_groups: [],
+ topic_list: {
+ can_create_topic: true,
+ draft: null,
+ draft_key: "new_topic",
+ draft_sequence: 1,
+ per_page: 30,
+ tags: [
+ {
+ id: 14,
+ name: "happy-monkey2",
+ slug: "happy-monkey2",
+ topic_count: 1,
+ },
+ ],
+ topics: [],
+ },
+ })
+ );
[
- "/tags/c/faq/4/planters/l/latest.json",
- "/tags/c/feature/2/planters/l/latest.json",
- "/tags/c/feature/2/planters/l/hot.json",
- "/tags/c/feature/2/none/planters/l/latest.json",
+ "/tags/c/faq/4/planters/12/l/latest.json",
+ "/tags/c/feature/2/planters/12/l/latest.json",
+ "/tags/c/feature/2/planters/12/l/hot.json",
+ "/tags/c/feature/2/none/planters/12/l/latest.json",
].forEach((url) => {
server.get(url, () => {
return helper.response({
@@ -377,8 +445,9 @@ acceptance("Tag info", function (needs) {
per_page: 30,
tags: [
{
- id: 1,
+ id: 12,
name: "planters",
+ slug: "planters",
topic_count: 1,
},
],
@@ -403,12 +472,13 @@ acceptance("Tag info", function (needs) {
});
});
- server.get("/tag/planters/info", () => {
+ server.get("/tag/12/info.json", () => {
return helper.response({
__rest_serializer: "1",
tag_info: {
id: 12,
name: "planters",
+ slug: "planters",
topic_count: 1,
staff: false,
synonyms: [
@@ -445,18 +515,20 @@ acceptance("Tag info", function (needs) {
],
});
});
- server.put("/tag/happy-monkey", (request) => {
+ server.put("/tag/13.json", (request) => {
const data = helper.parsePostData(request.requestBody);
+ // ID stays the same when renaming - use 13 (original tag ID)
return helper.response({
- tag: { id: data.tag.id, name: data.tag.name },
+ tag: { id: 13, name: data.tag.name, slug: data.tag.name },
});
});
- server.get("/tag/happy-monkey/info", () => {
+ server.get("/tag/13/info.json", () => {
return helper.response({
tag_info: {
id: 13,
name: "happy-monkey",
+ slug: "happy-monkey",
description: "happy monkey description",
topic_count: 1,
staff: false,
@@ -468,23 +540,18 @@ acceptance("Tag info", function (needs) {
});
});
- server.get("/tag/happy-monkey2/info", () => {
- return helper.response({
- tag_info: {
- id: 13,
- name: "happy-monkey2",
- description: "happy monkey description",
- topic_count: 1,
- staff: false,
- synonyms: [],
- tag_group_names: [],
- category_ids: [],
+ server.get("/tag/13/l/latest.json", () =>
+ helper.response({
+ users: [],
+ primary_groups: [],
+ topic_list: {
+ topics: [],
+ tags: [{ id: 13, name: "happy-monkey", slug: "happy-monkey" }],
},
- categories: [],
- });
- });
+ })
+ );
- server.delete("/tag/planters/synonyms/containers", () =>
+ server.delete("/tag/12/synonyms/22.json", () =>
helper.response({ success: true })
);
@@ -502,7 +569,7 @@ acceptance("Tag info", function (needs) {
test("tag info can show synonyms", async function (assert) {
updateCurrentUser({ moderator: false, admin: false });
- await visit("/tag/planters");
+ await visit("/tag/planters/12");
assert.dom("#show-tag-info").exists();
await click("#show-tag-info");
@@ -522,7 +589,7 @@ acceptance("Tag info", function (needs) {
test("tag info hides only current tag in synonyms dropdown", async function (assert) {
updateCurrentUser({ moderator: false, admin: true, can_edit_tags: true });
- await visit("/tag/happy-monkey");
+ await visit("/tag/happy-monkey/13");
assert.dom("#show-tag-info").exists();
await click("#show-tag-info");
@@ -544,7 +611,7 @@ acceptance("Tag info", function (needs) {
test("edit tag is showing input for name and description", async function (assert) {
updateCurrentUser({ moderator: false, admin: true, can_edit_tags: true });
- await visit("/tag/happy-monkey");
+ await visit("/tag/happy-monkey/13");
assert.dom("#show-tag-info").exists();
await click("#show-tag-info");
@@ -563,20 +630,24 @@ acceptance("Tag info", function (needs) {
await fillIn("#edit-description", "new description");
await click(".submit-edit");
- assert.strictEqual(currentURL(), "/tag/happy-monkey", "doesn't change URL");
+ assert.strictEqual(
+ currentURL(),
+ "/tag/happy-monkey/13",
+ "doesn't change URL"
+ );
await click(".edit-tag");
await fillIn("#edit-name", "happy-monkey2");
await click(".submit-edit");
assert.strictEqual(
currentURL(),
- "/tag/happy-monkey2",
+ "/tag/happy-monkey2/13",
"changes URL to new tag path"
);
});
test("tag info hides when tag filter removed", async function (assert) {
- await visit("/tag/happy-monkey");
+ await visit("/tag/happy-monkey/13");
await click("#show-tag-info");
assert.dom(".tag-info .tag-name").exists();
@@ -587,30 +658,30 @@ acceptance("Tag info", function (needs) {
});
test("can filter tags page by category", async function (assert) {
- await visit("/tag/planters");
+ await visit("/tag/planters/12");
await click(".category-breadcrumb .category-drop-header");
await click(`.category-breadcrumb .category-row[data-name="faq"]`);
- assert.strictEqual(currentURL(), "/tags/c/faq/4/planters");
+ assert.strictEqual(currentURL(), "/tags/c/faq/4/planters/12");
});
test("can switch between all/none subcategories", async function (assert) {
- await visit("/tag/planters");
+ await visit("/tag/planters/12");
await click(".category-breadcrumb .category-drop-header");
await click(`.category-breadcrumb .category-row[data-name="feature"]`);
- assert.strictEqual(currentURL(), "/tags/c/feature/2/planters");
+ assert.strictEqual(currentURL(), "/tags/c/feature/2/planters/12");
await click(".category-breadcrumb li:nth-of-type(2) .category-drop-header");
await click(
`.category-breadcrumb li:nth-of-type(2) .category-row[data-value="no-categories"]`
);
- assert.strictEqual(currentURL(), "/tags/c/feature/2/none/planters");
+ assert.strictEqual(currentURL(), "/tags/c/feature/2/none/planters/12");
});
test("sets document title correctly", async function (assert) {
- await visit("/tag/planters");
+ await visit("/tag/planters/12");
assert.strictEqual(
document.title,
i18n("tagging.filters.without_category", {
@@ -621,7 +692,7 @@ acceptance("Tag info", function (needs) {
await click(".category-breadcrumb .category-drop-header");
await click(`.category-breadcrumb .category-row[data-name="feature"]`);
- assert.strictEqual(currentURL(), "/tags/c/feature/2/planters");
+ assert.strictEqual(currentURL(), "/tags/c/feature/2/planters/12");
assert.strictEqual(
document.title,
i18n("tagging.filters.with_category", {
@@ -644,19 +715,19 @@ acceptance("Tag info", function (needs) {
});
test("can visit show-category-latest routes", async function (assert) {
- await visit("/tags/c/feature/2/planters");
+ await visit("/tags/c/feature/2/planters/12");
await click(".nav-item_latest a[href]");
- assert.strictEqual(currentURL(), "/tags/c/feature/2/planters/l/latest");
+ assert.strictEqual(currentURL(), "/tags/c/feature/2/planters/12/l/latest");
await click(".nav-item_hot a[href]");
- assert.strictEqual(currentURL(), "/tags/c/feature/2/planters/l/hot");
+ assert.strictEqual(currentURL(), "/tags/c/feature/2/planters/12/l/hot");
});
test("admin can manage tags", async function (assert) {
updateCurrentUser({ moderator: false, admin: true, can_edit_tags: true });
- await visit("/tag/planters");
+ await visit("/tag/planters/12");
assert.dom("#show-tag-info").exists();
await click("#show-tag-info");
@@ -679,7 +750,7 @@ acceptance("Tag info", function (needs) {
});
test("composer will not set tags if user cannot create them", async function (assert) {
- await visit("/tag/planters");
+ await visit("/tag/planters/12");
await click("#create-topic");
let composer = this.owner.lookup("service:composer");
assert.deepEqual(composer.get("model").tags, []);
@@ -694,16 +765,16 @@ acceptance("Tag show - create topic", function (needs) {
tags_listed_by_group: true,
});
needs.pretender((server, helper) => {
- server.get("/tag/:tag_name/notifications", (request) => {
+ server.get("/tag/0/notifications.json", () => {
return helper.response({
tag_notification: {
- id: 1,
- name: request.params.tag_name,
+ id: 0,
+ name: "none",
notification_level: 1,
},
});
});
- server.get("/tag/:tag_name/l/latest.json", (request) => {
+ server.get("/tag/0/l/latest.json", () => {
return helper.response({
users: [],
primary_groups: [],
@@ -715,8 +786,71 @@ acceptance("Tag show - create topic", function (needs) {
per_page: 30,
tags: [
{
- id: 1,
- name: request.params.tag_name,
+ id: 0,
+ name: "none",
+ slug: "none",
+ topic_count: 1,
+ },
+ ],
+ topics: [],
+ },
+ });
+ });
+ server.get("/tag/99/notifications.json", () => {
+ return helper.response({
+ tag_notification: {
+ id: 99,
+ name: "all",
+ notification_level: 1,
+ },
+ });
+ });
+ server.get("/tag/99/l/latest.json", () => {
+ return helper.response({
+ users: [],
+ primary_groups: [],
+ topic_list: {
+ can_create_topic: true,
+ draft: null,
+ draft_key: "new_topic",
+ draft_sequence: 1,
+ per_page: 30,
+ tags: [
+ {
+ id: 99,
+ name: "all",
+ slug: "all",
+ topic_count: 1,
+ },
+ ],
+ topics: [],
+ },
+ });
+ });
+ server.get("/tag/12/notifications.json", () => {
+ return helper.response({
+ tag_notification: {
+ id: 12,
+ name: "planters",
+ notification_level: 1,
+ },
+ });
+ });
+ server.get("/tag/12/l/latest.json", () => {
+ return helper.response({
+ users: [],
+ primary_groups: [],
+ topic_list: {
+ can_create_topic: true,
+ draft: null,
+ draft_key: "new_topic",
+ draft_sequence: 1,
+ per_page: 30,
+ tags: [
+ {
+ id: 12,
+ name: "planters",
+ slug: "planters",
topic_count: 1,
},
],
@@ -729,11 +863,11 @@ acceptance("Tag show - create topic", function (needs) {
test("composer will not set tags with all/none tags when creating topic", async function (assert) {
const composer = this.owner.lookup("service:composer");
- await visit("/tag/none");
+ await visit("/tag/none/0");
await click("#create-topic");
assert.deepEqual(composer.model.tags, []);
- await visit("/tag/all");
+ await visit("/tag/all/99");
await click("#create-topic");
assert.deepEqual(composer.model.tags, []);
});
@@ -741,7 +875,7 @@ acceptance("Tag show - create topic", function (needs) {
test("composer will set tags from selected tag", async function (assert) {
const composer = this.owner.lookup("service:composer");
- await visit("/tag/planters");
+ await visit("/tag/planters/12");
await click("#create-topic");
assert.deepEqual(composer.model.tags, ["planters"]);
});
diff --git a/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js b/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js
index 59eaa04af95..ea588732a9f 100644
--- a/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js
+++ b/frontend/discourse/tests/acceptance/topic-discovery-tracked-test.js
@@ -22,7 +22,7 @@ acceptance("Topic Discovery Tracked", function (needs) {
return helper.response(cloneJSON(topicFixtures["/latest.json"]));
});
- server.get("/tag/:tag_name/notifications", () => {
+ server.get("/tag/:tag_id/notifications.json", () => {
return helper.response({
tag_notification: {
id: "test",
@@ -31,10 +31,17 @@ acceptance("Topic Discovery Tracked", function (needs) {
});
});
- server.get("/tag/:tag_name/l/latest.json", (request) => {
+ server.get("/tag/:tag_id/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 }];
+ const tagId = parseInt(request.params.tag_id, 10);
+ response.topic_list.tags = [
+ {
+ id: tagId,
+ name: `tag-${tagId}`,
+ slug: `tag-${tagId}`,
+ },
+ ];
return helper.response(response);
});
});
@@ -265,7 +272,7 @@ acceptance("Topic Discovery Tracked", function (needs) {
},
]);
- await visit("/tag/some-other-tag");
+ await visit("/tag/some-other-tag/99");
assert
.dom("#navigation-bar li.unread")
@@ -281,7 +288,7 @@ acceptance("Topic Discovery Tracked", function (needs) {
"displays the right content on new link"
);
- await visit("/tag/some-other-tag?f=tracked");
+ await visit("/tag/some-other-tag/99?f=tracked");
assert
.dom("#navigation-bar li.unread")
diff --git a/frontend/discourse/tests/helpers/create-pretender.js b/frontend/discourse/tests/helpers/create-pretender.js
index 376f01c5285..c5e3118b021 100644
--- a/frontend/discourse/tests/helpers/create-pretender.js
+++ b/frontend/discourse/tests/helpers/create-pretender.js
@@ -107,13 +107,20 @@ export function applyDefaultHandlers(pretender) {
return response(json);
});
- pretender.get("/tags", () => {
+ pretender.get("/tags.json", () => {
return response({
tags: [
- { id: 123, name: "eviltrout", text: "eviltrout", count: 1 },
+ {
+ id: 123,
+ name: "eviltrout",
+ slug: "eviltrout",
+ text: "eviltrout",
+ count: 1,
+ },
{
id: 234,
name: "planned",
+ slug: "planned",
text: "planned",
count: 7,
pm_only: false,
@@ -121,6 +128,7 @@ export function applyDefaultHandlers(pretender) {
{
id: 345,
name: "private",
+ slug: "private",
text: "private",
count: 0,
pm_only: true,
@@ -133,15 +141,17 @@ export function applyDefaultHandlers(pretender) {
name: "Ford Cars",
tags: [
{
- id: "Escort",
+ id: 456,
name: "Escort",
+ slug: "escort",
text: "Escort",
count: 1,
pm_only: false,
},
{
- id: "focus",
+ id: 457,
name: "focus",
+ slug: "focus",
text: "focus",
count: 3,
pm_only: false,
@@ -153,15 +163,17 @@ export function applyDefaultHandlers(pretender) {
name: "Honda Cars",
tags: [
{
- id: "civic",
+ id: 458,
name: "civic",
+ slug: "civic",
text: "civic",
count: 4,
pm_only: false,
},
{
- id: "accord",
+ id: 459,
name: "accord",
+ slug: "accord",
text: "accord",
count: 2,
pm_only: false,
@@ -173,15 +185,17 @@ export function applyDefaultHandlers(pretender) {
name: "Makes",
tags: [
{
- id: "ford",
+ id: 460,
name: "ford",
+ slug: "ford",
text: "ford",
count: 5,
pm_only: false,
},
{
- id: "honda",
+ id: 461,
name: "honda",
+ slug: "honda",
text: "honda",
count: 6,
pm_only: false,
diff --git a/frontend/discourse/tests/unit/models/nav-item-test.js b/frontend/discourse/tests/unit/models/nav-item-test.js
index 721b364455c..a1c335fee76 100644
--- a/frontend/discourse/tests/unit/models/nav-item-test.js
+++ b/frontend/discourse/tests/unit/models/nav-item-test.js
@@ -28,7 +28,7 @@ module("Unit | Model | nav-item", function (hooks) {
href(
"latest",
{ tag: { id: 1, name: "bar", slug: "bar" } },
- "/tag/bar/l/latest",
+ "/tag/bar/1/l/latest",
"latest with tag"
);
href(
@@ -37,7 +37,7 @@ module("Unit | Model | nav-item", function (hooks) {
tag: { id: 1, name: "bar", slug: "bar" },
category: Category.findBySlugPath(["foo"]),
},
- "/tags/c/foo/123/bar/l/latest",
+ "/tags/c/foo/123/bar/1/l/latest",
"latest with tag and category"
);
});
diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rb
index 9f67727e6f9..fa76da43f8f 100644
--- a/lib/discourse_tagging.rb
+++ b/lib/discourse_tagging.rb
@@ -514,7 +514,7 @@ module DiscourseTagging
end
sql << <<~SQL
- SELECT #{distinct_clause} t.id, t.name, t.#{topic_count_column}, t.pm_topic_count, t.description,
+ SELECT #{distinct_clause} t.id, t.name, t.slug, t.#{topic_count_column}, t.pm_topic_count, t.description,
tgr.tgm_id as tgm_id, tgr.tag_group_id as tag_group_id, tgr.parent_tag_id as parent_tag_id,
tgr.one_per_topic as one_per_topic, t.target_tag_id
FROM tags t
diff --git a/plugins/discourse-rewind/app/services/discourse_rewind/action/most_viewed_tags.rb b/plugins/discourse-rewind/app/services/discourse_rewind/action/most_viewed_tags.rb
index a207626c9a4..b0e038082d3 100644
--- a/plugins/discourse-rewind/app/services/discourse_rewind/action/most_viewed_tags.rb
+++ b/plugins/discourse-rewind/app/services/discourse_rewind/action/most_viewed_tags.rb
@@ -6,10 +6,10 @@ module DiscourseRewind
class MostViewedTags < BaseReport
FakeData = {
data: [
- { tag_id: 1, name: "cats" },
- { tag_id: 2, name: "dogs" },
- { tag_id: 3, name: "countries" },
- { tag_id: 4, name: "management" },
+ { tag_id: 1, slug: "cats", name: "cats" },
+ { tag_id: 2, slug: "dogs", name: "dogs" },
+ { tag_id: 3, slug: "countries", name: "countries" },
+ { tag_id: 4, slug: "management", name: "management" },
],
identifier: "most-viewed-tags",
}
@@ -23,11 +23,11 @@ module DiscourseRewind
.joins("INNER JOIN topic_tags ON topic_tags.topic_id = topics.id")
.joins("INNER JOIN tags ON tags.id = topic_tags.tag_id")
.where(user: user, viewed_at: date, tags: { id: Tag.visible(Guardian.new).pluck(:id) })
- .group("tags.id, tags.name")
+ .group("tags.id, tags.name, tags.slug")
.order("COUNT(DISTINCT topic_views.topic_id) DESC")
.limit(4)
- .pluck("tags.id, tags.name")
- .map { |tag_id, name| { tag_id: tag_id, name: name } }
+ .pluck("tags.id, tags.slug, tags.name")
+ .map { |tag_id, slug, name| { tag_id: tag_id, slug: slug, name: name } }
{ data: most_viewed_tags, identifier: "most-viewed-tags" }
end
diff --git a/plugins/discourse-rewind/assets/javascripts/discourse/components/reports/most-viewed-tags.gjs b/plugins/discourse-rewind/assets/javascripts/discourse/components/reports/most-viewed-tags.gjs
index 345a75cba93..a323394366f 100644
--- a/plugins/discourse-rewind/assets/javascripts/discourse/components/reports/most-viewed-tags.gjs
+++ b/plugins/discourse-rewind/assets/javascripts/discourse/components/reports/most-viewed-tags.gjs
@@ -48,7 +48,7 @@ export default class MostViewedTags extends Component {
"folder-wrapper"
(if (eq this.openedTag data.name) "--opened" "")
}}
- href={{getURL (concat "/tag/" data.name)}}
+ href={{getURL (concat "/tag/" data.slug "/" data.tag_id)}}
{{on "click" (fn this.handleFolderClick data.name)}}
>
<span class="folder-tab"></span>
diff --git a/plugins/discourse-rewind/spec/system/page_objects/pages/rewind.rb b/plugins/discourse-rewind/spec/system/page_objects/pages/rewind.rb
index 08b6f7b45ed..7d09d936ffb 100644
--- a/plugins/discourse-rewind/spec/system/page_objects/pages/rewind.rb
+++ b/plugins/discourse-rewind/spec/system/page_objects/pages/rewind.rb
@@ -150,7 +150,7 @@ module PageObjects
def has_tag_in_report?(tag)
has_css?(
- "a.folder-wrapper[href='/tag/#{tag.name}'] .most-viewed-tags__tag",
+ "a.folder-wrapper[href='/tag/#{tag.slug}/#{tag.id}'] .most-viewed-tags__tag",
text: "##{tag.name}",
)
end
diff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rb
index 264bc42ab45..843ce98df56 100644
--- a/spec/models/tag_spec.rb
+++ b/spec/models/tag_spec.rb
@@ -205,6 +205,18 @@ RSpec.describe Tag do
)
end
end
+
+ context "with numeric-only tag names" do
+ it "uses id-tag fallback for empty slugs" do
+ numeric_tag = Fabricate(:tag, name: "1")
+ Fabricate(:topic, tags: [numeric_tag])
+ expect(numeric_tag.slug).to eq("")
+
+ result = Tag.top_tags
+ entry = result.find { |t| t[:id] == numeric_tag.id }
+ expect(entry[:slug]).to eq("#{numeric_tag.id}-tag")
+ end
+ end
end
describe "#pm_tags" do
@@ -347,8 +359,8 @@ RSpec.describe Tag do
describe "full_url" do
let(:tag) { Fabricate(:tag, name: "🚀") }
- it "percent encodes emojis" do
- expect(tag.full_url).to eq("http://test.localhost/tag/%F0%9F%9A%80")
+ it "uses slug/id format" do
+ expect(tag.full_url).to eq("http://test.localhost/tag/#{tag.id}-tag/#{tag.id}")
end
end
diff --git a/spec/requests/tags_controller_spec.rb b/spec/requests/tags_controller_spec.rb
index 81b3c9ea8a1..bcdfd07f385 100644
--- a/spec/requests/tags_controller_spec.rb
+++ b/spec/requests/tags_controller_spec.rb
@@ -433,8 +433,8 @@ RSpec.describe TagsController do
it "should handle synonyms" do
synonym = Fabricate(:tag, target_tag: tag)
get "/tag/#{synonym.name}/l/top.json?period=daily"
- expect(response.status).to eq(302)
- expect(response.redirect_url).to match(%r{/tag/#{tag.name}/l/top.json\?period=daily})
+ expect(response.status).to eq(301)
+ expect(response.redirect_url).to match(%r{/tag/test/#{tag.id}/l/top\.json\?period=daily})
end
it "is not creating infinite redirect loop when tag is a synonym of itself" do
@@ -452,7 +452,7 @@ RSpec.describe TagsController do
sign_in(admin)
- get "/tag/test"
+ get "/tag/#{tag.slug}/#{tag.id}"
expect(response.status).to eq(200)
end
@@ -480,7 +480,7 @@ RSpec.describe TagsController do
it "puts the tag description in the meta description" do
described_tag = Fabricate(:tag, name: "test2", description: "This is a description")
- get "/tag/#{described_tag.name}"
+ get "/tag/#{described_tag.slug}/#{described_tag.id}"
expect(response.status).to eq(200)
@@ -490,7 +490,7 @@ RSpec.describe TagsController do
end
it "has a default description for tags without a description" do
- get "/tag/test"
+ get "/tag/#{tag.slug}/#{tag.id}"
expect(response.status).to eq(200)
@@ -857,7 +857,7 @@ RSpec.describe TagsController do
end
it "can render a topic list from the latest endpoint" do
- get "/tag/#{tag.name}/l/latest"
+ get "/tag/#{tag.slug}/#{tag.id}/l/latest"
expect(response.status).to eq(200)
expect(response.body).to include("topic-list")
end
@@ -1545,7 +1545,7 @@ RSpec.describe TagsController do
end
describe "#destroy_synonym" do
- subject(:destroy_synonym) { delete("/tag/#{tag.name}/synonyms/#{synonym.name}.json") }
+ subject(:destroy_synonym) { delete("/tag/#{tag.id}/synonyms/#{synonym.id}.json") }
fab!(:tag)
fab!(:synonym) { Fabricate(:tag, target_tag: tag, name: "synonym") }
@@ -1572,13 +1572,15 @@ RSpec.describe TagsController do
end
it "returns error if tag isn't a synonym" do
- delete "/tag/#{Fabricate(:tag).name}/synonyms/#{synonym.name}.json"
+ other_tag = Fabricate(:tag)
+ delete "/tag/#{other_tag.id}/synonyms/#{synonym.id}.json"
expect(response.status).to eq(400)
expect_same_tag_names(tag.reload.synonyms, [synonym])
end
it "returns error if synonym not found" do
- delete "/tag/#{Fabricate(:tag).name}/synonyms/nope.json"
+ other_tag = Fabricate(:tag)
+ delete "/tag/#{other_tag.id}/synonyms/-1.json"
expect(response.status).to eq(404)
expect_same_tag_names(tag.reload.synonyms, [synonym])
end
diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rb
index 2b1e089c068..fc5aac17c01 100644
--- a/spec/serializers/site_serializer_spec.rb
+++ b/spec/serializers/site_serializer_spec.rb
@@ -188,11 +188,17 @@ RSpec.describe SiteSerializer do
expect(serialized[:anonymous_default_navigation_menu_tags]).to eq(
[
- { id: tag.id, name: "dev", slug: "dev", description: "some description", pm_only: false },
+ {
+ id: tag.id,
+ name: "dev",
+ slug: tag.slug,
+ description: "some description",
+ pm_only: false,
+ },
{
id: tag2.id,
name: "random",
- slug: "random",
+ slug: tag2.slug,
description: tag2.description,
pm_only: false,
},
@@ -353,22 +359,22 @@ RSpec.describe SiteSerializer do
{
id: tag3.id,
name: tag3.name,
- slug: tag3.slug,
- description: tag2.description,
+ slug: tag3.slug_for_url,
+ description: tag3.description,
pm_only: false,
},
{
id: tag1.id,
name: tag1.name,
- slug: tag1.slug,
+ slug: tag1.slug_for_url,
description: tag1.description,
pm_only: false,
},
{
id: tag2.id,
name: tag2.name,
- slug: tag2.slug,
- description: tag3.description,
+ slug: tag2.slug_for_url,
+ description: tag2.description,
pm_only: false,
},
],
@@ -383,6 +389,19 @@ RSpec.describe SiteSerializer do
expect(serialized[:navigation_menu_site_top_tags]).to eq(nil)
end
+ it "should use slug_for_url for tags with empty slugs" do
+ numeric_tag =
+ Fabricate(:tag, name: "1").tap { |tag| Fabricate.times(10, :topic, tags: [tag]) }
+
+ expect(numeric_tag.slug).to eq("")
+
+ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
+ numeric_entry =
+ serialized[:navigation_menu_site_top_tags].find { |t| t[:id] == numeric_tag.id }
+
+ expect(numeric_entry[:slug]).to eq("#{numeric_tag.id}-tag")
+ end
+
it "should return an empty array if site has no top tags" do
Tag.delete_all
diff --git a/spec/serializers/tag_group_serializer_spec.rb b/spec/serializers/tag_group_serializer_spec.rb
index 51bb49a3853..bb8663e49e1 100644
--- a/spec/serializers/tag_group_serializer_spec.rb
+++ b/spec/serializers/tag_group_serializer_spec.rb
@@ -23,4 +23,28 @@ RSpec.describe TagGroupSerializer do
serialized = TagGroupSerializer.new(tag_group, root: false).as_json
expect(serialized[:tags]).to contain_exactly({ id: tag.id, name: tag.name, slug: tag.slug })
end
+
+ it "uses slug_for_url for tags with empty slugs" do
+ numeric_tag = Fabricate(:tag, name: "42")
+ expect(numeric_tag.slug).to eq("")
+
+ tag_group = Fabricate(:tag_group, tags: [numeric_tag])
+ serialized = TagGroupSerializer.new(tag_group, root: false).as_json
+
+ expect(serialized[:tags]).to contain_exactly(
+ { id: numeric_tag.id, name: numeric_tag.name, slug: "#{numeric_tag.id}-tag" },
+ )
+ end
+
+ it "uses slug_for_url for parent_tag with empty slug" do
+ parent = Fabricate(:tag, name: "99")
+ expect(parent.slug).to eq("")
+
+ tag_group = Fabricate(:tag_group, parent_tag: parent)
+ serialized = TagGroupSerializer.new(tag_group, root: false).as_json
+
+ expect(serialized[:parent_tag]).to eq(
+ [{ id: parent.id, name: parent.name, slug: "#{parent.id}-tag" }],
+ )
+ end
end
diff --git a/spec/serializers/tag_serializer_spec.rb b/spec/serializers/tag_serializer_spec.rb
index 80297a2ec75..60df05ef934 100644
--- a/spec/serializers/tag_serializer_spec.rb
+++ b/spec/serializers/tag_serializer_spec.rb
@@ -14,6 +14,14 @@ RSpec.describe TagSerializer do
serialized = described_class.new(tag, scope: Guardian.new(user), root: false).as_json
expect(serialized[:slug]).to eq(tag.slug)
end
+
+ it "uses slug_for_url when slug is empty" do
+ numeric_tag = Fabricate(:tag, name: "123")
+ expect(numeric_tag.slug).to eq("")
+
+ serialized = described_class.new(numeric_tag, scope: Guardian.new(user), root: false).as_json
+ expect(serialized[:slug]).to eq("#{numeric_tag.id}-tag")
+ end
end
describe "#topic_count" do
diff --git a/spec/serializers/topic_list_item_serializer_spec.rb b/spec/serializers/topic_list_item_serializer_spec.rb
index 1f16100cfb6..0edb4b6ee60 100644
--- a/spec/serializers/topic_list_item_serializer_spec.rb
+++ b/spec/serializers/topic_list_item_serializer_spec.rb
@@ -97,6 +97,17 @@ RSpec.describe TopicListItemSerializer do
expect(json[:posters].length).to eq(1)
end
+
+ it "uses slug_for_url for tags with empty slugs" do
+ numeric_tag = Fabricate(:tag, name: "7")
+ expect(numeric_tag.slug).to eq("")
+
+ topic.tags << numeric_tag
+ json = TopicListItemSerializer.new(topic, scope: Guardian.new(admin), root: false).as_json
+ entry = json[:tags].find { |t| t[:id] == numeric_tag.id }
+
+ expect(entry[:slug]).to eq("#{numeric_tag.id}-tag")
+ end
end
describe "correctly serializes op_likes data" do
diff --git a/spec/services/hashtag_autocomplete_service_spec.rb b/spec/services/hashtag_autocomplete_service_spec.rb
index 79093d90a87..5153ec28f38 100644
--- a/spec/services/hashtag_autocomplete_service_spec.rb
+++ b/spec/services/hashtag_autocomplete_service_spec.rb
@@ -323,7 +323,9 @@ RSpec.describe HashtagAutocompleteService do
expect(result[:category].map(&:slug)).to eq(["the-book-club"])
expect(result[:category].map(&:relative_url)).to eq(["/c/the-book-club/#{category1.id}"])
expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books])
- expect(result[:tag].map(&:relative_url)).to eq(%w[/tag/fiction-books /tag/great-books])
+ expect(result[:tag].map(&:relative_url)).to eq(
+ ["/tag/fiction-books/#{tag2.id}", "/tag/great-books/#{tag1.id}"],
+ )
end
it "does not include category the user cannot access" do
@@ -336,7 +338,7 @@ RSpec.describe HashtagAutocompleteService do
Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: ["great-books"])
result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])
expect(result[:tag].map(&:slug)).to eq(%w[fiction-books])
- expect(result[:tag].map(&:relative_url)).to eq(["/tag/fiction-books"])
+ expect(result[:tag].map(&:relative_url)).to eq(["/tag/fiction-books/#{tag2.id}"])
end
it "handles type suffixes for slugs" do
@@ -345,7 +347,9 @@ RSpec.describe HashtagAutocompleteService do
expect(result[:category].map(&:slug)).to eq(["the-book-club"])
expect(result[:category].map(&:relative_url)).to eq(["/c/the-book-club/#{category1.id}"])
expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books])
- expect(result[:tag].map(&:relative_url)).to eq(%w[/tag/fiction-books /tag/great-books])
+ expect(result[:tag].map(&:relative_url)).to eq(
+ ["/tag/fiction-books/#{tag2.id}", "/tag/great-books/#{tag1.id}"],
+ )
end
it "handles parent:child category lookups" do
@@ -384,7 +388,9 @@ RSpec.describe HashtagAutocompleteService do
expect(result[:category].map(&:slug)).to eq(["the-book-club"])
expect(result[:category].map(&:relative_url)).to eq(["/c/the-book-club/#{category1.id}"])
expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books])
- expect(result[:tag].map(&:relative_url)).to eq(%w[/tag/fiction-books /tag/great-books])
+ expect(result[:tag].map(&:relative_url)).to eq(
+ ["/tag/fiction-books/#{tag2.id}", "/tag/great-books/#{tag1.id}"],
+ )
category2 = Fabricate(:category, name: "Great Books", slug: "great-books")
result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])
@@ -393,21 +399,27 @@ RSpec.describe HashtagAutocompleteService do
["/c/great-books/#{category2.id}", "/c/the-book-club/#{category1.id}"],
)
expect(result[:tag].map(&:slug)).to eq(%w[fiction-books])
- expect(result[:tag].map(&:relative_url)).to eq(%w[/tag/fiction-books])
+ expect(result[:tag].map(&:relative_url)).to eq(["/tag/fiction-books/#{tag2.id}"])
category1.destroy!
- Fabricate(:tag, name: "the-book-club")
+ book_club_tag = Fabricate(:tag, name: "the-book-club")
result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])
expect(result[:category].map(&:slug)).to eq(["great-books"])
expect(result[:category].map(&:relative_url)).to eq(["/c/great-books/#{category2.id}"])
expect(result[:tag].map(&:slug)).to eq(%w[fiction-books the-book-club])
- expect(result[:tag].map(&:relative_url)).to eq(%w[/tag/fiction-books /tag/the-book-club])
+ expect(result[:tag].map(&:relative_url)).to eq(
+ ["/tag/fiction-books/#{tag2.id}", "/tag/the-book-club/#{book_club_tag.id}"],
+ )
result = service.lookup(%w[the-book-club great-books fiction-books], %w[tag category])
expect(result[:category]).to eq([])
expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books the-book-club])
expect(result[:tag].map(&:relative_url)).to eq(
- %w[/tag/fiction-books /tag/great-books /tag/the-book-club],
+ [
+ "/tag/fiction-books/#{tag2.id}",
+ "/tag/great-books/#{tag1.id}",
+ "/tag/the-book-club/#{book_club_tag.id}",
+ ],
)
end
diff --git a/spec/system/discovery_breadcrumb_navigation_spec.rb b/spec/system/discovery_breadcrumb_navigation_spec.rb
index afe5564e76f..d5d1212cd79 100644
--- a/spec/system/discovery_breadcrumb_navigation_spec.rb
+++ b/spec/system/discovery_breadcrumb_navigation_spec.rb
@@ -79,7 +79,7 @@ describe "Navigating with breadcrumbs", type: :system do
discovery.tag_drop.select_row_by_name(tag.name)
expect(page).to have_current_path(
- "/tags/c/#{category3.slug}/#{category3.id}/none/#{tag.name}",
+ "/tags/c/#{category3.slug}/#{category3.id}/none/#{tag.slug}/#{tag.id}",
)
expect(discovery.topic_list).to have_topics(count: 1)
expect(discovery.topic_list).to have_topic(c3_topic_tagged)
@@ -99,9 +99,9 @@ describe "Navigating with breadcrumbs", type: :system do
c3_topic.update!(tags: [tag])
c3_child_topic.update!(tags: [tag])
- visit("/tags/c/#{category3.slug}/#{category3.id}/#{tag.name}")
+ visit("/tags/c/#{category3.slug}/#{category3.id}/#{tag.name}/#{tag.id}")
expect(page).to have_current_path(
- "/tags/c/#{category3.slug}/#{category3.id}/none/#{tag.name}",
+ "/tags/c/#{category3.slug}/#{category3.id}/none/#{tag.slug}/#{tag.id}",
)
expect(discovery.topic_list).to have_topic(c3_topic)
expect(discovery.topic_list).to have_topics(count: 1)
diff --git a/spec/system/dismissing_new_spec.rb b/spec/system/dismissing_new_spec.rb
index 28de37ba05a..ecfbf724ce8 100644
--- a/spec/system/dismissing_new_spec.rb
+++ b/spec/system/dismissing_new_spec.rb
@@ -190,7 +190,7 @@ RSpec.describe "Dismissing New", type: :system do
it "works on tag routes" do
sign_in(user)
- visit("/tag/#{tag.name}/l/new")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new")
expect(topic_list).to have_topics(count: 1)
expect(topic_list).to have_topic(tagged_first_post.topic)
@@ -207,7 +207,7 @@ RSpec.describe "Dismissing New", type: :system do
it "works on regular routes after visiting tagged route" do
sign_in(user)
- visit("/tag/#{tag.name}/l/new")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new")
expect(topic_list).to have_topics(count: 1)
diff --git a/spec/system/tags/tags_spec.rb b/spec/system/tags/tags_spec.rb
index 5ba395fd1c1..b2b555dd156 100644
--- a/spec/system/tags/tags_spec.rb
+++ b/spec/system/tags/tags_spec.rb
@@ -53,6 +53,35 @@ describe "Tags", type: :system do
let(:user_private_messages_page) { PageObjects::Pages::UserPrivateMessages.new }
let(:sidebar) { PageObjects::Components::NavigationMenu::Sidebar.new }
+ it "uses correct tag slug in URL when selecting a searched tag from tag drop" do
+ rare_tag = Fabricate(:tag, name: "rare-tag")
+ popular_tag = Fabricate(:tag, name: "popular-tag")
+ category_for_tags = Fabricate(:category)
+
+ 2.times do
+ Fabricate(:topic, category: category_for_tags, tags: [popular_tag]).tap do |t|
+ Fabricate(:post, topic: t)
+ end
+ end
+ Fabricate(:topic, category: category_for_tags, tags: [rare_tag]).tap do |t|
+ Fabricate(:post, topic: t)
+ end
+ CategoryTagStat.update_topic_counts
+
+ SiteSetting.max_tags_in_filter_list = 1
+
+ sign_in(user_tl1)
+ category_page.visit(category_for_tags)
+
+ discovery.tag_drop.expand
+ discovery.tag_drop.search(rare_tag.name)
+ discovery.tag_drop.select_row_by_name(rare_tag.name)
+
+ expect(page).to have_current_path(
+ "/tags/c/#{category_for_tags.slug}/#{category_for_tags.id}/#{rare_tag.slug}/#{rare_tag.id}",
+ )
+ end
+
it "displays tags on topics in topic lists" do
sign_in(user_tl1)
@@ -66,18 +95,20 @@ describe "Tags", type: :system do
expect(discovery.topic_list).to have_no_topic_tags(topic_with_no_tags)
expect(discovery.tag_drop).to have_selected_name("tags") # unselected
- # /latest -> /tag/tag-one (by clicking tag on topic)
+ # /latest -> /tag/tag-one/id (by clicking tag on topic)
discovery.topic_list.click_topic_tag(topic_with_one_tag, "tag-one")
- expect(page).to have_current_path("/tag/tag-one")
+ expect(page).to have_current_path("/tag/#{tag_one.slug}/#{tag_one.id}")
expect(discovery.topic_list).to have_topic(topic_with_one_tag)
# /c/category
category_page.visit(category)
expect(discovery.topic_list).to have_topic_tag(topic_in_category_with_tag, "tag-three")
- # /c/category -> /tags/c/category-slug/category-id/tag-name
+ # /c/category -> /tags/c/category-slug/category-id/tag-slug/tag-id
discovery.tag_drop.select_row_by_name("tag-three")
- expect(page).to have_current_path("/tags/c/#{category.slug}/#{category.id}/tag-three")
+ expect(page).to have_current_path(
+ "/tags/c/#{category.slug}/#{category.id}/#{tag_three.slug}/#{tag_three.id}",
+ )
expect(discovery.tag_drop).to have_selected_name("tag-three")
expect(discovery.topic_list).to have_topic(topic_in_category_with_tag)
@@ -88,9 +119,9 @@ describe "Tags", type: :system do
expect(discovery.topic_list).to have_no_topic(topic_with_no_tags)
expect(discovery.topic_list).to have_topic_tag(topic_with_one_tag, "tag-one")
- # -> /tag/tag-one to /tag/tag-two
+ # -> /tag/tag-one/id to /tag/tag-two/id
discovery.topic_list.click_topic_tag(topic_with_two_tags, "tag-two")
- expect(page).to have_current_path("/tag/tag-two")
+ expect(page).to have_current_path("/tag/#{tag_two.slug}/#{tag_two.id}")
expect(discovery.topic_list).to have_topic(topic_with_two_tags)
expect(discovery.topic_list).to have_no_topic(topic_with_one_tag)
@@ -114,7 +145,7 @@ describe "Tags", type: :system do
## Sidebar
expect(sidebar).to have_tag_section_links([tag_one, tag_three, tag_two])
sidebar.click_section_link(tag_one.name)
- expect(page).to have_current_path("/tag/tag-one")
+ expect(page).to have_current_path("/tag/#{tag_one.slug}/#{tag_one.id}")
expect(discovery.topic_list).to have_topic(topic_with_one_tag)
end
end
diff --git a/spec/system/tags_intersection_spec.rb b/spec/system/tags_intersection_spec.rb
index 64031bf3a53..9a941276b4d 100644
--- a/spec/system/tags_intersection_spec.rb
+++ b/spec/system/tags_intersection_spec.rb
@@ -32,7 +32,7 @@ describe "Tags intersection", type: :system do
expect(discovery.topic_list).to have_topics(count: 1)
end
- it "removes the main tag from the additional tags list" do
+ it "shortens and redirects URLs" do
visit("/tags/intersection/sour/tangy/sour")
expect(page).to have_current_path("/tags/intersection/sour/tangy")
@@ -40,7 +40,7 @@ describe "Tags intersection", type: :system do
expect(page).to have_current_path("/tags/intersection/sour/tangy")
visit("/tags/intersection/sour/sour")
- expect(page).to have_current_path("/tag/sour")
+ expect(page).to have_current_path("/tag/#{tag.slug}/#{tag.id}")
end
it "removes duplicates from the additional tags list" do
@@ -65,4 +65,49 @@ describe "Tags intersection", type: :system do
expect(page).to have_current_path("/tags/intersection/sour/sweet")
end
+
+ context "with capitalized tag names" do
+ fab!(:cap_tag) { Fabricate(:tag, name: "Spicy") }
+ fab!(:cap_tag2) { Fabricate(:tag, name: "Bitter") }
+ fab!(:cap_tag3) { Fabricate(:tag, name: "Savory") }
+
+ fab!(:cap_tagged_topic) { Fabricate(:topic, tags: [cap_tag, cap_tag2, cap_tag3]) }
+ fab!(:cap_the_topic) { Fabricate(:topic, category:, tags: [cap_tag, cap_tag2, cap_tag3]) }
+
+ it "displays tag names in the chooser and shows correct topics when adding and removing tags" do
+ visit("/tags/intersection/#{cap_tag.slug}/#{cap_tag2.slug}")
+
+ chooser = PageObjects::Components::SelectKit.new(".tags-intersection-chooser")
+ expect(chooser).to have_selected_names("Spicy", "Bitter")
+ expect(discovery.topic_list).to have_topics(count: 2)
+ expect(discovery.topic_list).to have_topic(cap_tagged_topic)
+ expect(discovery.topic_list).to have_topic(cap_the_topic)
+
+ chooser.expand
+ chooser.select_row_by_name("Savory")
+
+ expect(page).to have_current_path("/tags/intersection/Spicy/Bitter/Savory")
+ expect(chooser).to have_selected_names("Spicy", "Bitter", "Savory")
+ expect(discovery.topic_list).to have_topics(count: 2)
+ expect(discovery.topic_list).to have_topic(cap_tagged_topic)
+ expect(discovery.topic_list).to have_topic(cap_the_topic)
+
+ chooser.unselect_by_name("Bitter")
+
+ expect(page).to have_current_path("/tags/intersection/Spicy/Savory")
+ expect(chooser).to have_selected_names("Spicy", "Savory")
+ expect(discovery.topic_list).to have_topics(count: 2)
+ end
+
+ it "navigates to canonical tag URL when removing tags down to one" do
+ visit("/tags/intersection/#{cap_tag.slug}/#{cap_tag2.slug}")
+
+ chooser = PageObjects::Components::SelectKit.new(".tags-intersection-chooser")
+ chooser.unselect_by_name("Bitter")
+
+ expect(page).to have_current_path("/tag/#{cap_tag.slug}/#{cap_tag.id}")
+ expect(discovery.topic_list).to have_topic(cap_tagged_topic)
+ expect(discovery.topic_list).to have_topic(cap_the_topic)
+ end
+ end
end
diff --git a/spec/system/unified_new_topic_list_spec.rb b/spec/system/unified_new_topic_list_spec.rb
index 92dee105f28..b476c9d95fa 100644
--- a/spec/system/unified_new_topic_list_spec.rb
+++ b/spec/system/unified_new_topic_list_spec.rb
@@ -224,7 +224,7 @@ describe "Unified new topic list", type: :system do
context "when the /new topic list is scoped to a tag" do
it "shows new topics and replies with the tag" do
- visit("/tag/#{tag.name}/l/new")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new")
expect(topic_list).to have_topics(count: 2)
[new_reply_with_tag, new_topic_with_tag].each do |topic|
expect(topic_list).to have_topic(topic)
@@ -239,7 +239,7 @@ describe "Unified new topic list", type: :system do
end
it "shows only new topics with the tag when the user switches to the Topics tab" do
- visit("/tag/#{tag.name}/l/new")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new")
tabs_toggle.topics_tab.click
expect(topic_list).to have_topics(count: 1)
@@ -252,11 +252,11 @@ describe "Unified new topic list", type: :system do
expect(tabs_toggle.replies_tab).to have_count(1)
expect(tabs_toggle.topics_tab).to have_count(1)
- expect(page).to have_current_path("/tag/#{tag.name}/l/new?subset=topics")
+ expect(page).to have_current_path("/tag/#{tag.slug}/#{tag.id}/l/new?subset=topics")
end
it "shows only topics with new replies with the tag when the user switches to the Replies tab" do
- visit("/tag/#{tag.name}/l/new")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new")
tabs_toggle.replies_tab.click
@@ -270,17 +270,17 @@ describe "Unified new topic list", type: :system do
expect(tabs_toggle.replies_tab).to have_count(1)
expect(tabs_toggle.topics_tab).to have_count(1)
- expect(page).to have_current_path("/tag/#{tag.name}/l/new?subset=replies")
+ expect(page).to have_current_path("/tag/#{tag.slug}/#{tag.id}/l/new?subset=replies")
end
it "respects the subset query param and activates the appropriate tab" do
- visit("/tag/#{tag.name}/l/new?subset=topics")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new?subset=topics")
expect(tabs_toggle.all_tab).to be_inactive
expect(tabs_toggle.replies_tab).to be_inactive
expect(tabs_toggle.topics_tab).to be_active
- visit("/tag/#{tag.name}/l/new?subset=replies")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new?subset=replies")
expect(tabs_toggle.all_tab).to be_inactive
expect(tabs_toggle.replies_tab).to be_active
@@ -290,7 +290,7 @@ describe "Unified new topic list", type: :system do
it "live-updates the counts shown on the tabs" do
Fabricate(:post, topic: Fabricate(:topic, tags: [tag]))
- visit("/tag/#{tag.name}/l/new")
+ visit("/tag/#{tag.slug}/#{tag.id}/l/new")
expect(tabs_toggle.replies_tab).to have_count(1)
expect(tabs_toggle.topics_tab).to have_count(2)