This repository has been archived by the owner on Jun 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
357 lines (327 loc) · 12.3 KB
/
scripts.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// jQuery style QuerySelector
function $(selector, base = document) {
let elements = base.querySelectorAll(selector)
return elements.length === 1 ? elements[0] : elements
}
// Multi-element, multi-event attachment
function on(elements = document, events, listener, options) {
events = events.split(" ")
if (elements instanceof NodeList === false)
elements = [elements]
for (let event of events)
for (let element of elements)
element.addEventListener(event, listener, options)
}
// Mouse
let Mouse = undefined
on(document, "mousemove", (event) => {
if (!Mouse) Mouse = {}
let update = (event) => {
Mouse.x = Math.round(event.clientX / window.innerWidth * 100) / 100,
Mouse.y = Math.round(event.clientY / window.innerHeight * 100) / 100
}
update(event)
on(document, "click mousemove", update)
}, { once: true })
// Keyboard
let Keyboard = undefined
on(document, "keydown", (event) => {
if (!Keyboard) Keyboard = new Proxy({}, {
set: (obj, prop, value) => { obj[prop] = value; return true },
deleteProperty(obj, prop) { if (prop in obj) { delete obj[prop] } }
})
let animationFrameTimer
let update = (event) => {
if (event) {
if (event.type === "keydown") Keyboard[event.code] = true
else delete Keyboard[event.code]
}
if (Object.keys(Keyboard).length === 0)
return cancelAnimationFrame(animationFrameTimer)
animationFrameTimer = requestAnimationFrame(() => update())
}
update(event)
on(document, "keydown keyup", update)
on(window, "blur", () => { for (let key of Object.keys(Keyboard)) delete Keyboard[key] })
}, { once: true })
const $tetris = $(".tetris__article")
const $header = $(".tetris__articleHeader")
const $boxArts = $(".tetris__image.boxArt")
const $boxArtLinks = $(".tetris__imageLink.boxArt")
// 3-D Layered Box Art
on(window, "load", () => { setTimeout(() => $tetris.classList.add("loaded"), 500) }) // simulate loading
on($header, "mousemove", () => {
if (!Mouse) return
$tetris.style.setProperty("--x", Mouse.x)
$tetris.style.setProperty("--y", Mouse.y)
})
try {
setTimeout(() => { localStorage.setItem("tetris", true) }, 4500)
if (localStorage.getItem("tetris")) $tetris.classList.add("visited")
} catch (e) { console.warn("Unable to use localStorage.") }
on($boxArtLinks, "click", (event) => {
let normalize = (value, range) => (value * 2 - range) / range
let normalizedLayerX = normalize(event.layerX, event.target.offsetWidth)
if (Math.abs(normalizedLayerX) < 0.5) return
event.preventDefault()
for (let $boxArt of $boxArtLinks)
$boxArt.classList.toggle("flipped")
})
// Television Commercial
let $television = $(".tetris__imageLink.commercial")
let television = {
channel: 0,
volume: 50,
player: null,
guide: [
{ id: "E-ej_8XBwmI", channelID: "3", publication: "YouTube", title: "Game Boy: <em>Portable</em> Power", type: "Television Advertisement", publisher: "Nintendo", year: "1989" },
{ id: "x1tn4lk", channelID: "4", publication: "DailyMotion", title: "Teenage Mutant Ninja Turtles", type: "Animated Series", publisher: "Mirage Studios", year: "1987" },
],
states: "loading buffering cued end ended pause paused playing start unstarted video_start video_end waiting",
isOff() { return $television.classList.contains("off") },
isPlaying() { return $television.classList.contains("playing") },
isYouTube() { return this.guide[this.channel].publication.toLowerCase() === "youtube" },
toggle() {
if (this.isOff()) return
if (!this.player) return this.programChange()
if (this.isPlaying()) return this.pause()
else return this.play()
},
play() {
this.player[this.isYouTube() ? "playVideo" : "play"]()
},
pause() {
this.player[this.isYouTube() ? "pauseVideo" : "pause"]()
},
channelChange(direction) {
if (this.isOff()) return
this.channel += direction
if (this.channel >= this.guide.length) this.channel = 0
else if (this.channel < 0) this.channel = this.guide.length - 1
this.programChange()
$(".tetris__videoDisplay", $television).setAttribute("data-channel", this.guide[this.channel].channelID)
setTimeout(() => this.clearDisplay("channel"), 5000)
this.updateCitation()
},
channelDown() { return this.channelChange(-1) },
channelUp() { return this.channelChange(+1) },
updateCitation() {
$(".tetris__caption.commercial").innerHTML = `
<span class="tetris__citeTitle">${this.guide[this.channel].title}</span> ${this.guide[this.channel].type},
<cite class="tetris__citePublication">${this.guide[this.channel].publisher},</cite>
<time class="tetris__citeDate" datetime="${this.guide[this.channel].year}">${this.guide[this.channel].year}.</time>`
},
volumeChange(amount) {
if (this.isOff()) return
this.volume += (amount * 10)
this.volume = Math.min(this.volume, 100)
this.volume = Math.max(this.volume, 0)
if (this.player) this.player.setVolume(this.volume)
if (!amount) return
$(".tetris__videoDisplay", $television).setAttribute("data-volume", this.volume)
setTimeout(() => this.clearDisplay("volume"), 5000)
},
volumeDown() { return this.volumeChange(-1) },
volumeUp() { return this.volumeChange(+1) },
clearDisplay(display) {
$(".tetris__videoDisplay", $television).removeAttribute(`data-${display}`)
},
power() {
if (this.isPlaying())
this.pause()
$television.classList.toggle("off")
},
programChange() {
let program = this.guide[this.channel]
$(".tetris__video.commercial").outerHTML = "<div class='tetris__video commercial' id='player'></div>"
this.player = null
this.stateChange("loading")
if (this.isYouTube())
this.player = new YT.Player("player", {
videoId: program.id,
width: "512", height: "384",
playerVars: { "controls": 0, "modestbranding": 1,"autoplay": 1 },
events: {
onReady(event) { $television.classList.remove("loading"); television.volumeChange(0) },
onStateChange(event) { return television.stateChange.bind(television)(event) }
}
})
else {
this.player = DM.player("player", {
video: program.id,
width: "512", height: "384",
params: { autoplay: true, mute: false, controls: false, "queue-enable": false }
})
on(program.player, "playing pause end start video_start video_end waiting", event => television.stateChange.bind(television)(event))
}
},
stateChange(event) {
let state
for (state of this.states.split(" "))
$television.classList.toggle(state, false)
if (typeof(event) === "string")
state = event
else
state = this.isYouTube()
? Object.keys(YT.PlayerState).find(state => YT.PlayerState[state] === event.data).toLowerCase()
: event.type
$television.classList.toggle(state, true)
}
}
on(window, "load resize", event => {
let $map = $('map[name="television"]')
let $static = $('[usemap="#television"]')
let areas = [
{ click: "toggle",
shape: "rect", coords: "9.38%,10.29%,74.80%,76.04%" },
{ click: "channelDown",
shape: "rect", coords: "81.64%,20.70%,87.89%,24.87%" },
{ click: "channelUp",
shape: "rect", coords: "87.89%,20.70%,94.14%,24.87%" },
{ click: "volumeDown",
shape: "rect", coords: "81.64%,24.87%,87.89%,29.04%" },
{ click: "volumeUp",
shape: "rect", coords: "87.89%,24.87%,94.14%,29.04%" },
{ click: "power",
shape: "rect", coords: "87.89%,29.04%,94.14%,35.00%" }
]
$map.innerHTML = ""
for (area of areas) {
let coords = area.coords.split(",").map((coord, index) => {
if (coord.indexOf("%"))
return Math.floor($static[index % 2 ? "height" : "width"] * parseFloat(coord) / 100)
return coord
}).join(",")
let $area = document.createElement("area")
$area.setAttribute("href", "javascript:;")
$area.setAttribute("shape", area.shape)
$area.setAttribute("coords", coords)
$area.addEventListener("click", television[area.click].bind(television))
$map.appendChild($area)
}
})
// Scoring Table Toggle
function updateScoringTable(highSpeedScoring) {
for (level = 0; level < 10; level++) {
for (lineIndex = 0; lineIndex < 5; lineIndex++) {
let name = `level${level}__lines${lineIndex}`
let $output = $(`.tetris__table.scoring output[name="level${level}__lines${lineIndex}"]`)
if ($output.length === 0) {
$output = document.createElement("output")
$output.name = name
$output.setAttribute("data-tetris__level", level)
$output.setAttribute("data-tetris__heartLevel", `${level}♥`)
$cell = document.createElement(lineIndex === 0 ? "th" : "td")
if (lineIndex === 0)
$(".tetris__table.scoring thead tr").appendChild($cell)
else
$(`.tetris__table.scoring tbody tr:nth-child(${lineIndex})`).appendChild($cell)
$cell.appendChild($output)
}
let value = [1,40,100,300,1200][lineIndex] * (level + (lineIndex ? 1 : 0))
if (lineIndex === 0) {
let $heart = document.createElement("small")
$heart.textContent = "♥︎"
$output.value = value
if (highSpeedScoring)
setTimeout(() => { $output.appendChild($heart) }, level * 25)
else {
$output.appendChild($heart)
setTimeout(() => { $heart.remove() }, (10 - level) * 25)
}
continue
}
let heartScore = [1,40,100,300,1200][lineIndex] * (level + 10 + (lineIndex ? 1 : 0))
$output.setAttribute("data-tetris__score", value)
$output.setAttribute("data-tetris__heartScore", heartScore)
if (highSpeedScoring)
value = heartScore
animateValue($output, $output.value, value, 500)
}
}
$(".tetris__table.scoring").classList.toggle("highSpeed", highSpeedScoring ? true : false)
}
updateScoringTable()
function animateValue(element, start, end, duration) {
let range = end - start
let endTime = Date.now() + duration
let updateTimer = requestAnimationFrame(updateValue)
function updateValue() {
let now = Date.now()
let remaining = Math.max((endTime - now) / duration, 0)
let value = Math.round(end - (remaining * range))
element.innerHTML = value
if (value == end)
return cancelAnimationFrame(updateTimer)
updateTimer = requestAnimationFrame(updateValue)
}
}
animateValue("value", 100, 25, 5000);
let $toggleScoring = $(".tetris__toggle.scoring input")
on($toggleScoring, "change", event => {
event.target.classList.toggle("active")
updateScoringTable($toggleScoring.checked)
})
// Game Boy Music
let $gameboy = $(".tetris__imageLink.gameboy")
let touched = false
on($gameboy, "click touchend", event => {
if (event.type === "touchend") { touched = true; return }
if (!touched) {
event.preventDefault()
$gameboy.classList.toggle("playing")
if ($gameboy.classList.contains("playing"))
$gameboy.innerHTML = $gameboy.innerHTML
+ `<iframe class="tetris__gameboyMusic" width="560" height="315" src="https://www.youtube.com/embed/qYT9fl5cbao?start=10&end=49&autoplay=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`
else
$(".tetris__gameboyMusic").remove()
} })
// Color Scheme Toggle
let $toggleColorScheme = $(".tetris__toggle.colorScheme input")
on($toggleColorScheme, "change", event => {
event.target.classList.toggle("active")
document.body.classList.toggle("color-scheme-inverted") })
on(document, "DOMContentLoaded", event => {
if (window.matchMedia("(prefers-color-scheme: dark)"))
document.body.classList.toggle("color-scheme-inverted", true) })
// Optimization Support
// Webp images
new Promise(res => {
const webp = new Image()
webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA'
webp.onload = webp.onerror = function () {
res(webp.height === 2)
}
}).then(supportsWebp => document.documentElement.classList.add(supportsWebp ? "media-webp-true" : "media-webp-false"))
// Lazy-loaded images
on(document, "DOMContentLoaded", event => {
let imageObserver
let $images = $("[data-src], [data-srcset]")
let loadImage = function ($image) {
if ($image.dataset.srcset) $image.srcset = $image.dataset.srcset
if ($image.dataset.src) $image.src = $image.dataset.src
$image.removeAttribute("data-src")
$image.removeAttribute("data-srcset")
}
if ("IntersectionObserver" in window) {
imageObserver = new IntersectionObserver((entries, observer) => {
for (let entry of entries) {
if (entry.isIntersecting) {
loadImage(entry.target)
imageObserver.unobserve(entry.target)
}
}
}, { rootMargin: '50%'})
}
for (let $image of $images) {
if (imageObserver)
imageObserver.observe($image)
else
loadImage($image)
}
})
// Global site tag (gtag.js) - Google Analytics
window.dataLayer = window.dataLayer || []
function gtag(){ dataLayer.push(arguments) }
gtag('js', new Date())
gtag('config', 'UA-155363758-1')