moth

Monarch Of The Hill game server
git clone https://git.woozle.org/neale/moth.git

moth / theme
Neale Pickett  ·  2024-04-17

common.mjs

 1/**
 2 * Common functionality
 3 */
 4const Millisecond = 1
 5const Second = Millisecond * 1000
 6const Minute = Second * 60
 7
 8/** URL to the top of this MOTH server */
 9const BaseURL = new URL(".", location)
10
11/** A channel to monitor for state updates (or to notify of state updates) */
12const StateUpdateChannel = new BroadcastChannel("StateUpdate")
13
14/**
15 * Display a transient message to the user.
16 * 
17 * @param {String} message Message to display
18 * @param {Number} timeout How long before removing this message
19 */
20function Toast(message, timeout=5*Second) {
21    console.info(message)
22    for (let toasts of document.querySelectorAll(".toasts")) {
23        let p = toasts.appendChild(document.createElement("p"))
24        p.classList.add("toast")
25        p.textContent = message
26        setTimeout(() => p.remove(), timeout)
27    }
28}
29
30/**
31 * Run a function when the DOM has been loaded.
32 * 
33 * @param {function():void} cb Callback function
34 */
35function WhenDOMLoaded(cb) {
36    if (document.readyState === "loading") {
37        document.addEventListener("DOMContentLoaded", cb)
38    } else {
39        cb()
40    }    
41}
42
43/**
44 * Interprets a String as a Boolean.
45 * 
46 * Values like "no" or "disabled" to mean false here.
47 * 
48 * @param {String} s 
49 * @returns {Boolean}
50 */
51function StringTruthy(s) {
52    switch (s.toLowerCase()) {
53        case "disabled":
54        case "no":
55        case "off":
56        case "false":
57            return false
58    }
59    return true
60}
61
62
63/**
64 * Fetch the configuration object for this theme.
65 * 
66 * @returns {Promise.<Object>}
67 */
68async function Config() {
69    let obj = {}
70    try {
71        let resp = await fetch(
72            new URL("config.json", BaseURL), 
73            {
74                cache: "no-cache"
75            },
76        )
77        obj = await resp.json()
78    }
79    catch(err) {
80        obj = {}
81    }
82    return obj
83}
84
85export {
86    Millisecond,
87    Second,
88    Minute,
89    StateUpdateChannel,
90    BaseURL,
91    Toast,
92    WhenDOMLoaded,
93    StringTruthy,
94    Config,
95}