doomsday/index.html

439 lines
14 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Felix W. Dekker" />
<meta name="application-name" content="Converter" />
<meta name="description" content="Converts numbers to and from various bases." />
<meta name="theme-color" content="#0033cc" />
<title>Doomsday | FWDekker</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic"
crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
integrity="sha256-l85OmPOjvil/SOvVt3HnSSjzF1TUMyT9eV0c2BzEGzU=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.min.css"
integrity="sha256-Ro/wP8uUi8LR71kwIdilf78atpu8bTEwrK5ZotZo+Zc=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://static.fwdekker.com/css/milligram-common.css" crossorigin="anonymous" />
<style>
.invisible {
display: none;
}
.success-message {
color: green;
}
.error-message {
color: red;
}
input[data-entered=true]:valid {
border-color: green;
color: green;
}
input[data-entered=true]:invalid {
border-color: red;
color: red;
}
</style>
</head>
<body>
<main class="wrapper">
<!-- Header -->
<header class="header">
<section class="container">
<h1>Doomsday</h1>
<blockquote>
<p><em>
Test your mastery of <a href="https://en.wikipedia.org/wiki/Doomsday_rule">Conway's Doomsday</a>
rule.
</em></p>
</blockquote>
</section>
</header>
<!-- Input -->
<section class="container">
<form>
<p>
<label for="century-input" id="century-title-label">Century</label>
<input type="text" id="century-input" autocomplete="off" autofocus />
<span class="error-message invisible" id="century-error-label"></span>
</p>
<p>
<label for="year-input" id="year-title-label">Year</label>
<input type="text" id="year-input" autocomplete="off" />
<span class="error-message invisible" id="year-error-label"></span>
</p>
<p>
<label for="day-input" id="day-title-label">Day</label>
<input type="text" id="day-input" autocomplete="off" />
<span class="error-message invisible" id="day-error-label"></span>
</p>
</form>
</section>
<!-- Footer -->
<footer class="footer">
<section class="container">
Made by <a href="https://fwdekker.com/">Felix W. Dekker</a>.
Licensed under the
<a href="https://git.fwdekker.com/FWDekker/doomsday/src/branch/master/LICENSE">MIT License</a>.
Source code available on <a href="https://git.fwdekker.com/FWDekker/doomsday/">git</a>.
</section>
</footer>
</main>
<!-- Scripts -->
<script src="https://static.fwdekker.com/js/common.js" crossorigin="anonymous"></script>
<script>
/**
* Returns a number between `min` (inclusive) and `max` (inclusive).
*
* @param min the lower bound of permissible values
* @param max the upper bound of permissible values
*/
function generateRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
/**
* Given an expected value and an actual value, interprets the actual value as a weekday and returns `null` if they
* are equal; returns an empty string if they are not equal; and returns an error message otherwise.
*
* @param expected the weekday that `actual` should be equal to
* @param actual the weekday to compare to `expected`
*/
function compareWeekdays(expected, actual) {
switch (DoomsdayDate.expandDayString(actual)) {
case expected:
return null;
case undefined:
return "Unrecognized day of week.";
default:
return "";
}
}
/**
* An input that can be validated.
*
* In particular, the century, year, and day inputs of the Doomsday test.
*/
class ValidatableInput {
/**
* Constructs a new validatable input and registers event listeners.
*
* @param input the input that is validatable
* @param titleLabel the label with the `labelFor` property for the input given as the first parameter
* @param errorLabel the label to display errors in
*/
constructor(input, titleLabel, errorLabel) {
this.input = input;
this.titleLabel = titleLabel;
this.errorLabel = errorLabel;
this.input.addEventListener("keydown", event => {
if (event.key !== "Enter")
return;
this.input.dataset["entered"] = "true";
const errorMessage = this.validate(this.input.value);
if (errorMessage === null) {
this.showSuccess();
this.onValidInput();
} else {
this.showError(errorMessage);
this.selectInput();
this.onInvalidInput();
}
});
}
/**
* Returns `null` if the input is valid, or an error message explaining why it is invalid otherwise.
*
* This method **must** be implemented by subclasses.
*
* @param value the value of the input to validate
*/
validate(value) {
throw new Error("Implement this method.");
}
/**
* Runs when the user submits a valid input.
*
* This method **must** be implemented by subclasses.
*/
onValidInput() {
throw new Error("Implement this method.");
}
/**
* Runs when a user submits an invalid input.
*
* This method **must** be implemented by subclasses.
*/
onInvalidInput() {
throw new Error("Implement this method.");
}
/**
* Resets the input, title, and error message to their initial state, and removes the value from the input.
*/
reset() {
this.input.value = "";
this.input.dataset["entered"] = "false";
this.showSuccess();
this.titleLabel.classList.remove("success-message");
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.titleLabel.classList.remove("success-message");
this.titleLabel.classList.add("error-message");
this.errorLabel.classList.remove("invisible");
this.errorLabel.innerText = message;
}
/**
* Marks the input as valid and hides the error label.
*/
showSuccess() {
this.input.setCustomValidity("");
this.titleLabel.classList.remove("error-message");
this.titleLabel.classList.add("success-message");
this.errorLabel.classList.add("invisible");
this.errorLabel.innerText = "";
}
/**
* Updates the title label's contents.
*
* Does nothing by default. Implement this method to make it do something.
*/
updateTitle() {
// Do nothing
}
/**
* Focuses the input element.
*/
selectInput() {
this.input.select();
}
}
/**
* A wrapper around the good ol' `Date` class that provides a bunch of useful Doomsday-specific methods.
*/
class DoomsdayDate {
/**
* Wraps a `DoomsdayDate` around the given `Date`.
*
* @param date the `Date` to be wrapped
*/
constructor(date) {
this.date = date;
}
/**
* Returns the number of this `DoomsdayDate`'s century.
*/
getCentury() {
return Math.floor(this.date.getFullYear() / 100);
}
/**
* Returns the day of the week of the anchor of this `DoomsdayDate`'s century as a string.
*/
getCenturyAnchorString() {
const centuryAnchorNumber = (5 * (this.getCentury() % 4)) % 7 + 2;
return DoomsdayDate.dayNumberToString(centuryAnchorNumber);
};
/**
* Returns the day of the week of the anchor day of this `DoomsdayDate`'s year as a string.
*/
getYearAnchorString() {
const anchorDate = new Date(this.date);
anchorDate.setMonth(3); // April
anchorDate.setDate(4); // 4th
return DoomsdayDate.dayNumberToString(anchorDate.getDay());
};
/**
* Returns the day of the week of this `DoomsdayDate` as a string.
*/
getWeekdayString() {
return DoomsdayDate.dayNumberToString(this.date.getDay());
};
/**
* Returns the name of the day given its 0-based index, where 0 is `Sunday`.
*
* @param dayNumber the number of the day, as returned by `Date`'s `#getDay` function.
*/
static dayNumberToString(dayNumber) {
switch (dayNumber % 7) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
};
/**
* Returns the day of the week corresponding to the given string.
*
* This is a convenience method for interpreting (incomplete) user inputs.
*
* @param dayString the day of the week to expand
*/
static expandDayString(dayString) {
dayString = dayString.toLowerCase();
if (dayString.startsWith("m"))
return "Monday";
else if (dayString.startsWith("tu"))
return "Tuesday";
else if (dayString.startsWith("w"))
return "Wednesday";
else if (dayString.startsWith("th"))
return "Thursday";
else if (dayString.startsWith("f"))
return "Friday";
else if (dayString.startsWith("sa"))
return "Saturday";
else if (dayString.startsWith("su"))
return "Sunday";
else
return undefined;
}
/**
* Returns a random date in the range `0001-01-01` (inclusive) to `9999-12-31` (inclusive), wrapped inside a
* `DoomsdayDate` object.
*/
static random() {
// TODO Give custom dates to this method
const minDate = new Date("0001-01-01").getTime() / 86400000;
const maxDate = new Date("9999-12-31").getTime() / 86400000;
return new DoomsdayDate(new Date(generateRandom(minDate, maxDate) * 86400000));
}
}
doAfterLoad(() => {
let quizDate;
const centuryInput = new class extends ValidatableInput {
validate(value) {
return compareWeekdays(quizDate.getCenturyAnchorString(), value);
}
onValidInput() {
this.input.value = DoomsdayDate.expandDayString(this.input.value);
yearInput.selectInput();
}
onInvalidInput() {
// Do nothing
}
updateTitle() {
this.titleLabel.innerText = `Anchor day of century starting in ${quizDate.getCentury() * 100}?`;
}
}($("#century-input"), $("#century-title-label"), $("#century-error-label"));
const yearInput = new class extends ValidatableInput {
validate(value) {
return compareWeekdays(quizDate.getYearAnchorString(), value);
}
onValidInput() {
this.input.value = DoomsdayDate.expandDayString(this.input.value);
dayInput.selectInput();
}
onInvalidInput() {
// Do nothing
}
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) {
return compareWeekdays(quizDate.getWeekdayString(), value);
}
onValidInput() {
this.input.value = DoomsdayDate.expandDayString(this.input.value);
reloadQuiz();
}
onInvalidInput() {
// Do nothing
}
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() {
quizDate = DoomsdayDate.random();
centuryInput.reset();
yearInput.reset();
dayInput.reset();
centuryInput.selectInput();
}
// Let the fun begin
reloadQuiz();
});
</script>
</body>
</html>