Skip to content

Commit

Permalink
feat: replace HTML validation attrs with soft validation
Browse files Browse the repository at this point in the history
We mustn't prevent form submission, but we still want to give some feedback to the user.

Closes #57
  • Loading branch information
MHajoha authored and MartinGauk committed Sep 27, 2023
1 parent 26854ee commit 240eaed
Show file tree
Hide file tree
Showing 12 changed files with 335 additions and 36 deletions.
3 changes: 3 additions & 0 deletions amd/build/view_question.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions amd/build/view_question.min.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

146 changes: 146 additions & 0 deletions amd/src/view_question.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
* This file is part of the QuestionPy Moodle plugin - https://questionpy.org
*
* Moodle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Moodle is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Moodle. If not, see <http://www.gnu.org/licenses/>.
*/

import $ from "jquery";
import "theme_boost/bootstrap/popover";

/**
* If the given input(-like) element is labelled, returns the label element. Returns null otherwise.
*
* @param {HTMLElement} input
* @return {HTMLLabelElement | null}
* @see {@link https://html.spec.whatwg.org/multipage/forms.html#the-label-element}
*/
function getLabelFor(input) {
// A label can reference its labeled control in its for attribute.
const id = input.id;
if (id !== "") {
const label = document.querySelector(`label[for='${id}']`);
if (label) {
return label;
}
}

// Or the labeled control can be a descendant of the label.
const label = input.closest("label");
if (label) {
return label;
}

return null;
}

/**
* Marks the given input element as invalid.
*
* @param {HTMLElement} element
* @param {string} message validation message to show
* @param {boolean} ariaInvalid
*/
function markInvalid(element, message, ariaInvalid = true) {
element.classList.add("is-invalid");
if (ariaInvalid) {
element.setAttribute("aria-invalid", "true");
} else {
element.removeAttribute("aria-invalid");
}

let popoverTarget = element;
if (element.type === "checkbox" || element.type === "radio") {
// Checkboxes and radios make for a very small hit area for the popover, so we attach the popover to the label.
const label = getLabelFor(element);
if (!label) {
// No label -> Add the popover just to the checkbox.
popoverTarget = element;
} else if (label.contains(element)) {
// Label contains checkbox -> Add the popover just to the label.
popoverTarget = label;
} else {
// Separate label and checkbox -> Add the popover to both.
popoverTarget = [element, label];
}
}

$(popoverTarget).popover({
toggle: "popover",
trigger: "hover",
content: message
});
}

/**
* Undoes what {@link markInvalid} did.
*
* @param {HTMLInputElement} element
*/
function unmarkInvalid(element) {
element.classList.remove("is-invalid");
element.removeAttribute("aria-invalid");

$([element, getLabelFor(element)]).popover("dispose");
}

/**
* Softly (i.e. without preventing form submission) validates constraints on the given element.
*
* @param {HTMLInputElement} element
*/
async function checkConstraints(element) {
/* Our goal here is to show helpful localised validation messages without actually preventing form submission.
One way to achieve this would be to add the attribute "novalidate" to the form element, but that might interfere
with other questions (since they share the same form).
We also don't want to reimplement the validation logic already implemented by browsers.
Instead, the standard validation attributes are added, their validity checked, the message used to create a
popover, and the attributes removed. */
try {
if ("qpy_required" in element.dataset) {
element.setAttribute("required", "required");
}
for (const attr of ["pattern", "minlength", "maxlength", "min", "max"]) {
if (`qpy_${attr}` in element.dataset) {
element.setAttribute(attr, element.dataset[`qpy_${attr}`]);
}
}

const isValid = element.checkValidity();
if (isValid) {
unmarkInvalid(element);
} else {
// Aria-invalid shouldn't be set for missing inputs until the user has tried to submit them.
// https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-invalid
markInvalid(element, element.validationMessage, !element.validity.valueMissing);
}
} finally {
for (const attr of ["required", "pattern", "minlength", "maxlength", "min", "max"]) {
element.removeAttribute(attr);
}
}
}

/**
* Adds change event handlers for soft validation.
*/
export async function init() {
for (const element of document.querySelectorAll(`
[data-qpy_required], [data-qpy_pattern],
[data-qpy_minlength], [data-qpy_maxlength],
[data-qpy_min], [data-qpy_max]
`)) {
await checkConstraints(element);
element.addEventListener("change", event => checkConstraints(event.target));
}
}
12 changes: 11 additions & 1 deletion classes/question_metadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,25 @@ class question_metadata {
*/
public array $expecteddata = [];

/**
* @var string[] an array of required field names
* @see \question_manually_gradable::is_complete_response()
* @see \question_manually_gradable::is_gradable_response()
*/
public array $requiredfields = [];

/**
* Initializes a new instance.
*
* @param array|null $correctresponse if known, an array of `name => correct_value` entries for the expected
* response fields
* @param array $expecteddata an array of `name => PARAM_X` entries for the expected response fields
* @param string[] $requiredfields an array of required field names
*/
public function __construct(?array $correctresponse = null, array $expecteddata = []) {
public function __construct(?array $correctresponse = null, array $expecteddata = [],
array $requiredfields = []) {
$this->correctresponse = $correctresponse;
$this->expecteddata = $expecteddata;
$this->requiredfields = $requiredfields;
}
}
55 changes: 55 additions & 0 deletions classes/question_ui_renderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@ public function get_metadata(): question_metadata {
$name = $element->getAttribute("name");
if ($name) {
$this->metadata->expecteddata[$name] = PARAM_RAW;

if ($element->hasAttribute("required")) {
$this->metadata->requiredfields[] = $name;
}
}
}
}
Expand Down Expand Up @@ -215,6 +219,7 @@ private function render_part(DOMNode $part, question_attempt $qa, ?question_disp
try {
$this->hide_unwanted_feedback($xpath, $options);
$this->set_input_values_and_readonly($xpath, $qa, $options);
$this->soften_validation($xpath);
$this->shuffle_contents($xpath);
$this->add_styles($xpath);
$this->mangle_ids_and_names($xpath, $qa);
Expand Down Expand Up @@ -451,6 +456,56 @@ private function resolve_placeholders(DOMXPath $xpath): void {
}
}

/**
* Replaces the HTML attributes `pattern`, `required`, `minlength`, `maxlength` so that submission is not prevented.
*
* The standard attributes are replaced with `data-qpy_X`, which are then evaluated in JS.
* Ideally we'd also want to handle min and max here, but their evaluation in JS would be quite complicated.
*
* @param DOMXPath $xpath
* @return void
*/
private function soften_validation(DOMXPath $xpath): void {
/** @var DOMElement $element */
foreach ($xpath->query("//xhtml:input[@pattern]") as $element) {
$pattern = $element->getAttribute("pattern");
$element->removeAttribute("pattern");
$element->setAttribute("data-qpy_pattern", $pattern);
}

foreach ($xpath->query("(//xhtml:input | //xhtml:select | //xhtml:textarea)[@required]") as $element) {
$element->removeAttribute("required");
$element->setAttribute("data-qpy_required", "data-qpy_required");
$element->setAttribute("aria-required", "true");
}

foreach ($xpath->query("(//xhtml:input | //xhtml:textarea)[@minlength]") as $element) {
$minlength = $element->getAttribute("minlength");
$element->removeAttribute("minlength");
$element->setAttribute("data-qpy_minlength", $minlength);
}

foreach ($xpath->query("(//xhtml:input | //xhtml:textarea)[@maxlength]") as $element) {
$maxlength = $element->getAttribute("maxlength");
$element->removeAttribute("maxlength");
$element->setAttribute("data-qpy_maxlength", $maxlength);
}

foreach ($xpath->query("//xhtml:input[@min]") as $element) {
$min = $element->getAttribute("min");
$element->removeAttribute("min");
$element->setAttribute("data-qpy_min", $min);
$element->setAttribute("aria-valuemin", $min);
}

foreach ($xpath->query("//xhtml:input[@max]") as $element) {
$max = $element->getAttribute("max");
$element->removeAttribute("max");
$element->setAttribute("data-qpy_max", $max);
$element->setAttribute("aria-valuemax", $max);
}
}

/**
* Adds CSS classes to various elements to style them similarly to Moodle's own question types.
*
Expand Down
Loading

0 comments on commit 240eaed

Please sign in to comment.