Skip to content

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

FIX: Persist form fields that are cleared (#42541)

Régis Hanoldf1778be3ac3
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb
index 289625cfc41..dc8c639fa0e 100644
--- a/app/controllers/categories_controller.rb
+++ b/app/controllers/categories_controller.rb
@@ -295,10 +295,6 @@ class CategoriesController < ApplicationController
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?
-
old_permissions = cat.permissions_params
old_permissions = { Group[:everyone].name => 1 } if old_permissions.empty?
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rb
index 51866bee090..eb1b1665a75 100644
--- a/app/controllers/topics_controller.rb
+++ b/app/controllers/topics_controller.rb
@@ -429,7 +429,7 @@ class TopicsController < ApplicationController
return render_json_error(I18n.t("edit_conflict"), status: 409)
end
- if params[:category_id] && (params[:category_id].to_i != topic.category_id.to_i)
+ if params.key?(:category_id) && (params[:category_id].to_i != topic.category_id.to_i)
if topic.shared_draft
topic.shared_draft.update(category_id: params[:category_id])
params.delete(:category_id)
diff --git a/app/models/category.rb b/app/models/category.rb
index da4bd1e69b6..093cf0d4134 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -142,6 +142,7 @@ class Category < ActiveRecord::Base
validates :text_color, format: { with: /\A(\h{6}|\h{3})\z/ }
before_validation :normalize_default_top_period
+ before_validation :normalize_minimum_required_tags
before_save :apply_permissions
before_save :downcase_email
@@ -1196,7 +1197,7 @@ class Category < ActiveRecord::Base
end
def subcategory_list_includes_topics?
- subcategory_list_style.end_with?("with_featured_topics")
+ subcategory_list_style.to_s.end_with?("with_featured_topics")
end
%i[category_created category_updated category_destroyed].each do |event|
@@ -1391,6 +1392,10 @@ class Category < ActiveRecord::Base
self.default_top_period = nil if TopTopic.periods.exclude?(default_top_period&.to_sym)
end
+ def normalize_minimum_required_tags
+ self.minimum_required_tags = 0 if minimum_required_tags.blank?
+ end
+
def group_based_posting_review_mode?(post_type)
mode = category_setting&.public_send(:"#{post_type}_posting_review_mode")
CategorySetting::GROUP_BASED_MODES.include?(mode)
diff --git a/app/services/categories/types/base.rb b/app/services/categories/types/base.rb
index 1f51359c7cd..604e062d1bd 100644
--- a/app/services/categories/types/base.rb
+++ b/app/services/categories/types/base.rb
@@ -446,30 +446,20 @@ module Categories
end
schema[:site_settings]&.each do |setting_name, target_value|
- if target_value.is_a?(Hash)
- default = target_value[:default]
- custom_label = target_value[:label]
- custom_type = target_value[:type]
- custom_choices = target_value[:choices]
- else
- default = target_value
- custom_label = nil
- custom_type = nil
- custom_choices = nil
- end
+ config = target_value.is_a?(Hash) ? target_value : { default: target_value }
meta = SiteSetting.setting_metadata_hash(setting_name)
depends_on = SiteSetting.type_supervisor.dependencies[setting_name.to_sym]&.first&.to_s
entry = {
key: setting_name.to_s,
- default:,
+ default: config[:default],
current: SiteSetting.public_send(setting_name),
overridden: site_setting_overridden?(setting_name),
- type: custom_type || meta[:type],
- label: custom_label || meta[:humanized_name],
- choices: custom_choices || meta[:choices],
+ type: config[:type] || meta[:type],
+ label: config[:label] || meta[:humanized_name],
+ choices: config[:choices] || meta[:choices],
description: meta[:description],
- required: false,
+ required: config[:required],
show_on_create: true,
show_on_edit: true,
}
diff --git a/app/services/tag_settings_updater.rb b/app/services/tag_settings_updater.rb
index 7fdcc1d2693..8ebf7310663 100644
--- a/app/services/tag_settings_updater.rb
+++ b/app/services/tag_settings_updater.rb
@@ -41,7 +41,7 @@ class TagSettingsUpdater
def update_basic_attributes(params)
@tag.name = DiscourseTagging.clean_tag(params[:name]) if params[:name].present?
- @tag.slug = params[:slug] if params[:slug].present?
+ @tag.slug = params[:slug] if params.key?(:slug)
@tag.description = params[:description] if params.key?(:description)
end
diff --git a/frontend/discourse/admin/components/admin-config-area-cards/about/general-settings.gjs b/frontend/discourse/admin/components/admin-config-area-cards/about/general-settings.gjs
index c5dee9049f1..c2e5e2e9ee1 100644
--- a/frontend/discourse/admin/components/admin-config-area-cards/about/general-settings.gjs
+++ b/frontend/discourse/admin/components/admin-config-area-cards/about/general-settings.gjs
@@ -90,7 +90,7 @@ export default class AdminConfigAreasAboutGeneralSettings extends Component {
@action
setImage(upload, { set }) {
- set("aboutBannerImage", upload?.url);
+ set("aboutBannerImage", upload?.url ?? null);
}
<template>
diff --git a/frontend/discourse/admin/components/admin-logo-form.gjs b/frontend/discourse/admin/components/admin-logo-form.gjs
index bfcb3e41b49..c7d2b54c2ea 100644
--- a/frontend/discourse/admin/components/admin-logo-form.gjs
+++ b/frontend/discourse/admin/components/admin-logo-form.gjs
@@ -51,7 +51,7 @@ export default class AdminLogoForm extends Component {
if (upload) {
set(type, getURL(upload.url));
} else {
- set(type, undefined);
+ set(type, null);
}
}
diff --git a/frontend/discourse/admin/components/edit-category-localizations.gjs b/frontend/discourse/admin/components/edit-category-localizations.gjs
index 5f0992a9d64..57391d7fb2d 100644
--- a/frontend/discourse/admin/components/edit-category-localizations.gjs
+++ b/frontend/discourse/admin/components/edit-category-localizations.gjs
@@ -33,6 +33,7 @@ export default class EditCategoryLocalizations extends buildCategoryPanel(
@description={{i18n "category.localization.language_description"}}
@format="full"
@type="select"
+ @validation="required"
as |field|
>
<field.Control as |select|>
diff --git a/frontend/discourse/admin/components/upsert-category/appearance.gjs b/frontend/discourse/admin/components/upsert-category/appearance.gjs
index 404ecb9a446..d905254a469 100644
--- a/frontend/discourse/admin/components/upsert-category/appearance.gjs
+++ b/frontend/discourse/admin/components/upsert-category/appearance.gjs
@@ -9,6 +9,14 @@ import { CATEGORY_TEXT_COLORS } from "discourse/lib/constants";
import { applyMutableValueTransformer } from "discourse/lib/transformer";
import { i18n } from "discourse-i18n";
+function withStoredValue(options, storedValue) {
+ if (!storedValue || options.some((o) => o.value === storedValue)) {
+ return options;
+ }
+
+ return [...options, { name: storedValue, value: storedValue }];
+}
+
export default class UpsertCategoryAppearance extends Component {
@service site;
@@ -16,10 +24,6 @@ export default class UpsertCategoryAppearance extends Component {
return !this.args.transientData?.sort_order;
}
- get sortAscendingValue() {
- return this.args.transientData?.sort_ascending;
- }
-
get backgroundImageUrl() {
return this.args.transientData?.uploaded_background?.url ?? "";
}
@@ -43,6 +47,15 @@ export default class UpsertCategoryAppearance extends Component {
return this.args.category.isParent || !parentCategoryId;
}
+ @action
+ async onSortOrderSet(value, { name, set }) {
+ await set(name, value);
+
+ if (!value) {
+ await set("sort_ascending", null);
+ }
+ }
+
@action
onUploadDone(field, upload) {
this.args.form.set(field, { url: upload.url, id: upload.id });
@@ -54,7 +67,7 @@ export default class UpsertCategoryAppearance extends Component {
}
get subcategoryListStyles() {
- return [
+ const styles = [
{ name: i18n("category.subcategory_list_styles.rows"), value: "rows" },
{
name: i18n(
@@ -73,6 +86,8 @@ export default class UpsertCategoryAppearance extends Component {
value: "boxes_with_featured_topics",
},
];
+
+ return withStoredValue(styles, this.args.category.subcategory_list_style);
}
get availableViews() {
@@ -86,10 +101,9 @@ export default class UpsertCategoryAppearance extends Component {
customFields: this.args.category.custom_fields,
};
- return applyMutableValueTransformer(
- "category-available-views",
- views,
- context
+ return withStoredValue(
+ applyMutableValueTransformer("category-available-views", views, context),
+ this.args.category.default_view
);
}
@@ -101,14 +115,16 @@ export default class UpsertCategoryAppearance extends Component {
}
get listFilters() {
- return ["all", "none"].map((value) => ({
+ const filters = ["all", "none"].map((value) => ({
name: i18n(`category.list_filters.${value}`),
value,
}));
+
+ return withStoredValue(filters, this.args.category.default_list_filter);
}
get sortOrders() {
- return applyMutableValueTransformer("category-sort-orders", [
+ const orders = applyMutableValueTransformer("category-sort-orders", [
"likes",
"op_likes",
"views",
@@ -120,17 +136,8 @@ export default class UpsertCategoryAppearance extends Component {
])
.map((s) => ({ name: i18n("category.sort_options." + s), value: s }))
.toSorted((a, b) => a.name.localeCompare(b.name));
- }
- get sortAscendingOption() {
- const sortAscending = this.sortAscendingValue;
- if (sortAscending === "false") {
- return false;
- }
- if (sortAscending === "true") {
- return true;
- }
- return sortAscending;
+ return withStoredValue(orders, this.args.category.sort_order);
}
get sortAscendingOptions() {
@@ -245,6 +252,7 @@ export default class UpsertCategoryAppearance extends Component {
@title={{i18n "category.sort_order"}}
@format="max"
@type="select"
+ @onSet={{this.onSortOrderSet}}
as |field|
>
<field.Control
@@ -314,10 +322,7 @@ export default class UpsertCategoryAppearance extends Component {
@type="select"
as |field|
>
- <field.Control
- @nonePlaceholder={{i18n "category.sort_options.default"}}
- as |select|
- >
+ <field.Control @includeNone={{false}} as |select|>
{{#each this.subcategoryListStyles as |style|}}
<select.Option
@value={{style.value}}
diff --git a/frontend/discourse/admin/routes/new-category.js b/frontend/discourse/admin/routes/new-category.js
index 3489fe18a86..caff76b40d1 100644
--- a/frontend/discourse/admin/routes/new-category.js
+++ b/frontend/discourse/admin/routes/new-category.js
@@ -54,6 +54,7 @@ export default class NewCategory extends DiscourseRoute {
required_tag_groups: [],
form_template_ids: [],
minimum_required_tags: 0,
+ subcategory_list_style: "rows_with_featured_topics",
category_localizations: [],
});
}
diff --git a/frontend/discourse/app/form-kit/components/fk/control/image.gjs b/frontend/discourse/app/form-kit/components/fk/control/image.gjs
index 86f5d7ad801..2382e79e628 100644
--- a/frontend/discourse/app/form-kit/components/fk/control/image.gjs
+++ b/frontend/discourse/app/form-kit/components/fk/control/image.gjs
@@ -13,7 +13,7 @@ export default class FKControlImage extends FKBaseControl {
@action
removeImage() {
- this.setImage(undefined);
+ this.setImage(null);
}
get imageUrl() {
diff --git a/frontend/discourse/app/form-kit/components/fk/control/password.gjs b/frontend/discourse/app/form-kit/components/fk/control/password.gjs
index f8a260ebaae..3689f14d54a 100644
--- a/frontend/discourse/app/form-kit/components/fk/control/password.gjs
+++ b/frontend/discourse/app/form-kit/components/fk/control/password.gjs
@@ -41,7 +41,7 @@ export default class FKControlPassword extends FKBaseControl {
@action
handleInput(event) {
- const value = event.target.value === "" ? undefined : event.target.value;
+ const value = event.target.value === "" ? null : event.target.value;
this.args.field.set(value);
}
diff --git a/frontend/discourse/app/form-kit/lib/constants.js b/frontend/discourse/app/form-kit/lib/constants.js
index 3b1dbe8b15f..9876c9fbb92 100644
--- a/frontend/discourse/app/form-kit/lib/constants.js
+++ b/frontend/discourse/app/form-kit/lib/constants.js
@@ -4,5 +4,3 @@ export const VALIDATION_TYPES = {
focusout: "focusout",
input: "input",
};
-
-export const NO_VALUE_OPTION = "__NONE__";
diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.js
index 0656d84c111..3d80b2e20e2 100644
--- a/frontend/discourse/app/models/category.js
+++ b/frontend/discourse/app/models/category.js
@@ -798,7 +798,6 @@ export default class Category extends RestModel {
slug: this.slug,
color: this.color,
text_color: this.text_color,
- secure: this.secure,
permissions: this._permissionsForUpdate(),
auto_close_hours: this.auto_close_hours,
auto_close_based_on_last_post: this.get(
diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.js
index 7160e63c289..837ca7bb4b3 100644
--- a/frontend/discourse/app/models/composer.js
+++ b/frontend/discourse/app/models/composer.js
@@ -1243,11 +1243,17 @@ export default class Composer extends RestModel {
const topicProps = this.getProperties(
Object.keys(_edit_topic_serializer)
);
+ // user clicked "overwrite edits" button
+ if (!this.editConflict) {
+ topicProps.original_title = this.originalTitle;
+ topicProps.original_tags = this.originalTags;
+ }
+
// frontend should have featuredLink but backend needs featured_link
- if (topicProps.featuredLink) {
- topicProps.featured_link = topicProps.featuredLink;
- delete topicProps.featuredLink;
+ if (topicProps.featuredLink !== topic.featured_link) {
+ topicProps.featured_link = topicProps.featuredLink ?? null;
}
+ delete topicProps.featuredLink;
// If we're editing a shared draft, keep the original category
if (this.action === EDIT_SHARED_DRAFT) {
diff --git a/frontend/discourse/app/ui-kit/d-select.gjs b/frontend/discourse/app/ui-kit/d-select.gjs
index cb62935af24..639b7801c13 100644
--- a/frontend/discourse/app/ui-kit/d-select.gjs
+++ b/frontend/discourse/app/ui-kit/d-select.gjs
@@ -62,12 +62,12 @@ export default class DSelect extends Component {
// if an option has no value, event.target.value will be the content of the option
// this is why we use this magic value to represent no value
this.args.onChange(
- event.target.value === NO_VALUE_OPTION ? undefined : event.target.value
+ event.target.value === NO_VALUE_OPTION ? null : event.target.value
);
}
get hasSelectedValue() {
- return this.args.value && this.args.value !== NO_VALUE_OPTION;
+ return this.htmlSelectValue !== NO_VALUE_OPTION;
}
get includeNone() {
diff --git a/frontend/discourse/tests/acceptance/category-edit-test.js b/frontend/discourse/tests/acceptance/category-edit-test.js
index 90da3efbe1f..0527417d759 100644
--- a/frontend/discourse/tests/acceptance/category-edit-test.js
+++ b/frontend/discourse/tests/acceptance/category-edit-test.js
@@ -1,11 +1,15 @@
import { click, currentURL, fillIn, visit } from "@ember/test-helpers";
import { test } from "qunit";
import sinon from "sinon";
+import { cloneJSON } from "discourse/lib/object";
import DiscourseURL from "discourse/lib/url";
-import pretender from "discourse/tests/helpers/create-pretender";
+import pretender, {
+ fixturesByUrl,
+} from "discourse/tests/helpers/create-pretender";
import formKit from "discourse/tests/helpers/form-kit-helper";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import selectKit from "discourse/tests/helpers/select-kit-helper";
+import { NO_VALUE_OPTION } from "discourse/ui-kit/d-select";
import { i18n } from "discourse-i18n";
function latestCategorySavePayload() {
@@ -535,3 +539,96 @@ acceptance("Category Edit - no permission to edit", function (needs) {
assert.strictEqual(currentURL(), "/404");
});
});
+
+function seededCategory(overrides) {
+ const category = cloneJSON(fixturesByUrl["/c/1/show.json"]).category;
+ return { ...category, can_edit: true, ...overrides };
+}
+
+acceptance("Category Edit - resetting selects to default", function (needs) {
+ needs.user();
+ needs.pretender((server, helper) => {
+ server.get("/c/bug/find_by_slug.json", () =>
+ helper.response(200, {
+ category: seededCategory({
+ default_view: "top",
+ sort_order: "views",
+ sort_ascending: false,
+ }),
+ })
+ );
+ });
+
+ test("sends null for cleared selects instead of dropping them", async function (assert) {
+ await visit("/c/bug/edit/images");
+
+ assert.strictEqual(
+ formKit().field("default_view").value(),
+ "top",
+ "seeds the default view"
+ );
+ assert.strictEqual(
+ formKit().field("sort_order").value(),
+ "views",
+ "seeds the sort order"
+ );
+ assert.strictEqual(
+ formKit().field("sort_ascending").value(),
+ "false",
+ "seeds the sort direction"
+ );
+
+ await formKit().field("default_view").select(NO_VALUE_OPTION);
+ await formKit().field("sort_order").select(NO_VALUE_OPTION);
+
+ assert
+ .dom("[data-name='sort_ascending']")
+ .doesNotExist("hides the sort direction once the sort order is cleared");
+
+ await click(".admin-changes-banner .btn-primary");
+
+ const payload = latestCategorySavePayload();
+
+ assert.strictEqual(payload.default_view, null, "clears the default view");
+ assert.strictEqual(payload.sort_order, null, "clears the sort order");
+ assert.strictEqual(
+ payload.sort_ascending,
+ null,
+ "clears the sort direction alongside the sort order"
+ );
+ });
+});
+
+acceptance(
+ "Category Edit - sort order stored outside the core list",
+ function (needs) {
+ needs.user();
+ needs.pretender((server, helper) => {
+ server.get("/c/bug/find_by_slug.json", () =>
+ helper.response(200, {
+ category: seededCategory({ sort_order: "votes" }),
+ })
+ );
+ });
+
+ test("renders the stored value, and can clear it", async function (assert) {
+ await visit("/c/bug/edit/images");
+
+ assert
+ .dselect("[data-name='sort_order'] .d-select")
+ .hasSelectedOption(
+ { value: "votes", label: "votes" },
+ "renders and selects a stored value the core list doesn't provide"
+ );
+
+ await formKit().field("sort_order").select(NO_VALUE_OPTION);
+ await click(".admin-changes-banner .btn-primary");
+
+ assert.strictEqual(
+ latestCategorySavePayload().sort_order,
+ null,
+ "clears the stored value"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/components/form-kit/controls/select-test.gjs b/frontend/discourse/tests/integration/components/form-kit/controls/select-test.gjs
index 5e233fb764c..797861f5fea 100644
--- a/frontend/discourse/tests/integration/components/form-kit/controls/select-test.gjs
+++ b/frontend/discourse/tests/integration/components/form-kit/controls/select-test.gjs
@@ -41,6 +41,40 @@ module(
assert.deepEqual(data, { foo: "option-3" });
});
+ test("selecting none", async function (assert) {
+ let data = { foo: "option-2" };
+ const mutateData = (x) => (data = x);
+
+ await render(
+ <template>
+ <Form @onSubmit={{mutateData}} @data={{data}} as |form|>
+ <form.Field @type="select" @name="foo" @title="Foo" as |field|>
+ <field.Control as |select|>
+ <select.Option @value="option-1">Option 1</select.Option>
+ <select.Option @value="option-2">Option 2</select.Option>
+ </field.Control>
+ </form.Field>
+ </Form>
+ </template>
+ );
+
+ await formKit().field("foo").select(NO_VALUE_OPTION);
+
+ assert.form().field("foo").hasValue(NO_VALUE_OPTION);
+
+ await formKit().submit();
+
+ assert.true(
+ Object.hasOwn(data, "foo"),
+ "the key is kept in the submitted data"
+ );
+ assert.strictEqual(
+ data.foo,
+ null,
+ "the value is null, so it survives JSON serialization"
+ );
+ });
+
test("@disabled", async function (assert) {
await render(
<template>
diff --git a/frontend/discourse/tests/integration/ui-kit/d-select-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-select-test.gjs
index e3557602e85..2e0609da18b 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-select-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-select-test.gjs
@@ -26,6 +26,27 @@ module("Integration | ui-kit | DSelect", function (hooks) {
assert.verifySteps(["foo"]);
});
+ test("@onChange with the none option", async function (assert) {
+ let changedValue = "not called";
+ const handleChange = (value) => (changedValue = value);
+
+ await render(
+ <template>
+ <DSelect @value="foo" @onChange={{handleChange}} as |s|>
+ <s.Option @value="foo">The real foo</s.Option>
+ </DSelect>
+ </template>
+ );
+
+ await select(".d-select", NO_VALUE_OPTION);
+
+ assert.strictEqual(
+ changedValue,
+ null,
+ "emits null, so the cleared value survives JSON serialization"
+ );
+ });
+
test("no value", async function (assert) {
await render(<template><DSelect /></template>);
@@ -55,6 +76,27 @@ module("Integration | ui-kit | DSelect", function (hooks) {
});
});
+ test("selected falsy value", async function (assert) {
+ await render(
+ <template>
+ <DSelect @value={{false}} as |s|>
+ <s.Option @value={{false}}>The real false</s.Option>
+ <s.Option @value={{true}}>The real true</s.Option>
+ </DSelect>
+ </template>
+ );
+
+ assert.dselect().hasOption({
+ value: NO_VALUE_OPTION,
+ label: i18n("none_placeholder"),
+ });
+
+ assert.dselect().hasSelectedOption({
+ value: "false",
+ label: "The real false",
+ });
+ });
+
test("keeps the selection when options are rebuilt", async function (assert) {
class State {
@tracked
diff --git a/frontend/discourse/tests/unit/models/composer-test.js b/frontend/discourse/tests/unit/models/composer-test.js
index 6124ce580bc..1ee40bbb6ae 100644
--- a/frontend/discourse/tests/unit/models/composer-test.js
+++ b/frontend/discourse/tests/unit/models/composer-test.js
@@ -27,6 +27,34 @@ function openComposer(opts) {
return composer;
}
+async function editTopicViaComposer(opts = {}) {
+ const store = getOwner(this).lookup("service:store");
+ const { topicProps = {}, ...composerProps } = opts;
+
+ const composer = createComposer.call(this, {
+ action: EDIT,
+ post: store.createRecord("post", { id: 123, post_number: 1 }),
+ topic: store.createRecord("topic", {
+ id: 456,
+ title: "a title",
+ details: { can_edit: true },
+ ...topicProps,
+ }),
+ title: "a title",
+ reply: "the body",
+ ...composerProps,
+ });
+
+ let payload;
+ pretender.put("/t/topic/456", (request) => {
+ payload = JSON.parse(request.requestBody);
+ return response({ basic_topic: { title: composer.title } });
+ });
+
+ await composer.editPost({});
+ return payload;
+}
+
module("Unit | Model | composer", function (hooks) {
setupTest(hooks);
@@ -665,4 +693,65 @@ module("Unit | Model | composer", function (hooks) {
assert.strictEqual(composer.composeState, "open");
assert.true(composer.editConflict);
});
+
+ test("editPost sends the topic edit-conflict fields", async function (assert) {
+ const payload = await editTopicViaComposer.call(this, {
+ topicProps: { title: "the original title" },
+ title: "a brand new title",
+ originalTitle: "the original title",
+ originalTags: [{ id: 7, name: "bug" }],
+ });
+
+ assert.strictEqual(
+ payload.original_title,
+ "the original title",
+ "sends original_title so the server can detect a conflict"
+ );
+ assert.deepEqual(
+ payload.original_tags,
+ [{ id: 7, name: "bug" }],
+ "sends original_tags so the server can detect a conflict"
+ );
+ });
+
+ test("editPost omits the edit-conflict fields when overwriting edits", async function (assert) {
+ const payload = await editTopicViaComposer.call(this, {
+ topicProps: { title: "the original title" },
+ title: "a brand new title",
+ originalTitle: "the original title",
+ originalTags: [{ id: 7, name: "bug" }],
+ editConflict: true,
+ });
+
+ assert.false(
+ "original_title" in payload,
+ "lets the overwrite go through instead of conflicting again"
+ );
+ assert.false("original_tags" in payload, "same for the tags");
+ });
+
+ test("editPost only sends featured_link when it changed", async function (assert) {
+ const cleared = await editTopicViaComposer.call(this, {
+ topicProps: { featured_link: "https://discourse.org" },
+ featuredLink: null,
+ });
+ assert.strictEqual(
+ cleared.featured_link,
+ null,
+ "sends an explicit null when the link was cleared"
+ );
+ assert.false(
+ "featuredLink" in cleared,
+ "never sends the camelCase key the server ignores"
+ );
+
+ const unchanged = await editTopicViaComposer.call(this, {
+ topicProps: { featured_link: "https://discourse.org" },
+ featuredLink: "https://discourse.org",
+ });
+ assert.false(
+ "featured_link" in unchanged,
+ "leaves the link alone when it didn't change"
+ );
+ });
});
diff --git a/lib/post_revisor.rb b/lib/post_revisor.rb
index 6914eec94a8..a5d618ceeec 100644
--- a/lib/post_revisor.rb
+++ b/lib/post_revisor.rb
@@ -184,12 +184,12 @@ class PostRevisor
track_topic_field(:tags) { |tc, tags| tc.apply_tag_changes(tags) }
track_topic_field(:featured_link) do |topic_changes, featured_link|
- if !SiteSetting.topic_featured_link_enabled ||
- !topic_changes.guardian.can_edit_featured_link?(topic_changes.topic.category_id)
+ if featured_link.blank?
+ track_and_revise topic_changes, :featured_link, nil
+ elsif !topic_changes.guardian.can_edit_featured_link?(topic_changes.topic.category_id)
topic_changes.check_result(false)
else
- topic_changes.record_change("featured_link", topic_changes.topic.featured_link, featured_link)
- topic_changes.topic.featured_link = featured_link
+ track_and_revise topic_changes, :featured_link, featured_link
end
end
diff --git a/plugins/discourse-ai/app/models/ai_tool.rb b/plugins/discourse-ai/app/models/ai_tool.rb
index 436ed95cf7e..cd688e5e119 100644
--- a/plugins/discourse-ai/app/models/ai_tool.rb
+++ b/plugins/discourse-ai/app/models/ai_tool.rb
@@ -9,6 +9,8 @@ class AiTool < ActiveRecord::Base
validates :summary, presence: true, length: { maximum: 255 }
validates :script, presence: true, length: { maximum: 100_000 }
validates :created_by_id, presence: true
+ validates :rag_chunk_tokens, numericality: { greater_than: 0 }
+ validates :rag_chunk_overlap_tokens, numericality: { greater_than_or_equal_to: 0 }
belongs_to :created_by, class_name: "User"
belongs_to :rag_llm_model, class_name: "LlmModel"
has_many :rag_document_fragments, dependent: :destroy, as: :target
diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rb
index bed259814ed..196c402b3bf 100644
--- a/spec/models/category_spec.rb
+++ b/spec/models/category_spec.rb
@@ -51,6 +51,36 @@ RSpec.describe Category do
end
end
+ describe "#minimum_required_tags" do
+ it "is zero when blank" do
+ category = Fabricate.build(:category, user: user, minimum_required_tags: nil)
+ category.validate
+
+ expect(category.minimum_required_tags).to eq(0)
+ end
+
+ it "keeps a set value" do
+ category = Fabricate.build(:category, user: user, minimum_required_tags: 3)
+ category.validate
+
+ expect(category.minimum_required_tags).to eq(3)
+ end
+ end
+
+ describe "#subcategory_list_includes_topics?" do
+ def includes_topics?(style)
+ Category.new(subcategory_list_style: style).subcategory_list_includes_topics?
+ end
+
+ it "is true only for the styles that feature topics" do
+ expect(includes_topics?("rows_with_featured_topics")).to eq(true)
+ expect(includes_topics?("boxes_with_featured_topics")).to eq(true)
+ expect(includes_topics?("rows")).to eq(false)
+ expect(includes_topics?("boxes")).to eq(false)
+ expect(includes_topics?(nil)).to eq(false)
+ end
+ end
+
it "validates uniqueness in case insensitive way" do
Fabricate(:category_with_definition, name: "Cats")
cats = Fabricate.build(:category, name: "cats")
diff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rb
index 7d325adde5f..1b413e75318 100644
--- a/spec/requests/categories_controller_spec.rb
+++ b/spec/requests/categories_controller_spec.rb
@@ -445,6 +445,18 @@ RSpec.describe CategoriesController do
).not_to include(uncategorized.id)
end
+ it "lists the subcategories of a parent that has no subcategory list style" do
+ category.update!(subcategory_list_style: nil)
+ subcategory = Fabricate(:category, user: admin, parent_category: category)
+
+ get "/categories.json", params: { parent_category_id: category.id }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["category_list"]["categories"].map { |c| c["id"] }).to eq(
+ [subcategory.id],
+ )
+ end
+
describe "with page" do
before { sign_in(admin) }
@@ -1176,6 +1188,51 @@ RSpec.describe CategoriesController do
expect(cat_json["subcategory_count"]).to eq(nil)
end
+ context "with appearance settings set" do
+ before do
+ category.update!(
+ sort_order: "likes",
+ sort_ascending: true,
+ default_view: "top",
+ default_top_period: "weekly",
+ default_list_filter: "none",
+ )
+ end
+
+ it "resets the appearance settings that are sent as null" do
+ put "/categories/#{category.id}.json",
+ params: {
+ sort_order: nil,
+ sort_ascending: nil,
+ default_view: nil,
+ default_top_period: nil,
+ default_list_filter: nil,
+ },
+ as: :json
+
+ expect(response.status).to eq(200)
+ category.reload
+ expect(category.sort_order).to eq(nil)
+ expect(category.sort_ascending).to eq(nil)
+ expect(category.default_view).to eq(nil)
+ expect(category.default_top_period).to eq(nil)
+ expect(category.default_list_filter).to eq(nil)
+ end
+
+ it "keeps the appearance settings that are not sent at all" do
+ put "/categories/#{category.id}.json", params: { name: "hello" }, as: :json
+
+ expect(response.status).to eq(200)
+ category.reload
+ expect(category.name).to eq("hello")
+ expect(category.sort_order).to eq("likes")
+ expect(category.sort_ascending).to eq(true)
+ expect(category.default_view).to eq("top")
+ expect(category.default_top_period).to eq("weekly")
+ expect(category.default_list_filter).to eq("none")
+ end
+ end
+
it "does not update other fields" do
SiteSetting.tagging_enabled = true
tag_group_1 = Fabricate(:tag_group)
@@ -1353,6 +1410,21 @@ RSpec.describe CategoriesController do
expect(category.reload.minimum_required_tags).to eq(0)
end
+ it "can correctly convert explicit nulls to appropriate null values" do
+ category.update!(email_in: "[email protected]", minimum_required_tags: 5)
+
+ put "/categories/#{category.id}.json",
+ params: {
+ email_in: nil,
+ minimum_required_tags: nil,
+ },
+ as: :json
+
+ expect(response.status).to eq(200)
+ expect(category.reload.email_in).to be_nil
+ expect(category.reload.minimum_required_tags).to eq(0)
+ end
+
it "does not convert params when their key isn't present" do
category.update!(email_in: "[email protected]", minimum_required_tags: 5)
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index bd0395a6d32..1b49ede56a1 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -3029,6 +3029,16 @@ RSpec.describe TopicsController do
expect(topic.reload.category).to eq(category)
end
end
+
+ it "can not clear the category when the guardian disallows the move" do
+ topic.update!(category:)
+ Guardian.any_instance.stubs(:can_move_topic_to_category?).returns(false)
+
+ put "/t/#{topic.slug}/#{topic.id}.json", params: { category_id: nil }, as: :json
+
+ expect(response.status).to eq(403)
+ expect(topic.reload.category_id).to eq(category.id)
+ end
end
end
@@ -3086,6 +3096,49 @@ RSpec.describe TopicsController do
expect(response.status).to eq(422)
end
+
+ it "allows to remove the featured link" do
+ sign_in(trust_level_1)
+
+ tl1_topic = Fabricate(:topic, user: trust_level_1, featured_link: "https://discourse.org")
+ Fabricate(:post, user: post_author1, topic: tl1_topic)
+ put "/t/#{tl1_topic.slug}/#{tl1_topic.id}.json", params: { featured_link: nil }
+
+ expect(response.status).to eq(200)
+ expect(tl1_topic.reload.featured_link).to be_nil
+ end
+
+ it "removes the featured link when moving to a category that forbids them" do
+ sign_in(trust_level_1)
+
+ category = Fabricate(:category, topic_featured_link_allowed: false)
+ tl1_topic = Fabricate(:topic, user: trust_level_1, featured_link: "https://discourse.org")
+ Fabricate(:post, user: post_author1, topic: tl1_topic)
+ put "/t/#{tl1_topic.slug}/#{tl1_topic.id}.json",
+ params: {
+ category_id: category.id,
+ featured_link: nil,
+ }
+
+ expect(response.status).to eq(200)
+ expect(tl1_topic.reload.category_id).to eq(category.id)
+ expect(tl1_topic.featured_link).to be_nil
+ end
+
+ it "doesn't reject an edit that sends a blank featured link it cannot set" do
+ sign_in(trust_level_0)
+
+ tl0_topic = Fabricate(:topic, user: trust_level_0)
+ Fabricate(:post, user: post_author1, topic: tl0_topic)
+ put "/t/#{tl0_topic.slug}/#{tl0_topic.id}.json",
+ params: {
+ title: "A brand new title for this topic",
+ featured_link: nil,
+ }
+
+ expect(response.status).to eq(200)
+ expect(tl0_topic.reload.title).to eq("A brand new title for this topic")
+ end
end
end
diff --git a/spec/services/tag_settings_updater_spec.rb b/spec/services/tag_settings_updater_spec.rb
index dca7751607e..afa5df058a8 100644
--- a/spec/services/tag_settings_updater_spec.rb
+++ b/spec/services/tag_settings_updater_spec.rb
@@ -21,6 +21,24 @@ describe TagSettingsUpdater do
expect(tag.reload.slug).to eq("custom-slug")
end
+ it "regenerates the slug from the name when it is cleared" do
+ tag.update!(slug: "custom-slug")
+
+ result = TagSettingsUpdater.update(tag, admin, { slug: "" })
+
+ expect(result).to eq(true)
+ expect(tag.reload.slug).to eq(tag.name)
+ end
+
+ it "keeps the slug when it isn't provided" do
+ tag.update!(slug: "custom-slug")
+
+ result = TagSettingsUpdater.update(tag, admin, { description: "a description" })
+
+ expect(result).to eq(true)
+ expect(tag.reload.slug).to eq("custom-slug")
+ end
+
it "cleans tag name using DiscourseTagging" do
result = TagSettingsUpdater.update(tag, admin, { name: " New Name " })
diff --git a/spec/system/edit_category_reset_to_default_spec.rb b/spec/system/edit_category_reset_to_default_spec.rb
new file mode 100644
index 00000000000..e136fb1b18c
--- /dev/null
+++ b/spec/system/edit_category_reset_to_default_spec.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+describe "Edit Category Reset To Default" do
+ fab!(:admin)
+ fab!(:category) { Fabricate(:category, sort_order: "likes", default_view: "top") }
+
+ let(:category_page) { PageObjects::Pages::Category.new }
+ let(:form) { PageObjects::Components::FormKit.new(".form-kit") }
+
+ before { sign_in(admin) }
+
+ it "lets an admin put the sort order and the default view back to the default" do
+ category_page.visit_appearance(category)
+
+ expect(form.field("sort_order")).to have_value("likes")
+ expect(form.field("default_view")).to have_value("top")
+
+ form.field("sort_order").select_none
+ form.field("default_view").select_none
+ category_page.save_settings
+
+ try_until_success do
+ category.reload
+ expect(category.sort_order).to eq(nil)
+ expect(category.default_view).to eq(nil)
+ end
+
+ page.refresh
+
+ expect(form.field("sort_order")).to have_no_value
+ expect(form.field("default_view")).to have_no_value
+ end
+end
diff --git a/spec/system/page_objects/components/d_select.rb b/spec/system/page_objects/components/d_select.rb
index 73104a8a0dc..2d8cb448a07 100644
--- a/spec/system/page_objects/components/d_select.rb
+++ b/spec/system/page_objects/components/d_select.rb
@@ -3,6 +3,8 @@
module PageObjects
module Components
class DSelect < PageObjects::Components::Base
+ NO_VALUE_OPTION = "__NONE__"
+
attr_reader :select_element
def initialize(input)
@@ -24,6 +26,10 @@ module PageObjects
selector.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
JS
end
+
+ def has_no_value?
+ @select_element.has_css?("option[value='#{NO_VALUE_OPTION}']:checked", visible: :all)
+ end
end
end
end
diff --git a/spec/system/page_objects/components/form_kit.rb b/spec/system/page_objects/components/form_kit.rb
index 07685ba27ce..51e8b5d8fb7 100644
--- a/spec/system/page_objects/components/form_kit.rb
+++ b/spec/system/page_objects/components/form_kit.rb
@@ -203,6 +203,20 @@ module PageObjects
end
end
+ def select_none
+ select(PageObjects::Components::DSelect::NO_VALUE_OPTION)
+ end
+
+ def has_no_value?
+ if control_type == "select"
+ PageObjects::Components::DSelect.new(
+ component.find(".form-kit__control-select"),
+ ).has_no_value?
+ else
+ raise "'has_no_value?' is not supported for control type: #{control_type}"
+ end
+ end
+
def accept
if control_type == "question"
component.find(".form-kit__control-radio[value='true']").click