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 committed Sep 21, 2023
1 parent c351754 commit 4d42fcc
Show file tree
Hide file tree
Showing 13 changed files with 339 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.

157 changes: 157 additions & 0 deletions amd/src/view_question.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/*
* 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";
import {get_string as getString} from "core/str";

/**
* 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 checkConditions(element) {
if (element.dataset.qpy_required !== undefined) {
let isPresent;
if (element.type === "checkbox" || element.type === "radio") {
isPresent = element.checked;
} else {
isPresent = element.value !== null && element.value !== "";
}

if (!isPresent) {
const message = await getString("input_missing", "qtype_questionpy");
// 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, message, false);
return;
}
}

const pattern = element.dataset.qpy_pattern;
if (pattern !== undefined && element.value !== null && element.value !== ""
&& !element.value.match(`^(?:${pattern})$`)) {
const message = await getString("input_invalid", "qtype_questionpy");
markInvalid(element, message);
return;
}

const minLength = element.dataset.qpy_minlength;
if (minLength !== undefined && element.value !== null && element.value !== ""
&& element.value.length < parseInt(minLength)) {
const message = await getString("input_too_short", "qtype_questionpy", minLength);
markInvalid(element, message);
return;
}

const maxLength = element.dataset.qpy_maxlength;
if (maxLength !== undefined && element.value !== null && element.value !== ""
&& element.value.length > parseInt(maxLength)) {
const message = await getString("input_too_long", "qtype_questionpy", maxLength);
markInvalid(element, message);
return;
}

unmarkInvalid(element);
}

/**
* 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]")) {
await checkConditions(element);
element.addEventListener("change", event => checkConditions(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;
}
}
43 changes: 43 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,44 @@ 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 or @maxlength]") as $element) {
$minlength = $element->getAttribute("minlength");
if ($minlength !== "") {
$element->removeAttribute("minlength");
$element->setAttribute("data-qpy_minlength", $minlength);
}

$maxlength = $element->getAttribute("maxlength");
if ($maxlength !== "") {
$element->removeAttribute("maxlength");
$element->setAttribute("data-qpy_maxlength", $maxlength);
}
}
}

/**
* Adds CSS classes to various elements to style them similarly to Moodle's own question types.
*
Expand Down
6 changes: 6 additions & 0 deletions lang/en/qtype_questionpy.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@
// Question management.
$string['package_not_found'] = 'The requested package {$a->packagehash} does not exist.';

// Question UI.
$string['input_missing'] = 'This field is required.';
$string['input_invalid'] = 'Invalid input.';
$string['input_too_long'] = 'Please enter at most {$a} characters.';
$string['input_too_short'] = 'Please enter at least {$a} characters.';

// Connector.
$string['curl_init_error'] = 'Could not initialize cURL. Error number: {$a}';
$string['curl_exec_error'] = 'Error while fetching from server. Error number: {$a}';
Expand Down
Loading

0 comments on commit 4d42fcc

Please sign in to comment.