-
Notifications
You must be signed in to change notification settings - Fork 1
/
MMM-stoic-quotes.js
92 lines (82 loc) · 2.41 KB
/
MMM-stoic-quotes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
Module.register("MMM-stoic-quotes", {
defaults: {
size: "small",
interval: 24 * 60 * 60 * 1000,
runAtHour: undefined
},
start: function() {
if (this.config.runAtHour === undefined) {
setInterval(() => {
this.updateDom()
}, this.config.interval)
} else {
this.runAtTime(this.config.runAtHour)
}
},
getStyles: function() {
return ["stoic-quotes.css"]
},
getDom: async function() {
Log.info("Updating DOM")
const quote = await this.fetchQuote();
const element = document.createElement("div")
const sizeClass = this.parseSize(this.config.size)
element.className = `stoic-quotes ${sizeClass}`
const quoteElement = document.createElement("p")
quoteElement.innerHTML = quote.text || ""
quoteElement.id = "quoteText"
const authorElement = document.createElement("p")
authorElement.innerHTML = quote.author || ""
authorElement.id = "quoteAuthor"
element.appendChild(quoteElement)
element.appendChild(authorElement)
return element
},
runAtTime: function(targetHour) {
const now = new Date()
const delay = this.calculateRunningTime(now, targetHour)
Log.info(`Setting delay for stoic quotes to be ${delay}`)
setTimeout(() => {
this.updateDom()
this.runAtTime(targetHour)
}, delay)
},
calculateRunningTime: function(now, targetHour) {
const targetHourInt = parseInt(targetHour)
if (targetHourInt < 0 || targetHourInt > 23) {
throw new Error("targetHour must be between 0 and 23")
}
const targetTime = new Date(now)
targetTime.setHours(targetHourInt, 0, 0, 0) // Setting the target time for today
// If the target time is in the past (today), set it for tomorrow
if (now > targetTime) {
targetTime.setDate(targetTime.getDate() + 1);
}
return targetTime - now
},
parseSize: function(size) {
switch (size) {
case 'xsmall':
return "xsmall";
case 'small':
return "small";
case 'medium':
return "medium";
case 'large':
return "large";
case "xlarge":
return "xlarge"
default:
return "medium"
}
},
fetchQuote: async function() {
try {
const response = await fetch('https://stoic-quotes.com/api/quote');
const responseData = await response.json();
return responseData;
} catch (error) {
console.error('Fetch error:', error);
}
}
})