Skip to content

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

FEATURE: create tags inline on the /tags route (#36645)

Krisf6e08ec9aff6
diff --git a/app/assets/stylesheets/common/base/tagging.scss b/app/assets/stylesheets/common/base/tagging.scss
index dff0f0eb125..c534185cb9e 100644
--- a/app/assets/stylesheets/common/base/tagging.scss
+++ b/app/assets/stylesheets/common/base/tagging.scss
@@ -447,10 +447,58 @@ body.tags-intersection {
.tags-controls {
display: flex;
+ flex-wrap: wrap;
margin: 0;
+ .bulk-create-tags-form {
+ width: 100%;
+ display: flex;
+ align-items: end;
+ gap: 0.5em;
+ margin-block: 0.5em 1em;
+
+ textarea {
+ box-sizing: border-box;
+ min-height: 2.25em;
+ padding: 0.35em;
+ margin: 0;
+ width: min(20em, 100%);
+ border-radius: var(--d-input-border-radius);
+ }
+ }
+
h2 {
- order: -1;
- margin-right: auto;
+ margin: 0 auto 0 0;
+ }
+}
+
+.bulk-create-results {
+ .result-section {
+ display: flex;
+ gap: var(--space-1);
+ flex-wrap: wrap;
+
+ h4 {
+ margin: 0;
+ }
+
+ &.--failed {
+ display: flex;
+ flex-direction: column;
+ align-items: start;
+ }
+
+ &:not(:last-child) {
+ margin-bottom: var(--space-1);
+ }
+
+ ul {
+ margin: 0;
+ list-style-type: none;
+ }
+
+ li {
+ overflow-wrap: anywhere;
+ }
}
}
diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb
index 6a76f33d9cf..45fb66381a0 100644
--- a/app/controllers/tags_controller.rb
+++ b/app/controllers/tags_controller.rb
@@ -273,6 +273,16 @@ class TagsController < ::ApplicationController
end
end
+ def bulk_create
+ Tags::BulkCreate.call(guardian: guardian, params: params.permit(tag_names: [])) do
+ on_success { |results:| render json: results }
+ on_failed_policy(:can_admin_tags) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render_json_error(contract.errors.full_messages.first, status: :unprocessable_entity)
+ end
+ end
+ end
+
def list_unused
guardian.ensure_can_admin_tags!
render json: { tags: Tag.unused.pluck(:name) }
diff --git a/app/services/tags/bulk_create.rb b/app/services/tags/bulk_create.rb
new file mode 100644
index 00000000000..17d567d7a9f
--- /dev/null
+++ b/app/services/tags/bulk_create.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+# Creates multiple tags in bulk and returns detailed results for each tag.
+# Tags can be successfully created, already exist, or fail validation.
+#
+# @example
+# Tags::BulkCreate.call(
+# guardian: guardian,
+# params: {
+# tag_names: ["tag1", "tag2", "existing-tag"]
+# }
+# )
+#
+class Tags::BulkCreate
+ include Service::Base
+
+ # @!method self.call(guardian:, params:)
+ # @param [Guardian] guardian
+ # @param [Hash] params
+ # @option params [Array<String>] :tag_names Array of tag names to create (max 100)
+ # @return [Service::Base::Context] context with :results containing created, existing, and failed tags
+
+ policy :can_admin_tags
+
+ params do
+ attribute :tag_names, :array
+
+ validates :tag_names,
+ length: {
+ maximum: 100,
+ message: ->(object, data) { I18n.t("tags.bulk_create.too_many_tags", max: 100) },
+ },
+ if: -> { tag_names.present? }
+
+ validate :tag_names_must_be_array
+
+ def tag_names_must_be_array
+ raw_value = @attributes["tag_names"].value_before_type_cast
+ if raw_value.nil?
+ errors.add(:tag_names, I18n.t("tags.bulk_create.invalid_params"))
+ return
+ end
+ return if raw_value.is_a?(Array)
+ errors.add(:tag_names, I18n.t("tags.bulk_create.invalid_params"))
+ end
+ end
+
+ step :extract_raw_tag_names
+ step :normalize_tags
+ step :create_tags
+
+ private
+
+ def can_admin_tags(guardian:)
+ guardian.can_admin_tags?
+ end
+
+ def extract_raw_tag_names(params:)
+ raw_values = params.instance_variable_get(:@attributes)["tag_names"].value_before_type_cast
+ context[:raw_tag_names] = raw_values.map(&:to_s) if raw_values.is_a?(Array)
+ end
+
+ def normalize_tags(raw_tag_names:)
+ results = { created: [], existing: [], failed: {} }
+ validated_tags = []
+
+ raw_tag_names.each do |raw_name|
+ next if raw_name.blank?
+
+ normalized_input = raw_name.strip.downcase.gsub(/[[:space:]]+/, "-")
+
+ if normalized_input.length > SiteSetting.max_tag_length
+ results[:failed][raw_name] = I18n.t(
+ "tags.bulk_create.tag_too_long",
+ max: SiteSetting.max_tag_length,
+ )
+ next
+ end
+
+ tag_name = DiscourseTagging.clean_tag(raw_name)
+
+ if tag_name.blank?
+ results[:failed][raw_name] = I18n.t("tags.bulk_create.invalid_name")
+ next
+ end
+
+ if tag_name != normalized_input
+ results[:failed][raw_name] = I18n.t("tags.bulk_create.invalid_name")
+ next
+ end
+
+ validated_tags << { raw_name: raw_name, tag_name: tag_name }
+ end
+
+ context[:validated_tags] = validated_tags
+ context[:results] = results
+ end
+
+ def create_tags(validated_tags:, results:)
+ tag_names = validated_tags.map { |t| t[:tag_name] }
+ existing_tag_names = Tag.where(name: tag_names).pluck(:name).to_set
+
+ validated_tags.each do |tag_info|
+ tag_name = tag_info[:tag_name]
+ raw_name = tag_info[:raw_name]
+
+ if existing_tag_names.include?(tag_name)
+ results[:existing] << tag_name
+ else
+ tag = Tag.new(name: tag_name)
+ if tag.save
+ results[:created] << tag_name
+ else
+ results[:failed][raw_name] = tag.errors.full_messages.join(", ")
+ end
+ end
+ end
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index b465cc1d874..51209a974e1 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -5190,6 +5190,15 @@ en:
upload_description: "Upload a csv file to create tags in bulk"
upload_instructions: "One per line, optionally with a tag group in the format 'tag_name,tag_group'."
upload_successful: "Tags uploaded successfully"
+ bulk_create_inline_placeholder: "Create tags (comma-separated)"
+ bulk_create_button: "Create"
+ bulk_create_success:
+ one: "Created %{count} tag:"
+ other: "Created %{count} tags:"
+ bulk_create_already_exist:
+ one: "%{count} tag already exists:"
+ other: "%{count} tags already exist:"
+ bulk_create_some_failed: "Some tags failed to create:"
delete_unused_confirmation:
one: "%{count} tag will be deleted: %{tags}"
other: "%{count} tags will be deleted: %{tags}"
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index e04da80725b..0a2ca11ebb0 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -5450,6 +5450,11 @@ en:
one: "You must select at least %{count} tag."
other: "You must select at least %{count} tags."
upload_row_too_long: "The CSV file should have one tag per line. Optionally the tag can be followed by a comma, then the tag group name."
+ bulk_create:
+ invalid_params: "Invalid parameters. Please provide an array of tag names."
+ invalid_name: "Invalid tag name."
+ tag_too_long: "Tag is too long (max %{max} characters)."
+ too_many_tags: "Too many tags. You can create up to %{max} tags at once. For larger imports, use the CSV upload feature."
forbidden:
invalid:
one: "The tag you selected cannot be used"
diff --git a/config/routes.rb b/config/routes.rb
index e1217dacbb1..b4c2478e268 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1682,6 +1682,7 @@ Discourse::Application.routes.draw do
username: RouteFormat.username,
}
post "/upload" => "tags#upload"
+ post "/bulk_create" => "tags#bulk_create"
get "/unused" => "tags#list_unused"
delete "/unused" => "tags#destroy_unused"
diff --git a/frontend/discourse/app/controllers/tags/index.js b/frontend/discourse/app/controllers/tags/index.js
index 635080ed985..efaa5a621dd 100644
--- a/frontend/discourse/app/controllers/tags/index.js
+++ b/frontend/discourse/app/controllers/tags/index.js
@@ -1,10 +1,24 @@
+import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
import { action } from "@ember/object";
import { alias, notEmpty } from "@ember/object/computed";
+import { schedule } from "@ember/runloop";
+import { service } from "@ember/service";
+import autosize from "autosize";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
import discourseComputed from "discourse/lib/decorators";
import { optionalRequire } from "discourse/lib/utilities";
export default class TagsIndexController extends Controller {
+ @service router;
+
+ @tracked bulkTagInput = "";
+ @tracked isCreatingTags = false;
+ @tracked bulkCreateResults = null;
+
+ bulkTagTextarea = null;
+
sortedByCount = true;
sortedByName = false;
@@ -29,6 +43,17 @@ export default class TagsIndexController extends Controller {
return optionalRequire("discourse/admin/components/tags-admin-dropdown");
}
+ get canCreateTags() {
+ return this.bulkTagInput && this.bulkTagInput.trim().length > 0;
+ }
+
+ get hasFailedTags() {
+ return (
+ this.bulkCreateResults?.failed &&
+ Object.keys(this.bulkCreateResults.failed).length > 0
+ );
+ }
+
@discourseComputed("groupedByCategory", "groupedByTagGroup")
otherTagsTitleKey(groupedByCategory, groupedByTagGroup) {
if (!groupedByCategory && !groupedByTagGroup) {
@@ -57,4 +82,55 @@ export default class TagsIndexController extends Controller {
sortedByName: true,
});
}
+
+ @action
+ registerTextarea(element) {
+ this.bulkTagTextarea = element;
+ }
+
+ @action
+ async bulkCreateTags(event) {
+ event?.preventDefault();
+
+ if (!this.bulkTagInput || this.bulkTagInput.trim().length === 0) {
+ return;
+ }
+
+ const tagNames = this.bulkTagInput
+ .split(/[,\n\r]+/)
+ .map((tag) => tag.trim())
+ .filter((tag) => tag.length > 0);
+
+ if (tagNames.length === 0) {
+ return;
+ }
+
+ this.isCreatingTags = true;
+
+ try {
+ const response = await ajax("/tags/bulk_create.json", {
+ type: "POST",
+ data: { tag_names: tagNames },
+ });
+
+ this.bulkTagInput = "";
+ this.bulkCreateResults = response;
+
+ schedule("afterRender", () => {
+ if (this.bulkTagTextarea) {
+ autosize.update(this.bulkTagTextarea);
+ }
+ });
+ this.router.refresh();
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.isCreatingTags = false;
+ }
+ }
+
+ @action
+ dismissResults() {
+ this.bulkCreateResults = null;
+ }
}
diff --git a/frontend/discourse/app/templates/tags/index.gjs b/frontend/discourse/app/templates/tags/index.gjs
index a95e48a5e3c..804c86490e3 100644
--- a/frontend/discourse/app/templates/tags/index.gjs
+++ b/frontend/discourse/app/templates/tags/index.gjs
@@ -1,8 +1,15 @@
+import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import DButton from "discourse/components/d-button";
import DiscourseBanner from "discourse/components/discourse-banner";
+import ExpandingTextArea from "discourse/components/expanding-text-area";
import PluginOutlet from "discourse/components/plugin-outlet";
import TagList from "discourse/components/tag-list";
+import discourseTags from "discourse/helpers/discourse-tags";
import lazyHash from "discourse/helpers/lazy-hash";
+import withEventValue from "discourse/helpers/with-event-value";
+import { not, or } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
export default <template>
@@ -12,11 +19,84 @@ export default <template>
<div class="container tags-index">
+ {{#if @controller.bulkCreateResults}}
+ <div class="bulk-create-results alert alert-info">
+ <DButton
+ @action={{@controller.dismissResults}}
+ @icon="xmark"
+ class="btn-flat close"
+ />
+
+ {{#if @controller.bulkCreateResults.created.length}}
+ <div class="result-section">
+ <h4>
+ {{i18n
+ "tagging.bulk_create_success"
+ }}
+ </h4>
+ {{discourseTags null [email protected]}}
+ </div>
+ {{/if}}
+
+ {{#if @controller.bulkCreateResults.existing.length}}
+ <div class="result-section">
+ <h4>
+ {{i18n
+ "tagging.bulk_create_already_exist"
+ }}
+ </h4>
+ {{discourseTags null [email protected]}}
+ </div>
+ {{/if}}
+
+ {{#if @controller.hasFailedTags}}
+ <div class="result-section --failed">
+ <h4>{{i18n "tagging.bulk_create_some_failed"}}</h4>
+ <ul>
+ {{#each-in @controller.bulkCreateResults.failed as |tag error|}}
+ <li><code>{{tag}}</code>: {{error}}</li>
+ {{/each-in}}
+ </ul>
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+
<div class="container tags-controls">
+ <h2>{{i18n "tagging.tags"}}</h2>
{{#if @controller.canAdminTags}}
<@controller.TagsAdminDropdownComponent />
+ <form
+ class="bulk-create-tags-form"
+ {{on "submit" @controller.bulkCreateTags}}
+ >
+ <label for="bulk-tags-input" class="sr-only">
+ {{i18n "tagging.bulk_create_inline_placeholder"}}
+ </label>
+ <ExpandingTextArea
+ {{didInsert @controller.registerTextarea}}
+ {{on "input" (withEventValue (fn (mut @controller.bulkTagInput)))}}
+ value={{@controller.bulkTagInput}}
+ placeholder={{i18n "tagging.bulk_create_inline_placeholder"}}
+ disabled={{@controller.isCreatingTags}}
+ rows="1"
+ id="bulk-tags-input"
+ class="bulk-tags-input"
+ />
+ <DButton
+ @action={{@controller.bulkCreateTags}}
+ @disabled={{or
+ @controller.isCreatingTags
+ (not @controller.canCreateTags)
+ }}
+ @icon="tag"
+ @label="tagging.bulk_create_button"
+ class="btn-primary"
+ />
+ </form>
{{/if}}
- <h2>{{i18n "tagging.tags"}}</h2>
</div>
<div>
diff --git a/spec/services/tags/bulk_create_spec.rb b/spec/services/tags/bulk_create_spec.rb
new file mode 100644
index 00000000000..17e06b96717
--- /dev/null
+++ b/spec/services/tags/bulk_create_spec.rb
@@ -0,0 +1,195 @@
+# frozen_string_literal: true
+
+RSpec.describe(Tags::BulkCreate) do
+ describe described_class::Contract, type: :model do
+ it "rejects nil tag_names" do
+ contract = described_class.new(tag_names: nil)
+ expect(contract.valid?).to be false
+ expect(contract.errors[:tag_names]).to be_present
+ end
+
+ it "rejects non-array tag_names" do
+ contract = described_class.new(tag_names: "not an array")
+ expect(contract.valid?).to be false
+ expect(contract.errors[:tag_names]).to be_present
+ end
+
+ it "validates tag_names limit" do
+ contract = described_class.new(tag_names: (1..101).map { |i| "tag#{i}" })
+ expect(contract.valid?).to be false
+ expect(contract.errors[:tag_names]).to be_present
+ expect(contract.errors[:tag_names].first).to include("Too many tags")
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:current_user, :admin)
+
+ let(:params) { { tag_names: } }
+ let(:dependencies) { { guardian: current_user.guardian } }
+ let(:tag_names) { %w[tag1 tag2 tag3] }
+
+ context "when user is not allowed to perform the action" do
+ fab!(:current_user, :user)
+
+ it { is_expected.to fail_a_policy(:can_admin_tags) }
+ end
+
+ context "when contract is invalid" do
+ let(:tag_names) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when tag_names is not an array" do
+ let(:tag_names) { "not an array" }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when tag_names exceeds limit" do
+ let(:tag_names) { (1..101).map { |i| "tag#{i}" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates the tags" do
+ expect { result }.to change { Tag.count }.by(3)
+ expect(Tag.where(name: tag_names).count).to eq(3)
+ end
+
+ it "returns the created tags" do
+ expect(result.results[:created]).to contain_exactly("tag1", "tag2", "tag3")
+ expect(result.results[:existing]).to be_empty
+ expect(result.results[:failed]).to be_empty
+ end
+ end
+
+ context "when some tags already exist" do
+ fab!(:existing_tag) { Fabricate(:tag, name: "existing-tag") }
+
+ let(:tag_names) { %w[existing-tag new-tag] }
+
+ it { is_expected.to run_successfully }
+
+ it "creates only new tags" do
+ expect { result }.to change { Tag.count }.by(1)
+ end
+
+ it "reports existing tags separately" do
+ expect(result.results[:created]).to contain_exactly("new-tag")
+ expect(result.results[:existing]).to contain_exactly("existing-tag")
+ expect(result.results[:failed]).to be_empty
+ end
+ end
+
+ context "when tags need cleaning" do
+ let(:tag_names) { ["Tag With Spaces", "UPPERCASE"] }
+
+ it { is_expected.to run_successfully }
+
+ it "cleans tag names" do
+ result
+ expect(Tag.where(name: %w[tag-with-spaces uppercase]).count).to eq(2)
+ end
+
+ it "returns cleaned names" do
+ expect(result.results[:created]).to contain_exactly("tag-with-spaces", "uppercase")
+ end
+ end
+
+ context "when tag names are numbers" do
+ let(:tag_names) { [123, 456, 789] }
+
+ it { is_expected.to run_successfully }
+
+ it "converts numbers to strings and creates tags" do
+ expect { result }.to change { Tag.count }.by(3)
+ expect(Tag.where(name: %w[123 456 789]).count).to eq(3)
+ end
+
+ it "returns the created tags as strings" do
+ expect(result.results[:created]).to contain_exactly("123", "456", "789")
+ end
+ end
+
+ context "when tag names have leading zeros" do
+ let(:tag_names) { %w[0000 0123 00test] }
+
+ it { is_expected.to run_successfully }
+
+ it "preserves leading zeros" do
+ expect { result }.to change { Tag.count }.by(3)
+ expect(Tag.where(name: %w[0000 0123 00test]).count).to eq(3)
+ end
+
+ it "returns tags with leading zeros preserved" do
+ expect(result.results[:created]).to contain_exactly("0000", "0123", "00test")
+ end
+ end
+
+ context "when some tags are invalid" do
+ let(:tag_names) { ["", "valid-tag", " ", "%^&ui^&*", "!!!test"] }
+
+ it { is_expected.to run_successfully }
+
+ it "creates only valid tags" do
+ expect { result }.to change { Tag.count }.by(1)
+ end
+
+ it "reports failed tags" do
+ expect(result.results[:created]).to contain_exactly("valid-tag")
+ expect(result.results[:failed].keys).to contain_exactly("%^&ui^&*", "!!!test")
+ end
+ end
+
+ context "when a tag is too long" do
+ let(:long_tag) { "a" * (SiteSetting.max_tag_length + 1) }
+ let(:tag_names) { [long_tag, "short-tag"] }
+
+ it { is_expected.to run_successfully }
+
+ it "creates only valid tags" do
+ expect { result }.to change { Tag.count }.by(1)
+ end
+
+ it "reports the error" do
+ expect(result.results[:created]).to contain_exactly("short-tag")
+ expect(result.results[:failed][long_tag]).to be_present
+ expect(result.results[:failed][long_tag]).to include("too long")
+ end
+ end
+
+ context "when tag_names array is empty" do
+ let(:tag_names) { [] }
+
+ it { is_expected.to run_successfully }
+
+ it "returns empty results" do
+ expect(result.results[:created]).to be_empty
+ expect(result.results[:existing]).to be_empty
+ expect(result.results[:failed]).to be_empty
+ end
+ end
+
+ context "when mixing valid, existing, and invalid tags" do
+ fab!(:existing_tag) { Fabricate(:tag, name: "existing") }
+
+ let(:tag_names) { ["new-tag", "existing", "", "invalid@@@", "another-new"] }
+
+ it { is_expected.to run_successfully }
+
+ it "processes all tags correctly" do
+ expect { result }.to change { Tag.count }.by(2)
+ expect(result.results[:created]).to contain_exactly("new-tag", "another-new")
+ expect(result.results[:existing]).to contain_exactly("existing")
+ expect(result.results[:failed].keys).to contain_exactly("invalid@@@")
+ end
+ end
+ end
+end