A platform for community discussion. Free, open, simple.
FEATURE: Prioritize recently used tags in the composer tag picker (#41669)
Régis Hanol62bc006ea690
diff --git a/app/models/tag.rb b/app/models/tag.rbindex 4bcc9092d68..522c9f95c0e 100644--- a/app/models/tag.rb+++ b/app/models/tag.rb@@ -230,6 +230,24 @@ class Tag < ActiveRecord::BaseSQLend+ def self.recently_used_by(user, limit: 10)+ return [] if user.blank?++ recent_topic_ids =+ Topic+ .where(user:, archetype: Archetype.default)+ .order(created_at: :desc, id: :desc)+ .limit(limit)+ .select(:id)++ TopicTag+ .joins(:topic)+ .where(topic_id: recent_topic_ids)+ .group(:tag_id)+ .order(Arel.sql("MAX(topics.created_at) DESC, MAX(topics.id) DESC"))+ .pluck(:tag_id)+ end+def self.include_tags?SiteSetting.tagging_enabledenddiff --git a/app/services/tags/search.rb b/app/services/tags/search.rbindex 9c868e10784..9523f64b141 100644--- a/app/services/tags/search.rb+++ b/app/services/tags/search.rb@@ -25,6 +25,7 @@ class Tags::Searchattribute :filterForInput, :booleanattribute :excludeSynonyms, :booleanattribute :excludeHasSynonyms, :boolean+ attribute :prioritizeRecentTags, :booleanvalidate :limit_is_valid@@ -112,6 +113,10 @@ class Tags::Searchdef search_tags(params:, category:, guardian:)filter_options = params.filter_options.merge(category: category)+ if (recent_tag_ids = recent_priority_tag_ids(params:, guardian:))+ filter_options[:order_recent_tag_ids] = recent_tag_ids+ end+tags_with_counts, filter_result_context =DiscourseTagging.filter_allowed_tags(guardian, **filter_options, with_context: true)@@ -123,6 +128,14 @@ class Tags::Searchcontext[:forbidden_message] = nilend+ def recent_priority_tag_ids(params:, guardian:)+ return unless params.prioritizeRecentTags && params.term.blank?+ return if guardian.anonymous?+ return unless UpcomingChanges.enabled_for_user?(:prioritize_recently_used_tags, guardian.user)++ Tag.recently_used_by(guardian.user).presence+ end+def append_disabled_tags(params:, category:, tags:, guardian:)selected_ids = params.resolved_selected_tag_idsskip_ids = tags.map { |t| t[:id] } | selected_idsdiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 5676bffa7fc..9ac23962a02 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -2901,6 +2901,7 @@ en:enable_new_checkbox_style: "Enable the redesigned checkbox style for FormKit checkboxes."enable_new_post_reactions_menu: "Enable the redesigned post likes and reactions menu, with infinite scroll and a native mobile experience."enable_new_composer_actions: "Enable the redesigned composer actions menu and combo save button, with whisper, no-bump, and unlist toggles surfaced next to the save action."+ prioritize_recently_used_tags: "When adding tags while creating or editing a topic, show the tags the member has recently used on their own topics at the top of the list, before the most popular tags of the forum."experimental_impersonation_time_limit_minutes: "How long before an impersonation session is automatically ended."page_loading_indicator: "Configure the loading indicator which appears during page navigations within Discourse. 'Spinner' is a full page indicator. 'Slider' shows a narrow bar at the top of the screen."show_user_menu_avatars: "Show user avatars in the user menu"diff --git a/config/site_settings.yml b/config/site_settings.ymlindex bc97867720a..39fa335003f 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -4542,6 +4542,14 @@ experimental:status: "beta"impact: "feature,all_members"learn_more_url: "https://meta.discourse.org/t/-/403635"+ prioritize_recently_used_tags:+ default: false+ client: true+ hidden: true+ area: "experimental"+ upcoming_change:+ status: "conceptual"+ impact: "feature,all_members"rename_faq_to_guidelines:default: falsehidden: truediff --git a/frontend/discourse/app/components/composer-container.gjs b/frontend/discourse/app/components/composer-container.gjsindex f277cd97afc..1ee1e51adc1 100644--- a/frontend/discourse/app/components/composer-container.gjs+++ b/frontend/discourse/app/components/composer-container.gjs@@ -392,6 +392,7 @@ export default class ComposerContainer extends Component {disabled=this.composer.disableTagsChoosercategoryId=this.composer.model.categoryIdminimum=this.composer.model.minimumRequiredTags+ prioritizeRecentTags=true}}/><PluginOutletdiff --git a/frontend/discourse/app/components/topic-metadata.gjs b/frontend/discourse/app/components/topic-metadata.gjsindex 0c0e5910962..1170482ff63 100644--- a/frontend/discourse/app/components/topic-metadata.gjs+++ b/frontend/discourse/app/components/topic-metadata.gjs@@ -36,6 +36,7 @@ export default <template>minimum=@minimumRequiredTagsfilterPlaceholder="tagging.choose_for_topic"useHeaderFilter=true+ prioritizeRecentTags=true}}/></PluginOutlet>diff --git a/frontend/discourse/select-kit/components/mini-tag-chooser.js b/frontend/discourse/select-kit/components/mini-tag-chooser.jsindex c6f9dbf282c..efac16e6fe5 100644--- a/frontend/discourse/select-kit/components/mini-tag-chooser.js+++ b/frontend/discourse/select-kit/components/mini-tag-chooser.js@@ -6,7 +6,6 @@ import {classNameBindings,classNames,} from "@ember-decorators/component";-import { bind } from "discourse/lib/decorators";import { makeArray } from "discourse/lib/helpers";import MultiSelectComponent from "discourse/select-kit/components/multi-select";import {@@ -35,6 +34,7 @@ import TagRow from "./tag-row";useHeaderFilter: false,valueProperty: "id",nameProperty: "name",+ prioritizeRecentTags: false,})@pluginApiIdentifiers(["mini-tag-chooser"])export default class MiniTagChooser extends MultiSelectComponent {@@ -175,15 +175,21 @@ export default class MiniTagChooser extends MultiSelectComponent {data.filterForInput = true;}- return this.tagUtils.searchTags(- "/tags/filter/search",- data,- this._transformJson+ const prioritizeRecentTags =+ this.selectKit.options.prioritizeRecentTags &&+ this.siteSettings.prioritize_recently_used_tags &&+ isEmpty(filter);++ if (prioritizeRecentTags) {+ data.prioritizeRecentTags = true;+ }++ return this.tagUtils.searchTags("/tags/filter/search", data, (json) =>+ this._transformJson(json, { skipSort: prioritizeRecentTags }));}- @bind- _transformJson(json) {+ _transformJson(json, { skipSort = false } = {}) {if (this.isDestroyed || this.isDestroying) {return [];}@@ -193,7 +199,9 @@ export default class MiniTagChooser extends MultiSelectComponent {termMatchErrorMessage: json.forbidden_message,});- let results = this.tagUtils.sortSearchResults(json.results);+ let results = skipSort+ ? json.results+ : this.tagUtils.sortSearchResults(json.results);if (json.required_tag_group) {this.set(diff --git a/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjs b/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjsindex 0382175fd3f..85799d3dad2 100644--- a/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjs+++ b/frontend/discourse/tests/integration/components/select-kit/mini-tag-chooser-test.gjs@@ -3,6 +3,7 @@ import { click, findAll, render, triggerKeyEvent } from "@ember/test-helpers";import { module, test } from "qunit";import MiniTagChooser from "discourse/select-kit/components/mini-tag-chooser";import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";import selectKit from "discourse/tests/helpers/select-kit-helper";import { i18n } from "discourse-i18n";@@ -28,6 +29,81 @@ module(assert.strictEqual(this.subject.header().value(), "foo,bar");});+ test("forwards prioritizeRecentTags to the server when the option is enabled", async function (assert) {+ this.siteSettings.prioritize_recently_used_tags = true;+ let capturedParams;+ pretender.get("/tags/filter/search", (request) => {+ capturedParams = request.queryParams;+ return response({ results: [] });+ });++ await render(+ <template>+ <MiniTagChooser @options={{hash prioritizeRecentTags=true}} />+ </template>+ );+ await this.subject.expand();++ assert.strictEqual(+ capturedParams.prioritizeRecentTags,+ "true",+ "the option is registered and forwarded as a request param"+ );+ });++ test("keeps the server's recent-first order when tags_sort_alphabetically is enabled", async function (assert) {+ this.siteSettings.tags_sort_alphabetically = true;+ this.siteSettings.prioritize_recently_used_tags = true;+ pretender.get("/tags/filter/search", () =>+ response({+ results: [+ { id: "z-recent", name: "z-recent", count: 1 },+ { id: "a-popular", name: "a-popular", count: 100 },+ ],+ })+ );++ await render(+ <template>+ <MiniTagChooser @options={{hash prioritizeRecentTags=true}} />+ </template>+ );+ await this.subject.expand();++ assert.deepEqual(+ findAll(".select-kit-row").map((el) => el.dataset.value),+ ["z-recent", "a-popular"],+ "the recently used tag stays first instead of being sorted alphabetically"+ );+ });++ test("still sorts alphabetically once a filter term is typed", async function (assert) {+ this.siteSettings.tags_sort_alphabetically = true;+ this.siteSettings.prioritize_recently_used_tags = true;+ pretender.get("/tags/filter/search", () =>+ response({+ results: [+ { id: "z-recent", name: "z-recent", count: 1 },+ { id: "a-popular", name: "a-popular", count: 100 },+ ],+ })+ );++ await render(+ <template>+ <MiniTagChooser @options={{hash prioritizeRecentTags=true}} />+ </template>+ );+ await this.subject.expand();+ await this.subject.fillInFilter("recent");++ assert.deepEqual(+ findAll(".select-kit-row").map((el) => el.dataset.value),+ ["a-popular", "z-recent"],+ "recent-first ordering does not leak into the filtered view"+ );+ });+test("create a tag", async function (assert) {this.set("value", [{ id: "foo", name: "foo", slug: "foo" },diff --git a/lib/discourse_tagging.rb b/lib/discourse_tagging.rbindex 4551ad32666..5405817cb78 100644--- a/lib/discourse_tagging.rb+++ b/lib/discourse_tagging.rb@@ -508,6 +508,7 @@ module DiscourseTagging# exclude_synonyms: exclude synonyms from results# order_search_results: result should be ordered for name search results# order_popularity: order result by topic_count+ # order_recent_tag_ids: ordered tag ids (most recent first) to prioritize at the top of the results# excluded_tag_names: an array of tag names not to include in the resultsdef self.filter_allowed_tags(guardian, opts = {})selected_tag_ids =@@ -530,6 +531,10 @@ module DiscourseTaggingbuilder_params[:selected_tag_ids] = selected_tag_ids unless selected_tag_ids.empty?+ if opts[:order_recent_tag_ids].present?+ builder_params[:order_recent_tag_ids] = opts[:order_recent_tag_ids]+ end+sql = +"WITH #{TAG_GROUP_RESTRICTIONS_SQL}, #{CATEGORY_RESTRICTIONS_SQL}"if (opts[:for_input] || opts[:for_topic]) && filter_for_non_adminsql << ", #{PERMITTED_TAGS_SQL} "@@ -542,7 +547,9 @@ module DiscourseTaggingtopic_count_column = Tag.topic_count_column(guardian)distinct_clause =- if opts[:order_popularity]+ if opts[:order_recent_tag_ids].present?+ "DISTINCT ON (array_position(ARRAY[:order_recent_tag_ids]::int[], t.id), #{topic_count_column}, name)"+ elsif opts[:order_popularity]"DISTINCT ON (#{topic_count_column}, name)"elsif opts[:order_search_results] && opts[:term].present?"DISTINCT ON (lower(name) = lower(:cleaned_term), #{topic_count_column}, name)"@@ -695,7 +702,10 @@ module DiscourseTaggingendend- if opts[:order_popularity]+ if opts[:order_recent_tag_ids].present?+ builder.order_by("array_position(ARRAY[:order_recent_tag_ids]::int[], t.id) ASC NULLS LAST")+ builder.order_by("#{topic_count_column} DESC, name")+ elsif opts[:order_popularity]builder.order_by("#{topic_count_column} DESC, name")elsif opts[:order_search_results] && term.present?builder.order_by("lower(name) = lower(:cleaned_term) DESC, #{topic_count_column} DESC, name")diff --git a/spec/lib/discourse_tagging_spec.rb b/spec/lib/discourse_tagging_spec.rbindex 1bb471d6fd3..a5aafbd0ac8 100644--- a/spec/lib/discourse_tagging_spec.rb+++ b/spec/lib/discourse_tagging_spec.rb@@ -425,6 +425,81 @@ RSpec.describe DiscourseTagging doenddescribe "filter_allowed_tags" do+ context "when ordering by recent tag ids" do+ fab!(:popular_tag) { Fabricate(:tag, name: "popular", public_topic_count: 100) }+ fab!(:recent_tag) { Fabricate(:tag, name: "recent", public_topic_count: 1) }++ it "lists the given tag ids first, then falls back to popularity" do+ names =+ DiscourseTagging.filter_allowed_tags(+ guardian,+ for_input: true,+ order_recent_tag_ids: [recent_tag.id],+ ).map(&:name)++ expect(names.first).to eq("recent")+ expect(names).to include("popular")+ expect(names.index("recent")).to be < names.index("popular")+ end++ it "orders multiple recent tag ids by their position in the list" do+ names =+ DiscourseTagging.filter_allowed_tags(+ guardian,+ for_input: true,+ order_popularity: true,+ order_recent_tag_ids: [tag2.id, tag1.id],+ ).map(&:name)++ expect(names.first(2)).to eq([tag2.name, tag1.name])+ end++ it "produces the same result as popularity ordering when no recent tag ids are given" do+ with_empty =+ DiscourseTagging.filter_allowed_tags(+ guardian,+ for_input: true,+ order_popularity: true,+ order_recent_tag_ids: [],+ ).map(&:name)+ without =+ DiscourseTagging.filter_allowed_tags(+ guardian,+ for_input: true,+ order_popularity: true,+ ).map(&:name)++ expect(with_empty).to eq(without)+ end++ it "orders by staff_topic_count for staff without raising" do+ names =+ DiscourseTagging.filter_allowed_tags(+ admin_guardian,+ for_input: true,+ order_popularity: true,+ order_recent_tag_ids: [recent_tag.id],+ ).map(&:name)++ expect(names.first).to eq("recent")+ end++ it "does not surface a recent tag id the user is not allowed to see" do+ secret_tag = Fabricate(:tag, name: "secret")+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [secret_tag.name])++ names =+ DiscourseTagging.filter_allowed_tags(+ guardian,+ for_input: true,+ order_popularity: true,+ order_recent_tag_ids: [secret_tag.id],+ ).map(&:name)++ expect(names).not_to include("secret")+ end+ end+context "for input fields" doit "doesn't return selected tags if there's a search term" dotags =diff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rbindex 398898a7fe3..e56539c3416 100644--- a/spec/models/tag_spec.rb+++ b/spec/models/tag_spec.rb@@ -296,6 +296,51 @@ RSpec.describe Tag doendend+ describe ".recently_used_by" do+ it "returns the user's tags, most recently used first" do+ older_tag = Fabricate(:tag)+ newer_tag = Fabricate(:tag)+ Fabricate(:topic, user: user, tags: [older_tag])+ Fabricate(:topic, user: user, tags: [newer_tag])++ expect(Tag.recently_used_by(user)).to eq([newer_tag.id, older_tag.id])+ end++ it "orders by the topic's creation date, not its id" do+ recent_tag = Fabricate(:tag)+ old_tag = Fabricate(:tag)+ Fabricate(:topic, user: user, tags: [recent_tag], created_at: 1.minute.ago)+ Fabricate(:topic, user: user, tags: [old_tag], created_at: 1.year.ago)++ expect(Tag.recently_used_by(user)).to eq([recent_tag.id, old_tag.id])+ end++ it "excludes tags from private messages" do+ Fabricate(:private_message_topic, user: user, tags: [Fabricate(:tag)])++ expect(Tag.recently_used_by(user)).to be_empty+ end++ it "excludes tags from deleted topics" do+ Fabricate(:topic, user: user, tags: [Fabricate(:tag)]).trash!++ expect(Tag.recently_used_by(user)).to be_empty+ end++ it "only considers the given number of most recent topics" do+ older_tag = Fabricate(:tag)+ newer_tag = Fabricate(:tag)+ Fabricate(:topic, user: user, tags: [older_tag])+ Fabricate(:topic, user: user, tags: [newer_tag])++ expect(Tag.recently_used_by(user, limit: 1)).to eq([newer_tag.id])+ end++ it "returns an empty array for a user with no topics" do+ expect(Tag.recently_used_by(user)).to eq([])+ end+ end+describe ".ensure_consistency!" doit "should exclude private message topics" dotopicdiff --git a/spec/requests/tags_controller_spec.rb b/spec/requests/tags_controller_spec.rbindex 26d1e68a835..dd2d94768a0 100644--- a/spec/requests/tags_controller_spec.rb+++ b/spec/requests/tags_controller_spec.rb@@ -1597,6 +1597,26 @@ RSpec.describe TagsController do)end+ it "surfaces the signed-in user's recently used tags first when the upcoming change is enabled" do+ SiteSetting.prioritize_recently_used_tags = true+ Fabricate(:tag, name: "popular", public_topic_count: 100)+ recent = Fabricate(:tag, name: "recent", public_topic_count: 1)+ Fabricate(:topic, user: user, tags: [recent])+ sign_in(user)++ get "/tags/filter/search.json",+ params: {+ q: "",+ prioritizeRecentTags: true,+ filterForInput: true,+ }++ expect(response.status).to eq(200)+ names = response.parsed_body["results"].map { |tag| tag["name"] }+ expect(names.first).to eq("recent")+ expect(names).to include("popular")+ end+context "with category restriction" dofab!(:yup) { Fabricate(:tag, name: "yup") }fab!(:category) { Fabricate(:category, tags: [yup]) }diff --git a/spec/services/tags/search_spec.rb b/spec/services/tags/search_spec.rbindex cdb2b4357f3..a3fc5fe2582 100644--- a/spec/services/tags/search_spec.rb+++ b/spec/services/tags/search_spec.rb@@ -78,6 +78,49 @@ RSpec.describe(Tags::Search) doendend+ context "with prioritizeRecentTags on the blank composer dropdown" do+ fab!(:popular_tag) { Fabricate(:tag, name: "popular", public_topic_count: 100) }+ fab!(:recent_tag_a) { Fabricate(:tag, name: "recenta") }+ fab!(:recent_tag_b) { Fabricate(:tag, name: "recentb") }++ let(:params) { { prioritizeRecentTags: true, filterForInput: true } }++ before { SiteSetting.prioritize_recently_used_tags = true }++ def tag_names(call_params, guardian: Guardian.new(user))+ described_class.call(params: call_params, guardian:)[:tags].map { |tag| tag[:name] }+ end++ it "surfaces tags from the user's recent topics first, most recently used first" do+ Fabricate(:topic, user: user, tags: [recent_tag_a])+ Fabricate(:topic, user: user, tags: [recent_tag_b])++ names = tag_names(params)+ expect(names.first(2)).to eq(%w[recentb recenta])+ expect(names.index("recentb")).to be < names.index("popular")+ end++ it "falls back to popularity ordering when the upcoming change is disabled" do+ SiteSetting.prioritize_recently_used_tags = false+ Fabricate(:topic, user: user, tags: [recent_tag_a])++ expect(tag_names(params).first).to eq("popular")+ end++ it "falls back to popularity ordering for anonymous users" do+ Fabricate(:topic, user: user, tags: [recent_tag_a])++ expect(tag_names(params, guardian: Guardian.new).first).to eq("popular")+ end++ it "does not reorder once the user starts typing a term" do+ Fabricate(:topic, user: user, tags: [recent_tag_a])+ Fabricate(:topic, user: user, tags: [recent_tag_b])++ expect(tag_names(params.merge(q: "recent"))).to eq(%w[recenta recentb])+ end+ end+context "with a category" dofab!(:category)