mirror of
https://codeberg.org/vlw/big-black-coffee-button.git
synced 2025-09-13 16:23:42 +02:00
70 lines
No EOL
2.4 KiB
JavaScript
70 lines
No EOL
2.4 KiB
JavaScript
import { default as API } from "https://cdn.jsdelivr.net/npm/reflect-client@2.0.1/build/Reflect.js";
|
|
|
|
const STORAGE_KEY = "key";
|
|
const STORAGE_URL = "url";
|
|
|
|
function error(message) {
|
|
// Create wrapper for error messages
|
|
if (!document.querySelector("div#error")) {
|
|
const wrapper = document.createElement("div");
|
|
wrapper.id = "error";
|
|
|
|
// Remove wrapper element button
|
|
const closeButton = document.createElement("button");
|
|
closeButton.innerText = "Close error messages";
|
|
closeButton.addEventListener("click", () => wrapper.remove());
|
|
|
|
wrapper.appendChild(closeButton);
|
|
document.body.insertAdjacentElement("afterbegin", wrapper);
|
|
}
|
|
|
|
const element = document.createElement("pre");
|
|
element.innerText = message;
|
|
|
|
document.querySelector("div#error").insertAdjacentElement("afterbegin", element);
|
|
}
|
|
|
|
// Set logged in state on load if credentials exist
|
|
if (localStorage.getItem(STORAGE_URL) && localStorage.getItem(STORAGE_KEY)) {
|
|
document.body.classList.add("loggedin");
|
|
|
|
// Set login form credentials with values from storage
|
|
document.querySelector(`[name="${STORAGE_URL}"]`).value = localStorage.getItem(STORAGE_URL);
|
|
document.querySelector(`[name="${STORAGE_KEY}"]`).value = localStorage.getItem(STORAGE_KEY);
|
|
}
|
|
|
|
// Login form
|
|
document.querySelector("form").addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
|
|
// Set credentials in localStroage
|
|
const form = new FormData(event.target);
|
|
localStorage.setItem(STORAGE_URL, form.get(STORAGE_URL));
|
|
localStorage.setItem(STORAGE_KEY, form.get(STORAGE_KEY));
|
|
|
|
document.body.classList.add("loggedin");
|
|
});
|
|
|
|
// The Big Black Coffee Button
|
|
document.querySelector("button#coffee").addEventListener("click", async () => {
|
|
try {
|
|
// Attempt to pour some coffee
|
|
const url = new URL(localStorage.getItem(STORAGE_URL));
|
|
const resp = await new API(url.origin, localStorage.getItem(STORAGE_KEY)).call(url.pathname).post();
|
|
|
|
// Bail out and show error error if we didn't get a 2xx response code
|
|
if (!resp.ok) {
|
|
return error(await resp.text());
|
|
}
|
|
} catch (message) {
|
|
// Bail out if something went wrong with the API client
|
|
return error(message.toString());
|
|
}
|
|
|
|
// Play a fun little effect on success
|
|
const sfx = document.querySelector("audio");
|
|
sfx.addEventListener("playing", () => document.body.classList.add("coffeup"), { once: true });
|
|
sfx.addEventListener("ended", () => document.body.classList.remove("coffeup"), { once: true });
|
|
|
|
return sfx.play();
|
|
}); |