A platform for community discussion. Free, open, simple.
DEV: Add enum class support for list type site settings (#36699)
Keegan Georgef424579cc24e
diff --git a/frontend/discourse/admin/components/site-settings/compact-list.gjs b/frontend/discourse/admin/components/site-settings/compact-list.gjsindex 0eea27b841b..6ad4589c186 100644--- a/frontend/discourse/admin/components/site-settings/compact-list.gjs+++ b/frontend/discourse/admin/components/site-settings/compact-list.gjs@@ -6,10 +6,30 @@ import { uniqueItemsFromArray } from "discourse/lib/array-tools";import { makeArray } from "discourse/lib/helpers";import ListSetting from "discourse/select-kit/components/list-setting";+/**+ * Site setting component for compact list type settings.+ * Supports both static choices and dynamic enum-based validValues.+ *+ * @component CompactList+ * @param {Object} setting - The site setting object+ * @param {string} value - Current setting value (pipe-separated)+ * @param {Function} changeValueCallback - Callback when value changes+ * @param {boolean} allowAny - Whether to allow arbitrary values+ */export default class CompactList extends Component {@tracked createdChoices = null;tokenSeparator = "|";+ /**+ * @returns {boolean} Whether the setting has valid values from an enum class+ */+ get hasValidValues() {+ return this.args.setting.validValues?.length > 0;+ }++ /**+ * @returns {string[]} Current setting value split into array+ */get settingValue() {return this.args.value.toString()@@ -17,7 +37,21 @@ export default class CompactList extends Component {.filter(Boolean);}+ /**+ * Returns choices for the list setting. When validValues from an enum class+ * are available, uses those (converting values to strings for consistent+ * comparison). Otherwise falls back to static choices.+ *+ * @returns {Array<{name: string, value: string}|string>} Choices for the list+ */get settingChoices() {+ if (this.hasValidValues) {+ return this.args.setting.validValues.map((v) => ({+ name: v.name,+ value: String(v.value),+ }));+ }+return uniqueItemsFromArray([...makeArray(this.settingValue),...makeArray(this.args.setting.choices),@@ -43,6 +77,8 @@ export default class CompactList extends Component {@value={{this.settingValue}}@settingName={{@setting.setting}}@choices={{this.settingChoices}}+ @nameProperty={{if this.hasValidValues "name"}}+ @valueProperty={{if this.hasValidValues "value"}}@onChange={{this.onChangeListSetting}}@onChangeChoices={{this.onChangeChoices}}@options={{hash allowAny=@allowAny}}diff --git a/frontend/discourse/tests/integration/components/compact-list-test.gjs b/frontend/discourse/tests/integration/components/compact-list-test.gjsindex 9cf9f0b9541..4f1655eb996 100644--- a/frontend/discourse/tests/integration/components/compact-list-test.gjs+++ b/frontend/discourse/tests/integration/components/compact-list-test.gjs@@ -35,4 +35,100 @@ module("Integration | Component | compact-list site-setting", function (hooks) {assert.dom(".selected-content button").hasClass("disabled");});++ test("with valid_values from enum class", async function (assert) {+ this.set(+ "setting",+ SiteSetting.create({+ category: "foo",+ description: "Choose LLMs",+ placeholder: null,+ preview: null,+ secret: false,+ setting: "test_llm_list",+ type: "compact_list",+ default: "",+ value: "1|2",+ valid_values: [+ { name: "Model One", value: 1 },+ { name: "Model Two", value: 2 },+ { name: "Model Three", value: 3 },+ ],+ })+ );++ await render(+ <template><SiteSettingComponent @setting={{this.setting}} /></template>+ );++ const subject = selectKit(".list-setting");++ await subject.expand();++ assert.strictEqual(subject.rowByIndex(0).name(), "Model Three");+ assert.dom(".selected-content .selected-choice").exists({ count: 2 });+ });++ test("empty valid_values falls back to standard choices", async function (assert) {+ this.set(+ "setting",+ SiteSetting.create({+ category: "foo",+ description: "Choose items",+ placeholder: null,+ preview: null,+ secret: false,+ setting: "test_list",+ type: "compact_list",+ default: "",+ value: "a|b",+ valid_values: [],+ choices: ["a", "b", "c"],+ })+ );++ await render(+ <template><SiteSettingComponent @setting={{this.setting}} /></template>+ );++ const subject = selectKit(".list-setting");++ await subject.expand();++ assert.strictEqual(subject.rowByIndex(0).name(), "c");+ assert.dom(".selected-content .selected-choice").exists({ count: 2 });+ });++ test("valid_values converts integer values to strings for comparison", async function (assert) {+ this.set(+ "setting",+ SiteSetting.create({+ category: "foo",+ description: "Choose items",+ placeholder: null,+ preview: null,+ secret: false,+ setting: "test_list",+ type: "compact_list",+ default: "",+ value: "42",+ valid_values: [+ { name: "Item Forty-Two", value: 42 },+ { name: "Item Forty-Three", value: 43 },+ ],+ })+ );++ await render(+ <template><SiteSettingComponent @setting={{this.setting}} /></template>+ );++ const subject = selectKit(".list-setting");++ await subject.expand();++ // value "42" (string) should match valid_values 42 (integer)+ assert.dom(".selected-content .selected-choice").exists({ count: 1 });+ assert.strictEqual(subject.rowByIndex(0).name(), "Item Forty-Three");+ });});diff --git a/lib/site_settings/type_supervisor.rb b/lib/site_settings/type_supervisor.rbindex ece1fcaaf2b..838a622d87c 100644--- a/lib/site_settings/type_supervisor.rb+++ b/lib/site_settings/type_supervisor.rb@@ -191,7 +191,7 @@ class SiteSettings::TypeSupervisorlist_type = get_list_type(name)result = { type: type.to_s }- if type == :enum || list_type == "locale"+ if type == :enum || (type == :list && get_enum_class(name))if (klass = get_enum_class(name))result.merge!(valid_values: klass.values, translate_names: klass.translate_names?)else@@ -240,7 +240,7 @@ class SiteSettings::TypeSupervisorenddef validate_value(name, type, val)- if type == self.class.types[:enum] || get_list_type(name) == "locale"+ if type == self.class.types[:enum] || (type == self.class.types[:list] && get_enum_class(name))if get_enum_class(name)unless get_enum_class(name).valid_value?(val)raise Discourse::InvalidParameters.new("Invalid value `#{val}` for `#{name}`")diff --git a/spec/lib/site_settings/type_supervisor_spec.rb b/spec/lib/site_settings/type_supervisor_spec.rbindex c221cf82912..d6b2c9717e7 100644--- a/spec/lib/site_settings/type_supervisor_spec.rb+++ b/spec/lib/site_settings/type_supervisor_spec.rb@@ -552,4 +552,101 @@ RSpec.describe SiteSettings::TypeSupervisor doexpect(settings.type_supervisor.type_hash(:type_int)[:max]).to eq(10)endend++ describe "list type with enum class" do+ class TestListEnumClass+ def self.valid_value?(v)+ v.to_s.split("|").all? { |item| valid_items.include?(item) }+ end++ def self.valid_items+ %w[item1 item2 item3]+ end++ def self.values+ valid_items.map { |item| { name: item.titleize, value: item } }+ end++ def self.translate_names?+ true+ end+ end++ before do+ settings.setting(:type_list_enum, "", type: "list", enum: "TestListEnumClass")+ settings.setting(:type_list_no_enum, "", type: "list", choices: %w[a b c])+ settings.setting(+ :type_list_enum_with_choices,+ "",+ type: "list",+ enum: "TestListEnumClass",+ choices: %w[item1 item2],+ )+ settings.refresh!+ end++ describe "#type_hash" do+ it "returns valid_values from enum class for list type" do+ hash = settings.type_supervisor.type_hash(:type_list_enum)+ expect(hash[:type]).to eq "list"+ expect(hash[:valid_values]).to eq(+ [+ { name: "Item1", value: "item1" },+ { name: "Item2", value: "item2" },+ { name: "Item3", value: "item3" },+ ],+ )+ expect(hash[:translate_names]).to eq true+ end++ it "does not return valid_values for list type without enum" do+ hash = settings.type_supervisor.type_hash(:type_list_no_enum)+ expect(hash[:type]).to eq "list"+ expect(hash[:valid_values]).to be_nil+ expect(hash[:choices]).to eq %w[a b c]+ end++ it "returns both valid_values and choices when both enum and choices are specified" do+ hash = settings.type_supervisor.type_hash(:type_list_enum_with_choices)+ expect(hash[:type]).to eq "list"+ expect(hash[:valid_values]).to eq(+ [+ { name: "Item1", value: "item1" },+ { name: "Item2", value: "item2" },+ { name: "Item3", value: "item3" },+ ],+ )+ expect(hash[:choices]).to eq %w[item1 item2]+ end+ end++ describe "#to_db_value" do+ it "validates list values using enum class" do+ expect(settings.type_supervisor.to_db_value(:type_list_enum, "item1")).to eq [+ "item1",+ SiteSetting.types[:list],+ ]+ expect(settings.type_supervisor.to_db_value(:type_list_enum, "item1|item2")).to eq [+ "item1|item2",+ SiteSetting.types[:list],+ ]+ end++ it "raises when list value is not valid according to enum class" do+ expect { settings.type_supervisor.to_db_value(:type_list_enum, "invalid") }.to raise_error(+ Discourse::InvalidParameters,+ )+ expect {+ settings.type_supervisor.to_db_value(:type_list_enum, "item1|invalid")+ }.to raise_error(Discourse::InvalidParameters)+ end++ it "allows empty value for list with enum" do+ expect(settings.type_supervisor.to_db_value(:type_list_enum, "")).to eq [+ "",+ SiteSetting.types[:list],+ ]+ end+ end+ endend