Skip to content

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

FIX: Enforce required validation on form template composer fields (#42192)

Renato Atilioc211bcbbd6f8
diff --git a/app/assets/stylesheets/common/components/form-template-field.scss b/app/assets/stylesheets/common/components/form-template-field.scss
index 3e7156fecd2..39fb833a200 100644
--- a/app/assets/stylesheets/common/components/form-template-field.scss
+++ b/app/assets/stylesheets/common/components/form-template-field.scss
@@ -70,7 +70,8 @@
color: var(--primary-medium);
}
- &__upload-hidden-input {
+ &__upload-hidden-input,
+ &__composer-hidden-input {
position: absolute;
opacity: 0;
pointer-events: none;
diff --git a/frontend/discourse/app/components/form-template-field/composer.gjs b/frontend/discourse/app/components/form-template-field/composer.gjs
index e77786610f7..e65072725d6 100644
--- a/frontend/discourse/app/components/form-template-field/composer.gjs
+++ b/frontend/discourse/app/components/form-template-field/composer.gjs
@@ -1,19 +1,27 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
import { action } from "@ember/object";
+import { guidFor } from "@ember/object/internals";
import { next, schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import DEditor from "discourse/ui-kit/d-editor";
import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
export default class FormTemplateFieldComposer extends Component {
@service composer;
@service appEvents;
+ @service a11y;
@tracked composerValue = this.args.value || "";
- _claimAbortController = null;
+ fieldUid = `form-template-composer-${guidFor(this)}`;
+
+ #claimAbortController = null;
+ #editorTarget = null;
+ #validationFailed = false;
constructor() {
super(...arguments);
@@ -23,7 +31,20 @@ export default class FormTemplateFieldComposer extends Component {
willDestroy() {
super.willDestroy(...arguments);
this.appEvents.off("composer:replace-text", this, this.handleReplaceText);
- this._claimAbortController?.abort();
+ this.#claimAbortController?.abort();
+ }
+
+ get labelId() {
+ return `${this.fieldUid}-label`;
+ }
+
+ get validationInputId() {
+ return `${this.fieldUid}-validation`;
+ }
+
+ // mirrors the id the shared form template validation gives the error tip
+ get errorId() {
+ return `${this.validationInputId}-error`;
}
@action
@@ -39,45 +60,105 @@ export default class FormTemplateFieldComposer extends Component {
});
}
+ @action
+ handleInvalid() {
+ this.#validationFailed = true;
+ this.#syncEditorAccessibility();
+
+ this.a11y.announce(
+ i18n("form_templates.errors.value_missing.default"),
+ "assertive"
+ );
+ }
+
+ @action
+ handleValidationInput(event) {
+ if (event.currentTarget.validity.valid) {
+ this.#validationFailed = false;
+ this.#syncEditorAccessibility();
+ }
+ }
+
+ // reapplies the full state rather than toggling it, because switching
+ // between markdown and rich modes replaces the editor element
+ #syncEditorAccessibility() {
+ const editor = this.#editorTarget;
+
+ if (!editor) {
+ return;
+ }
+
+ // the label is only rendered when the template defines one
+ if (this.args.attributes?.label) {
+ editor.setAttribute("aria-labelledby", this.labelId);
+ } else {
+ editor.removeAttribute("aria-labelledby");
+ }
+
+ // the asterisk marking the field required is decorative, and the input
+ // carrying `required` is hidden, so the editor has to state it itself
+ if (this.args.validations?.required) {
+ editor.setAttribute("aria-required", "true");
+ } else {
+ editor.removeAttribute("aria-required");
+ }
+
+ if (this.#validationFailed) {
+ editor.setAttribute("aria-invalid", "true");
+ editor.setAttribute("aria-describedby", this.errorId);
+ } else {
+ editor.removeAttribute("aria-invalid");
+ editor.removeAttribute("aria-describedby");
+ }
+ }
+
@action
handleInput(event) {
this.composerValue = event.target.value;
next(this, () => {
this.args.onChange?.(event);
+ // the editor emits no form events of its own, so the input standing in
+ // for it has to report the change
+ document
+ .getElementById(this.validationInputId)
+ ?.dispatchEvent(new Event("input", { bubbles: true }));
});
}
@action
onEditorSetup(textManipulation) {
+ this.#editorTarget =
+ textManipulation.textarea || textManipulation.view?.dom;
+
+ this.#syncEditorAccessibility();
+
if (!this.args.uppyComposerUpload || !this.composer.allowUpload) {
return;
}
this.args.uppyComposerUpload.textManipulation = textManipulation;
- const editorTarget =
- textManipulation.textarea || textManipulation.view?.dom;
- if (!editorTarget) {
+ if (!this.#editorTarget) {
return;
}
- this._claimAbortController?.abort();
- this._claimAbortController = new AbortController();
- const { signal } = this._claimAbortController;
+ this.#claimAbortController?.abort();
+ this.#claimAbortController = new AbortController();
+ const { signal } = this.#claimAbortController;
const claimUploadTarget = () => {
this.args.uppyComposerUpload.textManipulation = textManipulation;
};
for (const event of ["focusin", "dragenter", "dragover"]) {
- editorTarget.addEventListener(event, claimUploadTarget, { signal });
+ this.#editorTarget.addEventListener(event, claimUploadTarget, { signal });
}
}
<template>
<div class="control-group form-template-field" data-field-type="composer">
{{#if @attributes.label}}
- <label class="form-template-field__label">
+ <label id={{this.labelId}} class="form-template-field__label">
{{@attributes.label}}
{{#if @validations.required}}
{{dIcon "asterisk" class="form-template-field__required-indicator"}}
@@ -90,7 +171,6 @@ export default class FormTemplateFieldComposer extends Component {
{{trustHTML @attributes.description}}
</span>
{{/if}}
- <input type="hidden" name={{@id}} value={{this.composerValue}} />
<DEditor
class="form-template-field__composer"
@value={{this.composerValue}}
@@ -98,6 +178,21 @@ export default class FormTemplateFieldComposer extends Component {
@placeholder={{@attributes.placeholder}}
@onSetup={{this.onEditorSetup}}
/>
+ {{! the editor is not a form control, so this stands in for it to carry the
+ value and native validation. must stay last: the error tip is only
+ inserted after a field with no next sibling }}
+ <input
+ id={{this.validationInputId}}
+ type="text"
+ name={{@id}}
+ value={{this.composerValue}}
+ required={{if @validations.required "required" ""}}
+ class="form-template-field__composer-hidden-input"
+ tabindex="-1"
+ aria-hidden="true"
+ {{on "invalid" this.handleInvalid}}
+ {{on "input" this.handleValidationInput}}
+ />
</div>
</template>
}
diff --git a/frontend/discourse/tests/acceptance/composer-form-template-test.js b/frontend/discourse/tests/acceptance/composer-form-template-test.js
index d8a246976a1..ac2844eff5b 100644
--- a/frontend/discourse/tests/acceptance/composer-form-template-test.js
+++ b/frontend/discourse/tests/acceptance/composer-form-template-test.js
@@ -1,9 +1,19 @@
-import { click, fillIn, settled, visit } from "@ember/test-helpers";
+import {
+ click,
+ currentURL,
+ fillIn,
+ find,
+ settled,
+ visit,
+} from "@ember/test-helpers";
import { test } from "qunit";
+import sinon from "sinon";
import { cloneJSON } from "discourse/lib/object";
import TopicFixtures from "discourse/tests/fixtures/topic";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import selectKit from "discourse/tests/helpers/select-kit-helper";
+import { i18n } from "discourse-i18n";
const FORM_TEMPLATES = [
{
@@ -40,6 +50,34 @@ const FORM_TEMPLATES = [
type: date
`,
},
+ {
+ id: 3,
+ name: "Required Composer Only",
+ template: `
+ - type: composer
+ id: md-description
+ attributes:
+ label: "Description"
+ validations:
+ required: true
+ `,
+ },
+ {
+ id: 4,
+ name: "Required Composer With Other Field",
+ template: `
+ - type: input
+ id: other-field
+ attributes:
+ label: "Other field"
+ - type: composer
+ id: md-description
+ attributes:
+ label: "Description"
+ validations:
+ required: true
+ `,
+ },
];
acceptance("Composer Form Template", function (needs) {
@@ -62,7 +100,7 @@ acceptance("Composer Form Template", function (needs) {
slug: "general",
permission: 1,
topic_template: null,
- form_template_ids: [1, 2],
+ form_template_ids: [1, 2, 3, 4],
},
{
id: 2,
@@ -82,7 +120,7 @@ acceptance("Composer Form Template", function (needs) {
});
});
- [1, 2].forEach((id) => {
+ [1, 2, 3, 4].forEach((id) => {
server.get(`/form-templates/${id}.json`, () => {
const index = id - 1;
@@ -180,4 +218,137 @@ acceptance("Composer Form Template", function (needs) {
.dom(".form-template-field__input[name='activity-date']")
.exists("it renders form template field");
});
+
+ test("blocks topic creation and shows a validation message when a required composer field is left empty", async function (assert) {
+ pretender.post("/posts", () => {
+ assert.true(
+ false,
+ "a topic should not be created while the required field is empty"
+ );
+ return response(200, { success: true });
+ });
+
+ await visit("/");
+
+ const composer = this.owner.lookup("service:composer");
+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");
+
+ await composer.openNewTopic({ formTemplate: FORM_TEMPLATES[2] });
+ await settled();
+
+ await fillIn("#reply-title", "A title that is long enough to be valid");
+ await click("#reply-control button.create");
+
+ assert.strictEqual(currentURL(), "/", "the topic is not created");
+ assert
+ .dom(".form-template-field__error")
+ .exists("a validation error message is shown");
+
+ assert
+ .dom(".d-editor-input")
+ .hasAttribute("aria-invalid", "true", "the editor is marked invalid");
+
+ const describedBy =
+ find(".d-editor-input").getAttribute("aria-describedby");
+ assert
+ .dom(`#${describedBy}`)
+ .hasText(
+ i18n("form_templates.errors.value_missing.default"),
+ "the editor is connected to the visible error"
+ );
+
+ assert.true(
+ announce.calledWith(
+ i18n("form_templates.errors.value_missing.default"),
+ "assertive"
+ ),
+ "the error is announced to screen readers"
+ );
+
+ await fillIn(".d-editor-input", "some content");
+
+ assert
+ .dom(".d-editor-input")
+ .doesNotHaveAttribute("aria-invalid", "the invalid state is cleared");
+ assert
+ .dom(".d-editor-input")
+ .doesNotHaveAttribute(
+ "aria-describedby",
+ "the error reference is cleared"
+ );
+ });
+
+ test("keeps the editor marked invalid after switching editor modes", async function (assert) {
+ await visit("/");
+
+ const composer = this.owner.lookup("service:composer");
+ await composer.openNewTopic({ formTemplate: FORM_TEMPLATES[2] });
+ await settled();
+
+ await fillIn("#reply-title", "A title that is long enough to be valid");
+ await click("#reply-control button.create");
+
+ assert
+ .dom(".d-editor-input")
+ .hasAttribute("aria-invalid", "true", "the editor starts out invalid");
+
+ assert
+ .dom(".d-editor-input")
+ .hasAttribute("aria-required", "true", "the editor starts out required");
+
+ await click(".composer-toggle-switch");
+
+ assert
+ .dom(".d-editor-input")
+ .hasAttribute(
+ "aria-required",
+ "true",
+ "the replacement editor is still marked required"
+ );
+
+ assert
+ .dom(".d-editor-input")
+ .hasAttribute(
+ "aria-invalid",
+ "true",
+ "the replacement editor is still marked invalid"
+ );
+
+ const describedBy =
+ find(".d-editor-input").getAttribute("aria-describedby");
+ assert
+ .dom(`#${describedBy}`)
+ .hasText(
+ i18n("form_templates.errors.value_missing.default"),
+ "the replacement editor is still connected to the visible error"
+ );
+ });
+
+ test("blocks topic creation when a required composer field is empty even if other fields are filled", async function (assert) {
+ pretender.post("/posts", () => {
+ assert.true(
+ false,
+ "a topic should not be created while the required field is empty"
+ );
+ return response(200, { success: true });
+ });
+
+ await visit("/");
+
+ const composer = this.owner.lookup("service:composer");
+ await composer.openNewTopic({ formTemplate: FORM_TEMPLATES[3] });
+ await settled();
+
+ await fillIn("#reply-title", "A title that is long enough to be valid");
+ await fillIn(
+ ".form-template-field__input[name='other-field']",
+ "some content"
+ );
+ await click("#reply-control button.create");
+
+ assert.strictEqual(currentURL(), "/", "the topic is not created");
+ assert
+ .dom(".form-template-field__error")
+ .exists("a validation error message is shown");
+ });
});
diff --git a/frontend/discourse/tests/integration/components/form-template-field/composer-test.gjs b/frontend/discourse/tests/integration/components/form-template-field/composer-test.gjs
index 545e27d3863..303a36bc21d 100644
--- a/frontend/discourse/tests/integration/components/form-template-field/composer-test.gjs
+++ b/frontend/discourse/tests/integration/components/form-template-field/composer-test.gjs
@@ -1,5 +1,12 @@
+import { hash } from "@ember/helper";
import { getOwner } from "@ember/owner";
-import { render, settled, triggerEvent, waitUntil } from "@ember/test-helpers";
+import {
+ find,
+ render,
+ settled,
+ triggerEvent,
+ waitUntil,
+} from "@ember/test-helpers";
import { module, test } from "qunit";
import sinon from "sinon";
import FormComposer from "discourse/components/form-template-field/composer";
@@ -327,6 +334,112 @@ module(
assert.dom(".d-editor-input").hasValue(expected);
});
+ test("marks the backing input as required when the field is required", async function (assert) {
+ stubAllowUpload(this, true);
+
+ await render(
+ <template>
+ <FormComposer
+ @id="field-1"
+ @onChange={{noop}}
+ @validations={{hash required=true}}
+ />
+ </template>
+ );
+
+ assert
+ .dom("input[name='field-1']")
+ .hasAttribute(
+ "required",
+ { any: true },
+ "the backing input is required"
+ );
+ });
+
+ test("does not mark the backing input as required when the field is not required", async function (assert) {
+ stubAllowUpload(this, true);
+
+ await render(
+ <template><FormComposer @id="field-1" @onChange={{noop}} /></template>
+ );
+
+ assert
+ .dom("input[name='field-1']")
+ .doesNotHaveAttribute("required", "the backing input is not required");
+ });
+
+ test("labels the editor with the field label", async function (assert) {
+ stubAllowUpload(this, true);
+
+ await render(
+ <template>
+ <FormComposer
+ @id="field-1"
+ @attributes={{hash label="Description"}}
+ @onChange={{noop}}
+ />
+ </template>
+ );
+
+ const label = find(".form-template-field__label");
+ assert
+ .dom(".d-editor-input")
+ .hasAttribute(
+ "aria-labelledby",
+ label.id,
+ "the editor is labelled by the field label"
+ );
+ });
+
+ test("marks the editor required when the field is required", async function (assert) {
+ stubAllowUpload(this, true);
+
+ await render(
+ <template>
+ <FormComposer
+ @id="field-1"
+ @validations={{hash required=true}}
+ @onChange={{noop}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".d-editor-input")
+ .hasAttribute(
+ "aria-required",
+ "true",
+ "the editor announces that it is required before submitting"
+ );
+ });
+
+ test("does not mark the editor required when the field is optional", async function (assert) {
+ stubAllowUpload(this, true);
+
+ await render(
+ <template><FormComposer @id="field-1" @onChange={{noop}} /></template>
+ );
+
+ assert
+ .dom(".d-editor-input")
+ .doesNotHaveAttribute("aria-required", "the editor is not required");
+ });
+
+ test("does not label the editor when the field has no label", async function (assert) {
+ stubAllowUpload(this, true);
+
+ await render(
+ <template><FormComposer @id="field-1" @onChange={{noop}} /></template>
+ );
+
+ assert
+ .dom(".d-editor-input")
+ .doesNotHaveAttribute(
+ "aria-labelledby",
+ "no dangling reference when the template defines no label"
+ );
+ });
+
test("composer:replace-text is a no-op when the field does not contain the markdown", async function (assert) {
stubAllowUpload(this, true);