Compare commits

..

17 Commits
master ... main

Author SHA1 Message Date
Florine W. Dekker 9eda7eeaf6
Remove exception on invalid input 2022-12-14 11:25:10 +01:00
Florine W. Dekker 3cc6350803
Remove unnecessary warning suppressions 2022-12-06 18:15:06 +01:00
Florine W. Dekker bde4482343
Select next input on closing details element 2022-11-28 07:51:14 +01:00
Florine W. Dekker e7a5f64f60
Upgrade to template v3 2022-11-21 08:27:22 +01:00
Florine W. Dekker a5f3a8793d
Keep footer wide 2022-11-17 14:41:07 +01:00
Florine W. Dekker 1006a852ad
Use very thin page layout 2022-11-17 14:39:19 +01:00
Florine W. Dekker 6fe7e610da
Use new `boxWithInput` element for inputs 2022-11-17 09:45:57 +01:00
Florine W. Dekker 7f61a0cb06
Update Luxon, remove workaround 2022-04-21 09:12:07 +02:00
Florine W. Dekker 667bec2263
Work around issue moment/luxon#1167 2022-03-29 16:20:38 +02:00
Florine W. Dekker 5096c171f6
Empty commit to trigger build 2022-03-16 08:45:49 +01:00
Florine W. Dekker 88348087bd Merge pull request 'Use proper date library' (#14) from dev into master
Reviewed-on: tools/doomsday#14
2022-03-16 08:29:05 +01:00
Florine W. Dekker e1b9092975
Reduce version number
Slightly more in line with semver, since the changes aren't as much as I had expected.
2022-03-16 08:25:54 +01:00
Florine W. Dekker 9b2a1600d5
Use Luxon to manipulate dates 2022-03-15 18:39:49 +01:00
Florine W. Dekker d443fb7c48
Naively rewrite to TypeScript 2022-03-08 20:38:16 +01:00
Florine W. Dekker 70d41cf072
Use local time to calculate weekday
Fixes an issue where a year's doomsday is incorrectly calculated depending on the timezone.
2022-03-02 12:39:17 +01:00
Florine W. Dekker d6060b1a1d
Update repository URL 2022-02-28 17:06:11 +01:00
Florine W. Dekker b3e37a562a
Merge branch 'tfofurn-master' 2021-11-14 01:57:01 +01:00
8 changed files with 232 additions and 266 deletions

View File

@ -16,7 +16,7 @@ module.exports = grunt => {
}, },
focus: { focus: {
dev: { dev: {
include: ["css", "html", "js"], include: ["css", "html", "ts"],
}, },
}, },
replace: { replace: {
@ -50,24 +50,25 @@ module.exports = grunt => {
files: ["src/main/**/*.html"], files: ["src/main/**/*.html"],
tasks: ["copy:html"], tasks: ["copy:html"],
}, },
js: { ts: {
files: ["src/main/**/*.js"], files: ["src/main/**/*.ts"],
tasks: ["webpack:dev", "replace:dev"], tasks: ["webpack:dev", "replace:dev"],
}, },
}, },
webpack: { webpack: {
options: { options: {
entry: "./src/main/js/main.js", entry: "./src/main/js/Main.ts",
module: { module: {
rules: [ rules: [
{ {
test: /\.js$/, test: /\.ts$/,
use: "ts-loader",
exclude: /node_modules/, exclude: /node_modules/,
}, },
], ],
}, },
resolve: { resolve: {
extensions: [".js"], extensions: [".ts"],
}, },
output: { output: {
filename: "bundle.js", filename: "bundle.js",

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2020 F.W. Dekker Copyright (c) 2020 Florine W. Dekker
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

BIN
package-lock.json generated

Binary file not shown.

View File

@ -1,12 +1,12 @@
{ {
"name": "doomsday", "name": "doomsday",
"version": "1.3.17", "version": "1.5.3",
"description": "Test your mastery of Conway's Doomsday rule.", "description": "Test your mastery of Conway's Doomsday rule.",
"author": "F.W. Dekker", "author": "Florine W. Dekker",
"browser": "dist/bundle.js", "browser": "dist/bundle.js",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git@git.fwdekker.com:FWDekker/doomsday.git" "url": "git@git.fwdekker.com:tools/doomsday.git"
}, },
"private": true, "private": true,
"scripts": { "scripts": {
@ -15,16 +15,22 @@
"dev:server": "grunt dev:server", "dev:server": "grunt dev:server",
"deploy": "grunt deploy" "deploy": "grunt deploy"
}, },
"dependencies": {
"luxon": "^3.1.1"
},
"devDependencies": { "devDependencies": {
"grunt": "^1.4.1", "@types/luxon": "^3.1.0",
"grunt": "^1.5.3",
"grunt-cli": "^1.4.3", "grunt-cli": "^1.4.3",
"grunt-contrib-clean": "^2.0.0", "grunt-contrib-clean": "^2.0.1",
"grunt-contrib-copy": "^1.0.0", "grunt-contrib-copy": "^1.0.0",
"grunt-contrib-watch": "^1.1.0", "grunt-contrib-watch": "^1.1.0",
"grunt-focus": "^1.0.0", "grunt-focus": "^1.0.0",
"grunt-text-replace": "^0.4.0", "grunt-text-replace": "^0.4.0",
"grunt-webpack": "^5.0.0", "grunt-webpack": "^5.0.0",
"webpack": "^5.64.0", "ts-loader": "^9.4.2",
"webpack-cli": "^4.9.1" "typescript": "^4.9.4",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
} }
} }

View File

@ -1,51 +1,23 @@
:root { input, button {
--error-color: red; width: unset;
--success-color: green;
} }
.inputs {
.row .column.quiz-button-column {
display: flex; display: flex;
align-items: flex-end;
} }
.row .column.quiz-button-column .quiz-button { .inputs input {
margin-bottom: 15px; flex: 1;
margin-right: 1rem;
} }
label, summary b { details[open] summary,
cursor: pointer; details summary:focus {
/*noinspection CssUnresolvedCustomProperty*/
color: var(--accordion-close-summary-color) !important;
} }
#day-title-label { details:not([open]) summary:not(:focus) {
margin-left: 17px; /*noinspection CssUnresolvedCustomProperty*/
} color: var(--accordion-open-summary-color) !important;
.success-message {
color: var(--success-color);
}
.error-message {
color: var(--error-color);
}
.success-box {
background-color: var(--success-color);
border-color: var(--success-color);
}
.error-box {
background-color: var(--error-color);
border-color: var(--error-color);
}
input[data-entered=true]:valid {
border-color: var(--success-color);
color: var(--success-color);
}
input[data-entered=true]:invalid {
border-color: var(--error-color);
color: var(--error-color);
} }

View File

@ -3,22 +3,28 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="F.W. Dekker" /> <meta name="author" content="Florine W. Dekker" />
<meta name="application-name" content="Doomsday" /> <meta name="application-name" content="Doomsday" />
<meta name="description" content="Test your mastery of Conway's Doomsday rule." /> <meta name="description" content="Test your mastery of Conway's Doomsday rule." />
<meta name="theme-color" content="#0033cc" /> <meta name="theme-color" content="#0033cc" />
<meta name="fwd:nav:target" content="#nav" />
<meta name="fwd:nav:highlight-path" content="/Tools/Doomsday/" />
<meta name="fwd:footer:target" content="#footer" />
<meta name="fwd:footer:vcs-url" content="https://git.fwdekker.com/tools/doomsday/" />
<meta name="fwd:footer:version" content="v%%VERSION_NUMBER%%" />
<meta name="fwd:validation:load-forms" />
<title>Doomsday | FWDekker</title> <title>Doomsday | FWDekker</title>
<link rel="stylesheet" href="https://static.fwdekker.com/fonts/roboto/roboto.css" /> <link rel="stylesheet" href="https://static.fwdekker.com/lib/template/3.x.x/template.css?v=%%VERSION_NUMBER%%" />
<link rel="stylesheet" href="https://static.fwdekker.com/lib/template/2.x.x/template.css" />
<!--suppress HtmlUnknownTarget --> <!--suppress HtmlUnknownTarget -->
<link rel="stylesheet" href="main.css?v=%%VERSION_NUMBER%%" /> <link rel="stylesheet" href="main.css?v=%%VERSION_NUMBER%%" />
<script async src="https://stats.fwdekker.com/count.js" <script async src="https://stats.fwdekker.com/count.js"
data-goatcounter="https://stats.fwdekker.com/count"></script> data-goatcounter="https://stats.fwdekker.com/count"></script>
</head> </head>
<body> <body>
<noscript> <noscript class="fwd-js-notice">
<img src="https://stats.fwdekker.com/count?p=/tools/doomsday/" alt="Counting pixel" /> <img src="https://stats.fwdekker.com/count?p=/tools/doomsday/" alt="Counting pixel" />
<p> <p>
@ -27,66 +33,58 @@
instructions on how to enable JavaScript in your web browser</a>. instructions on how to enable JavaScript in your web browser</a>.
</p> </p>
</noscript> </noscript>
<main class="hidden"> <nav id="nav"></nav>
<div id="nav"></div> <main class="hidden container">
<div id="contents"> <div role="document">
<div id="header"></div> <section>
<header class="fwd-header">
<hgroup>
<h1><a href=".">Doomsday</a></h1>
<h2>
Test your mastery of
<a href="https://en.wikipedia.org/wiki/Doomsday_rule" target="_blank">Conway's Doomsday rule</a>.
</h2>
</hgroup>
</header>
</section>
<!-- Input --> <section>
<section class="container">
<form> <form>
<details open id="century-details"> <details open id="century-details">
<summary><b id="century-title-label">Century</b></summary> <summary><b id="century-title-label" data-label-for="century-input">Century</b></summary>
<div class="row"> <div class="inputs">
<div class="column column-90"> <!--suppress HtmlFormInputWithoutLabel -->
<!--suppress HtmlFormInputWithoutLabel --> <input type="text" id="century-input" class="quiz-input" autocomplete="off" autofocus />
<input type="text" id="century-input" autocomplete="off" autofocus /> <button type="button" id="century-submit" class="quiz-button">Check</button>
</div>
<div class="column column-10 quiz-button-column">
<button type="button" class="quiz-button" id="century-submit">Check</button>
</div>
</div> </div>
</details> </details>
<details open id="year-details"> <details open id="year-details">
<summary><b id="year-title-label">Year</b></summary> <summary><b id="year-title-label" data-label-for="year-input">Year</b></summary>
<div class="row"> <div class="inputs">
<div class="column column-90"> <!--suppress HtmlFormInputWithoutLabel -->
<!--suppress HtmlFormInputWithoutLabel --> <input type="text" id="year-input" class="quiz-input" autocomplete="off" />
<input type="text" id="year-input" autocomplete="off" /> <button type="button" id="year-submit" class="quiz-button">Check</button>
</div>
<div class="column column-10 quiz-button-column">
<button type="button" class="quiz-button" id="year-submit">Check</button>
</div>
</div> </div>
</details> </details>
<div> <details open id="day-details">
<label for="day-input" id="day-title-label">Day</label> <summary><b id="day-title-label" data-label-for="day-input">Day</b></summary>
<div class="row"> <div class="inputs">
<div class="column column-90"> <!--suppress HtmlFormInputWithoutLabel -->
<input type="text" id="day-input" autocomplete="off" /> <input type="text" id="day-input" class="quiz-input" autocomplete="off" />
</div> <button type="button" id="day-submit" class="quiz-button">Check</button>
<div class="column column-10 quiz-button-column">
<button type="button" class="quiz-button" id="day-submit">Check</button>
</div>
</div> </div>
</div> </details>
<div class="row">&#8203;</div> <button type="button" id="reset-button">Reset</button>
<div class="row">
<div class="column">
<button type="button" id="reset-button">Reset</button>
</div>
</div>
</form> </form>
</section> </section>
<footer id="footer"></footer>
</div> </div>
<div id="footer"></div>
</main> </main>
<script src="https://static.fwdekker.com/lib/template/2.x.x/template.js"></script> <script src="https://static.fwdekker.com/lib/template/3.x.x/template.js?v=%%VERSION_NUMBER%%"></script>
<!--suppress HtmlUnknownTarget --> <!--suppress HtmlUnknownTarget -->
<script src="bundle.js?v=%%VERSION_NUMBER%%"></script> <script src="bundle.js?v=%%VERSION_NUMBER%%"></script>
</body> </body>

View File

@ -1,5 +1,7 @@
// noinspection JSUnresolvedVariable const {$, doAfterLoad} = (window as any).fwdekker;
const {$, doAfterLoad, footer, header, nav} = window.fwdekker; const {clearInputValidity, showInputInvalid, showInputValid} = (window as any).fwdekker.validation;
import {DateTime} from "luxon";
/** /**
@ -8,7 +10,7 @@ const {$, doAfterLoad, footer, header, nav} = window.fwdekker;
* @param min the lower bound of permissible values * @param min the lower bound of permissible values
* @param max the upper bound of permissible values * @param max the upper bound of permissible values
*/ */
function generateRandom(min, max) { function generateRandom(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min); return Math.floor(Math.random() * (max - min + 1) + min);
} }
@ -17,20 +19,30 @@ function generateRandom(min, max) {
* An input 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.
*
* @property input {HTMLInputElement} the input that is validatable
* @property titleLabel {HTMLElement} the label of which to update the text
* @property button {HTMLButtonElement} the submission button that activates validation
*/ */
class ValidatableInput { class ValidatableInput {
/**
* The input that is validatable.
*/
readonly input: HTMLInputElement;
/**
* The label of which to update the text.
*/
readonly titleLabel: HTMLElement;
/**
* The submission button that activates validation.
*/
readonly button: HTMLButtonElement;
/** /**
* Constructs a new validatable input and registers event listeners. * Constructs a new validatable input and registers event listeners.
* *
* @param input {HTMLInputElement} the input that is validatable * @param input the input that is validatable
* @param titleLabel {HTMLElement} the label of which to update the text * @param titleLabel the label of which to update the text
* @param button {HTMLButtonElement} the submission button that activates validation * @param button the submission button that activates validation
*/ */
constructor(input, titleLabel, button) { constructor(input: HTMLInputElement, titleLabel: HTMLElement, button: HTMLButtonElement) {
this.input = input; this.input = input;
this.titleLabel = titleLabel; this.titleLabel = titleLabel;
this.button = button; this.button = button;
@ -49,9 +61,7 @@ class ValidatableInput {
/** /**
* Handles the user submitting the input. * Handles the user submitting the input.
*/ */
onSubmit() { onSubmit(): void {
this.input.dataset["entered"] = "true";
if (this.isValid(this.input.value)) { if (this.isValid(this.input.value)) {
this.showSuccess(); this.showSuccess();
this.onValidInput(); this.onValidInput();
@ -65,72 +75,58 @@ class ValidatableInput {
/** /**
* Returns `true` if and only if the input is valid. * Returns `true` if and only if the input is valid.
* *
* This method **must** be implemented by subclasses. * Returns `false` by default. Implement this method to make it do something else.
* *
* @param value {string} the value of the input to validate * @param value the value of the input to validate
* @return {boolean} `true` if and only if the input is valid * @return `true` if and only if the input is valid
*/ */
isValid(value) { isValid(value: string): boolean {
throw new Error("Implement this method."); return false;
} }
/** /**
* Runs when the user submits a valid input. * Runs when the user submits a valid input.
* *
* This method **must** be implemented by subclasses. * Does nothing by default. Implement this method to make it do something.
*/ */
onValidInput() { onValidInput(): void {
throw new Error("Implement this method."); // Do nothing
} }
/** /**
* Runs when a user submits an invalid input. * Runs when a user submits an invalid input.
* *
* This method **must** be implemented by subclasses. * Does nothing by default. Implement this method to make it do something.
*/ */
onInvalidInput() { onInvalidInput(): void {
throw new Error("Implement this method."); // Do nothing
} }
/** /**
* Resets the input, title, and error message to their initial state, and removes the value from the input. * Resets the input, title, and error message to their initial state, and removes the value from the input.
*/ */
reset() { reset(): void {
this.input.value = ""; this.input.value = "";
this.input.dataset["entered"] = "false";
this.showSuccess(); this.showSuccess();
this.updateTitle(); this.updateTitle();
this.titleLabel.classList.remove("success-message"); clearInputValidity(this.input);
this.button.classList.remove("success-box");
} }
/** /**
* Marks the input as invalid. * Marks the input as invalid.
*/ */
showError() { showError(): void {
this.input.setCustomValidity("Incorrect"); showInputInvalid(this.input);
this.titleLabel.classList.remove("success-message");
this.titleLabel.classList.add("error-message");
this.button.classList.remove("success-box");
this.button.classList.add("error-box");
} }
/** /**
* Marks the input as valid. * Marks the input as valid.
*/ */
showSuccess() { showSuccess(): void {
this.input.setCustomValidity(""); showInputValid(this.input);
this.titleLabel.classList.remove("error-message");
this.titleLabel.classList.add("success-message");
this.button.classList.remove("error-box");
this.button.classList.add("success-box");
} }
/** /**
@ -138,7 +134,7 @@ class ValidatableInput {
* *
* Does nothing by default. Implement this method to make it do something. * Does nothing by default. Implement this method to make it do something.
*/ */
updateTitle() { updateTitle(): void {
// Do nothing // Do nothing
} }
@ -146,7 +142,7 @@ class ValidatableInput {
/** /**
* Focuses the input element. * Focuses the input element.
*/ */
selectInput() { selectInput(): void {
this.input.select(); this.input.select();
} }
} }
@ -155,46 +151,60 @@ class ValidatableInput {
* A wrapper around a `<details>` element that persists the state in local storage. * A wrapper around a `<details>` element that persists the state in local storage.
*/ */
class ToggleableSection { class ToggleableSection {
/**
* The name to identify this component with in persistent storage.
*
* @private
*/
private readonly name: string;
/**
* The element that can be toggled.
*
* @private
*/
private readonly details: HTMLDetailsElement;
/** /**
* Constructs a new `ToggleableSection`. * Constructs a new `ToggleableSection`.
* *
* @param name {string} the name to identify this component with in persistent storage * @param name the name to identify this component with in persistent storage
* @param details {HTMLDetailsElement} the element that can be toggled * @param details the element that can be toggled
*/ */
constructor(name, details) { constructor(name: string, details: HTMLDetailsElement) {
this._name = name; this.name = name;
this._details = details; this.details = details;
this._details.addEventListener("toggle", () => this.onToggle(this.isOpened())); this.details.addEventListener("toggle", () => this.onToggle(this.isOpened()));
this._loadToggle(); this.loadToggle();
} }
/** /**
* Returns `true` if and only if the component is currently open. * Returns `true` if and only if the component is currently open.
* *
* @return {boolean} `true` if and only if the component is currently open. * @return `true` if and only if the component is currently open.
*/ */
isOpened() { isOpened(): boolean {
return !!this._details.open; return this.details.open;
} }
/** /**
* Opens or closes the component. * Opens or closes the component.
* *
* @param isOpened {boolean} whether to open the component * @param isOpened whether to open the component
*/ */
setOpened(isOpened) { setOpened(isOpened: boolean): void {
this._details.open = isOpened; this.details.open = isOpened;
} }
/** /**
* This method is invoked whenever the component is toggled. * This method is invoked whenever the component is toggled.
* *
* @param isOpened {boolean} the new state of the component * @param isOpened the new state of the component
*/ */
onToggle(isOpened) { onToggle(isOpened: boolean): void {
this._storeToggle(); this.storeToggle();
} }
@ -203,8 +213,8 @@ class ToggleableSection {
* *
* @private * @private
*/ */
_storeToggle() { private storeToggle(): void {
localStorage.setItem(`/tools/doomsday//toggle-${this._name}`, "" + this.isOpened()); localStorage.setItem(`/tools/doomsday//toggle-${this.name}`, "" + this.isOpened());
} }
/** /**
@ -212,11 +222,11 @@ class ToggleableSection {
* *
* @private * @private
*/ */
_loadToggle() { private loadToggle(): void {
const target = localStorage.getItem(`/tools/doomsday//toggle-${this._name}`); const target = localStorage.getItem(`/tools/doomsday//toggle-${this.name}`);
if (target === null) { if (target === null) {
this.setOpened(true); this.setOpened(true);
this._storeToggle(); this.storeToggle();
return; return;
} }
@ -226,16 +236,20 @@ class ToggleableSection {
/** /**
* A wrapper around the good ol' `Date` class that provides a bunch of useful Doomsday-specific methods. * A wrapper around the good ol' `Date` class that provides a bunch of useful Doomsday-specific methods.
*
* @property {Date} date the underlying date
*/ */
class DoomsdayDate { class DoomsdayDate {
/**
* The underlying date.
*/
readonly date: DateTime;
/** /**
* Wraps a `DoomsdayDate` around the given date. * Wraps a `DoomsdayDate` around the given date.
* *
* @param date {Date} the date to be wrapped * @param date the date to be wrapped
*/ */
constructor(date) { constructor(date: DateTime) {
this.date = date; this.date = date;
} }
@ -243,83 +257,49 @@ class DoomsdayDate {
/** /**
* Returns the number of this `DoomsdayDate`'s century. * Returns the number of this `DoomsdayDate`'s century.
* *
* @return {number} the number of this `DoomsdayDate`'s century * @return the number of this `DoomsdayDate`'s century
*/ */
getCentury() { getCentury(): number {
return Math.floor(this.date.getFullYear() / 100); return Math.floor(this.date.year / 100);
} }
/** /**
* Returns the day of the week of the anchor of this `DoomsdayDate`'s century. * Returns the day of the week of the anchor of this `DoomsdayDate`'s century.
* *
* @return {string} the day of the week of the anchor of this `DoomsdayDate`'s century * @return the day of the week of the anchor of this `DoomsdayDate`'s century
*/ */
getCenturyAnchorString() { getCenturyAnchorString(): string {
const centuryAnchorNumber = (5 * (this.getCentury() % 4)) % 7 + 2; return this.date.set({year: this.getCentury() * 100, month: 4, day: 4}).setLocale("en-US").weekdayLong;
return DoomsdayDate.getWeekDayOf(centuryAnchorNumber);
}; };
/** /**
* Returns the day of the week of the anchor day of this `DoomsdayDate`'s year. * Returns the day of the week of the anchor day of this `DoomsdayDate`'s year.
* *
* @return {string} the day of the week of the anchor day of this `DoomsdayDate`'s year * @return the day of the week of the anchor day of this `DoomsdayDate`'s year
*/ */
getYearAnchorString() { getYearAnchorString(): string {
const anchorDate = new Date(this.date); return this.date.set({month: 4, day: 4}).setLocale("en-US").weekdayLong;
anchorDate.setDate(4); // 4th
anchorDate.setMonth(3); // April
anchorDate.setHours(0); // midnight local time
return DoomsdayDate.getWeekDayOf(anchorDate);
}; };
/** /**
* Returns the day of the week of this `DoomsdayDate`. * Returns the day of the week of this `DoomsdayDate`.
* *
* @return {string} the day of the week of this `DoomsdayDate` * @return the day of the week of this `DoomsdayDate`
*/ */
getWeekdayString() { getWeekdayString(): string {
return DoomsdayDate.getWeekDayOf(this.date); return this.date.setLocale("en-US").weekdayLong;
}; };
/** /**
* Returns the week day of [date]. * Returns the day of the week corresponding to `dayString`, or an empty string if no day was recognized.
*
* @param date {Date|number} the date to get the week day of; if it is a `number`, then 0 corresponds to Sunday
* @return {string} the name of the week day corresponding to [date]
*/
static getWeekDayOf(date) {
if (date instanceof Date) {
return date.toLocaleString("en-US", {timeZone: "GMT", weekday: "long"});
} else {
switch (date % 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. * This is a convenience method for interpreting (incomplete) user inputs.
* *
* @param dayString {string} the day of the week to expand * @param dayString the day of the week to expand
* @return {string} the day of the week corresponding to the given string * @return the day of the week corresponding to `dayString`, or an empty string if no day was recognized
*/ */
static expandDayString(dayString) { static expandDayString(dayString: string): string {
dayString = dayString.toLowerCase(); dayString = dayString.toLowerCase();
if (dayString.startsWith("m")) if (dayString.startsWith("m"))
return "Monday"; return "Monday";
@ -336,7 +316,7 @@ class DoomsdayDate {
else if (dayString.startsWith("su")) else if (dayString.startsWith("su"))
return "Sunday"; return "Sunday";
else else
return undefined; return "";
} }
/** /**
@ -347,50 +327,50 @@ class DoomsdayDate {
*/ */
static random() { static random() {
// TODO Give custom date range to this method // TODO Give custom date range to this method
const minDate = new Date("0001-01-01").getTime() / 86400000; const startDate = DateTime.utc(1, 1, 1);
const maxDate = new Date("9999-12-31").getTime() / 86400000; const dayRange = 9999 * 365 + (10000 / 400 * 97) - 1;
return new DoomsdayDate(new Date(generateRandom(minDate, maxDate) * 86400000)); return new DoomsdayDate(startDate.plus({days: generateRandom(0, dayRange)}))
} }
} }
doAfterLoad(() => { doAfterLoad(() => {
// Initialize template
$("#nav").appendChild(nav("/Tools/Doomsday/"));
$("#header").appendChild(header({
title: "Doomsday",
description: `
Test your mastery of \
<a href="https://en.wikipedia.org/wiki/Doomsday_rule">&#9099; Conway's Doomsday rule</a>
`
}));
$("#footer").appendChild(footer({
vcsURL: "https://git.fwdekker.com/FWDekker/doomsday/",
version: "v%%VERSION_NUMBER%%"
}));
$("main").classList.remove("hidden"); $("main").classList.remove("hidden");
// Initialize quiz // Initialize quiz
let quizDate; let quizDate: DoomsdayDate;
const centuryDetails = new class extends ToggleableSection { const centuryDetails = new class extends ToggleableSection {
onToggle(isOpened) { onToggle(isOpened: boolean): void {
super.onToggle(isOpened); super.onToggle(isOpened);
if (isOpened) centuryInput.selectInput(); if (isOpened) centuryInput.selectInput();
else if (yearDetails.isOpened()) yearInput.selectInput();
else if (dayDetails.isOpened()) dayInput.selectInput();
centuryInput.updateTitle(); centuryInput.updateTitle();
} }
}("century", $("#century-details")); }("century", $("#century-details"));
const yearDetails = new class extends ToggleableSection { const yearDetails = new class extends ToggleableSection {
onToggle(isOpened) { onToggle(isOpened: boolean): void {
super.onToggle(isOpened); super.onToggle(isOpened);
if (isOpened) yearInput.selectInput(); if (isOpened) yearInput.selectInput();
else if (dayDetails.isOpened()) dayInput.selectInput();
else if (centuryDetails.isOpened()) centuryInput.selectInput();
yearInput.updateTitle(); yearInput.updateTitle();
} }
}("year", $("#year-details")); }("year", $("#year-details"));
const dayDetails = new class extends ToggleableSection {
onToggle(isOpened: boolean): void {
super.onToggle(isOpened);
if (isOpened) dayInput.selectInput();
else if (centuryDetails.isOpened()) centuryInput.selectInput();
else if (yearDetails.isOpened()) yearInput.selectInput();
dayInput.updateTitle();
}
}("day", $("#day-details"));
const centuryInput = new class extends ValidatableInput { const centuryInput = new class extends ValidatableInput {
isValid(value) { isValid(value: string): boolean {
console.log("# Validate century"); console.log("# Validate century");
console.log(`Input: ${value}`); console.log(`Input: ${value}`);
console.log(`Expanded: ${DoomsdayDate.expandDayString(value)}`); console.log(`Expanded: ${DoomsdayDate.expandDayString(value)}`);
@ -398,16 +378,14 @@ doAfterLoad(() => {
return DoomsdayDate.expandDayString(value) === quizDate.getCenturyAnchorString(); return DoomsdayDate.expandDayString(value) === quizDate.getCenturyAnchorString();
} }
onValidInput() { onValidInput(): void {
this.input.value = DoomsdayDate.expandDayString(this.input.value); this.input.value = DoomsdayDate.expandDayString(this.input.value);
if (yearDetails.isOpened()) if (yearDetails.isOpened())
yearInput.selectInput(); yearInput.selectInput();
else else if (dayDetails.isOpened())
dayInput.selectInput(); dayInput.selectInput();
} else
resetButton.focus();
onInvalidInput() {
// Do nothing
} }
updateTitle() { updateTitle() {
@ -418,7 +396,7 @@ doAfterLoad(() => {
} }
}($("#century-input"), $("#century-title-label"), $("#century-submit")); }($("#century-input"), $("#century-title-label"), $("#century-submit"));
const yearInput = new class extends ValidatableInput { const yearInput = new class extends ValidatableInput {
isValid(value) { isValid(value: string): boolean {
console.log("# Validate year"); console.log("# Validate year");
console.log(`Input: ${value}`); console.log(`Input: ${value}`);
console.log(`Expanded: ${DoomsdayDate.expandDayString(value)}`); console.log(`Expanded: ${DoomsdayDate.expandDayString(value)}`);
@ -428,22 +406,21 @@ doAfterLoad(() => {
onValidInput() { onValidInput() {
this.input.value = DoomsdayDate.expandDayString(this.input.value); this.input.value = DoomsdayDate.expandDayString(this.input.value);
dayInput.selectInput(); if (dayDetails.isOpened())
} dayInput.selectInput();
else
onInvalidInput() { resetButton.focus();
// Do nothing
} }
updateTitle() { updateTitle() {
if (yearDetails.isOpened()) if (yearDetails.isOpened())
this.titleLabel.innerText = `Doomsday of year ${quizDate.date.getFullYear()}?`; this.titleLabel.innerText = `Doomsday of year ${quizDate.date.year}?`;
else else
this.titleLabel.innerText = `Year`; this.titleLabel.innerText = `Year`;
} }
}($("#year-input"), $("#year-title-label"), $("#year-submit")); }($("#year-input"), $("#year-title-label"), $("#year-submit"));
const dayInput = new class extends ValidatableInput { const dayInput = new class extends ValidatableInput {
isValid(value) { isValid(value: string): boolean {
console.log("# Validate day"); console.log("# Validate day");
console.log(`Input: ${value}`); console.log(`Input: ${value}`);
console.log(`Expanded: ${DoomsdayDate.expandDayString(value)}`); console.log(`Expanded: ${DoomsdayDate.expandDayString(value)}`);
@ -456,12 +433,11 @@ doAfterLoad(() => {
resetButton.focus(); resetButton.focus();
} }
onInvalidInput() {
// Do nothing
}
updateTitle() { updateTitle() {
this.titleLabel.innerText = `Weekday of ${quizDate.date.toISOString().substr(0, 10)}?`; if (dayDetails.isOpened())
this.titleLabel.innerText = `Weekday of ${quizDate.date.toISODate()}?`;
else
this.titleLabel.innerText = `Day`;
} }
}($("#day-input"), $("#day-title-label"), $("#day-submit")); }($("#day-input"), $("#day-title-label"), $("#day-submit"));
@ -479,7 +455,7 @@ doAfterLoad(() => {
function reloadQuiz() { function reloadQuiz() {
quizDate = DoomsdayDate.random(); quizDate = DoomsdayDate.random();
console.log("# Reset"); console.log("# Reset");
console.log(`New date: ${quizDate.date.toISOString().substr(0, 10)}`); console.log(`New date: ${quizDate.date.toISODate()}`);
console.log(` ${quizDate.date}`); console.log(` ${quizDate.date}`);
console.log(`Century#: ${quizDate.getCentury()}`); console.log(`Century#: ${quizDate.getCentury()}`);
console.log(`Century: ${quizDate.getCenturyAnchorString()}`); console.log(`Century: ${quizDate.getCenturyAnchorString()}`);
@ -493,8 +469,10 @@ doAfterLoad(() => {
centuryInput.selectInput(); centuryInput.selectInput();
else if (yearDetails.isOpened()) else if (yearDetails.isOpened())
yearInput.selectInput(); yearInput.selectInput();
else else {
dayDetails.setOpened(true);
dayInput.selectInput(); dayInput.selectInput();
}
} }
// Let the fun begin // Let the fun begin

11
tsconfig.json Normal file
View File

@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "es6",
"strict": true,
"rootDir": "./src/main/js/",
"outDir": "./dist/js/"
},
"include": [
"src/main/js/**/*.ts"
]
}