Improve code quality and add better input titles

This commit is contained in:
Florine W. Dekker 2020-01-25 17:01:32 +01:00
parent b475b9769e
commit 12986425ef
Signed by untrusted user: FWDekker
GPG Key ID: B1B567AF58D6EE0F
1 changed files with 95 additions and 75 deletions

View File

@ -54,28 +54,17 @@
<!-- Input --> <!-- Input -->
<section class="container"> <section class="container">
<form> <form>
<label for="century" id="century-label">Century</label> <label for="century-input" id="century-title-label">Century</label>
<input type="text" id="century" autocomplete="off" autofocus /> <!--list="weekdays"--> <input type="text" id="century-input" autocomplete="off" autofocus />
<span class="invisible error-message" id="century-error">Error message</span> <span class="error-message invisible" id="century-error-label"></span>
<label for="year" id="year-label">Year</label> <label for="year-input" id="year-title-label">Year</label>
<input type="text" id="year" autocomplete="off" /> <input type="text" id="year-input" autocomplete="off" />
<span class="invisible error-message" id="year-error">Error message</span> <span class="error-message invisible" id="year-error-label"></span>
<label for="day" id="day-label">Day</label> <label for="day-input" id="day-title-label">Day</label>
<input type="text" id="day" autocomplete="off" /> <input type="text" id="day-input" autocomplete="off" />
<span class="invisible error-message" id="day-error">Error message</span> <span class="error-message invisible" id="day-error-label"></span>
<!-- <datalist id="weekdays">-->
<!-- <option value="Monday">-->
<!-- <option value="Tuesday">-->
<!-- <option value="Wednesday">-->
<!-- <option value="Thursday">-->
<!-- <option value="Friday">-->
<!-- <option value="Saturday">-->
<!-- <option value="Sunday">-->
<!-- </datalist>-->
</form> </form>
</section> </section>
@ -102,43 +91,41 @@
* @param max the upper bound of permissible values * @param max the upper bound of permissible values
*/ */
function generateRandom(min, max) { function generateRandom(min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min); return Math.floor(Math.random() * (max - min + 1) + min);
} }
/** /**
* An element that can be validated. * An input that can be validated.
* *
* In particular, the century, year, and day inputs of the Doomsday test. * In particular, the century, year, and day inputs of the Doomsday test.
*/ */
class ValidatableElement { class ValidatableInput {
/** /**
* Constructs a new validatable element and registers event listeners. * Constructs a new validatable input and registers event listeners.
* *
* @param element the element that is validatable * @param input the input that is validatable
* @param titleLabel the label with the `labelFor` property for the element given as the first parameter * @param titleLabel the label with the `labelFor` property for the input given as the first parameter
* @param errorLabel the label to display errors in * @param errorLabel the label to display errors in
*/ */
constructor(element, titleLabel, errorLabel) { constructor(input, titleLabel, errorLabel) {
this.element = element; this.input = input;
this.titleLabel = titleLabel; this.titleLabel = titleLabel;
this.errorLabel = errorLabel; this.errorLabel = errorLabel;
this.element.addEventListener("keydown", event => { this.input.addEventListener("keydown", event => {
if (event.key !== "Enter") if (event.key !== "Enter")
return; return;
this.element.dataset["entered"] = "true"; this.input.dataset["entered"] = "true";
const errorMessage = this.validate(this.element.value); const errorMessage = this.validate(this.input.value);
this.element.setCustomValidity(errorMessage || "");
this.errorLabel.innerText = errorMessage || "";
if (errorMessage === null) { if (errorMessage === null) {
this.errorLabel.classList.add("invisible"); this.hideError();
this.onValidInput(); this.onValidInput();
} else { } else {
this.errorLabel.classList.remove("invisible"); this.showError(errorMessage);
this.element.select(); this.selectInput();
this.onInvalidInput(); this.onInvalidInput();
} }
}); });
@ -146,11 +133,11 @@
/** /**
* Returns `undefined` if the element is valid, or an error message explaining why it is invalid otherwise. * Returns `null` if the input is valid, or an error message explaining why it is invalid otherwise.
* *
* This method **must** be implemented by subclasses. * This method **must** be implemented by subclasses.
* *
* @param value the value of the element to validate * @param value the value of the input to validate
*/ */
validate(value) { validate(value) {
throw new Error("Implement this method."); throw new Error("Implement this method.");
@ -176,31 +163,53 @@
/** /**
* Resets the element to its initial state, removing error messages and user input. * Resets the input, title, and error message to their initial state, and removes the value from the input.
*/ */
reset() { reset() {
this.element.dataset["entered"] = "false"; this.input.value = "";
this.element.value = ""; this.input.dataset["entered"] = "false";
this.element.setCustomValidity("");
this.hideError();
this.updateTitle();
}
/**
* Marks the input as invalid and displays an error label with the given message.
*
* @param message the error message to display
*/
showError(message) {
this.input.setCustomValidity(message || "Invalid");
this.errorLabel.classList.remove("invisible");
this.errorLabel.innerText = message;
}
/**
* Marks the input as valid and hides the error label.
*/
hideError() {
this.input.setCustomValidity("");
this.errorLabel.classList.add("invisible"); this.errorLabel.classList.add("invisible");
this.errorLabel.innerText = ""; this.errorLabel.innerText = "";
} }
/** /**
* Focuses the input element. * Updates the title label's contents.
*
* Does nothing by default. Implement this method to make it do something.
*/ */
focus() { updateTitle() {
this.element.select(); // Do nothing
} }
/** /**
* Sets the title above the input. * Focuses the input element.
*
* @param title the title to set
*/ */
setTitle(title) { selectInput() {
this.titleLabel.innerText = title; this.input.select();
} }
} }
@ -218,13 +227,18 @@
} }
/**
* Returns the first year of this `DoomsdayDate`'s century.
*/
getCentury() {
return Math.floor(this.date.getFullYear() / 100) * 100;
}
/** /**
* Returns the day of the week of the anchor of this `DoomsdayDate`'s century as a string. * Returns the day of the week of the anchor of this `DoomsdayDate`'s century as a string.
*/ */
getCenturyAnchorString() { getCenturyAnchorString() {
const yearNumber = this.date.getFullYear(); const centuryAnchorNumber = (5 * (this.getCentury() % 4)) % 7 + 2;
const centuryNumber = Math.floor(yearNumber / 100);
const centuryAnchorNumber = (5 * (centuryNumber % 4)) % 7 + 2;
return DoomsdayDate.dayNumberToString(centuryAnchorNumber); return DoomsdayDate.dayNumberToString(centuryAnchorNumber);
}; };
@ -286,34 +300,41 @@
doAfterLoad(() => { doAfterLoad(() => {
let quizDate; let quizDate;
const centuryClass = new class extends ValidatableElement { const centuryInput = new class extends ValidatableInput {
validate(value) { validate(value) {
return value === quizDate.getCenturyAnchorString() ? null : ""; return value === quizDate.getCenturyAnchorString() ? null : "";
} }
onValidInput() { onValidInput() {
console.log("valid"); yearInput.selectInput();
yearClass.focus();
} }
onInvalidInput() { onInvalidInput() {
// Do nothing // Do nothing
} }
}($("#century"), $("#century-label"), $("#century-error"));
const yearClass = new class extends ValidatableElement { updateTitle() {
this.titleLabel.innerText = `Anchor day of century starting in ${quizDate.getCentury()}?`;
}
}($("#century-input"), $("#century-title-label"), $("#century-error-label"));
const yearInput = new class extends ValidatableInput {
validate(value) { validate(value) {
return value === quizDate.getYearAnchorString() ? null : ""; return value === quizDate.getYearAnchorString() ? null : "";
} }
onValidInput() { onValidInput() {
dayClass.focus(); dayInput.selectInput();
} }
onInvalidInput() { onInvalidInput() {
// Do nothing // Do nothing
} }
}($("#year"), $("#year-label"), $("#year-error"));
const dayClass = new class extends ValidatableElement { updateTitle() {
this.titleLabel.innerText = `Doomsday of year ${quizDate.date.getFullYear()}?`;
}
}($("#year-input"), $("#year-title-label"), $("#year-error-label"));
const dayInput = new class extends ValidatableInput {
validate(value) { validate(value) {
return value === quizDate.getWeekdayString() ? null : ""; return value === quizDate.getWeekdayString() ? null : "";
} }
@ -325,26 +346,25 @@
onInvalidInput() { onInvalidInput() {
// Do nothing // Do nothing
} }
}($("#day"), $("#day-label"), $("#day-error"));
updateTitle() {
this.titleLabel.innerText = `Weekday of ${quizDate.date.toISOString().substr(0, 10)}?`;
}
}($("#day-input"), $("#day-title-label"), $("#day-error-label"));
/**
* Generates a new date for the quiz and resets the inputs to reflect this.
*/
function reloadQuiz() { function reloadQuiz() {
quizDate = DoomsdayDate.random(); quizDate = DoomsdayDate.random();
centuryClass.reset(); centuryInput.reset();
yearClass.reset(); yearInput.reset();
dayClass.reset(); dayInput.reset();
centuryInput.selectInput();
centuryClass.setTitle("" + Math.floor(quizDate.date.getFullYear() / 100) * 100);
yearClass.setTitle("" + quizDate.date.getFullYear());
dayClass.setTitle("" + quizDate.date.toISOString().substr(0, 10));
centuryClass.focus();
// console.log(centuryToAnchor(quizDate));
// console.log(yearToAnchor(quizDate));
// console.log(dateToWeekDay(quizDate));
} }
// Let the fun begin
reloadQuiz(); reloadQuiz();
}); });
</script> </script>