Skip to content

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

DEV: Add a reusable SettingDefinitionField for FormKit setting fields (#41099)

Régis Hanol2641aac7c20a
diff --git a/frontend/discourse/admin/models/site-setting.js b/frontend/discourse/admin/models/site-setting.js
index a11dc19650c..ac6575ca15b 100644
--- a/frontend/discourse/admin/models/site-setting.js
+++ b/frontend/discourse/admin/models/site-setting.js
@@ -153,6 +153,20 @@ export default class SiteSetting extends EmberObject {
};
}
+ get definition() {
+ return {
+ key: this.setting,
+ label: this.humanized_name,
+ description: this.description,
+ type: this.type,
+ list_type: this.list_type,
+ min: this.min,
+ max: this.max,
+ choices: this.choices,
+ valid_values: this.valid_values,
+ };
+ }
+
get requiresConfirmation() {
switch (this.requires_confirmation) {
case SITE_SETTING_REQUIRES_CONFIRMATION_TYPES.simple:
diff --git a/frontend/discourse/app/components/edit-category-type-schema-fields.gjs b/frontend/discourse/app/components/edit-category-type-schema-fields.gjs
index 692aa7d8a6f..c1b989ee7ae 100644
--- a/frontend/discourse/app/components/edit-category-type-schema-fields.gjs
+++ b/frontend/discourse/app/components/edit-category-type-schema-fields.gjs
@@ -1,136 +1,10 @@
import Component from "@glimmer/component";
-import { fn, get, hash } from "@ember/helper";
-import { service } from "@ember/service";
+import { get, hash } from "@ember/helper";
+import SettingDefinitionField from "discourse/components/setting-definition-field";
import { bind } from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
-import GroupChooser from "discourse/select-kit/components/group-chooser";
-import { eq } from "discourse/truth-helpers";
-import DRelativeTimePicker from "discourse/ui-kit/d-relative-time-picker";
import { i18n } from "discourse-i18n";
-// NOTE: In future we may want to use FormKit versions of site setting components
-// here rather than this custom implementation. We are also only supporting a small
-// subset of site setting types / category field types for now, we can expand this as
-// needed.
-class SchemaFormField extends Component {
- @service site;
-
- get groupContent() {
- return this.site.groups;
- }
-
- toGroupIdArray(value) {
- if (Array.isArray(value)) {
- return value.map(Number);
- }
- if (typeof value === "string" && value.length) {
- return value.split("|").map(Number);
- }
- return [];
- }
-
- @bind
- setGroupIdString(field, ids) {
- field.set((ids ?? []).join("|"));
- }
-
- <template>
- {{#if (eq @entry.type "bool")}}
- <@formObject.Field
- @name={{@entry.key}}
- @type="checkbox"
- @title={{@entry.label}}
- @validation={{if @entry.required "required"}}
- @format="full"
- @showTitle={{false}}
- as |field|
- >
- <field.Control>{{@entry.description}}</field.Control>
- </@formObject.Field>
- {{else if (eq @entry.subtype "duration")}}
- <@formObject.Field
- @name={{@entry.key}}
- @title={{@entry.label}}
- @description={{@entry.description}}
- @validation={{if @entry.required "required"}}
- @format="full"
- @type="custom"
- as |field|
- >
- <DRelativeTimePicker
- @durationHours={{field.value}}
- @durationOutputUnit="hours"
- @onChange={{field.set}}
- />
- </@formObject.Field>
- {{else if (eq @entry.type "enum")}}
- <@formObject.Field
- @name={{@entry.key}}
- @title={{@entry.label}}
- @description={{@entry.description}}
- @validation={{if @entry.required "required"}}
- @labelFormat="full"
- @format="large"
- @type="select"
- as |field|
- >
- <field.Control as |select|>
- {{#each @entry.choices as |choice|}}
- <select.Option @value={{choice.value}}>
- {{choice.name}}
- </select.Option>
- {{/each}}
- </field.Control>
- </@formObject.Field>
- {{else if (eq @entry.type "group_list")}}
- <@formObject.Field
- @name={{@entry.key}}
- @title={{@entry.label}}
- @description={{@entry.description}}
- @validation={{if @entry.required "required"}}
- @labelFormat="full"
- @format="large"
- @type="custom"
- as |field|
- >
- <field.Control>
- <GroupChooser
- @content={{this.groupContent}}
- @value={{this.toGroupIdArray field.value}}
- @labelProperty="name"
- @onChange={{fn this.setGroupIdString field}}
- />
- </field.Control>
- </@formObject.Field>
- {{else if (eq @entry.type "integer")}}
- <@formObject.Field
- @name={{@entry.key}}
- @title={{@entry.label}}
- @description={{@entry.description}}
- @validation={{if @entry.required "required"}}
- @format="full"
- @type="input-number"
- as |field|
- >
- <field.Control min={{@entry.min}} max={{@entry.max}} />
- </@formObject.Field>
- {{else}}
- <@formObject.Field
- @name={{@entry.key}}
- @type="input"
- @title={{@entry.label}}
- @description={{@entry.description}}
- @validation={{if @entry.required "required"}}
- @labelFormat="full"
- @format="large"
- as |field|
- >
- <field.Control />
- </@formObject.Field>
- {{/if}}
- </template>
-}
-
export default class EditCategoryTypeSchemaFields extends Component {
get schema() {
return (
@@ -224,10 +98,9 @@ export default class EditCategoryTypeSchemaFields extends Component {
<@form.Object @name="custom_fields" as |customFields|>
{{#each this.schema.category_custom_fields as |entry|}}
{{#if (this.isFieldVisible entry)}}
- <SchemaFormField
- @category={{@category}}
- @entry={{entry}}
- @formObject={{customFields}}
+ <SettingDefinitionField
+ @definition={{entry}}
+ @form={{customFields}}
/>
{{/if}}
{{/each}}
@@ -240,10 +113,9 @@ export default class EditCategoryTypeSchemaFields extends Component {
<@form.Object @name="category_type_settings" as |categorySettings|>
{{#each this.schema.category_settings as |entry|}}
{{#if (this.isFieldVisible entry)}}
- <SchemaFormField
- @category={{@category}}
- @entry={{entry}}
- @formObject={{categorySettings}}
+ <SettingDefinitionField
+ @definition={{entry}}
+ @form={{categorySettings}}
/>
{{/if}}
{{/each}}
@@ -301,10 +173,9 @@ export default class EditCategoryTypeSchemaFields extends Component {
<div class="--dependent-border"></div>
<div class="--dependent-fields">
{{#each group.entries as |entry|}}
- <SchemaFormField
- @category={{@category}}
- @entry={{entry}}
- @formObject={{siteSettings}}
+ <SettingDefinitionField
+ @definition={{entry}}
+ @form={{siteSettings}}
/>
{{/each}}
</div>
@@ -312,10 +183,9 @@ export default class EditCategoryTypeSchemaFields extends Component {
{{/if}}
{{else}}
{{#each group.entries as |entry|}}
- <SchemaFormField
- @category={{@category}}
- @entry={{entry}}
- @formObject={{siteSettings}}
+ <SettingDefinitionField
+ @definition={{entry}}
+ @form={{siteSettings}}
/>
{{/each}}
{{/if}}
diff --git a/frontend/discourse/app/components/setting-definition-field.gjs b/frontend/discourse/app/components/setting-definition-field.gjs
new file mode 100644
index 00000000000..bdc4b842b0d
--- /dev/null
+++ b/frontend/discourse/app/components/setting-definition-field.gjs
@@ -0,0 +1,42 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import {
+ resolveSettingFieldType,
+ settingFieldValidation,
+} from "discourse/lib/setting-field-registry";
+
+export default class SettingDefinitionField extends Component {
+ @cached
+ get entry() {
+ return resolveSettingFieldType(this.args.definition);
+ }
+
+ get renderer() {
+ return this.entry.renderer;
+ }
+
+ get description() {
+ return this.entry.includeDescription === false
+ ? undefined
+ : this.args.definition.description;
+ }
+
+ get validation() {
+ return settingFieldValidation(this.args.definition);
+ }
+
+ <template>
+ <@form.Field
+ @name={{@definition.key}}
+ @title={{@definition.label}}
+ @description={{this.description}}
+ @validation={{this.validation}}
+ @type={{this.entry.type}}
+ @format={{this.entry.format}}
+ @labelFormat={{this.entry.labelFormat}}
+ as |field|
+ >
+ <this.renderer @field={{field}} @definition={{@definition}} />
+ </@form.Field>
+ </template>
+}
diff --git a/frontend/discourse/app/components/setting-field/bool.gjs b/frontend/discourse/app/components/setting-field/bool.gjs
new file mode 100644
index 00000000000..986b2122961
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/bool.gjs
@@ -0,0 +1,3 @@
+<template>
+ <@field.Control>{{@definition.description}}</@field.Control>
+</template>
diff --git a/frontend/discourse/app/components/setting-field/category-list.gjs b/frontend/discourse/app/components/setting-field/category-list.gjs
new file mode 100644
index 00000000000..07ed60ee3ff
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/category-list.gjs
@@ -0,0 +1,45 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { splitString } from "discourse/lib/utilities";
+import Category from "discourse/models/category";
+import CategorySelector from "discourse/select-kit/components/category-selector";
+
+export default class SettingFieldCategoryList extends Component {
+ @tracked selectedCategories = [];
+
+ constructor() {
+ super(...arguments);
+ this.loadCategories();
+ }
+
+ get categoryIds() {
+ return splitString(this.args.field.value, "|");
+ }
+
+ @action
+ async loadCategories() {
+ if (this.categoryIds.length) {
+ this.selectedCategories = await Category.asyncFindByIds(this.categoryIds);
+ } else {
+ this.selectedCategories = [];
+ }
+ }
+
+ @action
+ onChangeCategories(categories) {
+ this.args.field.set((categories || []).map((c) => c.id).join("|"));
+ }
+
+ <template>
+ <@field.Control>
+ <div {{didUpdate this.loadCategories @field.value}}>
+ <CategorySelector
+ @categories={{this.selectedCategories}}
+ @onChange={{this.onChangeCategories}}
+ />
+ </div>
+ </@field.Control>
+ </template>
+}
diff --git a/frontend/discourse/app/components/setting-field/compact-list.gjs b/frontend/discourse/app/components/setting-field/compact-list.gjs
new file mode 100644
index 00000000000..b4cca7c6663
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/compact-list.gjs
@@ -0,0 +1,39 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { bind } from "discourse/lib/decorators";
+import { splitString } from "discourse/lib/utilities";
+import ListSetting from "discourse/select-kit/components/list-setting";
+
+export default class SettingFieldCompactList extends Component {
+ get hasEnumChoices() {
+ return this.args.definition.valid_values?.length > 0;
+ }
+
+ get choices() {
+ if (this.hasEnumChoices) {
+ return this.args.definition.valid_values.map((v) => ({
+ name: v.name,
+ value: String(v.value),
+ }));
+ }
+ return this.args.definition.choices;
+ }
+
+ @bind
+ setList(field, values) {
+ field.set(Array.isArray(values) ? values.join("|") : values);
+ }
+
+ <template>
+ <@field.Control>
+ <ListSetting
+ @value={{splitString @field.value "|"}}
+ @choices={{this.choices}}
+ @settingName={{@definition.key}}
+ @nameProperty={{if this.hasEnumChoices "name"}}
+ @valueProperty={{if this.hasEnumChoices "value"}}
+ @onChange={{fn this.setList @field}}
+ />
+ </@field.Control>
+ </template>
+}
diff --git a/frontend/discourse/app/components/setting-field/duration.gjs b/frontend/discourse/app/components/setting-field/duration.gjs
new file mode 100644
index 00000000000..0406ff9989d
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/duration.gjs
@@ -0,0 +1,9 @@
+import DRelativeTimePicker from "discourse/ui-kit/d-relative-time-picker";
+
+<template>
+ <DRelativeTimePicker
+ @durationHours={{@field.value}}
+ @durationOutputUnit="hours"
+ @onChange={{@field.set}}
+ />
+</template>
diff --git a/frontend/discourse/app/components/setting-field/enum.gjs b/frontend/discourse/app/components/setting-field/enum.gjs
new file mode 100644
index 00000000000..54f4de25648
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/enum.gjs
@@ -0,0 +1,11 @@
+import { or } from "discourse/truth-helpers";
+
+<template>
+ <@field.Control as |select|>
+ {{#each (or @definition.valid_values @definition.choices) as |choice|}}
+ <select.Option @value={{choice.value}}>
+ {{choice.name}}
+ </select.Option>
+ {{/each}}
+ </@field.Control>
+</template>
diff --git a/frontend/discourse/app/components/setting-field/group-list.gjs b/frontend/discourse/app/components/setting-field/group-list.gjs
new file mode 100644
index 00000000000..16a5ade4360
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/group-list.gjs
@@ -0,0 +1,37 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { service } from "@ember/service";
+import { bind } from "discourse/lib/decorators";
+import { splitString } from "discourse/lib/utilities";
+import GroupChooser from "discourse/select-kit/components/group-chooser";
+
+export default class SettingFieldGroupList extends Component {
+ @service site;
+
+ get groupContent() {
+ return this.site.groups;
+ }
+
+ toGroupIdArray(value) {
+ if (Array.isArray(value)) {
+ return value.map(Number);
+ }
+ return splitString(value, "|").map(Number);
+ }
+
+ @bind
+ setGroupIdString(field, ids) {
+ field.set((ids ?? []).join("|"));
+ }
+
+ <template>
+ <@field.Control>
+ <GroupChooser
+ @content={{this.groupContent}}
+ @value={{this.toGroupIdArray @field.value}}
+ @labelProperty="name"
+ @onChange={{fn this.setGroupIdString @field}}
+ />
+ </@field.Control>
+ </template>
+}
diff --git a/frontend/discourse/app/components/setting-field/integer.gjs b/frontend/discourse/app/components/setting-field/integer.gjs
new file mode 100644
index 00000000000..07c91b4698e
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/integer.gjs
@@ -0,0 +1,3 @@
+<template>
+ <@field.Control min={{@definition.min}} max={{@definition.max}} />
+</template>
diff --git a/frontend/discourse/app/components/setting-field/string.gjs b/frontend/discourse/app/components/setting-field/string.gjs
new file mode 100644
index 00000000000..240459b04be
--- /dev/null
+++ b/frontend/discourse/app/components/setting-field/string.gjs
@@ -0,0 +1 @@
+<template><@field.Control /></template>
diff --git a/frontend/discourse/app/lib/setting-field-registry.js b/frontend/discourse/app/lib/setting-field-registry.js
new file mode 100644
index 00000000000..181df4b8489
--- /dev/null
+++ b/frontend/discourse/app/lib/setting-field-registry.js
@@ -0,0 +1,103 @@
+import BoolControl from "discourse/components/setting-field/bool";
+import CategoryListControl from "discourse/components/setting-field/category-list";
+import CompactListControl from "discourse/components/setting-field/compact-list";
+import DurationControl from "discourse/components/setting-field/duration";
+import EnumControl from "discourse/components/setting-field/enum";
+import GroupListControl from "discourse/components/setting-field/group-list";
+import IntegerControl from "discourse/components/setting-field/integer";
+import StringControl from "discourse/components/setting-field/string";
+
+const REGISTRY = {};
+
+export function registerSettingFieldType(type, entry) {
+ REGISTRY[type] = entry;
+}
+
+export function resolveSettingFieldType(definition) {
+ return REGISTRY[typeKeyFor(definition)] ?? REGISTRY.default;
+}
+
+export function settingFieldValidation(definition) {
+ const rules = [];
+
+ if (definition.required) {
+ rules.push("required");
+ }
+
+ if (definition.type === "integer") {
+ rules.push("number");
+ }
+
+ return rules.length > 0 ? rules.join("|") : undefined;
+}
+
+function typeKeyFor({ type, subtype, list_type }) {
+ if (subtype && REGISTRY[subtype]) {
+ return subtype;
+ }
+
+ let resolved = type;
+ if (type === "list" && list_type) {
+ resolved = `${list_type}_list`;
+ }
+
+ if (resolved && REGISTRY[resolved]) {
+ return resolved;
+ }
+
+ return "default";
+}
+
+registerSettingFieldType("bool", {
+ type: "checkbox",
+ format: "full",
+ includeDescription: false,
+ renderer: BoolControl,
+});
+
+registerSettingFieldType("integer", {
+ type: "input-number",
+ format: "full",
+ renderer: IntegerControl,
+});
+
+registerSettingFieldType("enum", {
+ type: "select",
+ format: "large",
+ labelFormat: "full",
+ renderer: EnumControl,
+});
+
+registerSettingFieldType("group_list", {
+ type: "custom",
+ format: "large",
+ labelFormat: "full",
+ renderer: GroupListControl,
+});
+
+registerSettingFieldType("category_list", {
+ type: "custom",
+ format: "large",
+ labelFormat: "full",
+ renderer: CategoryListControl,
+});
+
+registerSettingFieldType("compact_list", {
+ type: "custom",
+ format: "large",
+ labelFormat: "full",
+ renderer: CompactListControl,
+});
+
+registerSettingFieldType("duration", {
+ type: "custom",
+ format: "full",
+ renderer: DurationControl,
+});
+
+registerSettingFieldType("default", {
+ type: "input",
+ format: "large",
+ labelFormat: "full",
+ renderer: StringControl,
+});
diff --git a/frontend/discourse/tests/integration/components/setting-definition-field-test.gjs b/frontend/discourse/tests/integration/components/setting-definition-field-test.gjs
new file mode 100644
index 00000000000..1e80d563907
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/setting-definition-field-test.gjs
@@ -0,0 +1,239 @@
+import { array, hash } from "@ember/helper";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import Form from "discourse/components/form";
+import SettingDefinitionField from "discourse/components/setting-definition-field";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+
+module("Integration | Component | SettingDefinitionField", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("string falls back to a text input bound to the form", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_setting="hello"}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_setting"
+ type="string"
+ label="My setting"
+ description="A description"
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom("[data-name='my_setting'] input").exists();
+ assert
+ .dom("[data-name='my_setting'] .form-kit__container-title")
+ .containsText("My setting");
+ assert.dom("[data-name='my_setting'] input").hasValue("hello");
+ });
+
+ test("an unsupported type also falls back to a text input", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_setting="x"}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_setting"
+ type="not_a_real_type"
+ label="My setting"
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom("[data-name='my_setting'] input").exists();
+ assert.dom("[data-name='my_setting'] input").hasValue("x");
+ });
+
+ test("integer renders a number input with min/max", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_int="5"}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_int"
+ type="integer"
+ label="My int"
+ min=1
+ max=10
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom("[data-name='my_int'] input").hasAttribute("type", "number");
+ assert.dom("[data-name='my_int'] input").hasAttribute("min", "1");
+ assert.dom("[data-name='my_int'] input").hasAttribute("max", "10");
+ assert.dom("[data-name='my_int'] input").hasValue("5");
+ });
+
+ test("bool renders a checkbox with the description as its label and no title", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_bool=true}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_bool"
+ type="bool"
+ label="My bool"
+ description="Enable the thing"
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom("[data-name='my_bool'] input[type='checkbox']").exists();
+ assert.dom("[data-name='my_bool']").containsText("Enable the thing");
+ assert
+ .dom("[data-name='my_bool'] .form-kit__container-title")
+ .doesNotExist();
+ });
+
+ test("enum renders a select with the provided choices", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_enum="a"}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_enum"
+ type="enum"
+ label="My enum"
+ choices=(array
+ (hash value="a" name="Apple") (hash value="b" name="Banana")
+ )
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom("[data-name='my_enum'] select option[value='a']").exists();
+ assert.dom("[data-name='my_enum'] select option[value='b']").exists();
+ assert.form().field("my_enum").hasValue("a");
+ });
+
+ test("duration is matched by subtype and renders a relative time picker", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_duration=2}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_duration"
+ type="integer"
+ subtype="duration"
+ label="My duration"
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert
+ .dom("[data-name='my_duration'] input.relative-time-duration")
+ .exists();
+ });
+
+ test("group_list deserializes a pipe string and serializes the selection back", async function (assert) {
+ this.site.groups = [
+ { id: 1, name: "Donuts" },
+ { id: 2, name: "Cheese cake" },
+ ];
+
+ await render(
+ <template>
+ <Form @data={{hash my_groups="1"}} as |form data|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_groups"
+ type="group_list"
+ label="My groups"
+ }}
+ @form={{form}}
+ />
+ <span class="value-probe">{{data.my_groups}}</span>
+ </Form>
+ </template>
+ );
+
+ const groups = selectKit("[data-name='my_groups'] .group-chooser");
+ assert.strictEqual(
+ groups.header().value(),
+ "1",
+ "deserializes the pipe string into the selected group"
+ );
+
+ await groups.expand();
+ await groups.selectRowByValue(2);
+
+ assert
+ .dom(".value-probe")
+ .hasText("1|2", "serializes the selection back to a pipe string");
+ });
+
+ test("enum prefers valid_values over a raw string choices array (site setting shape)", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_enum="a"}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_enum"
+ type="enum"
+ label="My enum"
+ choices=(array "a" "b")
+ valid_values=(array
+ (hash value="a" name="Apple") (hash value="b" name="Banana")
+ )
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert
+ .dom("[data-name='my_enum'] select option[value='a']")
+ .hasText("Apple");
+ assert
+ .dom("[data-name='my_enum'] select option[value='b']")
+ .hasText("Banana");
+ assert.form().field("my_enum").hasValue("a");
+ });
+
+ test("list + list_type collapses to the compact_list control", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash my_list="a"}} as |form|>
+ <SettingDefinitionField
+ @definition={{hash
+ key="my_list"
+ type="list"
+ list_type="compact"
+ label="My list"
+ valid_values=(array
+ (hash value="a" name="Alpha") (hash value="b" name="Beta")
+ )
+ }}
+ @form={{form}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom("[data-name='my_list'] .list-setting").exists();
+ assert.dom("[data-name='my_list']").containsText("Alpha");
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/setting-field-registry-test.js b/frontend/discourse/tests/unit/lib/setting-field-registry-test.js
new file mode 100644
index 00000000000..1331c648195
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/setting-field-registry-test.js
@@ -0,0 +1,104 @@
+import { module, test } from "qunit";
+import CategoryListControl from "discourse/components/setting-field/category-list";
+import CompactListControl from "discourse/components/setting-field/compact-list";
+import DurationControl from "discourse/components/setting-field/duration";
+import GroupListControl from "discourse/components/setting-field/group-list";
+import StringControl from "discourse/components/setting-field/string";
+import {
+ resolveSettingFieldType,
+ settingFieldValidation,
+} from "discourse/lib/setting-field-registry";
+
+module("Unit | Lib | setting-field-registry", function () {
+ module("resolveSettingFieldType", function () {
+ test("resolves built-in types to their control", function (assert) {
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "bool" }).type,
+ "checkbox"
+ );
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "integer" }).type,
+ "input-number"
+ );
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "enum" }).type,
+ "select"
+ );
+ });
+
+ test("falls back to the string control for unknown/missing types", function (assert) {
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "not_a_real_type" }).renderer,
+ StringControl
+ );
+ assert.strictEqual(resolveSettingFieldType({}).renderer, StringControl);
+ });
+
+ test("matches a registered subtype before the base type", function (assert) {
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "integer", subtype: "duration" })
+ .renderer,
+ DurationControl,
+ "subtype wins over type"
+ );
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "integer", subtype: "nope" }).type,
+ "input-number",
+ "an unregistered subtype falls through to the type"
+ );
+ });
+
+ test("collapses list + list_type into the matching list control", function (assert) {
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "list", list_type: "group" }).renderer,
+ GroupListControl
+ );
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "list", list_type: "category" })
+ .renderer,
+ CategoryListControl
+ );
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "list", list_type: "compact" })
+ .renderer,
+ CompactListControl
+ );
+ });
+
+ test("resolves a first-class list type without a list_type discriminator", function (assert) {
+ assert.strictEqual(
+ resolveSettingFieldType({ type: "category_list" }).renderer,
+ CategoryListControl
+ );
+ });
+ });
+
+ module("settingFieldValidation", function () {
+ test("integer validates as a number", function (assert) {
+ assert.strictEqual(settingFieldValidation({ type: "integer" }), "number");
+ assert.strictEqual(
+ settingFieldValidation({ type: "integer", min: 0, max: 100 }),
+ "number",
+ "range is enforced by native min/max + the server, not a FormKit between rule"
+ );
+ });
+
+ test("non-integer without constraints has no validation", function (assert) {
+ assert.strictEqual(settingFieldValidation({ type: "string" }), undefined);
+ });
+
+ test("required is prepended", function (assert) {
+ assert.strictEqual(
+ settingFieldValidation({ type: "string", required: true }),
+ "required"
+ );
+ assert.strictEqual(
+ settingFieldValidation({
+ type: "integer",
+ required: true,
+ }),
+ "required|number"
+ );
+ });
+ });
+});
diff --git a/frontend/discourse/tests/unit/models/site-setting-test.js b/frontend/discourse/tests/unit/models/site-setting-test.js
new file mode 100644
index 00000000000..13855e86b81
--- /dev/null
+++ b/frontend/discourse/tests/unit/models/site-setting-test.js
@@ -0,0 +1,33 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import SiteSetting from "discourse/admin/models/site-setting";
+
+module("Unit | Model | site-setting", function (hooks) {
+ setupTest(hooks);
+
+ test("definition projects the setting onto the field definition contract", function (assert) {
+ const setting = SiteSetting.create({
+ setting: "title",
+ humanized_name: "Title",
+ description: "The name of the site",
+ type: "string",
+ list_type: null,
+ min: 1,
+ max: 100,
+ choices: ["a", "b"],
+ valid_values: ["a", "b"],
+ });
+
+ assert.deepEqual(setting.definition, {
+ key: "title",
+ label: "Title",
+ description: "The name of the site",
+ type: "string",
+ list_type: null,
+ min: 1,
+ max: 100,
+ choices: ["a", "b"],
+ valid_values: ["a", "b"],
+ });
+ });
+});
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-features/edit.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-features/edit.js
index 4d5f8762e6b..e0b7c5594ff 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-features/edit.js
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-ai-features/edit.js
@@ -21,33 +21,6 @@ export default class AdminPluginsShowDiscourseAiFeaturesEditController extends C
return this.settings.find((s) => s.setting === settingName);
}
- /**
- * Generates a FormKit validation string for a site setting.
- *
- * @param {Object} setting - The site setting object
- * @param {string} setting.type - The setting type (e.g., "integer", "bool", "string")
- * @param {number} [setting.min] - Minimum value for integer settings
- * @param {number} [setting.max] - Maximum value for integer settings
- * @returns {string|undefined} Validation string in FormKit format (e.g., "number|between:0,100")
- * or undefined if no validation is needed
- */
- @action
- getValidationFor(setting) {
- const validation = [];
-
- if (setting.type === "integer") {
- validation.push("number");
-
- if (setting.min !== undefined || setting.max !== undefined) {
- const min = setting.min ?? "";
- const max = setting.max ?? "";
- validation.push(`between:${min},${max}`);
- }
- }
-
- return validation.length > 0 ? validation.join("|") : undefined;
- }
-
@action
async save(data) {
if (this.formApi) {
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-features/edit.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-features/edit.gjs
index 5ebf894c21b..c12dcdb5fba 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-features/edit.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-features/edit.gjs
@@ -2,9 +2,8 @@ import { concat } from "@ember/helper";
import AdminConfigAreaCard from "discourse/admin/components/admin-config-area-card";
import BackButton from "discourse/components/back-button";
import Form from "discourse/components/form";
-import { eq, or } from "discourse/truth-helpers";
+import SettingDefinitionField from "discourse/components/setting-definition-field";
import { i18n } from "discourse-i18n";
-import AiFeatureSettingField from "discourse/plugins/discourse-ai/discourse/components/ai-feature-setting-field";
export default <template>
<BackButton
@@ -35,45 +34,10 @@ export default <template>
as |setting|
}}
{{#if setting}}
- <form.Field
- @name={{setting.setting}}
- @title={{setting.humanized_name}}
- @description={{if
- (eq setting.type "bool")
- null
- setting.description
- }}
- @format="large"
- @validation={{@controller.getValidationFor setting}}
- @type={{if
- (eq setting.type "bool")
- "checkbox"
- (if
- (eq setting.type "integer")
- "input-number"
- (if
- (eq setting.type "enum")
- "select"
- (if
- (or
- (eq setting.type "category_list")
- (eq setting.type "group_list")
- (eq setting.type "list")
- )
- "custom"
- "input"
- )
- )
- )
- }}
- as |field|
- >
- <AiFeatureSettingField
- @Control={{field.Control}}
- @setting={{setting}}
- @field={{field}}
- />
- </form.Field>
+ <SettingDefinitionField
+ @definition={{setting.definition}}
+ @form={{form}}
+ />
{{/if}}
{{/let}}
{{/each}}
@@ -81,44 +45,10 @@ export default <template>
{{/each}}
{{else}}
{{#each @model.feature_settings as |setting|}}
- <form.Field
- @name={{setting.setting}}
- @title={{setting.humanized_name}}
- @description={{if
- (eq setting.type "bool")
- null
- setting.description
- }}
- @format="large"
- @type={{if
- (eq setting.type "bool")
- "checkbox"
- (if
- (eq setting.type "integer")
- "input-number"
- (if
- (eq setting.type "enum")
- "select"
- (if
- (or
- (eq setting.type "category_list")
- (eq setting.type "group_list")
- (eq setting.type "list")
- )
- "custom"
- "input"
- )
- )
- )
- }}
- as |field|
- >
- <AiFeatureSettingField
- @Control={{field.Control}}
- @setting={{setting}}
- @field={{field}}
- />
- </form.Field>
+ <SettingDefinitionField
+ @definition={{setting.definition}}
+ @form={{form}}
+ />
{{/each}}
{{/if}}
<form.Actions>
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-feature-setting-field.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-feature-setting-field.gjs
deleted file mode 100644
index 590e140863d..00000000000
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-feature-setting-field.gjs
+++ /dev/null
@@ -1,135 +0,0 @@
-import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
-import { action } from "@ember/object";
-import didUpdate from "@ember/render-modifiers/modifiers/did-update";
-import { service } from "@ember/service";
-import Category from "discourse/models/category";
-import CategorySelector from "discourse/select-kit/components/category-selector";
-import ListSetting from "discourse/select-kit/components/list-setting";
-import { eq } from "discourse/truth-helpers";
-
-export default class AiFeatureSettingField extends Component {
- @service site;
-
- @tracked selectedCategories = [];
-
- parseList = (value) => {
- return value?.toString().split("|").filter(Boolean) || [];
- };
-
- serializeList = (callback) => {
- return (values) => {
- callback(Array.isArray(values) ? values.join("|") : values);
- };
- };
-
- constructor() {
- super(...arguments);
- if (this.controlType === "category_list") {
- this.#loadCategories();
- }
- }
-
- get groupChoices() {
- return (this.site.groups || []).map((g) => ({
- name: g.name,
- id: g.id.toString(),
- }));
- }
-
- async #loadCategories() {
- const ids = this.#categoryIds;
- if (ids.length) {
- this.selectedCategories = await Category.asyncFindByIds(ids);
- }
- }
-
- get #categoryIds() {
- return (this.args.field?.value || "").toString().split("|").filter(Boolean);
- }
-
- @action
- categoryValueChanged() {
- this.#loadCategories();
- }
-
- @action
- onChangeCategories(categories) {
- const value = (categories || []).map((c) => c.id).join("|");
- this.args.field.set(value);
- }
-
- get hasEnumChoices() {
- return this.args.setting.valid_values?.length > 0;
- }
-
- get compactListChoices() {
- if (this.hasEnumChoices) {
- return this.args.setting.valid_values.map((v) => ({
- name: v.name,
- value: String(v.value),
- }));
- }
- return this.args.setting.choices;
- }
-
- get controlType() {
- const { type, list_type } = this.args.setting;
-
- if (type === "list" && list_type) {
- return `${list_type}_list`;
- }
- return type;
- }
-
- <template>
- {{#if (eq this.controlType "bool")}}
- <@Control>
- {{@setting.description}}
- </@Control>
- {{else if (eq this.controlType "integer")}}
- <@Control />
- {{else if (eq this.controlType "enum")}}
- <@Control as |select|>
- {{#each @setting.valid_values as |option|}}
- <select.Option @value={{option.value}}>
- {{option.name}}
- </select.Option>
- {{/each}}
- </@Control>
- {{else if (eq this.controlType "category_list")}}
- <@Control>
- <div {{didUpdate this.categoryValueChanged @field.value}}>
- <CategorySelector
- @categories={{this.selectedCategories}}
- @onChange={{this.onChangeCategories}}
- />
- </div>
- </@Control>
- {{else if (eq this.controlType "group_list")}}
- <@Control>
- <ListSetting
- @value={{this.parseList @field.value}}
- @choices={{this.groupChoices}}
- @settingName={{@setting.setting}}
- @nameProperty="name"
- @valueProperty="id"
- @onChange={{this.serializeList @field.set}}
- />
- </@Control>
- {{else if (eq this.controlType "compact_list")}}
- <@Control>
- <ListSetting
- @value={{this.parseList @field.value}}
- @choices={{this.compactListChoices}}
- @settingName={{@setting.setting}}
- @nameProperty={{if this.hasEnumChoices "name"}}
- @valueProperty={{if this.hasEnumChoices "value"}}
- @onChange={{this.serializeList @field.set}}
- />
- </@Control>
- {{else}}
- <@Control />
- {{/if}}
- </template>
-}
diff --git a/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb
index 402f57709a8..280ad931eb9 100644
--- a/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb
+++ b/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb
@@ -74,7 +74,7 @@ RSpec.describe "Admin AI features configuration" do
expect(page).to have_css(".ai-feature-editor")
field = form.field("ai_bot_allowed_groups")
- expect(field.component).to have_css(".list-setting")
+ expect(field.component).to have_css(".group-chooser")
expect(field.component).to have_content(group_1.name)
expect(field.component).to have_content(group_2.name)
end
diff --git a/plugins/discourse-ai/test/javascripts/unit/controllers/admin-plugins-show-discourse-ai-features-edit-test.js b/plugins/discourse-ai/test/javascripts/unit/controllers/admin-plugins-show-discourse-ai-features-edit-test.js
index 7938bdec3df..7079624d039 100644
--- a/plugins/discourse-ai/test/javascripts/unit/controllers/admin-plugins-show-discourse-ai-features-edit-test.js
+++ b/plugins/discourse-ai/test/javascripts/unit/controllers/admin-plugins-show-discourse-ai-features-edit-test.js
@@ -6,100 +6,6 @@ module(
function (hooks) {
setupTest(hooks);
- test("getValidationFor returns correct validation for integer with min/max", function (assert) {
- const controller = this.owner.lookup(
- "controller:admin-plugins/show/discourse-ai-features/edit"
- );
-
- const setting = {
- type: "integer",
- min: 0,
- max: 100,
- };
-
- const validation = controller.getValidationFor(setting);
-
- assert.strictEqual(
- validation,
- "number|between:0,100",
- "should return number with between validator"
- );
- });
-
- test("getValidationFor returns correct validation for integer with only min", function (assert) {
- const controller = this.owner.lookup(
- "controller:admin-plugins/show/discourse-ai-features/edit"
- );
-
- const setting = {
- type: "integer",
- min: 5,
- };
-
- const validation = controller.getValidationFor(setting);
-
- assert.strictEqual(
- validation,
- "number|between:5,",
- "should return number with between validator (min only)"
- );
- });
-
- test("getValidationFor returns correct validation for integer with only max", function (assert) {
- const controller = this.owner.lookup(
- "controller:admin-plugins/show/discourse-ai-features/edit"
- );
-
- const setting = {
- type: "integer",
- max: 50,
- };
-
- const validation = controller.getValidationFor(setting);
-
- assert.strictEqual(
- validation,
- "number|between:,50",
- "should return number with between validator (max only)"
- );
- });
-
- test("getValidationFor returns number for integer without constraints", function (assert) {
- const controller = this.owner.lookup(
- "controller:admin-plugins/show/discourse-ai-features/edit"
- );
-
- const setting = {
- type: "integer",
- };
-
- const validation = controller.getValidationFor(setting);
-
- assert.strictEqual(
- validation,
- "number",
- "should return just number validator"
- );
- });
-
- test("getValidationFor returns undefined for non-integer types", function (assert) {
- const controller = this.owner.lookup(
- "controller:admin-plugins/show/discourse-ai-features/edit"
- );
-
- const setting = {
- type: "string",
- };
-
- const validation = controller.getValidationFor(setting);
-
- assert.strictEqual(
- validation,
- undefined,
- "should return undefined for non-integer types"
- );
- });
-
test("valuesEqual compares using toString", function (assert) {
const controller = this.owner.lookup(
"controller:admin-plugins/show/discourse-ai-features/edit"