Skip to content

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

UX: Add or remove category types with a dropdown (#39477)

Martin Brennan1ce56974302f
diff --git a/app/assets/stylesheets/common/base/edit-category.scss b/app/assets/stylesheets/common/base/edit-category.scss
index b6551f93f48..952a6516272 100644
--- a/app/assets/stylesheets/common/base/edit-category.scss
+++ b/app/assets/stylesheets/common/base/edit-category.scss
@@ -396,3 +396,47 @@ div.edit-category {
width: 100%;
}
}
+
+.category-type-selector {
+ width: var(--form-kit-max-input);
+
+ .d-multi-select-trigger__selected-item
+ .d-multi-select-trigger__selection-label {
+ max-width: unset;
+ }
+
+ &__result {
+ &.--unavailable {
+ .category-type-selector__icon {
+ opacity: 0.5;
+ }
+
+ .category-type-selector__name {
+ color: var(--primary-medium);
+ }
+
+ .category-type-selector__description {
+ opacity: 0.5;
+ }
+ }
+ }
+
+ &__content {
+ .d-multi-select__search-results {
+ min-height: 160px;
+ }
+ }
+
+ &__name {
+ font-weight: bold;
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ line-height: 1em;
+ padding: var(--space-1) 0;
+ }
+
+ .d-multi-select__result-label {
+ display: flex;
+ }
+}
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb
index 1448ba89c54..e68e92b732c 100644
--- a/app/controllers/categories_controller.rb
+++ b/app/controllers/categories_controller.rb
@@ -230,49 +230,18 @@ class CategoriesController < ApplicationController
category_params.delete(:position)
old_custom_fields = cat.custom_fields.dup
- category_params[:custom_fields]&.each do |key, value|
- if value.nil? || value == ""
- cat.custom_fields.delete(key)
- else
- cat.custom_fields[key] = if value.is_a?(TrueClass) || value.is_a?(FalseClass)
- value.to_s
- else
- value
- end
- end
- end
+ pending_custom_fields = category_params[:custom_fields]
category_params.delete(:custom_fields)
- if UpcomingChanges.enabled_for_user?(:enable_simplified_category_creation, current_user) &&
- params[:category_type_site_settings].present?
- # NOTE: The code in this block is pretty similar to what we are doing in
- # configure_site_settings in Categories::Types::Base, however here we
- # need to be able to update site settings across all category types for
- # the category and it's best to do this in one query rather than
- # multiple.
- #
- # Maybe in future we do something different, but this is a good starting point.
- category_type_settings =
- params[:category_type_site_settings].permit!.to_h.map do |name, value|
- { setting_name: name, value: }
- end
-
- # We do this because we want to allow updating hidden settings for the
- # category type, but not other settings. The configuration schema for a
- # category type defines which settings it wants to change, so that's a
- # good source to use as an allowlist here.
- allowed_setting_names = cat.category_type_site_setting_names
- SiteSetting::Update.call(
- guardian:,
- options: {
- allow_changing_hidden: allowed_setting_names,
- },
- params: {
- settings: category_type_settings,
- },
- )
+ # Handles adding or removing category types registered by plugins
+ # based on the multi-type selector in the General tab for categories.
+ if UpcomingChanges.enabled_for_user?(:enable_simplified_category_creation, current_user)
+ manage_category_types(cat, pending_custom_fields || {})
+ cat.reload
end
+ merge_pending_custom_fields!(cat, pending_custom_fields)
+
# properly null the value so the database constraint doesn't catch us
category_params[:email_in] = nil if category_params[:email_in]&.blank?
category_params[:minimum_required_tags] = 0 if category_params[:minimum_required_tags]&.blank?
@@ -547,6 +516,105 @@ class CategoriesController < ApplicationController
private
+ def merge_pending_custom_fields!(category, pending_custom_fields)
+ pending_custom_fields&.each do |key, value|
+ if value.nil? || value == ""
+ category.custom_fields.delete(key)
+ else
+ category.custom_fields[key] = if value.is_a?(TrueClass) || value.is_a?(FalseClass)
+ value.to_s
+ else
+ value
+ end
+ end
+ end
+ end
+
+ def manage_category_types(category, pending_custom_fields)
+ # NOTE: The code in this block is pretty similar to what we are doing in
+ # configure_site_settings in Categories::Types::Base, however here we
+ # need to be able to update site settings across all category types for
+ # the category and it's best to do this in one query rather than
+ # multiple.
+ #
+ # Maybe in future we do something different, but this is a good starting point.
+ if params[:category_type_site_settings].present?
+ category_type_settings =
+ params[:category_type_site_settings].permit!.to_h.map do |name, value|
+ { setting_name: name, value: }
+ end
+
+ # We do this because we want to allow updating hidden settings for the
+ # category type, but not other settings. The configuration schema for a
+ # category type defines which settings it wants to change, so that's a
+ # good source to use as an allowlist here.
+ allowed_setting_names = category.category_type_site_setting_names
+ SiteSetting::Update.call(
+ guardian:,
+ options: {
+ allow_changing_hidden: allowed_setting_names,
+ },
+ params: {
+ settings: category_type_settings,
+ },
+ )
+ end
+
+ if params.has_key?(:category_types)
+ # Discussion can never be removed as a category type, so we always add it back.
+ new_category_types =
+ Array(params[:category_types]).compact_blank.map(&:to_sym) + [:discussion]
+ current_category_types = category.category_types.keys
+ removed_category_types = current_category_types - new_category_types
+ added_category_types = new_category_types - current_category_types
+
+ # Some category custom fields (like
+ # DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD) control whether
+ # the type is enabled or not, so we need to remove them from the pending
+ # custom fields to avoid turning the type back on/off again.
+ (added_category_types + removed_category_types).each do |category_type|
+ Categories::TypeRegistry
+ .get(category_type)
+ .configuration_schema_keys(:category_custom_fields)
+ .each { |custom_field_key| pending_custom_fields.delete(custom_field_key) }
+ end
+
+ removed_category_types.each do |category_type|
+ Categories::Unconfigure.call(
+ guardian:,
+ params: {
+ category_id: category.id,
+ category_type:,
+ },
+ )
+ end
+
+ added_category_types.each do |category_type|
+ Categories::Configure.call(
+ guardian:,
+ params: {
+ category_id: category.id,
+ category_type:,
+ },
+ ) do |result|
+ on_failed_policy(:type_is_available) do
+ return(
+ render json: {
+ errors: [
+ I18n.t(
+ "category_types.not_available",
+ type_name: category_type.capitalize,
+ ),
+ ],
+ },
+ status: :unprocessable_entity
+ )
+ end
+ end
+ end
+ end
+ end
+
def topics_per_page
return SiteSetting.categories_topics if SiteSetting.categories_topics > 0
diff --git a/app/serializers/category_serializer.rb b/app/serializers/category_serializer.rb
index 13382413640..061a5330d03 100644
--- a/app/serializers/category_serializer.rb
+++ b/app/serializers/category_serializer.rb
@@ -43,7 +43,8 @@ class CategorySerializer < SiteCategorySerializer
:style_type,
:emoji,
:icon,
- :category_types
+ :category_types,
+ :available_category_types
has_one :category_setting, serializer: CategorySettingSerializer, embed: :objects
has_many :category_localizations, serializer: CategoryLocalizationSerializer, embed: :objects
@@ -160,4 +161,9 @@ class CategorySerializer < SiteCategorySerializer
return {} if !SiteSetting.enable_simplified_category_creation
object.category_types
end
+
+ def available_category_types
+ return [] if !SiteSetting.enable_simplified_category_creation
+ Categories::TypeRegistry.all.values.map(&:metadata)
+ end
end
diff --git a/app/services/categories/types/base.rb b/app/services/categories/types/base.rb
index 3c7e690ff19..411b1dd8947 100644
--- a/app/services/categories/types/base.rb
+++ b/app/services/categories/types/base.rb
@@ -98,10 +98,21 @@ module Categories
end
# Configure any category-specific settings or custom fields that are
- # specific to this category type.
+ # specific to this category type, including whatever setting or custom
+ # field values make this category type unique.
#
# This SHOULD be overridden by category types.
def configure_category(category, guardian:, configuration_values: {})
+ raise NotImplementedError
+ end
+
+ # Reverse whatever configure_category does to mark this category as
+ # a specific type. E.g. if there is a custom field that is set to true,
+ # unconfigure_category should set it to false.
+ #
+ # This SHOULD be overridden by category types.
+ def unconfigure_category(category, guardian:)
+ raise NotImplementedError
end
# Returns a hash describing the configuration schema for this category type.
@@ -165,6 +176,18 @@ module Categories
{}
end
+ # Convenience method to get the setting/custom field names (keys)
+ # for a given schema type.
+ #
+ # Valid values for the +schema_type+ parameter are:
+ # - :general_category_settings
+ # - :site_settings
+ # - :category_custom_fields
+ # - :category_settings
+ def configuration_schema_keys(schema_type)
+ (configuration_schema[schema_type]&.keys || []).map(&:to_sym)
+ end
+
# Validates the hash returned by +configuration_schema+ using JSONSchemer.
# Raises +ArgumentError+ with a descriptive message if invalid.
# Also validates that any site_settings keys are real SiteSettings (a
diff --git a/app/services/categories/types/discussion.rb b/app/services/categories/types/discussion.rb
index 5a19012ddcc..3210d71e1d5 100644
--- a/app/services/categories/types/discussion.rb
+++ b/app/services/categories/types/discussion.rb
@@ -14,6 +14,14 @@ module Categories
Category.none
end
+ def configure_category(category, guardian:, configuration_values: {})
+ # intentional noop, nothing to do here
+ end
+
+ def unconfigure_category(category, guardian:)
+ # intentional noop, nothing to do here
+ end
+
def category_matches?(category)
# NOTE (martin) For now, all categories are considered discussion categories,
# a discussion category is basically the old "vanilla" category type
diff --git a/app/services/categories/unconfigure.rb b/app/services/categories/unconfigure.rb
new file mode 100644
index 00000000000..ab3e992d1bd
--- /dev/null
+++ b/app/services/categories/unconfigure.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+module Categories
+ class Unconfigure
+ include Service::Base
+
+ params do
+ attribute :category_id, :integer
+ attribute :category_type, :string
+
+ validates :category_id, presence: true
+ validates :category_type, presence: true
+ validate :category_type_is_valid
+
+ def category_type_is_valid
+ return if category_type.blank?
+ return if Categories::TypeRegistry.valid?(category_type)
+
+ errors.add(:category_type, :invalid)
+ end
+ end
+
+ model :category
+ policy :can_modify_category
+ model :type_class
+
+ step :unconfigure_category
+ step :log_action
+ step :clear_category_type_counts_cache
+
+ private
+
+ def fetch_category(params:)
+ Category.find_by(id: params.category_id)
+ end
+
+ def can_modify_category(guardian:, category:)
+ guardian.can_edit_category?(category)
+ end
+
+ def fetch_type_class(params:)
+ Categories::TypeRegistry.get(params.category_type)
+ end
+
+ def unconfigure_category(type_class:, category:, guardian:)
+ type_class.unconfigure_category(category, guardian:)
+ end
+
+ def log_action(guardian:, category:, params:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "unconfigure_category_type",
+ { category_id: category.id, category_type: params.category_type },
+ )
+ end
+
+ def clear_category_type_counts_cache
+ Discourse.cache.delete(Categories::TypeRegistry::COUNTS_CACHE_KEY)
+ end
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index b041ab0c091..bff2650bc46 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -376,6 +376,7 @@ en:
broken_transformer_alert: "There was an error. Your site may not work properly."
broken_block_alert: "A block configuration error was detected. Check browser console for details."
broken_block_factory_alert: "A block failed to load. Some UI elements may not display correctly."
+ on_before_category_types_change_error: "An error occurred while changing the category types. Check the browser console for more information."
critical_deprecation:
notice: "<b>[Admin Notice]</b> %{source} contains code which needs updating. (id:%{id})"
@@ -4928,6 +4929,8 @@ en:
color_used: "Color in use"
predefined_colors: "Predefined color options"
name_placeholder: "One or two words recommended"
+ category_types: "Category types"
+ category_types_no_results: "No other category types found"
color_placeholder: "Any web color"
delete_confirm: "Are you sure you want to delete this category?"
delete_error: "There was an error deleting the category."
diff --git a/frontend/discourse/admin/components/upsert-category/general.gjs b/frontend/discourse/admin/components/upsert-category/general.gjs
index e9f099d3e97..4577c5ce3f0 100644
--- a/frontend/discourse/admin/components/upsert-category/general.gjs
+++ b/frontend/discourse/admin/components/upsert-category/general.gjs
@@ -1,6 +1,6 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
-import { concat, hash } from "@ember/helper";
+import { concat, fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
@@ -9,17 +9,23 @@ import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import DIconGridPicker from "discourse/components/d-icon-grid-picker";
+import DMultiSelect from "discourse/components/d-multi-select";
import DecoratedHtml from "discourse/components/decorated-html";
import EmojiPicker from "discourse/components/emoji-picker";
+import PluginOutlet from "discourse/components/plugin-outlet";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import categoryBadge from "discourse/helpers/category-badge";
import concatClass from "discourse/helpers/concat-class";
import icon from "discourse/helpers/d-icon";
+import emoji from "discourse/helpers/emoji";
+import lazyHash from "discourse/helpers/lazy-hash";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { uniqueItemsFromArray } from "discourse/lib/array-tools";
import { AUTO_GROUPS, CATEGORY_TEXT_COLORS } from "discourse/lib/constants";
+import { bind } from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
+import { runOnBeforeCategoryTypesChange } from "discourse/lib/on-before-category-types-change";
import Category from "discourse/models/category";
import Composer from "discourse/models/composer";
import PermissionType from "discourse/models/permission-type";
@@ -28,6 +34,8 @@ import GroupChooser from "discourse/select-kit/components/group-chooser";
import { eq, or } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
+const DISCUSSION_TYPE_ID = "discussion";
+
export default class UpsertCategoryGeneral extends Component {
@service appEvents;
@service site;
@@ -35,6 +43,7 @@ export default class UpsertCategoryGeneral extends Component {
@service toasts;
@service composer;
@service store;
+ @service categoryTypeChooser;
@tracked loadingDescription = false;
@tracked descriptionHtml = null;
@@ -51,6 +60,25 @@ export default class UpsertCategoryGeneral extends Component {
#previousPermissions = null;
+ constructor() {
+ super(...arguments);
+ this.categoryTypes = [...this.categoryTypeChooser.allTypes].map((type) => ({
+ ...type,
+ preventRemoval: type.id === DISCUSSION_TYPE_ID,
+ }));
+ }
+
+ @bind
+ mapCategoryTypeIdsToTypes(ids) {
+ if (!ids?.length) {
+ return [];
+ }
+
+ return ids
+ .map((id) => this.categoryTypes.find((type) => type.id === id))
+ .filter(Boolean);
+ }
+
@action
registerDescriptionListener() {
this.appEvents.on("composer:edited-post", this, this._refreshDescription);
@@ -335,8 +363,46 @@ export default class UpsertCategoryGeneral extends Component {
);
}
- get #isEditingExistingCategory() {
- return Boolean(this.args.category.id);
+ get isEditingExistingCategory() {
+ return this.args.category.id != null;
+ }
+
+ @bind
+ async loadTypes(term) {
+ return this.categoryTypes.filter((type) => {
+ if (type.id === DISCUSSION_TYPE_ID) {
+ return false;
+ }
+
+ return type.name.toLowerCase().includes(term.toLowerCase());
+ });
+ }
+
+ @action
+ async onChangeCategoryTypes(field, newSelectedTypes) {
+ const nextTypes = [...newSelectedTypes];
+
+ const previousTypes = this.mapCategoryTypeIdsToTypes(field.value);
+
+ const allowed = await runOnBeforeCategoryTypesChange({
+ nextTypes,
+ previousTypes,
+ category: this.args.category,
+ form: this.args.form,
+ transientData: this.args.transientData,
+ });
+
+ if (!allowed) {
+ this.typeSelectorDMenuApi?.close();
+ return;
+ }
+
+ field.set(nextTypes.map((type) => type.id));
+ }
+
+ @action
+ onRegisterTypeSelectorDMenuApi(api) {
+ this.typeSelectorDMenuApi = api;
}
#parentPermissionsAllowEveryone(parentPermissions) {
@@ -353,7 +419,7 @@ export default class UpsertCategoryGeneral extends Component {
}
#shouldRetainPermissionsForParent(parentPermissions) {
- if (!this.#isEditingExistingCategory) {
+ if (!this.isEditingExistingCategory) {
return false;
}
@@ -371,7 +437,7 @@ export default class UpsertCategoryGeneral extends Component {
async onParentCategoryChange(parentCategoryId) {
if (!parentCategoryId) {
this.args.form.set("visibility", null);
- if (!this.#isEditingExistingCategory) {
+ if (!this.isEditingExistingCategory) {
this.#setFormPermissions([this.#everyoneFullPermission]);
}
return;
@@ -523,6 +589,62 @@ export default class UpsertCategoryGeneral extends Component {
}
<template>
+ {{#if this.isEditingExistingCategory}}
+ <@form.Field
+ @name="category_types"
+ @title={{i18n "category.category_types"}}
+ @format="max"
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <DMultiSelect
+ id={{field.id}}
+ @loadFn={{this.loadTypes}}
+ @onChange={{fn this.onChangeCategoryTypes field}}
+ @selection={{this.mapCategoryTypeIdsToTypes field.value}}
+ @onRegisterDMenuApi={{this.onRegisterTypeSelectorDMenuApi}}
+ @contentClass="category-type-selector__content"
+ @noResultsLabel={{i18n "category.category_types_no_results"}}
+ class="category-type-selector"
+ >
+ <:result as |type|>
+ <div
+ class={{concatClass
+ "category-type-selector__result"
+ (unless type.available "--unavailable")
+ (concat "--category-type-" type.id)
+ }}
+ >
+ <div class="category-type-selector__name">
+ <span class="category-type-selector__icon">
+ {{emoji type.icon}}
+ </span>
+
+ {{type.name}}
+
+ {{#unless type.available}}
+ <span class="category-type-selector__result-badge">
+ <PluginOutlet
+ @name="category-type-selector-result-badge"
+ @outletArgs={{lazyHash type=type}}
+ />
+ </span>
+ {{/unless}}
+ </div>
+ <div class="category-type-selector__description">
+ {{type.description}}
+ </div>
+ </div>
+ </:result>
+ <:selection as |type|>
+ {{type.name}}
+ </:selection>
+ </DMultiSelect>
+ </field.Control>
+ </@form.Field>
+ {{/if}}
+
<@form.Section
class={{concatClass
"edit-category-tab"
diff --git a/frontend/discourse/admin/controllers/edit-category/tabs.js b/frontend/discourse/admin/controllers/edit-category/tabs.js
index 778391f9976..76a335e6203 100644
--- a/frontend/discourse/admin/controllers/edit-category/tabs.js
+++ b/frontend/discourse/admin/controllers/edit-category/tabs.js
@@ -156,6 +156,7 @@ export default class EditCategoryTabsController extends Controller {
data.custom_fields = { ...(this.model.custom_fields ?? {}) };
data.category_type_site_settings = {};
+ data.category_types = Object.keys(this.model.categoryTypes ?? {});
Object.values(this.model.categoryTypes ?? {}).forEach((categoryType) => {
categoryType.configuration_schema.category_custom_fields?.forEach(
diff --git a/frontend/discourse/admin/routes/edit-category.js b/frontend/discourse/admin/routes/edit-category.js
index 2fbe0f66508..ecd0b618968 100644
--- a/frontend/discourse/admin/routes/edit-category.js
+++ b/frontend/discourse/admin/routes/edit-category.js
@@ -5,6 +5,7 @@ import { i18n } from "discourse-i18n";
export default class EditCategory extends DiscourseRoute {
@service router;
+ @service categoryTypeChooser;
model(params) {
return this.site.lazy_load_categories
@@ -27,6 +28,10 @@ export default class EditCategory extends DiscourseRoute {
updatedParent.setupGroupsAndPermissions();
}
}
+
+ if (model.available_category_types) {
+ this.categoryTypeChooser.allTypes = model.available_category_types;
+ }
}
titleToken() {
diff --git a/frontend/discourse/admin/routes/new-category/setup.js b/frontend/discourse/admin/routes/new-category/setup.js
index 66d0b9c9c45..372b6b892b5 100644
--- a/frontend/discourse/admin/routes/new-category/setup.js
+++ b/frontend/discourse/admin/routes/new-category/setup.js
@@ -18,8 +18,10 @@ export default class NewCategorySetup extends DiscourseRoute {
}
afterModel(model) {
- if (model.types.length === 1) {
- const type = model.types[0];
+ this.categoryTypeChooser.allTypes = model.types;
+
+ if (this.categoryTypeChooser.allTypes.length === 1) {
+ const type = this.categoryTypeChooser.allTypes[0];
this.categoryTypeChooser.choose(
type.id,
type.name,
diff --git a/frontend/discourse/app/components/d-multi-select.gjs b/frontend/discourse/app/components/d-multi-select.gjs
index 4c084096b7b..c7ba3c81d84 100644
--- a/frontend/discourse/app/components/d-multi-select.gjs
+++ b/frontend/discourse/app/components/d-multi-select.gjs
@@ -50,6 +50,10 @@ export default class DMultiSelect extends Component {
return this.args.label ?? i18n("multi_select.label");
}
+ get noResultsLabel() {
+ return this.args.noResultsLabel ?? i18n("multi_select.no_results");
+ }
+
@cached
get data() {
if (this.isDestroying || this.isDestroyed) {
@@ -175,6 +179,10 @@ export default class DMultiSelect extends Component {
remove(selectedItem, event) {
event?.stopPropagation();
+ if (selectedItem.preventRemoval) {
+ return;
+ }
+
// Reset preselected item since the available options will change
this.preselectedItem = null;
@@ -235,6 +243,7 @@ export default class DMultiSelect extends Component {
@offset={{@offset}}
@matchTriggerMinWidth={{@matchTriggerMinWidth}}
@matchTriggerWidth={{@matchTriggerWidth}}
+ @onRegisterApi={{@onRegisterDMenuApi}}
...attributes
>
<:trigger>
@@ -242,6 +251,7 @@ export default class DMultiSelect extends Component {
<div class="d-multi-select-trigger__selection">
{{#each @selection as |item|}}
<button
+ type="button"
class="d-multi-select-trigger__selected-item"
{{on "click" (fn this.remove item)}}
title={{this.getDisplayText item}}
@@ -250,10 +260,13 @@ export default class DMultiSelect extends Component {
item
to="selection"
}}</span>
- {{icon
- "xmark"
- class="d-multi-select-trigger__remove-selection-icon"
- }}
+
+ {{#unless item.preventRemoval}}
+ {{icon
+ "xmark"
+ class="d-multi-select-trigger__remove-selection-icon"
+ }}
+ {{/unless}}
</button>
{{/each}}
</div>
@@ -268,7 +281,10 @@ export default class DMultiSelect extends Component {
/>
</:trigger>
<:content>
- <DropdownMenu class="d-multi-select__content" as |menu|>
+ <DropdownMenu
+ class={{concatClass "d-multi-select__content" @contentClass}}
+ as |menu|
+ >
<menu.item class="d-multi-select__search-container">
{{icon "magnifying-glass"}}
<TextField
@@ -320,7 +336,7 @@ export default class DMultiSelect extends Component {
</div>
{{else}}
<div class="d-multi-select__search-no-results">
- {{i18n "multi_select.no_results"}}
+ {{this.noResultsLabel}}
</div>
{{/if}}
{{/if}}
diff --git a/frontend/discourse/app/lib/on-before-category-types-change.js b/frontend/discourse/app/lib/on-before-category-types-change.js
new file mode 100644
index 00000000000..354bea35298
--- /dev/null
+++ b/frontend/discourse/app/lib/on-before-category-types-change.js
@@ -0,0 +1,66 @@
+import { isTesting } from "discourse/lib/environment";
+
+const callbacks = [];
+
+/**
+ * @typedef {Object} OnBeforeCategoryTypesChangeContext
+ * @property {Object[]} nextTypes - Normalized category type objects after the empty-to-discussion rule
+ * (id, name, description, icon).
+ * @property {Object[]} previousTypes - Snapshot of the selection before this change (shallow-copied
+ * array, same object references as before).
+ * @property {object} category - The category being edited.
+ * @property {Object} form - The Form API object for the edit category form.
+ * @property {Object} [transientData] - Transient data from the Form wrapper, when available.
+ */
+
+/**
+ * Registers a callback to run when the user changes category type selection in the
+ * simplified category editor (upsert "general" tab). When `enable_simplified_category_creation` is
+ * on, the callback runs in registration order. If any callback’s resolved value is falsy, the new
+ * selection is not applied.
+ *
+ * The callback may be `async` (e.g. to show a modal and await the result). Return a **truthy**
+ * value to allow the change, or a **falsy** value to block it. On thrown errors, the change is
+ * blocked and an error is reported; in tests, the error is rethrown.
+ *
+ * @param {function(OnBeforeCategoryTypesChangeContext): (boolean|undefined|Promise<boolean|undefined>)} fn
+ */
+export function registerOnBeforeCategoryTypesChange(fn) {
+ callbacks.push(fn);
+}
+
+/**
+ * Clear registered callbacks. For tests.
+ */
+export function resetOnBeforeCategoryTypesChange() {
+ callbacks.length = 0;
+}
+
+/**
+ * @param {OnBeforeCategoryTypesChangeContext} ctx
+ * @returns {Promise<boolean>}
+ */
+export async function runOnBeforeCategoryTypesChange(ctx) {
+ for (const fn of callbacks) {
+ try {
+ const result = await fn(ctx);
+ if (!result) {
+ return false;
+ }
+ } catch (error) {
+ document.dispatchEvent(
+ new CustomEvent("discourse-error", {
+ detail: {
+ messageKey: "on_before_category_types_change_error",
+ error,
+ },
+ })
+ );
+ if (isTesting()) {
+ throw error;
+ }
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index a773af25928..4883fc3cb10 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -84,6 +84,7 @@ import {
import { registerIconRenderer, replaceIcon } from "discourse/lib/icon-library";
import { registerModelTransformer } from "discourse/lib/model-transformers";
import { registerNotificationTypeRenderer } from "discourse/lib/notification-types-manager";
+import { registerOnBeforeCategoryTypesChange } from "discourse/lib/on-before-category-types-change";
import { addGTMPageChangedCallback } from "discourse/lib/page-tracker";
import {
extraConnectorClass,
@@ -3338,6 +3339,26 @@ class _PluginApi {
registeredEditCategoryTabs.push(tab);
}
+ /**
+ * Register a callback that runs when the user changes category type selection in the
+ * **simplified** category editor (General tab) when `enable_simplified_category_creation` is
+ * enabled. It does not run on the legacy category editor.
+ *
+ * Callbacks run in order. Each may be `async`. The change applies only if every callback
+ * returns a **truthy** value; a **falsy** return blocks the new selection. If a callback
+ * throws, the error is reported and the change is blocked; in tests the error is rethrown.
+ *
+ * The callback receives:
+ * - `nextTypes` - normalized type objects after the empty-to-discussion rule
+ * - `previousTypes` - selection before this change
+ * - `category`, `form`, and optionally `transientData`
+ *
+ * @param {function(Object): (boolean|undefined|Promise<boolean|undefined>)} fn
+ */
+ registerOnBeforeCategoryTypesChange(fn) {
+ registerOnBeforeCategoryTypesChange(fn);
+ }
+
/**
* Registers block components to render in a designated outlet.
*
diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.js
index 816b2a496eb..21cdcd364e5 100644
--- a/frontend/discourse/app/models/category.js
+++ b/frontend/discourse/app/models/category.js
@@ -494,6 +494,7 @@ export default class Category extends RestModel {
init() {
super.init(...arguments);
this.setupGroupsAndPermissions();
+ this.setupCategoryTypes();
}
setupCategoryTypes() {
@@ -848,6 +849,7 @@ export default class Category extends RestModel {
}),
...this._categoryTypeSaveProperties(id),
...this._pluginSaveProperties(),
+ category_types: this.category_types,
}),
type: id ? "PUT" : "POST",
});
diff --git a/frontend/discourse/app/services/category-type-chooser.js b/frontend/discourse/app/services/category-type-chooser.js
index bb32cf67064..b9ff2244568 100644
--- a/frontend/discourse/app/services/category-type-chooser.js
+++ b/frontend/discourse/app/services/category-type-chooser.js
@@ -6,6 +6,7 @@ export default class CategoryTypeChooser extends Service {
_selection = null;
_setupComplete = false;
+ _allTypes = null;
get isEnabled() {
return this.siteSettings.enable_simplified_category_creation;
@@ -15,6 +16,14 @@ export default class CategoryTypeChooser extends Service {
return this._selection !== null || this._setupComplete;
}
+ get allTypes() {
+ return this._allTypes;
+ }
+
+ set allTypes(types) {
+ this._allTypes = types;
+ }
+
choose(typeId, typeName, typeSchema, typeTitle, count) {
this._selection = { type: typeId, typeName, typeSchema, typeTitle, count };
this._setupComplete = true;
diff --git a/frontend/discourse/tests/acceptance/category-edit-test.js b/frontend/discourse/tests/acceptance/category-edit-test.js
index 6033ff1b5a9..dde32b80330 100644
--- a/frontend/discourse/tests/acceptance/category-edit-test.js
+++ b/frontend/discourse/tests/acceptance/category-edit-test.js
@@ -278,6 +278,20 @@ acceptance(
{ permission_type: 1, group_name: "moderators", group_id: 2 },
],
custom_fields: {},
+ category_types: [
+ {
+ id: "discussion",
+ name: "Discussion",
+ configuration_schema: {},
+ },
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {},
+ },
+ ],
},
})
);
@@ -297,6 +311,20 @@ acceptance(
{ permission_type: 1, group_name: "moderators", group_id: 2 },
{ permission_type: 1, group_name: "custom_group", group_id: 4 },
],
+ category_types: [
+ {
+ id: "discussion",
+ name: "Discussion",
+ configuration_schema: {},
+ },
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {},
+ },
+ ],
},
})
);
@@ -315,6 +343,20 @@ acceptance(
group_permissions: [
{ permission_type: 1, group_name: "custom_group", group_id: 4 },
],
+ category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {},
+ },
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {},
+ },
+ ],
},
})
);
@@ -333,6 +375,20 @@ acceptance(
group_permissions: [
{ permission_type: 1, group_name: "everyone", group_id: 0 },
],
+ category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {},
+ },
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {},
+ },
+ ],
},
})
);
@@ -356,6 +412,20 @@ acceptance(
{ permission_type: 1, group_name: "staff", group_id: 3 },
],
custom_fields: {},
+ category_types: [
+ {
+ id: "discussion",
+ name: "Discussion",
+ configuration_schema: {},
+ },
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {},
+ },
+ ],
},
})
);
diff --git a/frontend/discourse/tests/fixtures/category-fixtures.js b/frontend/discourse/tests/fixtures/category-fixtures.js
index de36b2c9f15..f819dbd289e 100644
--- a/frontend/discourse/tests/fixtures/category-fixtures.js
+++ b/frontend/discourse/tests/fixtures/category-fixtures.js
@@ -40,13 +40,20 @@ const categoryFixtures = {
"Can't delete this category because it has 2030 topics. Oldest topic is <a href=\"https://localhost:3000/t/when-a-new-post-appears-in-a-topic-the-bookmark-isn-t-updated/39\">When a new post appears in a topic, the bookmark isn't updated</a>.",
allow_badges: true,
custom_fields: {},
- category_types: {
- discussion: {
+ category_types: [
+ {
id: "discussion",
name: "Discussion",
configuration_schema: {}
},
- }
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {}
+ },
+ ],
},
},
"/c/11/show.json": {
@@ -120,13 +127,20 @@ const categoryFixtures = {
uploaded_background_dark: null,
required_tag_groups: [{ min_count: 1, name: "TagGroup1" }],
category_localizations: [],
- category_types: {
- discussion: {
+ category_types: [
+ {
id: "discussion",
name: "Discussion",
configuration_schema: {}
},
- }
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {}
+ },
+ ],
},
},
"/c/2481/show.json": {
@@ -142,13 +156,20 @@ const categoryFixtures = {
group_permissions: [
{ permission_type: 1, group_name: "moderators", group_id: 2 },
],
- category_types: {
- discussion: {
+ category_types: [
+ {
id: "discussion",
name: "Discussion",
configuration_schema: {}
},
- }
+ ],
+ available_category_types: [
+ {
+ id: "support",
+ name: "Support",
+ configuration_schema: {}
+ },
+ ],
},
},
};
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index 0567f2c388b..6b2112e4ce7 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -57,6 +57,7 @@ import { forceMobile, resetMobile } from "discourse/lib/mobile";
import { resetModelTransformers } from "discourse/lib/model-transformers";
import { resetNotificationTypeRenderers } from "discourse/lib/notification-types-manager";
import { cloneJSON, deepMerge } from "discourse/lib/object";
+import { resetOnBeforeCategoryTypesChange } from "discourse/lib/on-before-category-types-change";
import {
clearCache as clearOutletCache,
resetExtraClasses,
@@ -275,6 +276,7 @@ export function testCleanup(container, app) {
clearPluginHeaderActionComponents();
clearRegisteredTabs();
clearRegisteredEditCategoryTabs();
+ resetOnBeforeCategoryTypesChange();
clearAddedTrackedPostProperties();
clearAddedTrackedTopicProperties();
resetGroupPostSmallActionCodes();
diff --git a/frontend/discourse/tests/integration/components/d-multi-select-test.gjs b/frontend/discourse/tests/integration/components/d-multi-select-test.gjs
index 7c5698c3b3f..a38338a0341 100644
--- a/frontend/discourse/tests/integration/components/d-multi-select-test.gjs
+++ b/frontend/discourse/tests/integration/components/d-multi-select-test.gjs
@@ -45,7 +45,7 @@ class TestComponent extends Component {
</template>
}
-module("Integration | Component | d-multi-select", function (hooks) {
+module("Integration | Component | DMultiSelect", function (hooks) {
setupRenderingTest(hooks);
test("filter", async function (assert) {
@@ -248,6 +248,44 @@ module("Integration | Component | d-multi-select", function (hooks) {
assert.dom(".d-multi-select__result:nth-child(1)").hasText("foo");
});
+ test("prevents removal of selected item with preventRemoval", async function (assert) {
+ const selection = [
+ { id: 1, name: "foo", preventRemoval: true },
+ { id: 2, name: "bar" },
+ ];
+ await render(
+ <template><TestComponent @selection={{selection}} /></template>
+ );
+
+ // Both items are selected
+ assert
+ .dom(".d-multi-select-trigger__selected-item:nth-child(1)")
+ .hasText("foo");
+ assert
+ .dom(".d-multi-select-trigger__selected-item:nth-child(2)")
+ .hasText("bar");
+ assert.dom(".d-multi-select__result").doesNotExist();
+
+ // Clicking the first selected item should not remove it
+ await click(".d-multi-select-trigger__selected-item:nth-child(1)");
+
+ // Clicking the second selected item should remove it
+ await click(".d-multi-select-trigger__selected-item:nth-child(2)");
+
+ // Only the first item should be selected
+ assert
+ .dom(".d-multi-select-trigger__selected-item:nth-child(1)")
+ .hasText("foo");
+ assert
+ .dom(".d-multi-select-trigger__selected-item:nth-child(2)")
+ .doesNotExist();
+
+ // The other item can now be re-selected in the results
+ await click(".d-multi-select-trigger");
+ assert.dom(".d-multi-select__result").exists({ count: 1 });
+ assert.dom(".d-multi-select__result:nth-child(1)").hasText("bar");
+ });
+
test("preselect item", async function (assert) {
await render(<template><TestComponent /></template>);
await click(".d-multi-select-trigger");
diff --git a/frontend/discourse/tests/unit/lib/on-before-category-types-change-test.js b/frontend/discourse/tests/unit/lib/on-before-category-types-change-test.js
new file mode 100644
index 00000000000..438be3857e3
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/on-before-category-types-change-test.js
@@ -0,0 +1,97 @@
+import { module, test } from "qunit";
+import {
+ registerOnBeforeCategoryTypesChange,
+ resetOnBeforeCategoryTypesChange,
+ runOnBeforeCategoryTypesChange,
+} from "discourse/lib/on-before-category-types-change";
+
+const ctx = {
+ nextTypes: [],
+ previousTypes: [],
+ category: {},
+ form: {},
+ transientData: undefined,
+};
+
+module("Unit | lib | on-before-category-types-change", function (hooks) {
+ hooks.beforeEach(function () {
+ resetOnBeforeCategoryTypesChange();
+ });
+
+ test("no callbacks means allow", async function (assert) {
+ assert.true(
+ await runOnBeforeCategoryTypesChange(ctx),
+ "empty registry allows"
+ );
+ });
+
+ test("callback returning false vetoes", async function (assert) {
+ registerOnBeforeCategoryTypesChange(() => false);
+ assert.false(await runOnBeforeCategoryTypesChange(ctx));
+ });
+
+ test("callback returning true allows", async function (assert) {
+ registerOnBeforeCategoryTypesChange(() => true);
+ assert.true(await runOnBeforeCategoryTypesChange(ctx));
+ });
+
+ test("stops at first false and does not run following callbacks", async function (assert) {
+ let firstCount = 0;
+ let secondCount = 0;
+ registerOnBeforeCategoryTypesChange(() => {
+ firstCount += 1;
+ return false;
+ });
+ registerOnBeforeCategoryTypesChange(() => {
+ secondCount += 1;
+ return true;
+ });
+ assert.false(await runOnBeforeCategoryTypesChange(ctx));
+ assert.strictEqual(firstCount, 1, "first callback runs once");
+ assert.strictEqual(secondCount, 0, "second callback not invoked");
+ });
+
+ test("runs in order and all must allow", async function (assert) {
+ const order = [];
+ registerOnBeforeCategoryTypesChange(() => {
+ order.push(1);
+ return true;
+ });
+ registerOnBeforeCategoryTypesChange(() => {
+ order.push(2);
+ return true;
+ });
+ assert.true(await runOnBeforeCategoryTypesChange(ctx));
+ assert.deepEqual(order, [1, 2]);
+ });
+
+ test("async callback that resolves true allows", async function (assert) {
+ registerOnBeforeCategoryTypesChange(async () => true);
+ assert.true(await runOnBeforeCategoryTypesChange(ctx));
+ });
+
+ test("async callback that resolves false vetoes", async function (assert) {
+ registerOnBeforeCategoryTypesChange(async () => false);
+ assert.false(await runOnBeforeCategoryTypesChange(ctx));
+ });
+
+ test("throws in callback rethrows in tests and vetoes in production path", async function (assert) {
+ registerOnBeforeCategoryTypesChange(() => {
+ throw new Error("guard failed");
+ });
+ await assert.rejects(
+ runOnBeforeCategoryTypesChange(ctx),
+ /guard failed/,
+ "rethrows in test environment"
+ );
+ });
+
+ test("passes the same context object to the callback", async function (assert) {
+ const localCtx = { a: 1, nextTypes: [] };
+ registerOnBeforeCategoryTypesChange((c) => {
+ assert.strictEqual(c, localCtx, "context is the same object reference");
+ return true;
+ });
+ assert.true(await runOnBeforeCategoryTypesChange(localCtx));
+ });
+});
diff --git a/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rb b/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rb
index 595b3571fb5..3d1ffe32969 100644
--- a/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rb
+++ b/plugins/discourse-solved/app/services/discourse_solved/categories/types/support.rb
@@ -49,6 +49,13 @@ module DiscourseSolved
DiscourseSolved::AcceptedAnswerCache.reset_accepted_answer_cache
end
+ def unconfigure_category(category, guardian:)
+ category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD] = "false"
+ category.save!
+
+ DiscourseSolved::AcceptedAnswerCache.reset_accepted_answer_cache
+ end
+
def configuration_schema
{
general_category_settings: {
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/upsert-category-support.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/upsert-category-support.gjs
index 4a91dd8505c..f3ab7ebf741 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/components/upsert-category-support.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/upsert-category-support.gjs
@@ -1,7 +1,6 @@
import Component from "@glimmer/component";
import { action } from "@ember/object";
import { service } from "@ember/service";
-import DButton from "discourse/components/d-button";
import EditCategoryTypeSchemaFields from "discourse/components/edit-category-type-schema-fields";
import { popupAjaxError } from "discourse/lib/ajax-error";
import Category from "discourse/models/category";
@@ -57,18 +56,7 @@ export default class UpsertCategorySupport extends Component {
@category={{@category}}
@categoryType="support"
@form={{@form}}
- >
- <:beforeSiteSettings>
- <div class="support-category--danger-zone">
- <DButton
- class="btn-small support-category__remove-type"
- @action={{this.removeSupportCategory}}
- @icon="link-slash"
- @label="solved.category_type_support.remove_support_type"
- />
- </div>
- </:beforeSiteSettings>
- </EditCategoryTypeSchemaFields>
+ />
{{else}}
{{i18n "solved.category_type_support.not_support_type"}}
{{/if}}
diff --git a/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rb b/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rb
index 83ac32f5116..b30d67240f3 100644
--- a/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rb
+++ b/plugins/discourse-solved/spec/models/discourse_solved/categories_types_support_spec.rb
@@ -100,6 +100,20 @@ RSpec.describe DiscourseSolved::Categories::Types::Support do
end
end
+ describe ".unconfigure_category" do
+ before { described_class.configure_category(category, guardian: admin.guardian) }
+
+ it "removes the enable_accepted_answers custom field" do
+ expect(category.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD]).to eq(
+ "true",
+ )
+ described_class.unconfigure_category(category, guardian: admin.guardian)
+ expect(
+ category.reload.custom_fields[DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD],
+ ).to eq("false")
+ end
+ end
+
describe ".find_matches" do
fab!(:other_category, :category)
diff --git a/plugins/discourse-solved/spec/requests/categories_controller_spec.rb b/plugins/discourse-solved/spec/requests/categories_controller_spec.rb
new file mode 100644
index 00000000000..4fa623d7cf9
--- /dev/null
+++ b/plugins/discourse-solved/spec/requests/categories_controller_spec.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+RSpec.describe CategoriesController do
+ fab!(:category)
+ fab!(:admin)
+
+ before do
+ sign_in(admin)
+ SiteSetting.enable_simplified_category_creation = true
+ SiteSetting.enable_support_category_type_setup = true
+ end
+
+ describe "#update" do
+ it "can add the support type to the category" do
+ expect(category.enable_accepted_answers?).to eq(false)
+
+ put "/categories/#{category.id}.json", params: { category_types: ["support"] }
+
+ expect(response.status).to eq(200)
+ cat_json = response.parsed_body["category"]
+ expect(cat_json["category_types"].keys).to include("support", "discussion")
+
+ expect(category.reload.category_types.keys).to include(:support)
+ expect(category.reload.category_types.keys).to include(:discussion)
+ expect(category.enable_accepted_answers?).to eq(true)
+ end
+
+ it "can remove the support type from the category" do
+ Categories::Configure.call(
+ guardian: admin.guardian,
+ params: {
+ category_type: "support",
+ category_id: category.id,
+ },
+ )
+
+ expect(category.enable_accepted_answers?).to eq(true)
+ put "/categories/#{category.id}.json", params: { category_types: [] }
+
+ expect(response.status).to eq(200)
+ cat_json = response.parsed_body["category"]
+ expect(cat_json["category_types"].keys).not_to include("support")
+ expect(cat_json["category_types"].keys).to include("discussion")
+
+ expect(category.reload.category_types.keys).not_to include(:support)
+ expect(category.reload.category_types.keys).to include(:discussion)
+ expect(category.enable_accepted_answers?).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rb b/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rb
index 2e43a398dbc..43703a462ba 100644
--- a/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rb
+++ b/plugins/discourse-solved/spec/system/support_category_type_setup_spec.rb
@@ -66,6 +66,22 @@ RSpec.describe "Support Category Type Setup" do
end
end
+ context "for an existing category with no support category type" do
+ fab!(:category)
+
+ it "can add the support category type" do
+ visit("/c/#{category.slug}/edit")
+ category_type_selector = PageObjects::Components::DMenu.new(".category-type-selector")
+ category_type_selector.expand
+ category_type_selector.option(".category-type-selector__result.--category-type-support").click
+ banner.click_save
+ expect(toast).to have_success(I18n.t("js.saved"))
+ expect(page).to have_css(".nav-pills .edit-category-support")
+ category.reload
+ expect(category.category_types.keys).to eq(%i[discussion support])
+ end
+ end
+
context "when there is a support category already configured" do
fab!(:category)
@@ -121,17 +137,15 @@ RSpec.describe "Support Category Type Setup" do
expect(SiteSetting.show_who_marked_solved).to eq(true)
end
- it "can remove the support type from the category" do
- visit("/c/#{category.slug}/edit/support")
- page.find(".support-category--danger-zone .support-category__remove-type").click
- expect(dialog).to have_content(
- I18n.t("js.solved.category_type_support.confirm_remove_support_type"),
- )
- dialog.click_yes
+ it "can remove the support category type" do
+ visit("/c/#{category.slug}/edit")
+ category_type_selector = PageObjects::Components::DMenu.new(".category-type-selector")
+ category_type_selector.remove_selected_option("Support")
+ banner.click_save
expect(toast).to have_success(I18n.t("js.saved"))
- expect(page).to have_css(".edit-category-general.active")
- expect(page).to have_current_path("/c/#{category.slug}/edit/general")
- expect(category.reload.custom_fields["enable_accepted_answers"]).to eq("false")
+ expect(page).to have_no_css(".nav-pills .edit-category-support")
+ category.reload
+ expect(category.category_types.keys).to eq(%i[discussion])
end
end
diff --git a/plugins/discourse-topic-voting/app/services/discourse_topic_voting/categories/types/ideas.rb b/plugins/discourse-topic-voting/app/services/discourse_topic_voting/categories/types/ideas.rb
index 3543f12a095..b37f06f0c87 100644
--- a/plugins/discourse-topic-voting/app/services/discourse_topic_voting/categories/types/ideas.rb
+++ b/plugins/discourse-topic-voting/app/services/discourse_topic_voting/categories/types/ideas.rb
@@ -16,7 +16,9 @@ module DiscourseTopicVoting
end
def category_matches?(category)
- Category.can_vote?(category.id)
+ return false if !SiteSetting.topic_voting_enabled
+
+ DiscourseTopicVoting::CategorySetting.exists?(category_id: category.id)
end
def find_matches
@@ -27,6 +29,12 @@ module DiscourseTopicVoting
category.discourse_topic_voting_category_setting ||=
DiscourseTopicVoting::CategorySetting.new(category: category)
category.discourse_topic_voting_category_setting.save!
+ Category.reset_voting_cache
+ end
+
+ def unconfigure_category(category, guardian:)
+ category.discourse_topic_voting_category_setting.destroy!
+ Category.reset_voting_cache
end
def configuration_schema
diff --git a/plugins/discourse-topic-voting/assets/javascripts/discourse/components/upsert-category-ideas.gjs b/plugins/discourse-topic-voting/assets/javascripts/discourse/components/upsert-category-ideas.gjs
index 9c89deeec17..73ebce60381 100644
--- a/plugins/discourse-topic-voting/assets/javascripts/discourse/components/upsert-category-ideas.gjs
+++ b/plugins/discourse-topic-voting/assets/javascripts/discourse/components/upsert-category-ideas.gjs
@@ -1,7 +1,6 @@
import Component from "@glimmer/component";
import { action } from "@ember/object";
import { service } from "@ember/service";
-import DButton from "discourse/components/d-button";
import EditCategoryTypeSchemaFields from "discourse/components/edit-category-type-schema-fields";
import { popupAjaxError } from "discourse/lib/ajax-error";
import Category from "discourse/models/category";
@@ -53,20 +52,7 @@ export default class UpsertCategoryIdeas extends Component {
@category={{@category}}
@categoryType="ideas"
@form={{@form}}
- >
- <:beforeSiteSettings>
- {{#if @category.id}}
- <div class="ideas-category--danger-zone">
- <DButton
- class="btn-small ideas-category__remove-type"
- @action={{this.removeIdeasCategory}}
- @icon="link-slash"
- @label="topic_voting.category_type_ideas.remove_ideas_type"
- />
- </div>
- {{/if}}
- </:beforeSiteSettings>
- </EditCategoryTypeSchemaFields>
+ />
{{else}}
{{i18n "topic_voting.category_type_ideas.not_ideas_type"}}
{{/if}}
diff --git a/plugins/discourse-topic-voting/lib/discourse_topic_voting/categories_controller_extension.rb b/plugins/discourse-topic-voting/lib/discourse_topic_voting/categories_controller_extension.rb
index f208dbf6f88..bed2dcfbb83 100644
--- a/plugins/discourse-topic-voting/lib/discourse_topic_voting/categories_controller_extension.rb
+++ b/plugins/discourse-topic-voting/lib/discourse_topic_voting/categories_controller_extension.rb
@@ -8,6 +8,10 @@ module DiscourseTopicVoting
category_params = super
+ # TODO: Remove this whole controller extension when this gets promoted
+ # to Permanent
+ return category_params if SiteSetting.enable_ideas_category_type_setup
+
if @vote_enabled && !@category&.discourse_topic_voting_category_setting
category_params[:discourse_topic_voting_category_setting_attributes] = {}
elsif !@vote_enabled && @category&.discourse_topic_voting_category_setting
diff --git a/plugins/discourse-topic-voting/spec/requests/categories_controller_spec.rb b/plugins/discourse-topic-voting/spec/requests/categories_controller_spec.rb
index 0ea276c6ede..9daac6cebf6 100644
--- a/plugins/discourse-topic-voting/spec/requests/categories_controller_spec.rb
+++ b/plugins/discourse-topic-voting/spec/requests/categories_controller_spec.rb
@@ -47,4 +47,53 @@ describe CategoriesController do
put "/categories/#{category.id}.json", params: { hello: "world" }
expect(response.status).to eq(200)
end
+
+ describe "#update" do
+ before do
+ Category.reset_voting_cache
+ SiteSetting.enable_simplified_category_creation = true
+ SiteSetting.enable_ideas_category_type_setup = true
+ end
+
+ after do
+ SiteSetting.enable_simplified_category_creation = false
+ SiteSetting.enable_ideas_category_type_setup = false
+ end
+
+ it "can add the ideas type to the category" do
+ expect(Category.can_vote?(category.id)).to eq(false)
+
+ put "/categories/#{category.id}.json", params: { category_types: ["ideas"] }
+
+ expect(response.status).to eq(200)
+ cat_json = response.parsed_body["category"]
+ expect(cat_json["category_types"].keys).to include("ideas", "discussion")
+
+ expect(category.reload.category_types.keys).to include(:ideas)
+ expect(category.reload.category_types.keys).to include(:discussion)
+ expect(Category.can_vote?(category.id)).to eq(true)
+ end
+
+ it "can remove the ideas type from the category" do
+ Categories::Configure.call(
+ guardian: admin.guardian,
+ params: {
+ category_type: "ideas",
+ category_id: category.id,
+ },
+ )
+
+ expect(Category.can_vote?(category.id)).to eq(true)
+ put "/categories/#{category.id}.json", params: { category_types: [] }
+
+ expect(response.status).to eq(200)
+ cat_json = response.parsed_body["category"]
+ expect(cat_json["category_types"].keys).not_to include("ideas")
+ expect(cat_json["category_types"].keys).to include("discussion")
+
+ expect(category.reload.category_types.keys).not_to include(:ideas)
+ expect(category.reload.category_types.keys).to include(:discussion)
+ expect(Category.can_vote?(category.id)).to eq(false)
+ end
+ end
end
diff --git a/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/categories/types/ideas_spec.rb b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/categories/types/ideas_spec.rb
index 41fd786beab..11f118a54e3 100644
--- a/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/categories/types/ideas_spec.rb
+++ b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/categories/types/ideas_spec.rb
@@ -69,6 +69,22 @@ RSpec.describe DiscourseTopicVoting::Categories::Types::Ideas do
end
end
+ describe ".unconfigure_category" do
+ fab!(:admin)
+
+ before { described_class.configure_category(category, guardian: admin.guardian) }
+
+ it "removes the topic_voting_category_setting record" do
+ expect(Category.can_vote?(category.id)).to eq(true)
+
+ expect {
+ described_class.unconfigure_category(category, guardian: admin.guardian)
+ }.to change { DiscourseTopicVoting::CategorySetting.count }.by(-1)
+
+ expect(Category.can_vote?(category.id)).to eq(false)
+ end
+ end
+
describe ".configuration_schema" do
it "returns expected keys" do
schema = described_class.configuration_schema
diff --git a/plugins/discourse-topic-voting/spec/system/ideas_category_type_setup_spec.rb b/plugins/discourse-topic-voting/spec/system/ideas_category_type_setup_spec.rb
index 2ff3e849348..10d366304b4 100644
--- a/plugins/discourse-topic-voting/spec/system/ideas_category_type_setup_spec.rb
+++ b/plugins/discourse-topic-voting/spec/system/ideas_category_type_setup_spec.rb
@@ -102,19 +102,6 @@ RSpec.describe "Ideas Category Type Setup" do
expect(page).to have_no_field("category_type_site_settings.topic_voting_tl0_vote_limit")
expect(page).to have_no_field("category_type_site_settings.topic_voting_alert_votes_left")
end
-
- it "can remove the ideas type from the category" do
- visit("/c/#{category.slug}/edit/ideas")
- page.find(".ideas-category--danger-zone .ideas-category__remove-type").click
- expect(dialog).to have_content(
- I18n.t("js.topic_voting.category_type_ideas.confirm_remove_ideas_type"),
- )
- dialog.click_yes
- expect(toast).to have_success(I18n.t("js.saved"))
- expect(page).to have_css(".edit-category-general.active")
- expect(page).to have_current_path("/c/#{category.slug}/edit/general")
- expect(Category.can_vote?(category.reload.id)).to eq(false)
- end
end
context "when visiting the Ideas tab for a non-ideas category" do
diff --git a/spec/requests/api/schemas/json/category_create_response.json b/spec/requests/api/schemas/json/category_create_response.json
index 45730e1cf0e..3d7f27b2498 100644
--- a/spec/requests/api/schemas/json/category_create_response.json
+++ b/spec/requests/api/schemas/json/category_create_response.json
@@ -355,6 +355,45 @@
},
"category_types": {
"type": "object"
+ },
+ "available_category_types": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "icon": {
+ "type": "string"
+ },
+ "available": {
+ "type": "boolean"
+ },
+ "configuration_schema": {
+ "type": "object"
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "title",
+ "description",
+ "icon",
+ "available",
+ "configuration_schema"
+ ]
+ }
}
},
"required": [
diff --git a/spec/requests/api/schemas/json/category_update_response.json b/spec/requests/api/schemas/json/category_update_response.json
index fb0955c0a09..55910535ec1 100644
--- a/spec/requests/api/schemas/json/category_update_response.json
+++ b/spec/requests/api/schemas/json/category_update_response.json
@@ -358,6 +358,45 @@
},
"category_types": {
"type": "object"
+ },
+ "available_category_types": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "icon": {
+ "type": "string"
+ },
+ "available": {
+ "type": "boolean"
+ },
+ "configuration_schema": {
+ "type": "object"
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "title",
+ "description",
+ "icon",
+ "available",
+ "configuration_schema"
+ ]
+ }
}
},
"required": [
diff --git a/spec/services/categories/unconfigure_spec.rb b/spec/services/categories/unconfigure_spec.rb
new file mode 100644
index 00000000000..0aa23ebbded
--- /dev/null
+++ b/spec/services/categories/unconfigure_spec.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+RSpec.describe Categories::Unconfigure do
+ describe Categories::Unconfigure::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:category_id) }
+ it { is_expected.to validate_presence_of(:category_type) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:category)
+
+ let(:params) { { category_id: category.id, category_type: "discussion" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when params are invalid" do
+ let(:params) { { category_id: nil, category_type: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when category type is invalid" do
+ let(:params) { super().merge(category_type: "invalid_type") }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when category is not found" do
+ let(:params) { super().merge(category_id: -1) }
+
+ it { is_expected.to fail_to_find_a_model(:category) }
+ end
+
+ context "when user cannot modify category" do
+ fab!(:user)
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_modify_category) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "calls unconfigure_category on the type class" do
+ Categories::Types::Discussion.expects(:unconfigure_category).once
+ result
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ action: UserHistory.actions[:custom_staff],
+ custom_type: "unconfigure_category_type",
+ acting_user_id: admin.id,
+ )
+ expect(UserHistory.last.details).to include("category_type")
+ end
+
+ it "clears the category type counts cache" do
+ Discourse.cache.write(Categories::TypeRegistry::COUNTS_CACHE_KEY, "cached_value")
+ result
+ expect(Discourse.cache.read(Categories::TypeRegistry::COUNTS_CACHE_KEY)).to be_nil
+ end
+ end
+ end
+end
diff --git a/spec/system/page_objects/components/d_menu.rb b/spec/system/page_objects/components/d_menu.rb
index f0353b52f3b..a425eef6a81 100644
--- a/spec/system/page_objects/components/d_menu.rb
+++ b/spec/system/page_objects/components/d_menu.rb
@@ -41,6 +41,10 @@ module PageObjects
end
end
+ def remove_selected_option(title)
+ find(".d-multi-select-trigger__selected-item", text: title).click
+ end
+
def option(selector, match = nil)
params = {}
params[:match] = match if match
diff --git a/spec/system/page_objects/components/select_kit.rb b/spec/system/page_objects/components/select_kit.rb
index 7dc748993a1..52db8c04ddb 100644
--- a/spec/system/page_objects/components/select_kit.rb
+++ b/spec/system/page_objects/components/select_kit.rb
@@ -25,8 +25,10 @@ module PageObjects
has_no_css?(@context)
end
- def expanded_component
- return expand if is_collapsed?
+ def expanded_component(skip_collapsed_check: false)
+ # Skip collapsed check to avoid infinite loop when called
+ # from .expand
+ return expand if is_collapsed? && !skip_collapsed_check
find(@context + ".is-expanded")
end
@@ -89,7 +91,7 @@ module PageObjects
def expand
collapsed_component.find(".select-kit-header", visible: :all).click
- expanded_component
+ expanded_component(skip_collapsed_check: true)
end
def collapse
diff --git a/spec/system/simplified_category_creation_spec.rb b/spec/system/simplified_category_creation_spec.rb
index 2625f73d236..7ed6e56736b 100644
--- a/spec/system/simplified_category_creation_spec.rb
+++ b/spec/system/simplified_category_creation_spec.rb
@@ -19,7 +19,7 @@ describe "Simplified Category Creation" do
describe "Selecting category type when setting up a new category" do
it "automatically skips category type selection when only one type (discussion) is available" do
- visit("/new-category/setup")
+ category_page.visit_new_category
expect(page).to have_content(I18n.t("js.category.create_with_type", typeName: "discussion"))
expect(page).to have_current_path("/new-category/general")
end
@@ -250,6 +250,12 @@ describe "Simplified Category Creation" do
expect(page).to have_content("Updated category description")
expect(toasts).to have_success(I18n.t("js.category.description_updated"))
end
+
+ it "does not allow selecting other category types when creating a new category" do
+ category_page.visit_new_category
+ expect(page).to have_content(I18n.t("js.category.create_with_type", typeName: "discussion"))
+ expect(page).to have_no_css(".category-type-selector")
+ end
end
describe "Security Tab" do