-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
96 lines (86 loc) · 3.37 KB
/
script.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
93
94
95
96
class QuoteFactory {
constructor() {
this.mainElm = document.querySelector("main")
this.quoteDiv = document.getElementById("quote")
this.controlsDiv = document.getElementById("controls")
this.showControls = false
this.quoteDuration = 9500
this.quotesDataURL = "https://raw.githubusercontent.com/rohith/quoted/master/data/quotes.md"
this.fadeDuration = 500 // comes from style.styl with opacity transition time
this.colors = [
"rgb(44, 62, 80)",
"rgb(192, 57, 43)",
"rgb(211, 84, 0)",
"rgb(22, 160, 133)",
"rgb(39, 174, 96)",
"rgb(41, 128, 185)",
"rgb(142, 68, 173)"
].sort(() => Math.random() - 0.5)
}
boot() {
this.setupUtils()
this.bindEvents()
this.fetchQuotes()
this.registerSW()
}
setupUtils() {
Array.prototype.nextItem = function (currentItem) {
let currentIndex = this.indexOf(currentItem)
return currentIndex < 0 || currentIndex === this.length - 1 ? this[0] : this[currentIndex + 1]
}
}
bindEvents() {
if (("share" in navigator)) {
this.showControls = true
document.getElementById("share").onclick = this.shareQuote
}
}
fetchQuotes() {
fetch(this.quotesDataURL)
.then(response => response.text())
.then(data => {
this.quotes = data.split("\n").map(s => s.trim()).filter(s => s).sort(() => Math.random() - 0.5)
this.quoteDiv.classList.toggle("fade")
setTimeout(() => {
this.changeQuote()
if (this.showControls) {
this.controlsDiv.classList.remove("fade")
} else {
this.controlsDiv.style.display = "none"
}
setInterval(() => this.changeQuote(), this.quoteDuration)
}, this.fadeDuration);
})
}
registerSW() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("sw.js")
.then(() => console.log("Service Worker Registered"))
.catch(e => console.error(`Service Worker not Registered due to ${JSON.stringify(e)}`))
}
}
shareQuote() {
navigator.share({
title: document.title,
text: document.getElementById("quote").innerText,
url: window.location.origin
}).catch(error => console.log("Error Sharing:", error))
}
changeQuote() {
this.quoteDiv.innerText = this.quotes.nextItem(this.quoteDiv.innerText)
this.changeBGColor()
this.quoteDiv.classList.toggle("fade")
setTimeout(() => {
this.quoteDiv.classList.toggle("fade")
}, this.quoteDuration - this.fadeDuration)
}
changeBGColor() {
let currentColor = this.mainElm.style.backgroundColor,
currentIndex = this.colors.indexOf(currentColor),
nextIndex = currentIndex >= 0 ? (currentIndex < this.colors.length - 1 ? currentIndex + 1 : 0) : 0
this.mainElm.style.backgroundColor = this.colors[nextIndex]
}
}
window.addEventListener("load", () => {
new QuoteFactory().boot()
})