Skip to content

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

FIX: Allow clearing optional values in objects settings (#44114)

Régis Hanol9f98d51bbbd6
diff --git a/docs/developer-guides/docs/05-themes-components/10-objects-for-theme-settings.md b/docs/developer-guides/docs/05-themes-components/10-objects-for-theme-settings.md
index 1ad21573aa9..558e2a1fe05 100644
--- a/docs/developer-guides/docs/05-themes-components/10-objects-for-theme-settings.md
+++ b/docs/developer-guides/docs/05-themes-components/10-objects-for-theme-settings.md
@@ -108,7 +108,7 @@ links:
#### Required properties
-All properties defined are optional by default. To mark a property as required, simply annotate the property with `required: true. A property can also be marked as optional by annotating the property with `required: false`.
+All properties defined are optional by default. To mark a property as required, simply annotate the property with `required: true`. A property can also be marked as optional by annotating the property with `required: false`.
```yaml
links:
@@ -125,6 +125,8 @@ links:
required: false
```
+Blank `string`, `datetime` and `icon` values and empty `categories`, `groups` and `tags` lists count as missing: required properties reject them and optional properties skip their validations. `false` counts as set.
+
#### Custom Validations
For certain property types, there are built in support for custom validations which can be declared by annotating the property with the `validations` keyword.
@@ -140,8 +142,8 @@ links:
type: string
required: true
validations:
- min: 1
- max: 2048
+ min_length: 1
+ max_length: 2048
url: true
```
diff --git a/frontend/discourse/admin/components/schema-setting/editor.gjs b/frontend/discourse/admin/components/schema-setting/editor.gjs
index cfd4631a8e3..917c28b331f 100644
--- a/frontend/discourse/admin/components/schema-setting/editor.gjs
+++ b/frontend/discourse/admin/components/schema-setting/editor.gjs
@@ -10,7 +10,7 @@ import { popupAjaxError } from "discourse/lib/ajax-error";
import { cloneJSON } from "discourse/lib/object";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import Category from "discourse/models/category";
-import { gt, not } from "discourse/truth-helpers";
+import { not } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import { i18n } from "discourse-i18n";
@@ -61,26 +61,19 @@ export default class SchemaSettingNewEditor extends Component {
}
get fields() {
- const list = [];
-
if (!this.activeObject) {
- return list;
+ return [];
}
- for (const [name, spec] of Object.entries(this.activeSchema.properties)) {
- if (spec.type === "objects") {
- continue;
- }
-
- list.push({
+ return Object.entries(this.activeSchema.properties)
+ .filter(([, spec]) => spec.type !== "objects")
+ .map(([name, spec]) => ({
name,
spec,
- description: this.fieldDescription(name, spec),
- label: this.fieldLabel(name, spec),
- });
- }
-
- return list;
+ description:
+ this.#propertyMetadata(name, "description") || spec.description,
+ label: this.#propertyMetadata(name, "label") || spec.label || name,
+ }));
}
get canMoveUp() {
@@ -111,81 +104,40 @@ export default class SchemaSettingNewEditor extends Component {
@action
generateSchemaTitle(object, schema, index) {
- let title;
+ let title = object[schema.identifier];
if (schema.properties[schema.identifier]?.type === "categories") {
- title = object[schema.identifier]
- ?.map((categoryId) => {
- return (
+ title = title
+ ?.map(
+ (categoryId) =>
this.args.setting.metadata?.categories?.[categoryId]?.name ||
Category.findById(categoryId)?.name
- );
- })
+ )
.filter(Boolean)
.join(", ");
- } else {
- title = object[schema.identifier];
}
return title || `${schema.name} ${index + 1}`;
}
- descriptions(fieldName, key) {
- // The `property_descriptions` metadata is an object with keys in the following format as an example:
- //
- // {
- // some_property.description: <some description>,
- // some_property.label: <some label>,
- // some_objects_property.some_other_property.description: <some description>,
- // some_objects_property.some_other_property.label: <some label>,
- // }
- const descriptions = this.args.setting.metadata?.property_descriptions;
-
- if (!descriptions) {
- return;
- }
-
- if (this.activeSchemaPaths.length > 0) {
- key = `${this.activeSchemaPaths.join(".")}.${fieldName}.${key}`;
- } else {
- key = `${fieldName}.${key}`;
- }
-
- return descriptions[key];
- }
-
- fieldLabel(fieldName, spec) {
- return this.descriptions(fieldName, "label") || spec?.label || fieldName;
- }
-
- fieldDescription(fieldName, spec) {
- return this.descriptions(fieldName, "description") || spec?.description;
- }
-
@action
clickBack() {
- const {
- dataPaths: lastDataPaths,
- schemaPaths: lastSchemaPaths,
- index: lastIndex,
- } = this.history.pop();
-
- this.activeDataPaths = lastDataPaths;
- this.activeSchemaPaths = lastSchemaPaths;
- this.activeIndex = lastIndex;
+ const { dataPaths, schemaPaths, index } = this.history.pop();
+
+ this.activeDataPaths = dataPaths;
+ this.activeSchemaPaths = schemaPaths;
+ this.activeIndex = index;
}
@action
addChildItem(propertyName, parentNodeIndex) {
- this.activeData[parentNodeIndex][propertyName].push(
+ const children = this.activeData[parentNodeIndex][propertyName];
+
+ children.push(
this.#prepareObject({}, this.activeSchema.properties[propertyName].schema)
);
- this.onChildClick(
- this.activeData[parentNodeIndex][propertyName].length - 1,
- propertyName,
- parentNodeIndex
- );
+ this.onChildClick(children.length - 1, propertyName, parentNodeIndex);
}
@action
@@ -196,25 +148,26 @@ export default class SchemaSettingNewEditor extends Component {
@action
async removeItem() {
- let confirm = true;
-
- if (this.args.schema.deleteWarning) {
- confirm = await this._confirmRemove(this.args.schema.deleteWarning);
- }
-
- if (!confirm) {
+ const warning = this.args.schema.deleteWarning;
+ const confirmed =
+ !warning ||
+ (await this.dialog.deleteConfirm({
+ title: warning.title,
+ message: warning.message,
+ }));
+
+ if (!confirmed) {
return;
}
this.activeData.splice(this.activeIndex, 1);
- if (this.activeData.length > 0) {
- this.activeIndex = Math.max(this.activeIndex - 1, 0);
- } else if (this.history.length > 0) {
+ if (this.activeData.length === 0 && this.history.length > 0) {
this.clickBack();
- } else {
- this.activeIndex = 0;
+ return;
}
+
+ this.activeIndex = Math.max(this.activeIndex - 1, 0);
}
@action
@@ -225,16 +178,14 @@ export default class SchemaSettingNewEditor extends Component {
@action
moveUp() {
if (this.canMoveUp) {
- this.#swapAdjacentItems(this.activeIndex, this.activeIndex - 1);
- this.activeIndex = this.activeIndex - 1;
+ this.#moveActiveItem(-1);
}
}
@action
moveDown() {
if (this.canMoveDown) {
- this.#swapAdjacentItems(this.activeIndex, this.activeIndex + 1);
- this.activeIndex = this.activeIndex + 1;
+ this.#moveActiveItem(1);
}
}
@@ -250,8 +201,10 @@ export default class SchemaSettingNewEditor extends Component {
this.router.transitionTo(this.args.routeToRedirect, this.args.id);
})
.catch((e) => {
- if (e.jqXHR.responseJSON && e.jqXHR.responseJSON.errors) {
- this.validationErrorMessage = e.jqXHR.responseJSON.errors[0];
+ const errors = e.jqXHR?.responseJSON?.errors;
+
+ if (errors) {
+ this.validationErrorMessage = errors[0];
} else {
popupAjaxError(e);
}
@@ -260,38 +213,20 @@ export default class SchemaSettingNewEditor extends Component {
}
#resolveDataFromPaths(paths) {
- if (paths.length === 0) {
- return this.data;
- }
-
- let data = this.data;
-
- paths.forEach((path) => {
- data = data[path];
- });
-
- return data;
+ return paths.reduce((data, path) => data[path], this.data);
}
#resolveSchemaFromPaths(paths) {
- if (paths.length === 0) {
- return this.schema;
- }
-
- let schema = this.schema;
-
- paths.forEach((path) => {
- schema = schema.properties[path].schema;
- });
-
- return schema;
+ return paths.reduce(
+ (schema, path) => schema.properties[path].schema,
+ this.schema
+ );
}
- #swapAdjacentItems(fromIndex, toIndex) {
- const item = this.activeData[fromIndex];
-
- this.activeData.splice(fromIndex, 1);
- this.activeData.splice(toIndex, 0, item);
+ #moveActiveItem(offset) {
+ const [item] = this.activeData.splice(this.activeIndex, 1);
+ this.activeData.splice(this.activeIndex + offset, 0, item);
+ this.activeIndex += offset;
}
#prepareObject(object, schema) {
@@ -302,6 +237,10 @@ export default class SchemaSettingNewEditor extends Component {
this.#prepareObject(child, spec.schema)
)
);
+ } else if (spec.required && spec.type === "boolean") {
+ object[name] ??= false;
+ } else if (spec.required && spec.type === "enum") {
+ object[name] ??= spec.default;
} else if (Array.isArray(object[name])) {
object[name] = trackedArray(object[name]);
}
@@ -310,15 +249,10 @@ export default class SchemaSettingNewEditor extends Component {
return trackedObject(object);
}
- async _confirmRemove(warning) {
- return new Promise((resolve) => {
- this.dialog.deleteConfirm({
- title: warning?.title,
- message: warning?.message,
- didCancel: () => resolve(false),
- didConfirm: () => resolve(true),
- });
- });
+ #propertyMetadata(fieldName, key) {
+ return this.args.setting.metadata?.property_descriptions?.[
+ [...this.activeSchemaPaths, fieldName, key].join(".")
+ ];
}
<template>
@@ -385,7 +319,7 @@ export default class SchemaSettingNewEditor extends Component {
@icon="chevron-down"
/>
- {{#if (gt this.fields.length 0)}}
+ {{#if this.fields.length}}
<DButton
class="btn-danger schema-setting-editor__remove-btn"
@action={{this.removeItem}}
diff --git a/frontend/discourse/admin/components/schema-setting/number-field.gjs b/frontend/discourse/admin/components/schema-setting/number-field.gjs
index a6f64fc8ffb..6af00a19f6f 100644
--- a/frontend/discourse/admin/components/schema-setting/number-field.gjs
+++ b/frontend/discourse/admin/components/schema-setting/number-field.gjs
@@ -44,6 +44,11 @@ export default class SchemaSettingNumberField extends Component {
@action
onInput(event) {
this.touched = true;
+
+ if (event.currentTarget.validity.badInput) {
+ return;
+ }
+
let inputValue = event.currentTarget.value;
if (isNaN(inputValue)) {
diff --git a/frontend/discourse/admin/components/schema-setting/types/enum.gjs b/frontend/discourse/admin/components/schema-setting/types/enum.gjs
index 5031ec86408..04f441f9ddd 100644
--- a/frontend/discourse/admin/components/schema-setting/types/enum.gjs
+++ b/frontend/discourse/admin/components/schema-setting/types/enum.gjs
@@ -1,34 +1,23 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
-import { action } from "@ember/object";
+import { hash } from "@ember/helper";
import FieldInputDescription from "discourse/admin/components/schema-setting/field-input-description";
import ComboBox from "discourse/select-kit/components/combo-box";
+import { not } from "discourse/truth-helpers";
export default class SchemaSettingTypeEnum extends Component {
- @tracked
- value =
- this.args.value || (this.args.spec.required && this.args.spec.default);
-
get content() {
- return this.args.spec.choices.map((choice) => {
- return {
- name: choice,
- id: choice,
- };
- });
- }
-
- @action
- onInput(newVal) {
- this.value = newVal;
- this.args.onChange(newVal);
+ return this.args.spec.choices.map((choice) => ({
+ name: choice,
+ id: choice,
+ }));
}
<template>
<ComboBox
@content={{this.content}}
- @onChange={{this.onInput}}
- @value={{this.value}}
+ @onChange={{@onChange}}
+ @options={{hash clearable=(not @spec.required)}}
+ @value={{@value}}
/>
<FieldInputDescription @description={{@description}} />
</template>
diff --git a/frontend/discourse/tests/fixtures/theme-setting-schema-data.js b/frontend/discourse/tests/fixtures/theme-setting-schema-data.js
index 781a1376c66..74f7c8549b3 100644
--- a/frontend/discourse/tests/fixtures/theme-setting-schema-data.js
+++ b/frontend/discourse/tests/fixtures/theme-setting-schema-data.js
@@ -1,12 +1,10 @@
-import SiteSetting from "discourse/admin/models/site-setting";
import ThemeSettings from "discourse/admin/models/theme-settings";
-export const SCHEMA_MODES = {
- THEME: "theme",
- SITE_SETTING: "SITE_SETTING",
-};
+export function objectsSetting(attrs) {
+ return ThemeSettings.create({ setting: "objects_setting", ...attrs });
+}
-export default function schemaAndData(version = 1, mode = SCHEMA_MODES.THEME) {
+export default function schemaAndData(version = 1) {
let schema, data;
if (version === 1) {
@@ -173,40 +171,17 @@ export default function schemaAndData(version = 1, mode = SCHEMA_MODES.THEME) {
} else if (version === 3) {
schema = {
name: "something",
- identifier: "name",
properties: {
- name: {
- type: "string",
- },
- integer_field: {
- type: "integer",
- },
- float_field: {
- type: "float",
- },
boolean_field: {
type: "boolean",
},
- category_field: {
- type: "categories",
- },
- group_field: {
- type: "groups",
- },
- tags_field: {
- type: "tags",
- }
},
};
data = [
{
- name: "lamb",
- integer_field: 92,
boolean_field: true,
},
{
- name: "cow",
- integer_field: 820,
boolean_field: false,
},
];
@@ -237,17 +212,5 @@ export default function schemaAndData(version = 1, mode = SCHEMA_MODES.THEME) {
throw new Error("unknown fixture version");
}
- if (mode === SCHEMA_MODES.SITE_SETTING) {
- return SiteSetting.create({
- schema,
- value: data,
- setting: "objects_setting"
- })
- }
-
- return ThemeSettings.create({
- objects_schema: schema,
- value: data,
- setting: "objects_setting"
- });
+ return objectsSetting({ objects_schema: schema, value: data });
}
diff --git a/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs b/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs
index d58cc9011a6..184b11205ee 100644
--- a/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs
+++ b/frontend/discourse/tests/integration/components/admin-schema-setting/editor-test.gjs
@@ -7,192 +7,128 @@ import {
waitFor,
} from "@ember/test-helpers";
import { module, test } from "qunit";
+import sinon from "sinon";
import AdminSchemaSettingEditor from "discourse/admin/components/schema-setting/editor";
-import SiteSetting from "discourse/admin/models/site-setting";
-import ThemeSettings from "discourse/admin/models/theme-settings";
import DialogHolder from "discourse/dialog-holder/components/dialog-holder";
import schemaAndData, {
- SCHEMA_MODES,
+ objectsSetting,
} from "discourse/tests/fixtures/theme-setting-schema-data";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import pretender, {
+ parsePostData,
+ response,
+} from "discourse/tests/helpers/create-pretender";
import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
-class TreeFromDOM {
- constructor() {
- this.refresh();
- }
-
- refresh() {
- this.nodes = findAll(
+const tree = {
+ get nodes() {
+ return findAll(
".schema-setting-editor__tree .schema-setting-editor__tree-node.--parent"
- ).map((container, index) => {
- const li = container;
- const active = li.classList.contains("--active");
-
- const children = findAll(
+ ).map((element, index) => ({
+ element,
+ active: element.classList.contains("--active"),
+ textElement: element.querySelector(
+ ".schema-setting-editor__tree-node-text"
+ ),
+ children: findAll(
`.schema-setting-editor__tree-node.--child[data-test-parent-index="${index}"]`
- ).map((child) => {
- return {
- element: child,
- textElement: child.querySelector(
- ".schema-setting-editor__tree-node-text"
- ),
- };
- });
-
- const addButtons = findAll(
+ ).map((child) => ({
+ element: child,
+ textElement: child.querySelector(
+ ".schema-setting-editor__tree-node-text"
+ ),
+ })),
+ addButtons: findAll(
`.schema-setting-editor__tree-add-button.--child[data-test-parent-index="${index}"]`
- );
+ ),
+ }));
+ },
+};
+
+const inputFields = {
+ get count() {
+ return findAll(".schema-field").length;
+ },
+
+ get fields() {
+ return Object.fromEntries(
+ findAll(".schema-field").map((field) => [
+ field.dataset.name,
+ {
+ labelElement: field.querySelector(".schema-field__label"),
+ inputElement: field.querySelector(".schema-field__input").children[0],
+ countElement: field.querySelector(".schema-field__input-count"),
+ errorElement: field.querySelector(".schema-field__input-error"),
+ descriptionElement: field.querySelector(
+ ".schema-field__input-description"
+ ),
+ selector: `.schema-field[data-name="${field.dataset.name}"]`,
+ },
+ ])
+ );
+ },
+};
- return {
- active,
- children,
- addButtons,
- element: li,
- textElement: li.querySelector(".schema-setting-editor__tree-node-text"),
- };
- });
- }
+const TOP_LEVEL_ADD_BTN = ".schema-setting-editor__tree-add-button.--root";
+const REMOVE_ITEM_BTN = ".schema-setting-editor__remove-btn";
+const MOVE_UP_BTN = ".schema-setting-editor__move-up-btn";
+const MOVE_DOWN_BTN = ".schema-setting-editor__move-down-btn";
+const SAVE_BTN = ".schema-setting-editor__footer .btn-primary";
+
+function renderEditor(setting) {
+ return render(
+ <template>
+ <DialogHolder />
+ <AdminSchemaSettingEditor
+ @id="1"
+ @routeToRedirect="adminCustomizeThemes.show"
+ @schema={{setting.objects_schema}}
+ @setting={{setting}}
+ />
+ </template>
+ );
}
-class InputFieldsFromDOM {
- constructor() {
- this.refresh();
- }
+async function captureSavedValue(owner) {
+ sinon.stub(owner.lookup("service:router"), "transitionTo");
- refresh() {
- this.fields = {};
- this.count = 0;
+ let savedValue;
+ pretender.put("/admin/themes/1/setting", (request) => {
+ savedValue = JSON.parse(parsePostData(request.requestBody).value);
+ return response({});
+ });
- findAll(".schema-field").forEach((field) => {
- this.count += 1;
+ await click(SAVE_BTN);
- this.fields[field.dataset.name] = {
- labelElement: field.querySelector(".schema-field__label"),
- inputElement: field.querySelector(".schema-field__input").children[0],
- countElement: field.querySelector(".schema-field__input-count"),
- errorElement: field.querySelector(".schema-field__input-error"),
- descriptionElement: field.querySelector(
- ".schema-field__input-description"
- ),
- selector: `.schema-field[data-name="${field.dataset.name}"]`,
- };
- });
- }
+ return savedValue;
}
-const TOP_LEVEL_ADD_BTN = ".schema-setting-editor__tree-add-button.--root";
-const REMOVE_ITEM_BTN = ".schema-setting-editor__remove-btn";
-const MOVE_UP_BTN = ".schema-setting-editor__move-up-btn";
-const MOVE_DOWN_BTN = ".schema-setting-editor__move-down-btn";
-
module(
"Integration | Admin | Themes | Component | SchemaSetting | Editor",
function (hooks) {
setupRenderingTest(hooks);
- test("activates the first node by default", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- assert.strictEqual(tree.nodes.length, 3);
- assert.true(tree.nodes[0].active, "the first node is active");
- assert.false(tree.nodes[1].active, "other nodes are not active");
- });
-
- test("renders the 2nd level of nested items for the active item only", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- assert.true(tree.nodes[0].active);
-
- assert.strictEqual(
- tree.nodes[0].children.length,
- 2,
- "the children of the active node are shown"
- );
-
- assert.false(tree.nodes[1].active);
- assert.strictEqual(
- tree.nodes[1].children.length,
- 0,
- "the children of an active node aren't shown"
- );
-
- await click(tree.nodes[1].element);
-
- tree.refresh();
-
- assert.false(tree.nodes[0].active);
- assert.strictEqual(
- tree.nodes[0].children.length,
- 0,
- "the children of an active node aren't shown"
- );
-
- assert.true(tree.nodes[1].active);
- assert.strictEqual(
- tree.nodes[1].children.length,
- 3,
- "the children of the active node are shown"
- );
- });
-
test("allows navigating through multiple levels of nesting", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
+ await renderEditor(schemaAndData(1));
assert.strictEqual(tree.nodes.length, 3);
+ assert.true(tree.nodes[0].active, "the first node is active by default");
assert.dom(tree.nodes[0].textElement).hasText("item 1");
assert.strictEqual(tree.nodes[0].children.length, 2);
assert.dom(tree.nodes[0].children[0].textElement).hasText("child 1-1");
assert.dom(tree.nodes[0].children[1].textElement).hasText("child 1-2");
+ assert.false(tree.nodes[1].active);
assert.dom(tree.nodes[1].textElement).hasText("item 2");
- assert.strictEqual(tree.nodes[1].children.length, 0);
+ assert.strictEqual(
+ tree.nodes[1].children.length,
+ 0,
+ "only the active node's children are shown"
+ );
await click(tree.nodes[1].element);
- tree.refresh();
-
assert.strictEqual(tree.nodes.length, 3);
assert.dom(tree.nodes[0].textElement).hasText("item 1");
assert.false(tree.nodes[0].active);
@@ -207,10 +143,8 @@ module(
await click(tree.nodes[1].children[1].element);
- tree.refresh();
assert.strictEqual(tree.nodes.length, 4);
- const inputFields = new InputFieldsFromDOM();
assert.dom(inputFields.fields.name.labelElement).hasText("Level 2 Label");
assert
.dom(inputFields.fields.name.descriptionElement)
@@ -246,8 +180,6 @@ module(
await click(tree.nodes[1].children[1].element);
- tree.refresh();
-
assert.strictEqual(tree.nodes.length, 5);
assert.dom(tree.nodes[0].textElement).hasText("grandchild 2-2-1");
@@ -267,129 +199,54 @@ module(
assert.strictEqual(tree.nodes[3].children.length, 0);
});
- test("the back button is only shown when the navigation is at least one level deep", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- assert.dom(".--back-btn").doesNotExist();
-
- const tree = new TreeFromDOM();
- await click(tree.nodes[0].children[0].element);
-
- assert.dom(".--back-btn").exists();
- tree.refresh();
- assert.dom(tree.nodes[0].textElement).hasText("child 1-1");
-
- await click(tree.nodes[0].children[0].element);
-
- tree.refresh();
- assert.dom(tree.nodes[0].textElement).hasText("grandchild 1-1-1");
- assert.dom(".--back-btn").exists();
-
- await click(".--back-btn");
-
- tree.refresh();
- assert.dom(tree.nodes[0].textElement).hasText("child 1-1");
- assert.dom(".--back-btn").exists();
-
- await click(".--back-btn");
-
- tree.refresh();
- assert.dom(tree.nodes[0].textElement).hasText("item 1");
- assert.dom(".--back-btn").doesNotExist();
- });
+ test("the back button navigates to the previous level", async function (assert) {
+ await renderEditor(schemaAndData(1));
- test("the back button navigates to the index of the active element at the previous level", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
+ assert.dom(".--back-btn").doesNotExist("hidden at the root level");
- const tree = new TreeFromDOM();
await click(tree.nodes[1].element);
-
- tree.refresh();
await click(tree.nodes[1].children[1].element);
- await click(".--back-btn");
- tree.refresh();
-
- assert.strictEqual(tree.nodes.length, 3);
-
- assert.dom(tree.nodes[0].textElement).hasText("item 1");
- assert.false(tree.nodes[0].active);
- assert.strictEqual(tree.nodes[0].children.length, 0);
-
- assert.dom(tree.nodes[1].textElement).hasText("item 2");
- assert.true(tree.nodes[1].active);
- assert.strictEqual(tree.nodes[1].children.length, 3);
- });
-
- test("the back button label includes the name of the item at the previous level", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
- await click(tree.nodes[1].element);
+ assert
+ .dom(".--back-btn")
+ .hasText(
+ i18n("admin.customize.schema.back_button", { name: "item 2" })
+ );
- tree.refresh();
- await click(tree.nodes[1].children[1].element);
+ await click(tree.nodes[1].children[0].element);
- assert.dom(".--back-btn").hasText(
- i18n("admin.customize.schema.back_button", {
- name: "item 2",
- })
- );
+ assert
+ .dom(".--back-btn")
+ .hasText(
+ i18n("admin.customize.schema.back_button", { name: "child 2-2" })
+ );
- tree.refresh();
- await click(tree.nodes[1].children[0].element);
+ await click(".--back-btn");
- assert.dom(".--back-btn").hasText(
- i18n("admin.customize.schema.back_button", {
- name: "child 2-2",
- })
+ assert.dom(tree.nodes[1].textElement).hasText("child 2-2");
+ assert.true(
+ tree.nodes[1].active,
+ "the previously active child is restored"
);
+ assert
+ .dom(".--back-btn")
+ .hasText(
+ i18n("admin.customize.schema.back_button", { name: "item 2" })
+ );
+ await click(tree.nodes[0].element);
await click(".--back-btn");
- assert.dom(".--back-btn").hasText(
- i18n("admin.customize.schema.back_button", {
- name: "item 2",
- })
+ assert.dom(tree.nodes[1].textElement).hasText("item 2");
+ assert.true(
+ tree.nodes[1].active,
+ "the previously active item is restored"
);
+ assert.dom(".--back-btn").doesNotExist("hidden again at the root level");
});
test("input fields are rendered even if they're not present in the data", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
identifier: "id",
@@ -413,26 +270,13 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
assert.strictEqual(inputFields.count, 2);
assert.dom(inputFields.fields.id.inputElement).hasValue("bu1");
assert.dom(inputFields.fields.name.inputElement).hasValue("Big U");
- const tree = new TreeFromDOM();
await click(tree.nodes[1].element);
- inputFields.refresh();
assert.strictEqual(inputFields.count, 2);
assert.dom(inputFields.fields.id.inputElement).hasValue("fi2");
@@ -440,20 +284,7 @@ module(
});
test("input fields for items at different levels", async function (assert) {
- const setting = schemaAndData(2);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(schemaAndData(2));
assert.strictEqual(inputFields.count, 2);
assert.dom(inputFields.fields.name.labelElement).hasText("name");
@@ -462,23 +293,13 @@ module(
assert.dom(inputFields.fields.name.inputElement).hasValue("nice section");
assert.dom(inputFields.fields.icon.inputElement).hasValue("arrow");
- const tree = new TreeFromDOM();
await click(tree.nodes[1].element);
- inputFields.refresh();
- tree.refresh();
-
assert.strictEqual(inputFields.count, 2);
- assert.dom(inputFields.fields.name.labelElement).hasText("name");
- assert.dom(inputFields.fields.icon.labelElement).hasText("icon");
-
assert.dom(inputFields.fields.name.inputElement).hasValue("cool section");
assert.dom(inputFields.fields.icon.inputElement).hasValue("bell");
- await click(tree.nodes[1].children[0].element);
-
- tree.refresh();
- inputFields.refresh();
+ await click(tree.nodes[1].children[1].element);
assert.strictEqual(inputFields.count, 3);
assert.dom(inputFields.fields.text.labelElement).hasText("text");
@@ -494,8 +315,7 @@ module(
});
test("input fields of type string", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
identifier: "id",
@@ -517,18 +337,7 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
assert.dom(inputFields.fields.id.labelElement).hasText("id*");
assert.dom(inputFields.fields.id.countElement).hasText("3/5");
@@ -537,8 +346,6 @@ module(
assert.dom(inputFields.fields.id.countElement).hasText("1/5");
- inputFields.refresh();
-
assert.dom(inputFields.fields.id.errorElement).hasText(
i18n("admin.customize.schema.fields.string.too_short", {
count: 2,
@@ -555,8 +362,7 @@ module(
});
test("input fields of type integer", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
identifier: "id",
@@ -578,20 +384,8 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
- assert.dom(inputFields.fields.id.labelElement).hasText("id*");
assert.dom(inputFields.fields.id.inputElement).hasValue("6");
assert
@@ -600,8 +394,6 @@ module(
await fillIn(inputFields.fields.id.inputElement, "922229");
- inputFields.refresh();
-
assert.dom(inputFields.fields.id.errorElement).hasText(
i18n("admin.customize.schema.fields.number.too_large", {
count: 10,
@@ -610,8 +402,6 @@ module(
await fillIn(inputFields.fields.id.inputElement, "0");
- inputFields.refresh();
-
assert.dom(inputFields.fields.id.errorElement).hasText(
i18n("admin.customize.schema.fields.number.too_small", {
count: 5,
@@ -620,16 +410,13 @@ module(
await fillIn(inputFields.fields.id.inputElement, "");
- inputFields.refresh();
-
assert
.dom(inputFields.fields.id.errorElement)
.hasText(i18n("admin.customize.schema.fields.required"));
});
test("input fields of type float", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
identifier: "id",
@@ -651,95 +438,75 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
- assert.dom(inputFields.fields.id.labelElement).hasText("id*");
assert.dom(inputFields.fields.id.inputElement).hasValue("6.5");
- assert
- .dom(inputFields.fields.id.inputElement)
- .hasAttribute("type", "number");
-
- await fillIn(inputFields.fields.id.inputElement, "100.0");
-
- inputFields.refresh();
-
- assert.dom(inputFields.fields.id.errorElement).hasText(
- i18n("admin.customize.schema.fields.number.too_large", {
- count: 10.5,
- })
- );
-
await fillIn(inputFields.fields.id.inputElement, "0.2");
- inputFields.refresh();
-
assert.dom(inputFields.fields.id.errorElement).hasText(
i18n("admin.customize.schema.fields.number.too_small", {
count: 5.5,
- })
+ }),
+ "fractional input is parsed as a float"
);
-
- await fillIn(inputFields.fields.id.inputElement, "");
-
- inputFields.refresh();
-
- assert
- .dom(inputFields.fields.id.errorElement)
- .hasText(i18n("admin.customize.schema.fields.required"));
});
test("input fields of type boolean", async function (assert) {
- const setting = schemaAndData(3);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
+ await renderEditor(schemaAndData(3));
- const inputFields = new InputFieldsFromDOM();
- assert
- .dom(inputFields.fields.boolean_field.labelElement)
- .hasText("boolean_field");
assert.dom(inputFields.fields.boolean_field.inputElement).isChecked();
- await click(inputFields.fields.boolean_field.inputElement);
- const tree = new TreeFromDOM();
+ await click(inputFields.fields.boolean_field.inputElement);
await click(tree.nodes[1].element);
- inputFields.refresh();
- assert
- .dom(inputFields.fields.boolean_field.labelElement)
- .hasText("boolean_field");
assert.dom(inputFields.fields.boolean_field.inputElement).isNotChecked();
- tree.refresh();
await click(tree.nodes[0].element);
- inputFields.refresh();
assert.dom(inputFields.fields.boolean_field.inputElement).isNotChecked();
});
+ test("stores the defaults of required boolean and enum fields", async function (assert) {
+ await renderEditor(
+ objectsSetting({
+ objects_schema: {
+ name: "something",
+ properties: {
+ required_boolean_field: { type: "boolean", required: true },
+ optional_boolean_field: { type: "boolean" },
+ optional_enum_field: {
+ type: "enum",
+ default: "cool",
+ choices: ["nice", "cool", "awesome"],
+ },
+ required_enum_field: {
+ type: "enum",
+ required: true,
+ default: "awesome",
+ choices: ["nice", "cool", "awesome"],
+ },
+ },
+ },
+ value: [{}, { required_boolean_field: true }],
+ })
+ );
+
+ await click(TOP_LEVEL_ADD_BTN);
+
+ assert.deepEqual(
+ await captureSavedValue(this.owner),
+ [
+ { required_boolean_field: false, required_enum_field: "awesome" },
+ { required_boolean_field: true, required_enum_field: "awesome" },
+ { required_boolean_field: false, required_enum_field: "awesome" },
+ ],
+ "existing and new items store required defaults, keep stored values and leave optional fields unset"
+ );
+ });
+
test("input fields of type enum", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
properties: {
@@ -766,18 +533,7 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
const enumSelector = selectKit(
`${inputFields.fields.enum_field.selector} .select-kit`
@@ -785,23 +541,36 @@ module(
assert.strictEqual(enumSelector.header().value(), null);
+ await enumSelector.expand();
+ await enumSelector.selectRowByValue("cool");
+ await click(enumSelector.clearButton());
+
+ assert.strictEqual(
+ enumSelector.header().value(),
+ null,
+ "optional enums can be cleared"
+ );
+
const requiredEnumSelector = selectKit(
`${inputFields.fields.required_enum_field.selector} .select-kit`
);
assert.strictEqual(requiredEnumSelector.header().value(), "awesome");
+ assert.strictEqual(requiredEnumSelector.header().label(), "awesome");
await requiredEnumSelector.expand();
await requiredEnumSelector.selectRowByValue("nice");
assert.strictEqual(requiredEnumSelector.header().value(), "nice");
+ assert.strictEqual(
+ requiredEnumSelector.clearButton(),
+ null,
+ "required enums can't be cleared"
+ );
- const tree = new TreeFromDOM();
await click(tree.nodes[1].element);
assert.strictEqual(requiredEnumSelector.header().value(), "cool");
- tree.refresh();
-
await click(tree.nodes[0].element);
assert.strictEqual(requiredEnumSelector.header().value(), "nice");
@@ -812,7 +581,7 @@ module(
test("input fields of type icon", async function (assert) {
pretender.get("/svg-sprite/picker-search", () =>
- response(200, {
+ response({
icons: [
{ id: "gamepad", name: "gamepad" },
{ id: "heart", name: "heart" },
@@ -821,8 +590,7 @@ module(
})
);
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
properties: {
@@ -838,18 +606,7 @@ module(
value: [{ required_icon_field: "heart" }],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
assert
.dom(
@@ -870,11 +627,16 @@ module(
assert
.dom(`${inputFields.fields.icon_field.selector} .d-icon-grid-picker`)
.hasAttribute("data-value", "gamepad");
+
+ assert.deepEqual(
+ await captureSavedValue(this.owner),
+ [{ required_icon_field: "heart", icon_field: "gamepad" }],
+ "the picked icon is stored"
+ );
});
test("input fields of type categories that is not required with min and max validations", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
properties: {
@@ -898,22 +660,7 @@ module(
value: [{}],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
-
- assert
- .dom(inputFields.fields.not_required_category.labelElement)
- .hasText("not_required_category");
+ await renderEditor(setting);
const categorySelector = selectKit(
`${inputFields.fields.not_required_category.selector} .select-kit`
@@ -925,8 +672,6 @@ module(
await categorySelector.selectRowByIndex(1);
await categorySelector.collapse();
- inputFields.refresh();
-
assert.dom(inputFields.fields.not_required_category.errorElement).hasText(
i18n("admin.customize.schema.fields.categories.at_least", {
count: 2,
@@ -947,16 +692,13 @@ module(
await categorySelector.deselectItemByIndex(0);
await categorySelector.collapse();
- inputFields.refresh();
-
assert
.dom(inputFields.fields.not_required_category.errorElement)
.doesNotExist();
});
test("input fields of type categories", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
identifier: "id",
@@ -982,22 +724,7 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
-
- assert
- .dom(inputFields.fields.required_category.labelElement)
- .hasText("required_category*");
+ await renderEditor(setting);
let categorySelector = selectKit(
`${inputFields.fields.required_category.selector} .select-kit`
@@ -1009,8 +736,6 @@ module(
await categorySelector.deselectItemByValue("6");
await categorySelector.collapse();
- inputFields.refresh();
-
assert.dom(inputFields.fields.required_category.errorElement).hasText(
i18n("admin.customize.schema.fields.categories.at_least", {
count: 1,
@@ -1019,8 +744,7 @@ module(
});
test("input field of type categories with schema's identifier set to categories field", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "category",
identifier: "category",
@@ -1059,18 +783,7 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
+ await renderEditor(setting);
assert.dom(tree.nodes[0].textElement).hasText("support, something");
@@ -1085,9 +798,6 @@ module(
"the back button uses the parent's category identifier"
);
await click(".--back-btn");
- tree.refresh();
-
- const inputFields = new InputFieldsFromDOM();
const categorySelector = selectKit(
`${inputFields.fields.category.selector} .select-kit`
@@ -1101,14 +811,11 @@ module(
await click(TOP_LEVEL_ADD_BTN);
- tree.refresh();
-
assert.dom(tree.nodes[1].textElement).hasText("category 2");
});
test("input fields of type tags which is required", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
identifier: "id",
@@ -1135,18 +842,7 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
let tagSelector = selectKit(
`${inputFields.fields.required_tags_with_validations.selector} .select-kit`
@@ -1168,8 +864,6 @@ module(
assert.strictEqual(tagSelector.header().value(), null);
- inputFields.refresh();
-
assert
.dom(inputFields.fields.required_tags_with_validations.errorElement)
.hasText(
@@ -1183,8 +877,6 @@ module(
assert.strictEqual(tagSelector.header().name(), "gazelle");
- inputFields.refresh();
-
assert
.dom(inputFields.fields.required_tags_with_validations.errorElement)
.hasText(
@@ -1201,8 +893,6 @@ module(
await tagSelector.deselectItemByName("gazelle");
await tagSelector.collapse();
- inputFields.refresh();
-
assert.dom(inputFields.fields.required_tags.errorElement).hasText(
i18n("admin.customize.schema.fields.tags.at_least", {
count: 1,
@@ -1211,8 +901,7 @@ module(
});
test("input fields of type groups", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
properties: {
@@ -1236,18 +925,7 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(setting);
let groupsSelector = selectKit(
`${inputFields.fields.required_groups.selector} .select-kit`
@@ -1260,18 +938,12 @@ module(
await groupsSelector.deselectItemByValue("1");
await groupsSelector.collapse();
- inputFields.refresh();
-
assert.dom(inputFields.fields.required_groups.errorElement).hasText(
i18n("admin.customize.schema.fields.groups.at_least", {
count: 1,
})
);
- assert
- .dom(inputFields.fields.groups_with_validations.labelElement)
- .hasText("groups_with_validations");
-
groupsSelector = selectKit(
`${inputFields.fields.groups_with_validations.selector} .select-kit`
);
@@ -1284,8 +956,6 @@ module(
assert.strictEqual(groupsSelector.header().value(), "1");
- inputFields.refresh();
-
assert
.dom(inputFields.fields.groups_with_validations.errorElement)
.hasText(
@@ -1311,8 +981,7 @@ module(
{ id: 2, name: "moderators" },
];
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
properties: {
@@ -1329,18 +998,8 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
+ await renderEditor(setting);
- const inputFields = new InputFieldsFromDOM();
const groupsSelector = selectKit(
`${inputFields.fields.group_ids.selector} .select-kit`
);
@@ -1362,8 +1021,7 @@ module(
});
test("generic identifier is used when identifier is not specified in the schema", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "section",
properties: {
@@ -1406,18 +1064,7 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
+ await renderEditor(setting);
assert.dom(tree.nodes[0].textElement).hasText("section 1");
assert.dom(tree.nodes[0].children[0].textElement).hasText("link 1");
@@ -1426,13 +1073,11 @@ module(
await click(tree.nodes[1].element);
- tree.refresh();
-
assert.dom(tree.nodes[1].children[0].textElement).hasText("link 1");
await click(tree.nodes[0].element);
await click(REMOVE_ITEM_BTN);
- tree.refresh();
+
assert
.dom(tree.nodes[0].textElement)
.hasText("section 1", "the remaining item is renumbered");
@@ -1441,19 +1086,7 @@ module(
test("identifier field instantly updates in the navigation tree when the input field is changed", async function (assert) {
const setting = schemaAndData(2);
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
- const tree = new TreeFromDOM();
+ await renderEditor(setting);
await focus(inputFields.fields.name.inputElement);
await fillIn(
@@ -1476,9 +1109,6 @@ module(
await click(tree.nodes[0].children[0].element);
- inputFields.refresh();
- tree.refresh();
-
await fillIn(
inputFields.fields.text.inputElement,
"Security instead of Privacy"
@@ -1490,21 +1120,7 @@ module(
});
test("edits are remembered when navigating between levels", async function (assert) {
- const setting = schemaAndData(2);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
- const tree = new TreeFromDOM();
+ await renderEditor(schemaAndData(2));
await fillIn(
inputFields.fields.name.inputElement,
@@ -1513,9 +1129,6 @@ module(
await click(tree.nodes[1].element);
- tree.refresh();
- inputFields.refresh();
-
await fillIn(
inputFields.fields.name.inputElement,
"cool section is no longer cool"
@@ -1523,9 +1136,6 @@ module(
await click(tree.nodes[1].children[1].element);
- tree.refresh();
- inputFields.refresh();
-
assert.dom(".--back-btn").hasText(
i18n("admin.customize.schema.back_button", {
name: "cool section is no longer cool",
@@ -1535,9 +1145,6 @@ module(
await fillIn(inputFields.fields.text.inputElement, "Talk to us");
await click(".--back-btn");
- tree.refresh();
- inputFields.refresh();
-
assert.dom(tree.nodes[0].textElement).hasText("changed section name");
assert
@@ -1553,15 +1160,11 @@ module(
await click(tree.nodes[1].children[1].element);
- tree.refresh();
- inputFields.refresh();
-
assert.dom(inputFields.fields.text.inputElement).hasValue("Talk to us");
});
test("adding an object to the root list of objects which is empty by default", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
properties: {
@@ -1573,75 +1176,19 @@ module(
value: [],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
+ await renderEditor(setting);
assert.dom(TOP_LEVEL_ADD_BTN).hasText("something");
- await click(TOP_LEVEL_ADD_BTN);
- const tree = new TreeFromDOM();
+ await click(TOP_LEVEL_ADD_BTN);
assert.dom(tree.nodes[0].textElement).hasText("something 1");
- const inputFields = new InputFieldsFromDOM();
-
assert.dom(inputFields.fields.name.labelElement).hasText("name");
});
- test("adding a parent and multiple nested objects", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- assert.dom(TOP_LEVEL_ADD_BTN).hasText("level1");
-
- const tree = new TreeFromDOM();
-
- assert.strictEqual(tree.nodes.length, 3);
-
- await click(TOP_LEVEL_ADD_BTN);
- tree.refresh();
-
- assert.strictEqual(tree.nodes.length, 4);
- assert.true(tree.nodes[2].active);
- assert.dom(tree.nodes[2].textElement).hasText("level1 3");
- assert.dom(TOP_LEVEL_ADD_BTN).hasText("level1");
-
- await click(tree.nodes[2].addButtons[0]);
- await click(TOP_LEVEL_ADD_BTN);
- tree.refresh();
-
- assert.strictEqual(
- tree.nodes.length,
- 3,
- "both children and the add button are visible"
- );
- assert
- .dom(tree.nodes[1].textElement)
- .hasText("level2 2", "the second child appears without reopening");
- assert.true(tree.nodes[1].active, "the second child is selected");
- });
-
test("adding an object to a child list of objects when an object has multiple objects properties", async function (assert) {
- const setting = ThemeSettings.create({
- setting: "objects_setting",
+ const setting = objectsSetting({
objects_schema: {
name: "something",
properties: {
@@ -1679,129 +1226,39 @@ module(
],
});
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
+ await renderEditor(setting);
await click(tree.nodes[0].addButtons[0]);
- tree.refresh();
-
assert.dom(tree.nodes[0].textElement).hasText("link 1");
- const inputFields = new InputFieldsFromDOM();
-
assert.dom(inputFields.fields.url.labelElement).hasText("url");
});
- test("adding an object to a child list of objects", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
+ test("adding objects to nested lists of objects", async function (assert) {
+ await renderEditor(schemaAndData(1));
- assert.strictEqual(tree.nodes[0].children.length, 2);
assert.dom(tree.nodes[0].addButtons[0]).hasText("level2");
await click(tree.nodes[0].addButtons[0]);
- tree.refresh();
-
- assert.dom(tree.nodes[2].textElement).hasText("level2 3");
-
- const inputFields = new InputFieldsFromDOM();
-
- assert.dom(inputFields.fields.name.labelElement).hasText("Level 2 Label");
-
- await click(TOP_LEVEL_ADD_BTN);
- tree.refresh();
-
- assert.dom(tree.nodes[3].textElement).hasText("level2 4");
- });
-
- test("navigating 1 level deep and adding an object to the child list of objects that's displayed as the root list", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- await click(tree.nodes[0].children[0].element);
- tree.refresh();
assert.dom(TOP_LEVEL_ADD_BTN).hasText("level2");
- assert.strictEqual(tree.nodes.length, 3);
-
- await click(TOP_LEVEL_ADD_BTN);
- await click(TOP_LEVEL_ADD_BTN);
-
- tree.refresh();
- assert.strictEqual(tree.nodes.length, 5);
assert.dom(tree.nodes[2].textElement).hasText("level2 3");
- assert.dom(tree.nodes[3].textElement).hasText("level2 4");
- });
-
- test("adding multiple grandchildren to a newly added child", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- await click(tree.nodes[0].addButtons[0]);
- tree.refresh();
-
+ assert.dom(inputFields.fields.name.labelElement).hasText("Level 2 Label");
assert.dom(tree.nodes[2].addButtons[0]).hasText("level3");
assert.strictEqual(tree.nodes[2].children.length, 0);
await click(tree.nodes[2].addButtons[0]);
await click(TOP_LEVEL_ADD_BTN);
- tree.refresh();
-
assert.strictEqual(
tree.nodes.length,
3,
"both grandchildren and the add button are visible"
);
- const inputFields = new InputFieldsFromDOM();
+
await fillIn(inputFields.fields.name.inputElement, "Second grandchild");
+
assert
.dom(tree.nodes[1].textElement)
.hasText(
@@ -1811,41 +1268,24 @@ module(
});
test("removing an object from the root list of objects", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(schemaAndData(1));
assert.strictEqual(tree.nodes.length, 3);
assert.dom(tree.nodes[0].textElement).hasText("item 1");
assert.dom(tree.nodes[1].textElement).hasText("item 2");
assert.dom(inputFields.fields.name.inputElement).hasValue("item 1");
+ await click(tree.nodes[1].element);
await click(REMOVE_ITEM_BTN);
- tree.refresh();
- inputFields.refresh();
-
assert.strictEqual(tree.nodes.length, 2);
- assert.dom(tree.nodes[0].textElement).hasText("item 2");
- assert.dom(inputFields.fields.name.inputElement).hasValue("item 2");
+ assert.dom(tree.nodes[0].textElement).hasText("item 1");
+ assert
+ .dom(inputFields.fields.name.inputElement)
+ .hasValue("item 1", "the previous item becomes active");
await click(REMOVE_ITEM_BTN);
- tree.refresh();
- inputFields.refresh();
-
assert.strictEqual(tree.nodes.length, 1);
assert.strictEqual(inputFields.count, 0);
assert.dom(REMOVE_ITEM_BTN).doesNotExist();
@@ -1853,63 +1293,27 @@ module(
});
test("removing an object with delete warning from the root list of objects", async function (assert) {
- const setting = schemaAndData(4);
-
- await render(
- <template>
- <DialogHolder />
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
- const inputFields = new InputFieldsFromDOM();
+ await renderEditor(schemaAndData(4));
+ await click(REMOVE_ITEM_BTN);
+ await click(".dialog-footer .btn-default");
- assert.strictEqual(tree.nodes.length, 3);
- assert.dom(tree.nodes[0].textElement).hasText("item 1");
- assert.dom(tree.nodes[1].textElement).hasText("item 2");
+ assert.strictEqual(tree.nodes.length, 3, "cancelling keeps the item");
await click(REMOVE_ITEM_BTN);
assert.dom("#dialog-title").hasText("Delete warning title");
assert.dom(".dialog-body").includesText("Delete warning message");
- assert.dom(".dialog-footer .btn-danger").hasText(i18n("delete"));
- assert.dom(".dialog-footer .btn-default").hasText(i18n("cancel_value"));
await click(".dialog-footer .btn-danger");
- tree.refresh();
- inputFields.refresh();
-
assert.strictEqual(tree.nodes.length, 2);
assert.dom(tree.nodes[0].textElement).hasText("item 2");
});
test("navigating 1 level deep and removing an object from the child list of objects", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- await click(tree.nodes[0].children[1].element);
- tree.refresh();
+ await renderEditor(schemaAndData(1));
- const inputFields = new InputFieldsFromDOM();
+ await click(tree.nodes[0].children[0].element);
assert.strictEqual(tree.nodes.length, 3);
assert.dom(tree.nodes[0].textElement).hasText("child 1-1");
@@ -1918,792 +1322,75 @@ module(
await click(REMOVE_ITEM_BTN);
- tree.refresh();
- inputFields.refresh();
-
assert.strictEqual(tree.nodes.length, 2);
assert.dom(tree.nodes[0].textElement).hasText("child 1-2");
assert.dom(inputFields.fields.name.inputElement).hasValue("child 1-2");
- // removing the last object navigates back to the previous level
await click(REMOVE_ITEM_BTN);
- tree.refresh();
- inputFields.refresh();
-
assert.strictEqual(tree.nodes.length, 3);
assert.strictEqual(tree.nodes[0].children.length, 0);
assert.dom(tree.nodes[0].textElement).hasText("item 1");
assert.dom(tree.nodes[1].textElement).hasText("item 2");
assert.dom(inputFields.fields.name.inputElement).hasValue("item 1");
- assert.dom(".--back-btn").doesNotExist();
+ assert
+ .dom(".--back-btn")
+ .doesNotExist(
+ "removing the last child navigates back to the parent level"
+ );
});
- test("move buttons reorder root level items correctly", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
+ test("move buttons reorder items", async function (assert) {
+ await renderEditor(schemaAndData(1));
- // Verify initial order
- assert.dom(tree.nodes[0].textElement).hasText("item 1");
- assert.dom(tree.nodes[1].textElement).hasText("item 2");
+ assert.dom(MOVE_UP_BTN).isDisabled("the first item can't move up");
+ assert.dom(MOVE_DOWN_BTN).isNotDisabled();
- // Test move up: Select second item and move up
await click(tree.nodes[1].element);
- tree.refresh();
+
+ assert.dom(MOVE_UP_BTN).isNotDisabled();
+ assert.dom(MOVE_DOWN_BTN).isDisabled("the last item can't move down");
+
await click(MOVE_UP_BTN);
- tree.refresh();
assert.dom(tree.nodes[0].textElement).hasText("item 2");
assert.dom(tree.nodes[1].textElement).hasText("item 1");
- // Test move down: Select first item (was originally second) and move down
- await click(tree.nodes[0].element);
- tree.refresh();
await click(MOVE_DOWN_BTN);
- tree.refresh();
- // Should be back to original order
assert.dom(tree.nodes[0].textElement).hasText("item 1");
assert.dom(tree.nodes[1].textElement).hasText("item 2");
- });
-
- test("move buttons are disabled appropriately for root level items", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- // First item should have move up disabled
- await click(tree.nodes[0].element);
- tree.refresh();
-
- assert.dom(MOVE_UP_BTN).isDisabled();
- assert.dom(MOVE_DOWN_BTN).isNotDisabled();
-
- // Last item should have move down disabled
- await click(tree.nodes[1].element);
- tree.refresh();
-
- assert.dom(MOVE_UP_BTN).isNotDisabled();
- assert.dom(MOVE_DOWN_BTN).isDisabled();
- });
-
- test("move up button reorders nested items correctly", async function (assert) {
- const setting = schemaAndData(1);
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminCustomizeThemes.show"
- @schema={{setting.objects_schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- // Navigate to nested level
- await click(tree.nodes[0].children[1].element);
- tree.refresh();
-
- // Verify initial order of nested items
- assert.dom(tree.nodes[0].textElement).hasText("child 1-1");
- assert.dom(tree.nodes[1].textElement).hasText("child 1-2");
-
- // Select second nested item
- await click(tree.nodes[1].element);
- tree.refresh();
- // Click move up button
+ await click(tree.nodes[1].children[1].element);
await click(MOVE_UP_BTN);
- tree.refresh();
-
- // Verify nested items are reordered
- assert.dom(tree.nodes[0].textElement).hasText("child 1-2");
- assert.dom(tree.nodes[1].textElement).hasText("child 1-1");
- });
- }
-);
-
-module(
- "Integration | Admin | Plugins | Component | SchemaSetting | Editor",
- function (hooks) {
- setupRenderingTest(hooks);
-
- test("input fields of type string", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- name: {
- type: "string",
- },
- },
- },
- value: [
- {
- name: "some name",
- },
- ],
- });
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const inputFields = new InputFieldsFromDOM();
- const tree = new TreeFromDOM();
- assert.dom(inputFields.fields.name.labelElement).hasText("name");
- assert.dom(inputFields.fields.name.inputElement).hasValue("some name");
- assert.dom(tree.nodes[0].textElement).hasText("something 1");
- });
- test("input fields of type integer", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- id: {
- type: "integer",
- required: true,
- validations: {
- max: 5,
- min: 2,
- },
- },
- },
- },
- value: [
- {
- id: 3,
- },
- ],
- });
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const inputFields = new InputFieldsFromDOM();
- assert.dom(inputFields.fields.id.labelElement).hasText("id*");
- assert.dom(inputFields.fields.id.inputElement).hasValue("3");
assert
- .dom(inputFields.fields.id.inputElement)
- .hasAttribute("type", "number");
- await fillIn(inputFields.fields.id.inputElement, "100");
- inputFields.refresh();
- assert.dom(inputFields.fields.id.errorElement).hasText(
- i18n("admin.customize.schema.fields.number.too_large", {
- count: 5,
- })
- );
- await fillIn(inputFields.fields.id.inputElement, "0");
- inputFields.refresh();
- assert.dom(inputFields.fields.id.errorElement).hasText(
- i18n("admin.customize.schema.fields.number.too_small", {
- count: 2,
- })
- );
+ .dom(tree.nodes[0].textElement)
+ .hasText("child 2-2", "nested items can be moved");
+ assert.dom(tree.nodes[1].textElement).hasText("child 2-1");
});
- test("input fields of type float", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- id: {
- type: "float",
- required: true,
- validations: {
- max: 5.5,
- min: 2.5,
- },
+ test("multiple upload fields have unique IDs", async function (assert) {
+ await renderEditor(
+ objectsSetting({
+ objects_schema: {
+ name: "something",
+ properties: {
+ first_upload: { type: "upload" },
+ second_upload: { type: "upload" },
},
},
- },
- value: [
- {
- id: 3.5,
- },
- ],
- });
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const inputFields = new InputFieldsFromDOM();
- assert.dom(inputFields.fields.id.labelElement).hasText("id*");
- assert.dom(inputFields.fields.id.inputElement).hasValue("3.5");
- assert
- .dom(inputFields.fields.id.inputElement)
- .hasAttribute("type", "number");
- await fillIn(inputFields.fields.id.inputElement, "100.0");
- inputFields.refresh();
- assert.dom(inputFields.fields.id.errorElement).hasText(
- i18n("admin.customize.schema.fields.number.too_large", {
- count: 5.5,
+ value: [{}],
})
);
- await fillIn(inputFields.fields.id.inputElement, "0.2");
- inputFields.refresh();
- assert.dom(inputFields.fields.id.errorElement).hasText(
- i18n("admin.customize.schema.fields.number.too_small", {
- count: 2.5,
- })
- );
- });
- test("input fields of type boolean", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- boolean_field: {
- type: "boolean",
- },
- },
- },
- value: [
- {
- boolean_field: true,
- },
- ],
- });
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const inputFields = new InputFieldsFromDOM();
assert
- .dom(inputFields.fields.boolean_field.labelElement)
- .hasText("boolean_field");
- assert.dom(inputFields.fields.boolean_field.inputElement).isChecked();
- });
-
- test("input fields of type enum", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- enum_field: {
- type: "enum",
- default: "awesome",
- choices: ["nice", "cool", "awesome"],
- },
- },
- },
- value: [
- {
- enum_field: "awesome",
- },
- ],
- });
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const inputFields = new InputFieldsFromDOM();
+ .dom("#schema-field-upload-objects_setting-first_upload")
+ .exists("the first upload field has an id based on its name");
assert
- .dom(inputFields.fields.enum_field.labelElement)
- .hasText("enum_field");
- assert.dom(inputFields.fields.enum_field.inputElement).hasText("awesome");
- });
-
- test("input fields of type categories that is not required with min and max validations", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- not_required_category: {
- type: "categories",
- validations: {
- min: 2,
- max: 3,
- },
- },
- },
- },
- metadata: {
- categories: {
- 6: {
- id: 6,
- name: "some category",
- },
- },
- },
- value: [{}],
- });
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const inputFields = new InputFieldsFromDOM();
- assert
- .dom(inputFields.fields.not_required_category.labelElement)
- .hasText("not_required_category");
- const categorySelector = selectKit(
- `${inputFields.fields.not_required_category.selector} .select-kit`
- );
- assert.strictEqual(categorySelector.header().value(), null);
- await categorySelector.expand();
- await categorySelector.selectRowByIndex(1);
- await categorySelector.collapse();
- inputFields.refresh();
- assert.dom(inputFields.fields.not_required_category.errorElement).hasText(
- i18n("admin.customize.schema.fields.categories.at_least", {
- count: 2,
- })
- );
- await categorySelector.expand();
- await categorySelector.selectRowByIndex(2);
- await categorySelector.selectRowByIndex(3);
- await categorySelector.selectRowByIndex(4);
- assert
- .dom(categorySelector.error())
- .hasText("You can only select 3 items.");
-
- await categorySelector.deselectItemByIndex(0);
- await categorySelector.deselectItemByIndex(0);
- await categorySelector.deselectItemByIndex(0);
- await categorySelector.collapse();
-
- inputFields.refresh();
-
- assert
- .dom(inputFields.fields.not_required_category.errorElement)
- .doesNotExist();
- });
-
- test("input fields of type tags which is required", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- required_tags: {
- type: "tags",
- required: true,
- },
- required_tags_with_validations: {
- type: "tags",
- required: true,
- validations: {
- min: 2,
- max: 3,
- },
- },
- },
- },
- value: [
- {
- required_tags: ["gazelle"],
- required_tags_with_validations: ["gazelle", "cat"],
- },
- ],
- });
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const inputFields = new InputFieldsFromDOM();
-
- let tagSelector = selectKit(
- `${inputFields.fields.required_tags_with_validations.selector} .select-kit`
- );
-
- assert.strictEqual(tagSelector.header().name(), "gazelle,cat");
-
- await tagSelector.expand();
- await tagSelector.selectRowByIndex(2);
- await tagSelector.collapse();
-
- assert.strictEqual(tagSelector.header().name(), "gazelle,cat,dog");
-
- await tagSelector.expand();
- await tagSelector.deselectItemByName("gazelle");
- await tagSelector.deselectItemByName("cat");
- await tagSelector.deselectItemByName("dog");
- await tagSelector.collapse();
-
- assert.strictEqual(tagSelector.header().value(), null);
-
- inputFields.refresh();
-
- assert
- .dom(inputFields.fields.required_tags_with_validations.errorElement)
- .hasText(
- i18n("admin.customize.schema.fields.tags.at_least", {
- count: 2,
- })
- );
-
- await tagSelector.expand();
- await tagSelector.selectRowByIndex(1);
-
- assert.strictEqual(tagSelector.header().name(), "gazelle");
-
- inputFields.refresh();
-
- assert
- .dom(inputFields.fields.required_tags_with_validations.errorElement)
- .hasText(
- i18n("admin.customize.schema.fields.tags.at_least", {
- count: 2,
- })
- );
-
- tagSelector = selectKit(
- `${inputFields.fields.required_tags.selector} .select-kit`
- );
-
- await tagSelector.expand();
- await tagSelector.deselectItemByName("gazelle");
- await tagSelector.collapse();
-
- inputFields.refresh();
-
- assert.dom(inputFields.fields.required_tags.errorElement).hasText(
- i18n("admin.customize.schema.fields.tags.at_least", {
- count: 1,
- })
- );
- });
-
- test("input fields of type groups", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- required_groups: {
- type: "groups",
- required: true,
- },
- groups_with_validations: {
- type: "groups",
- validations: {
- min: 2,
- max: 3,
- },
- },
- },
- },
- value: [
- {
- required_groups: [0, 1],
- },
- ],
- });
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
-
- let groupsSelector = selectKit(
- `${inputFields.fields.required_groups.selector} .select-kit`
- );
-
- assert.strictEqual(groupsSelector.header().value(), "0,1");
-
- await groupsSelector.expand();
- await groupsSelector.deselectItemByValue("0");
- await groupsSelector.deselectItemByValue("1");
- await groupsSelector.collapse();
-
- inputFields.refresh();
-
- assert.dom(inputFields.fields.required_groups.errorElement).hasText(
- i18n("admin.customize.schema.fields.groups.at_least", {
- count: 1,
- })
- );
-
- assert
- .dom(inputFields.fields.groups_with_validations.labelElement)
- .hasText("groups_with_validations");
-
- groupsSelector = selectKit(
- `${inputFields.fields.groups_with_validations.selector} .select-kit`
- );
-
- assert.strictEqual(groupsSelector.header().value(), null);
-
- await groupsSelector.expand();
- await groupsSelector.selectRowByIndex(1);
- await groupsSelector.collapse();
-
- assert.strictEqual(groupsSelector.header().value(), "1");
-
- inputFields.refresh();
-
- assert
- .dom(inputFields.fields.groups_with_validations.errorElement)
- .hasText(
- i18n("admin.customize.schema.fields.groups.at_least", {
- count: 2,
- })
- );
-
- await groupsSelector.expand();
- await groupsSelector.selectRowByIndex(2);
- await groupsSelector.selectRowByIndex(3);
- await groupsSelector.selectRowByIndex(4);
-
- assert
- .dom(groupsSelector.error())
- .hasText("You can only select 3 items.");
- });
-
- test("allows navigating through multiple levels of nesting", async function (assert) {
- const setting = schemaAndData(1, SCHEMA_MODES.SITE_SETTING);
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
- const tree = new TreeFromDOM();
- const inputFields = new InputFieldsFromDOM();
- assert.strictEqual(tree.nodes.length, 3);
- assert.dom(tree.nodes[0].textElement).hasText("item 1");
- assert.dom(tree.nodes[1].textElement).hasText("item 2");
- assert.dom(inputFields.fields.name.inputElement).hasValue("item 1");
- assert.dom(inputFields.fields.name.labelElement).hasText("name");
- assert.dom(".--back-btn").doesNotExist();
-
- await click(tree.nodes[0].children[0].element);
- tree.refresh();
- inputFields.refresh();
- assert.dom(inputFields.fields.name.labelElement).hasText("Level 2 Label");
- assert
- .dom(inputFields.fields.name.descriptionElement)
- .hasText("Description for level 2");
- });
-
- test("move buttons reorder items correctly", async function (assert) {
- const setting = schemaAndData(1, SCHEMA_MODES.SITE_SETTING);
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- // Verify initial order
- assert.dom(tree.nodes[0].textElement).hasText("item 1");
- assert.dom(tree.nodes[1].textElement).hasText("item 2");
-
- // Test move up: Select second item and move up
- await click(tree.nodes[1].element);
- tree.refresh();
- await click(MOVE_UP_BTN);
- tree.refresh();
-
- assert.dom(tree.nodes[0].textElement).hasText("item 2");
- assert.dom(tree.nodes[1].textElement).hasText("item 1");
-
- // Test move down: Select first item (was originally second) and move down
- await click(tree.nodes[0].element);
- tree.refresh();
- await click(MOVE_DOWN_BTN);
- tree.refresh();
-
- // Should be back to original order
- assert.dom(tree.nodes[0].textElement).hasText("item 1");
- assert.dom(tree.nodes[1].textElement).hasText("item 2");
- });
-
- test("move buttons are disabled appropriately", async function (assert) {
- const setting = schemaAndData(1, SCHEMA_MODES.SITE_SETTING);
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const tree = new TreeFromDOM();
-
- // First item should have move up disabled
- await click(tree.nodes[0].element);
- tree.refresh();
-
- assert.dom(MOVE_UP_BTN).isDisabled();
- assert.dom(MOVE_DOWN_BTN).isNotDisabled();
-
- // Last item should have move down disabled
- await click(tree.nodes[1].element);
- tree.refresh();
-
- assert.dom(MOVE_UP_BTN).isNotDisabled();
- assert.dom(MOVE_DOWN_BTN).isDisabled();
- });
-
- test("multiple upload fields have unique IDs", async function (assert) {
- const setting = SiteSetting.create({
- setting: "objects_setting",
- schema: {
- name: "something",
- properties: {
- first_upload: {
- type: "upload",
- },
- second_upload: {
- type: "upload",
- },
- },
- },
- value: [{}],
- });
-
- await render(
- <template>
- <AdminSchemaSettingEditor
- @id="1"
- @routeToRedirect="adminPlugins.show.settings"
- @schema={{setting.schema}}
- @setting={{setting}}
- />
- </template>
- );
-
- const inputFields = new InputFieldsFromDOM();
-
- // Verify both upload fields exist
- assert
- .dom(inputFields.fields.first_upload.labelElement)
- .hasText("first_upload");
- assert
- .dom(inputFields.fields.second_upload.labelElement)
- .hasText("second_upload");
-
- // The UppyImageUploader components should have unique IDs based on field names
- const firstUploadId =
- inputFields.fields.first_upload.inputElement.id ||
- inputFields.fields.first_upload.inputElement.querySelector(
- "[id^='schema-field-upload-']"
- )?.id;
- const secondUploadId =
- inputFields.fields.second_upload.inputElement.id ||
- inputFields.fields.second_upload.inputElement.querySelector(
- "[id^='schema-field-upload-']"
- )?.id;
-
- assert.true(
- !!firstUploadId,
- "First upload field should have an ID attribute"
- );
- assert.true(
- !!secondUploadId,
- "Second upload field should have an ID attribute"
- );
- assert.notStrictEqual(
- firstUploadId,
- secondUploadId,
- "Upload field IDs should be unique"
- );
- assert.true(
- firstUploadId?.includes("first_upload"),
- "First upload ID should include field name"
- );
- assert.true(
- secondUploadId?.includes("second_upload"),
- "Second upload ID should include field name"
- );
+ .dom("#schema-field-upload-objects_setting-second_upload")
+ .exists("the second upload field has an id based on its name");
});
}
);
diff --git a/lib/schema_settings_object_validator.rb b/lib/schema_settings_object_validator.rb
index 42b3b2b6037..2aedaa6ef1e 100644
--- a/lib/schema_settings_object_validator.rb
+++ b/lib/schema_settings_object_validator.rb
@@ -3,17 +3,23 @@
class SchemaSettingsObjectValidator
class << self
def validate_objects(schema:, objects:)
- error_messages = []
+ valid_ids_lookup = valid_ids_lookup_for(schema:, objects:)
- objects.each_with_index do |object, index|
- humanize_error_messages(
- new(schema: schema, object: object).validate,
- index:,
- error_messages:,
- )
+ objects.each_with_index.flat_map do |object, index|
+ new(schema:, object:, valid_ids_lookup:).validate.flat_map do |pointer, errors|
+ errors.humanize_messages("/#{index}#{pointer}")
+ end
end
+ end
- error_messages
+ def valid_ids_lookup_for(schema:, objects:)
+ Hash.new do |lookup, type|
+ column = TYPE_TO_MODEL_MAP[type][:column] || :id
+ values = property_values_of_type(schema:, objects:, type:)
+ values = values.grep(column == :name ? String : Integer)
+
+ lookup[type] = TYPE_TO_MODEL_MAP[type][:klass].where(column => values).pluck(column).to_set
+ end
end
def property_values_of_type(schema:, objects:, type:)
@@ -53,10 +59,7 @@ class SchemaSettingsObjectValidator
def hydrate_uploads(schema:, objects:, cdn: false)
return objects if objects.blank?
- upload_ids =
- property_values_of_type(schema: schema, objects: objects, type: "upload").select do |value|
- value.is_a?(Integer)
- end
+ upload_ids = property_values_of_type(schema:, objects:, type: "upload").grep(Integer)
return objects if upload_ids.empty?
uploads_by_id = Upload.where(id: upload_ids).index_by(&:id)
@@ -103,12 +106,6 @@ class SchemaSettingsObjectValidator
symbol_key = property_name.to_sym
symbol_key if object.key?(symbol_key)
end
-
- def humanize_error_messages(errors, index:, error_messages:)
- errors.each do |property_json_pointer, error_details|
- error_messages.push(*error_details.humanize_messages("/#{index}#{property_json_pointer}"))
- end
- end
end
class SchemaSettingsObjectErrors
@@ -147,13 +144,13 @@ class SchemaSettingsObjectValidator
end
end
- def initialize(schema:, object:, json_pointer_prefix: "", errors: {}, valid_ids_lookup: {})
+ def initialize(schema:, object:, json_pointer_prefix: "", errors: {}, valid_ids_lookup: nil)
@object = object.with_indifferent_access
- @schema_name = schema[:name]
@properties = schema[:properties]
@errors = errors
@json_pointer_prefix = json_pointer_prefix
- @valid_ids_lookup = valid_ids_lookup
+ @valid_ids_lookup =
+ valid_ids_lookup || self.class.valid_ids_lookup_for(schema:, objects: [object])
end
def validate
@@ -187,7 +184,7 @@ class SchemaSettingsObjectValidator
.new(
schema:,
object:,
- valid_ids_lookup:,
+ valid_ids_lookup: @valid_ids_lookup,
json_pointer_prefix: "#{@json_pointer_prefix}#{property_name}/#{index}/",
errors: @errors,
)
@@ -196,9 +193,18 @@ class SchemaSettingsObjectValidator
end
def validate_property(property_name, property_attributes)
- return if property_attributes[:required] && !is_property_present?(property_name)
return if !has_valid_property_value_type?(property_attributes, property_name)
- !has_valid_property_value?(property_attributes, property_name)
+
+ if absent?(@object[property_name])
+ add_error(property_name, :required) if property_attributes[:required]
+ return
+ end
+
+ has_valid_property_value?(property_attributes, property_name)
+ end
+
+ def absent?(value)
+ value != false && value.blank?
end
def has_valid_property_value_type?(property_attributes, property_name)
@@ -218,7 +224,7 @@ class SchemaSettingsObjectValidator
if upload = Upload.get_from_url(value)
@object[property_name] = upload.id
# upload already verified via get_from_url, so we can add it to valid ids
- (@valid_ids_lookup["upload"] ||= Set.new) << upload.id
+ @valid_ids_lookup["upload"] << upload.id
true
else
false
@@ -254,16 +260,14 @@ class SchemaSettingsObjectValidator
type = property_attributes[:type]
value = @object[property_name]
- return true if value.nil?
-
case type
when "topic", "upload", "post"
- if !valid_ids(type).include?(value)
+ if !@valid_ids_lookup[type].include?(value)
add_error(property_name, :"not_valid_#{type}_value")
return false
end
when "tags", "categories", "groups"
- if !Array(value).to_set.subset?(valid_ids(type))
+ if !value.to_set.subset?(@valid_ids_lookup[type])
add_error(property_name, :"not_valid_#{type}_value")
return false
end
@@ -278,17 +282,7 @@ class SchemaSettingsObjectValidator
return false
end
when "datetime"
- return true if value.blank?
- begin
- # DateTime.iso8601 checks the format but does not enforce timezone presence
- # so we need to do an additional check for the presence of timezone info.
- DateTime.iso8601(value)
- if value.include?("T") && (value.end_with?("Z") || value.match?(/[+-]\d{2}:\d{2}$/))
- return true
- end
- add_error(property_name, :not_valid_datetime_value)
- return false
- rescue ArgumentError, TypeError
+ if !DatetimeSettingValidator.new.valid_value?(value)
add_error(property_name, :not_valid_datetime_value)
return false
end
@@ -322,15 +316,6 @@ class SchemaSettingsObjectValidator
true
end
- def is_property_present?(property_name)
- if @object[property_name].blank?
- add_error(property_name, :required)
- false
- else
- true
- end
- end
-
def add_error(property_name, key, i18n_opts = {})
pointer = json_pointer(property_name)
@errors[pointer] ||= SchemaSettingsObjectErrors.new
@@ -341,10 +326,6 @@ class SchemaSettingsObjectValidator
"/#{@json_pointer_prefix}#{property_name}"
end
- def valid_ids_lookup
- @valid_ids_lookup ||= {}
- end
-
TYPE_TO_MODEL_MAP = {
"categories" => {
klass: Category,
@@ -368,18 +349,6 @@ class SchemaSettingsObjectValidator
}
private_constant :TYPE_TO_MODEL_MAP
- def valid_ids(type)
- valid_ids_lookup[type] ||= begin
- column = TYPE_TO_MODEL_MAP[type][:column] || :id
-
- Set.new(
- TYPE_TO_MODEL_MAP[type][:klass].where(
- column => fetch_property_values_of_type(@properties, @object, type),
- ).pluck(column),
- )
- end
- end
-
def fetch_property_values_of_type(properties, object, type)
values = Set.new
diff --git a/spec/lib/schema_settings_object_validator_spec.rb b/spec/lib/schema_settings_object_validator_spec.rb
index 827735c0b57..df08b2b1bd7 100644
--- a/spec/lib/schema_settings_object_validator_spec.rb
+++ b/spec/lib/schema_settings_object_validator_spec.rb
@@ -1,6 +1,11 @@
# frozen_string_literal: true
RSpec.describe SchemaSettingsObjectValidator do
+ def errors_for(schema, object) =
+ described_class.new(schema:, object:).validate.transform_values(&:full_messages)
+
+ def schema_with(name, **attributes) = { name: "section", properties: { name => attributes } }
+
describe ".property_values_of_type" do
it "returns an empty array when objects array is empty" do
schema = { name: "section", properties: { upload: { type: "upload" } } }
@@ -130,10 +135,53 @@ RSpec.describe SchemaSettingsObjectValidator do
],
)
end
+
+ it "looks up the valid ids of each type once for all objects, ignoring malformed values" do
+ tag_1 = Fabricate(:tag)
+ tag_2 = Fabricate(:tag)
+ tag_3 = Fabricate(:tag)
+
+ schema = {
+ name: "section",
+ properties: {
+ links: {
+ type: "objects",
+ schema: {
+ name: "link",
+ properties: {
+ tags_property: {
+ type: "tags",
+ },
+ },
+ },
+ },
+ tags_property: {
+ type: "tags",
+ },
+ },
+ }
+
+ objects = [
+ { tags_property: [tag_1.name], links: [{ tags_property: [tag_2.name] }] },
+ { tags_property: [tag_3.name] },
+ { tags_property: [{ "name" => tag_1.name }] },
+ ]
+
+ queries =
+ track_sql_queries do
+ expect(described_class.validate_objects(schema:, objects:)).to eq(
+ [
+ "The property at JSON Pointer '/2/tags_property' must be an array of valid tag names.",
+ ],
+ )
+ end
+
+ expect(queries.length).to eq(1)
+ end
end
describe "#validate" do
- it "returns errors when required properties are missing" do
+ it "returns errors when required properties are missing or blank" do
schema = {
name: "section",
properties: {
@@ -145,6 +193,19 @@ RSpec.describe SchemaSettingsObjectValidator do
type: "string",
required: true,
},
+ category_property: {
+ type: "categories",
+ required: true,
+ },
+ enum_property: {
+ type: "enum",
+ choices: [true, false],
+ required: true,
+ },
+ integer_property: {
+ type: "integer",
+ required: true,
+ },
links: {
type: "objects",
schema: {
@@ -175,478 +236,374 @@ RSpec.describe SchemaSettingsObjectValidator do
},
}
- errors = described_class.new(schema:, object: {}).validate
+ object = {
+ title: " ",
+ description: "",
+ category_property: [],
+ enum_property: false,
+ integer_property: "",
+ links: [{ child_links: [{}, {}] }, {}],
+ }
- expect(errors.keys).to contain_exactly("/description", "/title")
- expect(errors["/description"].full_messages).to contain_exactly("must be present")
- expect(errors["/title"].full_messages).to contain_exactly("must be present")
+ expect(errors_for(schema, object)).to eq(
+ "/title" => ["must be present"],
+ "/description" => ["must be present"],
+ "/category_property" => ["must be present"],
+ "/integer_property" => ["must be an integer"],
+ "/links/0/name" => ["must be present"],
+ "/links/0/child_links/0/title" => ["must be present"],
+ "/links/0/child_links/1/title" => ["must be present"],
+ "/links/1/name" => ["must be present"],
+ )
+ end
- errors =
- described_class.new(
- schema: schema,
- object: {
- links: [{ child_links: [{}, {}] }, {}],
+ it "returns no errors when optional properties are blank" do
+ schema = {
+ name: "section",
+ properties: {
+ string_property: {
+ type: "string",
+ validations: {
+ url: true,
+ },
},
- ).validate
-
- expect(errors.keys).to eq(
- %w[
- /title
- /description
- /links/0/name
- /links/0/child_links/0/title
- /links/0/child_links/1/title
- /links/1/name
- ],
- )
+ datetime_property: {
+ type: "datetime",
+ },
+ category_property: {
+ type: "categories",
+ validations: {
+ min: 1,
+ },
+ },
+ },
+ }
- expect(errors["/title"].full_messages).to contain_exactly("must be present")
- expect(errors["/description"].full_messages).to contain_exactly("must be present")
- expect(errors["/links/0/name"].full_messages).to contain_exactly("must be present")
+ object = { string_property: "", datetime_property: "", category_property: [] }
- expect(errors["/links/0/child_links/0/title"].full_messages).to contain_exactly(
- "must be present",
- )
+ expect(errors_for(schema, object)).to eq({})
+ end
- expect(errors["/links/0/child_links/1/title"].full_messages).to contain_exactly(
- "must be present",
- )
+ it "returns errors for missing properties of every type only when required" do
+ properties =
+ %w[string integer float boolean datetime icon upload topic post categories groups tags]
+ .index_with { |type| { type: } }
+ .merge("enum" => { type: "enum", choices: ["a"] })
+ required_properties =
+ properties.transform_values { |attributes| attributes.merge(required: true) }
- expect(errors["/links/1/name"].full_messages).to contain_exactly("must be present")
+ expect(errors_for({ name: "section", properties: }, {})).to eq({})
+
+ expect(errors_for({ name: "section", properties: required_properties }, {})).to eq(
+ properties.keys.to_h { |name| ["/#{name}", ["must be present"]] },
+ )
end
context "for enum properties" do
- def schema(required: false)
- property = {
- name: "section",
- properties: {
- enum_property: {
- type: "enum",
- choices: ["choice 1", 2, false],
- },
- },
- }
-
- property[:properties][:enum_property][:required] = true if required
- property
- end
+ let(:schema) { schema_with(:enum_property, type: "enum", choices: ["choice 1", 2, false]) }
it "returns no errors when the value is in the enum" do
- expect(
- described_class.new(schema: schema, object: { enum_property: "choice 1" }).validate,
- ).to eq({})
+ expect(errors_for(schema, { enum_property: "choice 1" })).to eq({})
end
it "returns errors when the value is not in the enum" do
- errors =
- described_class.new(schema: schema, object: { enum_property: "random_value" }).validate
-
- expect(errors.keys).to eq(["/enum_property"])
-
- expect(errors["/enum_property"].full_messages).to contain_exactly(
- "must be one of the following: [\"choice 1\", 2, false]",
+ expect(errors_for(schema, { enum_property: "random_value" })).to eq(
+ "/enum_property" => ["must be one of the following: [\"choice 1\", 2, false]"],
)
end
-
- it "returns no errors when an optional enum property is missing" do
- expect(described_class.new(schema: schema(required: false), object: {}).validate).to eq({})
- end
-
- it "returns errors when a required enum property is missing" do
- errors = described_class.new(schema: schema(required: true), object: {}).validate
-
- expect(errors.keys).to eq(["/enum_property"])
-
- expect(errors["/enum_property"].full_messages).to contain_exactly("must be present")
- end
end
context "for boolean properties" do
- let(:schema) { { name: "section", properties: { boolean_property: { type: "boolean" } } } }
+ let(:schema) { schema_with(:boolean_property, type: "boolean", required: true) }
- it "returns no errors for a boolean value" do
- expect(
- described_class.new(schema: schema, object: { boolean_property: true }).validate,
- ).to eq({})
+ it "returns no errors when the required boolean is true or false" do
+ expect(errors_for(schema, { boolean_property: true })).to eq({})
- expect(
- described_class.new(schema: schema, object: { boolean_property: false }).validate,
- ).to eq({})
+ expect(errors_for(schema, { boolean_property: false })).to eq({})
end
it "returns errors for a non-boolean value" do
- errors =
- described_class.new(schema: schema, object: { boolean_property: "string" }).validate
-
- expect(errors.keys).to eq(["/boolean_property"])
- expect(errors["/boolean_property"].full_messages).to contain_exactly("must be a boolean")
+ expect(errors_for(schema, { boolean_property: "string" })).to eq(
+ "/boolean_property" => ["must be a boolean"],
+ )
end
end
context "for float properties" do
- let(:schema) { { name: "section", properties: { float_property: { type: "float" } } } }
+ let(:schema) { schema_with(:float_property, type: "float") }
it "returns no errors for an integer or float value" do
- expect(described_class.new(schema: schema, object: { float_property: 1.5 }).validate).to eq(
- {},
- )
-
- expect(described_class.new(schema: schema, object: { float_property: 1 }).validate).to eq(
- {},
- )
- end
-
- it "returns no errors when an optional value is missing" do
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
-
- it "returns errors when a required value is missing" do
- schema = {
- name: "section",
- properties: {
- float_property: {
- type: "float",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
+ expect(errors_for(schema, { float_property: 1.5 })).to eq({})
- expect(errors.keys).to eq(["/float_property"])
- expect(errors["/float_property"].full_messages).to contain_exactly("must be present")
+ expect(errors_for(schema, { float_property: 1 })).to eq({})
end
it "returns errors for a non-float value" do
- errors = described_class.new(schema: schema, object: { float_property: "string" }).validate
-
- expect(errors.keys).to eq(["/float_property"])
- expect(errors["/float_property"].full_messages).to contain_exactly("must be a float")
+ expect(errors_for(schema, { float_property: "string" })).to eq(
+ "/float_property" => ["must be a float"],
+ )
end
it "returns errors when the number fails minimum or maximum validation" do
- schema = {
- name: "section",
- properties: {
- float_property: {
- type: "float",
- validations: {
- min: 5.5,
- max: 11.5,
- },
- },
- },
- }
-
- errors = described_class.new(schema: schema, object: { float_property: 4.5 }).validate
+ schema = schema_with(:float_property, type: "float", validations: { min: 5.5, max: 11.5 })
- expect(errors.keys).to eq(["/float_property"])
-
- expect(errors["/float_property"].full_messages).to contain_exactly(
- "must be larger than or equal to 5.5",
+ expect(errors_for(schema, { float_property: 4.5 })).to eq(
+ "/float_property" => ["must be larger than or equal to 5.5"],
)
- errors = described_class.new(schema: schema, object: { float_property: 12.5 }).validate
-
- expect(errors.keys).to eq(["/float_property"])
-
- expect(errors["/float_property"].full_messages).to contain_exactly(
- "must be smaller than or equal to 11.5",
+ expect(errors_for(schema, { float_property: 12.5 })).to eq(
+ "/float_property" => ["must be smaller than or equal to 11.5"],
)
end
end
context "for integer properties" do
- let(:schema) { { name: "section", properties: { integer_property: { type: "integer" } } } }
+ let(:schema) { schema_with(:integer_property, type: "integer") }
it "returns no errors for an integer value" do
- expect(described_class.new(schema: schema, object: { integer_property: 1 }).validate).to eq(
- {},
- )
+ expect(errors_for(schema, { integer_property: 1 })).to eq({})
end
- it "returns no errors when the optional integer is missing" do
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
+ it "returns errors for a non-integer value" do
+ ["string", 1.0].each do |value|
+ expect(errors_for(schema, { integer_property: value })).to eq(
+ "/integer_property" => ["must be an integer"],
+ )
+ end
end
- it "returns errors when the required integer is missing" do
- schema = {
- name: "section",
- properties: {
- integer_property: {
- type: "integer",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
+ it "returns errors only when the integer fails range validation" do
+ schema = schema_with(:integer_property, type: "integer", validations: { min: 5, max: 10 })
- expect(errors.keys).to eq(["/integer_property"])
- expect(errors["/integer_property"].full_messages).to contain_exactly("must be present")
- end
+ expect(errors_for(schema, { integer_property: 6 })).to eq({})
- it "returns errors for a non-integer value" do
- errors =
- described_class.new(schema: schema, object: { integer_property: "string" }).validate
+ expect(errors_for(schema, { integer_property: 4 })).to eq(
+ "/integer_property" => ["must be larger than or equal to 5"],
+ )
- expect(errors.keys).to eq(["/integer_property"])
- expect(errors["/integer_property"].full_messages).to contain_exactly("must be an integer")
+ expect(errors_for(schema, { integer_property: 11 })).to eq(
+ "/integer_property" => ["must be smaller than or equal to 10"],
+ )
+ end
+ end
- errors = described_class.new(schema: schema, object: { integer_property: 1.0 }).validate
+ context "for string properties" do
+ let(:schema) { schema_with(:string_property, type: "string") }
- expect(errors.keys).to eq(["/integer_property"])
- expect(errors["/integer_property"].full_messages).to contain_exactly("must be an integer")
+ it "returns no errors for a string value" do
+ expect(errors_for(schema, { string_property: "string" })).to eq({})
end
- it "returns no errors when the integer satisfies range validation" do
- schema = {
- name: "section",
- properties: {
- integer_property: {
- type: "integer",
- validations: {
- min: 5,
- max: 10,
- },
- },
- },
- }
-
- expect(described_class.new(schema: schema, object: { integer_property: 6 }).validate).to eq(
- {},
+ it "returns errors for a non-string value" do
+ expect(errors_for(schema, { string_property: 1 })).to eq(
+ "/string_property" => ["must be a string"],
)
end
- it "returns errors when the integer fails range validation" do
- schema = {
- name: "section",
- properties: {
- integer_property: {
- type: "integer",
- validations: {
- min: 5,
- max: 10,
- },
- },
- },
- }
+ it "returns errors only when the string is not a valid URL" do
+ schema = schema_with(:string_property, type: "string", validations: { url: true })
- errors = described_class.new(schema: schema, object: { integer_property: 4 }).validate
+ expect(errors_for(schema, { string_property: "https://www.example.com" })).to eq({})
- expect(errors.keys).to eq(["/integer_property"])
+ expect(errors_for(schema, { string_property: "/some-path/to/some-where" })).to eq({})
- expect(errors["/integer_property"].full_messages).to contain_exactly(
- "must be larger than or equal to 5",
+ expect(errors_for(schema, { string_property: "not a url" })).to eq(
+ "/string_property" => ["must be a valid URL"],
)
+ end
- errors = described_class.new(schema: schema, object: { integer_property: 11 }).validate
+ it "returns errors only when the string fails length validation" do
+ validations = { min_length: 5, max_length: 10 }
+ schema = schema_with(:string_property, type: "string", validations:)
- expect(errors.keys).to eq(["/integer_property"])
+ expect(errors_for(schema, { string_property: "123456" })).to eq({})
+
+ expect(errors_for(schema, { string_property: "1234" })).to eq(
+ "/string_property" => ["must be at least 5 characters long"],
+ )
- expect(errors["/integer_property"].full_messages).to contain_exactly(
- "must be smaller than or equal to 10",
+ expect(errors_for(schema, { string_property: "12345678910" })).to eq(
+ "/string_property" => ["must be at most 10 characters long"],
)
end
end
- context "for string properties" do
- let(:schema) { { name: "section", properties: { string_property: { type: "string" } } } }
+ context "for topic properties" do
+ let(:schema) { schema_with(:topic_property, type: "topic") }
- it "returns no errors for a string value" do
- expect(
- described_class.new(schema: schema, object: { string_property: "string" }).validate,
- ).to eq({})
+ it "returns no errors for a valid topic ID" do
+ topic = Fabricate(:topic)
+
+ expect(errors_for(schema, { topic_property: topic.id })).to eq({})
end
- it "returns no errors when the optional string is missing" do
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
+ it "returns errors for an invalid topic ID" do
+ ["string", 99_999_999].each do |value|
+ expect(errors_for(schema, { topic_property: value })).to eq(
+ "/topic_property" => ["must be a valid topic id"],
+ )
+ end
end
+ end
- it "returns errors when the required string is missing" do
- schema = {
+ context "for upload properties" do
+ let(:schema) do
+ {
name: "section",
properties: {
- string_property: {
- type: "string",
- required: true,
+ upload_property: {
+ type: "upload",
+ },
+ upload_property_2: {
+ type: "upload",
},
},
}
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/string_property"])
- expect(errors["/string_property"].full_messages).to contain_exactly("must be present")
end
- it "returns errors for a non-string value" do
- schema = { name: "section", properties: { string_property: { type: "string" } } }
- errors = described_class.new(schema: schema, object: { string_property: 1 }).validate
+ it "returns no errors for a valid upload URL and ID" do
+ upload_1 = Fabricate(:upload)
+ upload_2 = Fabricate(:upload)
- expect(errors.keys).to eq(["/string_property"])
- expect(errors["/string_property"].full_messages).to contain_exactly("must be a string")
- end
+ object = { upload_property: upload_1.url, upload_property_2: upload_2.id }
- it "returns no errors when the string is a valid URL" do
- schema = {
- name: "section",
- properties: {
- string_property: {
- type: "string",
- validations: {
- url: true,
- },
- },
- },
- }
+ expect(errors_for(schema, object)).to eq({})
+ end
- expect(
- described_class.new(
- schema: schema,
- object: {
- string_property: "https://www.example.com",
- },
- ).validate,
- ).to eq({})
-
- expect(
- described_class.new(
- schema: schema,
- object: {
- string_property: "/some-path/to/some-where",
- },
- ).validate,
- ).to eq({})
+ it "returns errors for an invalid upload ID or URL" do
+ ["/invalid/upload/url.png", 99_999_999].each do |value|
+ expect(errors_for(schema, { upload_property: value })).to eq(
+ "/upload_property" => ["must be a valid upload id"],
+ )
+ end
end
+ end
- it "returns errors when the string is not a valid URL" do
- schema = {
- name: "section",
- properties: {
- string_property: {
- type: "string",
- validations: {
- url: true,
- },
- },
- },
- }
+ context "for tag properties" do
+ fab!(:tag_1, :tag)
+ fab!(:tag_2, :tag)
+ fab!(:tag_3, :tag)
+
+ let(:schema) { schema_with(:tags_property, type: "tags") }
- errors =
- described_class.new(schema: schema, object: { string_property: "not a url" }).validate
+ it "returns no errors for valid tag names" do
+ expect(errors_for(schema, { tags_property: [tag_1.name, tag_2.name] })).to eq({})
+ end
- expect(errors.keys).to eq(["/string_property"])
- expect(errors["/string_property"].full_messages).to contain_exactly("must be a valid URL")
+ it "returns errors for invalid tag names" do
+ ["string", ["some random tag name", tag_1.name]].each do |value|
+ expect(errors_for(schema, { tags_property: value })).to eq(
+ "/tags_property" => ["must be an array of valid tag names"],
+ )
+ end
end
- it "returns no errors when the string satisfies length validation" do
- schema = {
- name: "section",
- properties: {
- string_property: {
- type: "string",
- validations: {
- min_length: 5,
- max_length: 10,
- },
- },
- },
- }
+ it "returns errors when the tag count fails range validation" do
+ schema = schema_with(:tags_property, type: "tags", validations: { min: 2, max: 2 })
+
+ expect(errors_for(schema, { tags_property: [tag_1.name] })).to eq(
+ "/tags_property" => ["must have at least 2 tag names"],
+ )
- expect(
- described_class.new(schema: schema, object: { string_property: "123456" }).validate,
- ).to eq({})
+ expect(errors_for(schema, { tags_property: [tag_1.name, tag_2.name, tag_3.name] })).to eq(
+ "/tags_property" => ["must have at most 2 tag names"],
+ )
end
+ end
- it "returns errors when the string fails length validation" do
- schema = {
- name: "section",
- properties: {
- string_property: {
- type: "string",
- validations: {
- min_length: 5,
- max_length: 10,
- },
- },
- },
- }
+ context "for groups properties" do
+ let(:schema) { schema_with(:groups_property, type: "groups") }
+
+ it "returns no errors for valid group IDs" do
+ group = Fabricate(:group)
- errors = described_class.new(schema: schema, object: { string_property: "1234" }).validate
+ expect(errors_for(schema, { groups_property: [group.id] })).to eq({})
+ end
- expect(errors.keys).to eq(["/string_property"])
+ it "returns errors for invalid group IDs" do
+ ["string", [99_999_999]].each do |value|
+ expect(errors_for(schema, { groups_property: value })).to eq(
+ "/groups_property" => ["must be an array of valid group ids"],
+ )
+ end
+ end
- expect(errors["/string_property"].full_messages).to contain_exactly(
- "must be at least 5 characters long",
- )
+ it "returns errors when the group count fails range validation" do
+ group_1 = Fabricate(:group)
+ group_2 = Fabricate(:group)
+ group_3 = Fabricate(:group)
- errors =
- described_class.new(schema: schema, object: { string_property: "12345678910" }).validate
+ schema = schema_with(:group_property, type: "groups", validations: { min: 2, max: 2 })
- expect(errors.keys).to eq(["/string_property"])
+ expect(errors_for(schema, { group_property: [group_1.id] })).to eq(
+ "/group_property" => ["must have at least 2 group ids"],
+ )
- expect(errors["/string_property"].full_messages).to contain_exactly(
- "must be at most 10 characters long",
+ expect(errors_for(schema, { group_property: [group_1.id, group_2.id, group_3.id] })).to eq(
+ "/group_property" => ["must have at most 2 group ids"],
)
end
end
- context "for topic properties" do
- it "returns no errors for a valid topic ID" do
- topic = Fabricate(:topic)
+ context "for post properties" do
+ let(:schema) { schema_with(:post_property, type: "post") }
- schema = { name: "section", properties: { topic_property: { type: "topic" } } }
+ it "returns no errors for a valid post ID" do
+ post = Fabricate(:post)
- expect(
- described_class.new(schema: schema, object: { topic_property: topic.id }).validate,
- ).to eq({})
+ expect(errors_for(schema, { post_property: post.id })).to eq({})
end
- it "returns no errors when the optional topic ID is missing" do
- schema = { name: "section", properties: { topic_property: { type: "topic" } } }
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
+ it "returns errors for an invalid post ID" do
+ ["string", 99_999_999].each do |value|
+ expect(errors_for(schema, { post_property: value })).to eq(
+ "/post_property" => ["must be a valid post id"],
+ )
+ end
end
+ end
- it "returns errors when the required topic ID is missing" do
- schema = {
- name: "section",
- properties: {
- topic_property: {
- type: "topic",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
+ context "for categories properties" do
+ fab!(:category_1, :category)
+ fab!(:category_2, :category)
- expect(errors.keys).to eq(["/topic_property"])
- expect(errors["/topic_property"].full_messages).to contain_exactly("must be present")
- end
+ let(:schema) { schema_with(:category_property, type: "categories") }
- it "returns errors when the topic ID is not an integer" do
- schema = { name: "section", properties: { topic_property: { type: "topic" } } }
+ it "returns no errors for valid category IDs" do
+ expect(errors_for(schema, { category_property: [category_1.id, category_2.id] })).to eq({})
+ end
- errors = described_class.new(schema: schema, object: { topic_property: "string" }).validate
+ it "returns errors when the category list contains non-integers" do
+ expect(errors_for(schema, { category_property: ["string"] })).to eq(
+ "/category_property" => ["must be an array of valid category ids"],
+ )
+ end
- expect(errors.keys).to eq(["/topic_property"])
+ it "returns errors when the category count fails range validation" do
+ schema = schema_with(:category_property, type: "categories", validations: { min: 2 })
- expect(errors["/topic_property"].full_messages).to contain_exactly(
- "must be a valid topic id",
+ expect(errors_for(schema, { category_property: [category_1.id] })).to eq(
+ "/category_property" => ["must have at least 2 category ids"],
)
end
- it "returns errors for an unknown topic ID" do
+ it "returns errors when the category list contains invalid IDs" do
schema = {
name: "section",
properties: {
- topic_property: {
- type: "topic",
+ category_property: {
+ type: "categories",
+ },
+ category_property_2: {
+ type: "categories",
},
- child_topics: {
+ child_categories: {
type: "objects",
schema: {
- name: "child_topic",
+ name: "child_category",
properties: {
- topic_property_2: {
- type: "topic",
+ category_property_3: {
+ type: "categories",
},
},
},
@@ -654,797 +611,59 @@ RSpec.describe SchemaSettingsObjectValidator do
},
}
+ object = {
+ category_property: [99_999_999, category_1.id],
+ category_property_2: [99_999_999],
+ child_categories: [
+ { category_property_3: [99_999_999, category_2.id] },
+ { category_property_3: [category_2.id] },
+ ],
+ }
+
queries =
track_sql_queries do
- errors =
- described_class.new(
- schema:,
- object: {
- topic_property: 99_999_999,
- child_topics: [{ topic_property_2: 99_999_999 }],
- },
- ).validate
-
- expect(errors.keys).to eq(%w[/topic_property /child_topics/0/topic_property_2])
-
- expect(errors["/topic_property"].full_messages).to contain_exactly(
- "must be a valid topic id",
- )
-
- expect(errors["/child_topics/0/topic_property_2"].full_messages).to contain_exactly(
- "must be a valid topic id",
+ expect(errors_for(schema, object)).to eq(
+ "/category_property" => ["must be an array of valid category ids"],
+ "/category_property_2" => ["must be an array of valid category ids"],
+ "/child_categories/0/category_property_3" => [
+ "must be an array of valid category ids",
+ ],
)
end
- # only 1 SQL query should be executed to check if topic ids are valid
- expect(queries.length).to eq(1)
- end
- end
-
- context "for upload properties" do
- it "returns no errors for a valid upload ID" do
- upload = Fabricate(:upload)
-
- schema = { name: "section", properties: { upload_property: { type: "upload" } } }
-
- expect(
- described_class.new(schema: schema, object: { upload_property: upload.id }).validate,
- ).to eq({})
- end
-
- it "returns no errors when the optional upload ID is missing" do
- schema = { name: "section", properties: { upload_property: { type: "upload" } } }
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
-
- it "returns errors when the required upload ID is missing" do
- schema = {
- name: "section",
- properties: {
- upload_property: {
- type: "upload",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/upload_property"])
- expect(errors["/upload_property"].full_messages).to contain_exactly("must be present")
- end
-
- it "returns errors when the upload ID is not an integer" do
- schema = { name: "section", properties: { upload_property: { type: "upload" } } }
-
- errors = described_class.new(schema: schema, object: { upload_property: "string" }).validate
-
- expect(errors.keys).to eq(["/upload_property"])
-
- expect(errors["/upload_property"].full_messages).to contain_exactly(
- "must be a valid upload id",
- )
- end
-
- it "returns errors when the upload value is an invalid URL" do
- schema = { name: "section", properties: { upload_property: { type: "upload" } } }
-
- errors =
- described_class.new(
- schema: schema,
- object: {
- upload_property: "/invalid/upload/url.png",
- },
- ).validate
-
- expect(errors.keys).to eq(["/upload_property"])
-
- expect(errors["/upload_property"].full_messages).to contain_exactly(
- "must be a valid upload id",
- )
- end
-
- it "returns errors for an unknown upload ID" do
- schema = {
- name: "section",
- properties: {
- upload_property: {
- type: "upload",
- },
- child_uploads: {
- type: "objects",
- schema: {
- name: "child_upload",
- properties: {
- upload_property_2: {
- type: "upload",
- },
- },
- },
- },
- },
- }
-
- queries =
- track_sql_queries do
- errors =
- described_class.new(
- schema:,
- object: {
- upload_property: 99_999_999,
- child_uploads: [{ upload_property_2: 99_999_999 }],
- },
- ).validate
-
- expect(errors.keys).to eq(%w[/upload_property /child_uploads/0/upload_property_2])
-
- expect(errors["/upload_property"].full_messages).to contain_exactly(
- "must be a valid upload id",
- )
-
- expect(errors["/child_uploads/0/upload_property_2"].full_messages).to contain_exactly(
- "must be a valid upload id",
- )
- end
-
- # only 1 SQL query should be executed to check if upload ids are valid
- expect(queries.length).to eq(1)
- end
- end
-
- context "for tag properties" do
- fab!(:tag_1, :tag)
- fab!(:tag_2, :tag)
- fab!(:tag_3, :tag)
-
- it "returns no errors for valid tag names" do
- schema = { name: "section", properties: { tags_property: { type: "tags" } } }
-
- expect(
- described_class.new(
- schema: schema,
- object: {
- tags_property: [tag_1.name, tag_2.name],
- },
- ).validate,
- ).to eq({})
- end
-
- it "returns no errors when the optional tag list is missing" do
- schema = { name: "section", properties: { tags_property: { type: "tags" } } }
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
-
- it "returns errors when the required tag list is missing" do
- schema = {
- name: "section",
- properties: {
- tags_property: {
- type: "tags",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/tags_property"])
- expect(errors["/tags_property"].full_messages).to contain_exactly("must be present")
- end
-
- it "returns errors when the tag value is not an array" do
- schema = { name: "section", properties: { tags_property: { type: "tags" } } }
-
- errors = described_class.new(schema: schema, object: { tags_property: "string" }).validate
-
- expect(errors.keys).to eq(["/tags_property"])
-
- expect(errors["/tags_property"].full_messages).to contain_exactly(
- "must be an array of valid tag names",
- )
- end
-
- it "returns errors when the tag count fails range validation" do
- schema = {
- name: "section",
- properties: {
- tags_property: {
- type: "tags",
- validations: {
- min: 1,
- max: 2,
- },
- },
- },
- }
-
- errors = described_class.new(schema: schema, object: { tags_property: [] }).validate
-
- expect(errors.keys).to eq(["/tags_property"])
-
- expect(errors["/tags_property"].full_messages).to contain_exactly(
- "must have at least 1 tag name",
- )
-
- errors =
- described_class.new(
- schema: schema,
- object: {
- tags_property: [tag_1.name, tag_2.name, tag_3.name],
- },
- ).validate
-
- expect(errors.keys).to eq(["/tags_property"])
-
- expect(errors["/tags_property"].full_messages).to contain_exactly(
- "must have at most 2 tag names",
- )
- end
-
- it "returns errors when the list contains invalid tag names" do
- schema = {
- name: "section",
- properties: {
- tags_property: {
- type: "tags",
- },
- child_tags: {
- type: "objects",
- schema: {
- name: "child_tag",
- properties: {
- tags_property_2: {
- type: "tags",
- },
- },
- },
- },
- },
- }
-
- tag_1
-
- queries =
- track_sql_queries do
- errors =
- described_class.new(
- schema:,
- object: {
- tags_property: ["some random tag name", tag_1.name],
- child_tags: [{ tags_property_2: ["some random tag name", tag_1.name, "abcdef"] }],
- },
- ).validate
-
- expect(errors.keys).to eq(%w[/tags_property /child_tags/0/tags_property_2])
-
- expect(errors["/tags_property"].full_messages).to contain_exactly(
- "must be an array of valid tag names",
- )
-
- expect(errors["/child_tags/0/tags_property_2"].full_messages).to contain_exactly(
- "must be an array of valid tag names",
- )
- end
-
- # only 1 SQL query should be executed to check if tag ids are valid
- expect(queries.length).to eq(1)
- end
- end
-
- context "for groups properties" do
- it "returns no errors for valid group IDs" do
- group = Fabricate(:group)
-
- schema = { name: "section", properties: { groups_property: { type: "groups" } } }
-
- expect(
- described_class.new(schema: schema, object: { groups_property: [group.id] }).validate,
- ).to eq({})
- end
-
- it "returns no errors when the optional group list is missing" do
- schema = { name: "section", properties: { groups_property: { type: "groups" } } }
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
-
- it "returns errors when the required group list is missing" do
- schema = {
- name: "section",
- properties: {
- groups_property: {
- type: "groups",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/groups_property"])
- expect(errors["/groups_property"].full_messages).to contain_exactly("must be present")
- end
-
- it "returns errors when the group value is not an array of valid IDs" do
- schema = { name: "section", properties: { groups_property: { type: "groups" } } }
-
- errors = described_class.new(schema: schema, object: { groups_property: "string" }).validate
-
- expect(errors.keys).to eq(["/groups_property"])
-
- expect(errors["/groups_property"].full_messages).to contain_exactly(
- "must be an array of valid group ids",
- )
- end
-
- it "returns errors when the group count fails range validation" do
- group_1 = Fabricate(:group)
- group_2 = Fabricate(:group)
- group_3 = Fabricate(:group)
-
- schema = {
- name: "section",
- properties: {
- group_property: {
- type: "groups",
- validations: {
- min: 1,
- max: 2,
- },
- },
- },
- }
-
- errors = described_class.new(schema: schema, object: { group_property: [] }).validate
-
- expect(errors.keys).to eq(["/group_property"])
-
- expect(errors["/group_property"].full_messages).to contain_exactly(
- "must have at least 1 group id",
- )
-
- errors =
- described_class.new(
- schema: schema,
- object: {
- group_property: [group_1.id, group_2.id, group_3.id],
- },
- ).validate
-
- expect(errors.keys).to eq(["/group_property"])
-
- expect(errors["/group_property"].full_messages).to contain_exactly(
- "must have at most 2 group ids",
- )
- end
-
- it "returns errors when the list contains invalid group IDs" do
- schema = {
- name: "section",
- properties: {
- groups_property: {
- type: "groups",
- },
- child_groups: {
- type: "objects",
- schema: {
- name: "child_group",
- properties: {
- groups_property_2: {
- type: "groups",
- },
- },
- },
- },
- },
- }
-
- queries =
- track_sql_queries do
- errors =
- described_class.new(
- schema:,
- object: {
- groups_property: [99_999_999],
- child_groups: [{ groups_property_2: [99_999_999] }],
- },
- ).validate
-
- expect(errors.keys).to eq(%w[/groups_property /child_groups/0/groups_property_2])
-
- expect(errors["/groups_property"].full_messages).to contain_exactly(
- "must be an array of valid group ids",
- )
-
- expect(errors["/child_groups/0/groups_property_2"].full_messages).to contain_exactly(
- "must be an array of valid group ids",
- )
- end
-
- # only 1 SQL query should be executed to check if group ids are valid
- expect(queries.length).to eq(1)
- end
- end
-
- context "for post properties" do
- it "returns no errors for a valid post ID" do
- post = Fabricate(:post)
-
- schema = { name: "section", properties: { post_property: { type: "post" } } }
-
- expect(
- described_class.new(schema: schema, object: { post_property: post.id }).validate,
- ).to eq({})
- end
-
- it "returns no errors when the optional post ID is missing" do
- schema = { name: "section", properties: { post_property: { type: "post" } } }
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
-
- it "returns errors when the required post ID is missing" do
- schema = {
- name: "section",
- properties: {
- post_property: {
- type: "post",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/post_property"])
- expect(errors["/post_property"].full_messages).to contain_exactly("must be present")
- end
-
- it "returns errors when the post ID is not an integer" do
- schema = { name: "section", properties: { post_property: { type: "post" } } }
-
- errors = described_class.new(schema: schema, object: { post_property: "string" }).validate
-
- expect(errors.keys).to eq(["/post_property"])
-
- expect(errors["/post_property"].full_messages).to contain_exactly("must be a valid post id")
- end
-
- it "returns errors for an unknown post ID" do
- schema = {
- name: "section",
- properties: {
- post_property: {
- type: "post",
- },
- child_posts: {
- type: "objects",
- schema: {
- name: "child_post",
- properties: {
- post_property_2: {
- type: "post",
- },
- },
- },
- },
- },
- }
-
- queries =
- track_sql_queries do
- errors =
- described_class.new(
- schema:,
- object: {
- post_property: 99_999_999,
- child_posts: [{ post_property_2: 99_999_999 }],
- },
- ).validate
-
- expect(errors.keys).to eq(%w[/post_property /child_posts/0/post_property_2])
-
- expect(errors["/post_property"].full_messages).to contain_exactly(
- "must be a valid post id",
- )
-
- expect(errors["/child_posts/0/post_property_2"].full_messages).to contain_exactly(
- "must be a valid post id",
- )
- end
-
- # only 1 SQL query should be executed to check if post ids are valid
- expect(queries.length).to eq(1)
- end
- end
-
- context "for categories properties" do
- fab!(:category_1, :category)
- fab!(:category_2, :category)
-
- it "returns no errors for valid category IDs" do
- schema = { name: "section", properties: { category_property: { type: "categories" } } }
-
- expect(
- described_class.new(
- schema: schema,
- object: {
- category_property: [category_1.id, category_2.id],
- },
- ).validate,
- ).to eq({})
- end
-
- it "returns no errors when the optional category list is missing" do
- schema = { name: "section", properties: { category_property: { type: "categories" } } }
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
-
- it "returns errors when the required category list is empty" do
- schema = {
- name: "section",
- properties: {
- category_property: {
- type: "categories",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: { category_property: [] }).validate
-
- expect(errors.keys).to eq(["/category_property"])
- expect(errors["/category_property"].full_messages).to contain_exactly("must be present")
- end
-
- it "returns errors when the required category list is missing" do
- schema = {
- name: "section",
- properties: {
- category_property: {
- type: "categories",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/category_property"])
- expect(errors["/category_property"].full_messages).to contain_exactly("must be present")
- end
-
- it "returns errors when the category list contains non-integers" do
- schema = { name: "section", properties: { category_property: { type: "categories" } } }
-
- errors =
- described_class.new(schema: schema, object: { category_property: ["string"] }).validate
-
- expect(errors.keys).to eq(["/category_property"])
-
- expect(errors["/category_property"].full_messages).to contain_exactly(
- "must be an array of valid category ids",
- )
- end
-
- it "returns errors when the category count fails range validation" do
- schema = {
- name: "section",
- properties: {
- category_property: {
- type: "categories",
- validations: {
- min: 1,
- max: 2,
- },
- },
- },
- }
-
- errors = described_class.new(schema: schema, object: { category_property: [] }).validate
-
- expect(errors.keys).to eq(["/category_property"])
-
- expect(errors["/category_property"].full_messages).to contain_exactly(
- "must have at least 1 category id",
- )
- end
-
- it "returns errors when the category list contains invalid IDs" do
- schema = {
- name: "section",
- properties: {
- category_property: {
- type: "categories",
- },
- category_property_2: {
- type: "categories",
- },
- child_categories: {
- type: "objects",
- schema: {
- name: "child_category",
- properties: {
- category_property_3: {
- type: "categories",
- },
- },
- },
- },
- },
- }
-
- object = {
- category_property: [99_999_999, category_1.id],
- category_property_2: [99_999_999],
- child_categories: [
- { category_property_3: [99_999_999, category_2.id] },
- { category_property_3: [category_2.id] },
- ],
- }
-
- queries =
- track_sql_queries do
- errors = described_class.new(schema:, object:).validate
-
- expect(errors.keys).to eq(
- %w[/category_property /category_property_2 /child_categories/0/category_property_3],
- )
-
- expect(errors["/category_property"].full_messages).to contain_exactly(
- "must be an array of valid category ids",
- )
-
- expect(errors["/category_property_2"].full_messages).to contain_exactly(
- "must be an array of valid category ids",
- )
-
- expect(
- errors["/child_categories/0/category_property_3"].full_messages,
- ).to contain_exactly("must be an array of valid category ids")
- end
-
- # only 1 SQL query should be executed to check if category ids are valid
expect(queries.length).to eq(1)
end
end
context "for datetime properties" do
- let(:schema) { { name: "section", properties: { datetime_property: { type: "datetime" } } } }
-
- it "returns no errors for a valid UTC datetime" do
- expect(
- described_class.new(
- schema: schema,
- object: {
- datetime_property: "2024-12-29T15:30:00Z",
- },
- ).validate,
- ).to eq({})
-
- expect(
- described_class.new(
- schema: schema,
- object: {
- datetime_property: "2024-12-29T15:30:00.000Z",
- },
- ).validate,
- ).to eq({})
- end
-
- it "returns no errors for an ISO 8601 datetime with a timezone offset" do
- expect(
- described_class.new(
- schema: schema,
- object: {
- datetime_property: "2024-12-29T15:30:00+05:30",
- },
- ).validate,
- ).to eq({})
- end
-
- it "returns no errors when the optional datetime is missing" do
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
+ let(:schema) { schema_with(:datetime_property, type: "datetime") }
- it "returns no errors when the optional datetime is blank" do
- expect(
- described_class.new(schema: schema, object: { datetime_property: "" }).validate,
- ).to eq({})
- end
-
- it "returns errors when the required datetime is missing" do
- schema = {
- name: "section",
- properties: {
- datetime_property: {
- type: "datetime",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/datetime_property"])
- expect(errors["/datetime_property"].full_messages).to contain_exactly("must be present")
+ it "returns no errors for an ISO 8601 datetime with a timezone" do
+ %w[2024-12-29T15:30:00Z 2024-12-29T15:30:00.000Z 2024-12-29T15:30:00+05:30].each do |value|
+ expect(errors_for(schema, { datetime_property: value })).to eq({})
+ end
end
it "returns errors for an invalid datetime" do
- errors =
- described_class.new(
- schema: schema,
- object: {
- datetime_property: "not a datetime",
- },
- ).validate
-
- expect(errors.keys).to eq(["/datetime_property"])
- expect(errors["/datetime_property"].full_messages).to contain_exactly(
- "must be a valid datetime",
- )
- end
-
- it "returns errors for a date-only string" do
- errors =
- described_class.new(schema: schema, object: { datetime_property: "2024-12-29" }).validate
-
- expect(errors.keys).to eq(["/datetime_property"])
- expect(errors["/datetime_property"].full_messages).to contain_exactly(
- "must be a valid datetime",
- )
- end
-
- it "returns errors for a datetime without a timezone" do
- errors =
- described_class.new(
- schema: schema,
- object: {
- datetime_property: "2024-12-29T15:30:00",
- },
- ).validate
-
- expect(errors.keys).to eq(["/datetime_property"])
- expect(errors["/datetime_property"].full_messages).to contain_exactly(
- "must be a valid datetime",
- )
- end
-
- it "returns errors when the datetime is not a string" do
- errors = described_class.new(schema: schema, object: { datetime_property: 123 }).validate
-
- expect(errors.keys).to eq(["/datetime_property"])
- expect(errors["/datetime_property"].full_messages).to contain_exactly(
- "must be a valid datetime",
- )
+ ["not a datetime", "2024-12-29", "2024-12-29T15:30:00", 123].each do |value|
+ expect(errors_for(schema, { datetime_property: value })).to eq(
+ "/datetime_property" => ["must be a valid datetime"],
+ )
+ end
end
end
context "for icon properties" do
- let(:schema) { { name: "section", properties: { icon_property: { type: "icon" } } } }
+ let(:schema) { schema_with(:icon_property, type: "icon") }
it "returns no errors for an icon string" do
- expect(
- described_class.new(schema: schema, object: { icon_property: "heart" }).validate,
- ).to eq({})
- end
-
- it "returns no errors when the optional icon is missing" do
- expect(described_class.new(schema: schema, object: {}).validate).to eq({})
- end
-
- it "returns errors when the required icon is missing" do
- schema = {
- name: "section",
- properties: {
- icon_property: {
- type: "icon",
- required: true,
- },
- },
- }
- errors = described_class.new(schema: schema, object: {}).validate
-
- expect(errors.keys).to eq(["/icon_property"])
- expect(errors["/icon_property"].full_messages).to contain_exactly("must be present")
+ expect(errors_for(schema, { icon_property: "heart" })).to eq({})
end
it "returns errors for an invalid icon" do
- errors = described_class.new(schema: schema, object: { icon_property: 1 }).validate
-
- expect(errors.keys).to eq(["/icon_property"])
- expect(errors["/icon_property"].full_messages).to contain_exactly("must be an icon name")
+ expect(errors_for(schema, { icon_property: 1 })).to eq(
+ "/icon_property" => ["must be an icon name"],
+ )
end
end
end
diff --git a/spec/system/admin_editing_objects_typed_theme_setting_spec.rb b/spec/system/admin_editing_objects_typed_theme_setting_spec.rb
index 03c5b362d45..752f59cbe07 100644
--- a/spec/system/admin_editing_objects_typed_theme_setting_spec.rb
+++ b/spec/system/admin_editing_objects_typed_theme_setting_spec.rb
@@ -9,28 +9,23 @@ RSpec.describe "Admin editing objects type" do
describe "when editing a theme setting of objects type" do
fab!(:theme)
- let(:objects_setting) do
+ let(:admin_customize_themes_page) { PageObjects::Pages::AdminCustomizeThemes.new }
+
+ before do
theme.set_field(
target: :settings,
name: "yaml",
- value:
- File.read("#{Rails.root.join("spec/fixtures/theme_settings/objects_settings.yaml")}"),
+ value: File.read(Rails.root.join("spec/fixtures/theme_settings/objects_settings.yaml")),
)
theme.save!
- theme.settings[:objects_setting]
end
- let(:admin_customize_themes_page) { PageObjects::Pages::AdminCustomizeThemes.new }
-
- before { objects_setting }
-
it "displays property labels and descriptions from the locale file" do
theme.set_field(
target: :translations,
name: "en",
- value:
- File.read("#{Rails.root.join("spec/fixtures/theme_locales/objects_settings/en.yaml")}"),
+ value: File.read(Rails.root.join("spec/fixtures/theme_locales/objects_settings/en.yaml")),
)
theme.save!
@@ -100,12 +95,8 @@ RSpec.describe "Admin editing objects type" do
end
it "displays the validation errors when an admin tries to save the setting with an invalid value" do
- visit("/admin/customize/themes/#{theme.id}")
-
- admin_objects_theme_setting_editor =
- admin_customize_themes_page.click_edit_objects_setting_button("objects_setting")
-
- admin_objects_theme_setting_editor
+ admin_objects_setting_editor_page
+ .visit_theme(theme, "objects_setting")
.fill_in_field("name", "")
.click_link("section 2")
.fill_in_field("name", "")
@@ -118,43 +109,27 @@ RSpec.describe "Admin editing objects type" do
)
end
- it "allows an admin to pick an icon for an icon type property" do
- SiteSetting.svg_icon_subset = "gamepad"
-
+ it "allows an admin to type a decimal into a float property" do
theme.set_field(target: :settings, name: "yaml", value: <<~YAML)
- links_setting:
+ ratios:
type: objects
default:
- - title: link
- icon: heart
+ - {}
schema:
- name: link
+ name: ratio
properties:
- title:
- type: string
- icon:
- type: icon
+ ratio:
+ type: float
YAML
theme.save!
- visit("/admin/customize/themes/#{theme.id}")
-
- admin_objects_theme_setting_editor =
- admin_customize_themes_page.click_edit_objects_setting_button("links_setting")
-
- icon_picker = PageObjects::Components::DIconGridPicker.new(".schema-field[data-name='icon']")
-
- expect(icon_picker).to have_selected_icon("heart")
-
- icon_picker.expand
- icon_picker.filter("gamepad")
- icon_picker.select_icon("gamepad")
-
- admin_objects_theme_setting_editor.save
+ admin_objects_setting_editor_page
+ .visit_theme(theme, "ratios")
+ .type_in_field("ratio", "7.5")
+ .save
- expect(theme.reload.settings[:links_setting].value).to eq(
- [{ "title" => "link", "icon" => "gamepad" }],
- )
+ expect(page).to have_current_path("/admin/customize/themes/#{theme.id}")
+ expect(theme.reload.settings[:ratios].value).to eq([{ "ratio" => 7.5 }])
end
it "allows an admin to edit a theme setting of objects type via the settings editor" do
diff --git a/spec/system/page_objects/pages/admin_objects_setting_editor.rb b/spec/system/page_objects/pages/admin_objects_setting_editor.rb
index 3fd2ca9e4c2..1ccefc81152 100644
--- a/spec/system/page_objects/pages/admin_objects_setting_editor.rb
+++ b/spec/system/page_objects/pages/admin_objects_setting_editor.rb
@@ -43,6 +43,11 @@ module PageObjects
self
end
+ def type_in_field(field_name, value)
+ input_field(field_name).send_keys(value)
+ self
+ end
+
def add_object_in_root
find(".schema-setting-editor__tree-add-button.--root").click
self