forked from Animenosekai/freeWolframAlpha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
598 lines (544 loc) · 25.4 KB
/
main.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/* constants.js */
const QUERY_URL = "https://freewolframalpha-api.vercel.app/query?question={question}&timeout={timeout}&podstate={podstate}"
const AUTOCOMPLETE_URL = "https://freewolframalpha-api.vercel.app/autocomplete?question={question}"
const RECALCULATION_URL = "https://freewolframalpha-api.vercel.app/recalculate?domain={domain}&id={id}"
const RELATEDQUERIES_URL = "https://freewolframalpha-api.vercel.app/related?domain={domain}&id={id}"
const TIMEOUT = 3
/* events.js */
async function hashChange() {
equationInput.focus()
equationInput.value = decodeURIComponent(location.hash.slice(1))
//document.getElementById("inputOutput").innerText = decodeURIComponent(location.hash.slice(1))
if (decodeURIComponent(location.hash.slice(1)).replace(" ", '') == "") {
//document.getElementById("inputOutput").innerText = "Enter what you want to calculate or know about"
goHome()
}
}
function parse() {
document.querySelectorAll("dropdown > option").forEach((item) => {
try {
item.remove()
} catch {
console.warn("An error occured while removing the stray option:", item)
}
})
document.querySelectorAll("dropdown").forEach((item) => {
try {
while (item.previousElementSibling.tagName != "H2")
item.parentNode.insertBefore(item, item.previousElementSibling)
item.previousElementSibling.append(item)
} catch {
console.warn("An error occured while moving the drop-down menu right next to the nearest heading:", item)
}
})
document.querySelectorAll("option").forEach((item) => {
try {
item.text = item.getAttribute("name")
} catch {
console.warn("An error occured while extracting the names of all available options:", item)
}
})
document.querySelectorAll("select").forEach((item) => {
try {
item.value = item.getAttribute("value")
} catch {
console.warn("An error occured while extracting the currently selected option name:", item)
}
})
document.querySelectorAll("select").forEach((item) => {
try {
item.style = `
background: white;
color: orangered;
border: thin solid darkorange;
border-radius: .5em;
`
} catch {
console.warn("An error occured while styling the drop-down menu:", item)
}
})
document.querySelectorAll("select").forEach((item) => {
try {
item.onchange = () => inputSubmit(item.value)
} catch {
console.warn("An error occured. The selected changes to the following drop-down menus will not send requests for status update properly:", item)
}
})
Array.prototype.slice.call(document.getElementsByTagName('pre')).forEach((item) => {
try {
item.remove();
} catch {
console.warn("An error occured while removing the following item")
console.log(item)
}
});
Array.prototype.forEach.call(document.getElementById("pod").getElementsByTagName("h2"), (item) => {
try {
item.classList.add("pod-header")
} catch {
console.warn("An error occured while setting the pod-header with the following item")
console.log(item)
}
});
Array.prototype.forEach.call(document.getElementById("pod").getElementsByTagName("img"), (item) => {
try {
if (item.parentNode.tagName == "SUBPOD" && item.parentNode.getAttribute("title") == "") {
item.setAttribute("onclick", "document.getElementById('equationInput').value = this.getAttribute('alt'); inputSubmit();")
item.classList.add("clickable-result")
}
} catch {
console.warn("An error occured while setting the direct query for the following item")
console.log(item)
}
});
Array.prototype.forEach.call(document.getElementById("pod").getElementsByTagName("info"), (item) => {
try {
item.querySelector("img").setAttribute("onclick", "window.open(this.parentNode.querySelector('link').getAttribute('url'), '_blank')")
} catch {
console.warn("An error occured while setting the info linking for the following item")
console.log(item)
}
});
document.getElementById("pod").querySelectorAll("imagesource").forEach((item) => {
try {
item.parentNode.querySelector("img").setAttribute("source-forward", item.innerText)
item.parentNode.querySelector("img").setAttribute("onclick", "window.open(this.getAttribute('source-forward'), '_blank')")
item.classList.add("unload")
} catch {
console.warn("An error occured while setting link for the following item")
console.log(item)
}
});
document.getElementById("pod-height").style.height = document.getElementById("pod").offsetHeight + 50 + "px"
document.getElementById('equationFooter').style.display = "block"
}
async function inputSubmit(podstate) {
try {
document.querySelectorAll("relatedqueries").forEach((item) => {
item.remove()
})
document.querySelectorAll("related-height").forEach((item) => {
item.remove()
})
} catch {
console.info("No Related Queries Container to remove")
}
document.getElementById("pod").setAttribute("home-type", "")
createSkeleton()
document.getElementById('equationFooter').style.display = "none"
if (document.getElementById("equationInput").value.replace(" ", '') == "") {
goHome();
return;
}
window.location.hash = encode(document.getElementById("equationInput").value)
states.currentEquation++;
let equationNumber = states.currentEquation
document.getElementById("equationInput").focus()
document.getElementById("equationInput").blur()
document.querySelector("title").innerText = document.getElementById("equationInput").value + " - Wolfram|Alpha"
request(QUERY_URL.format({
podstate: podstate,
question: encode(document.getElementById("equationInput").value),
timeout: String(TIMEOUT)
}))
.then((xml) => {
if (xml) {
if (states.currentEquation == equationNumber) {
store.xml = xml
store.equation = document.getElementById("equationInput").value
if (store.xml.includes('input parameter not present in query')) {
goHome()
} else {
states.home = false
document.getElementById("pod").innerHTML = xml.replace(/plaintext/g, 'pre').replace(/<pod title../g, '<h2>').replace(/.......scanner/gs, '</h2><!').replace(/statelist/g, 'select').replace(/states/g, 'dropdown').replace(/state/g, 'option')
parse()
if (document.querySelector("didyoumeans")) {
document.querySelector("didyoumeans").lastElementChild.style.marginBottom = "20px"
document.querySelectorAll("didyoumean").forEach((item) => {
item.setAttribute("onclick", "document.getElementById('equationInput').value = this.innerText; inputSubmit();")
})
}
if (document.querySelector("tips")) {
document.querySelector("tips").lastElementChild.style.marginBottom = "20px"
}
// related queries
if (document.getElementById("pod").querySelector("queryresult").getAttribute("related") != "") {
url = new URL(document.getElementById("pod").querySelector("queryresult").getAttribute("related"))
request(RELATEDQUERIES_URL.format({
domain: url.host,
id: url.searchParams.get("id")
}))
.then((response) => {
if (response) {
let tempRelated = document.createElement("temp")
tempRelated.innerHTML = response
if (tempRelated.querySelector("relatedqueries").getAttribute("count") != "0") {
document.getElementById("pod-height").parentNode.appendChild(tempRelated.querySelector("relatedqueries"))
document.querySelector("relatedqueries").lastElementChild.style.marginBottom = "20px"
let newRelatedHeight = document.createElement("related-height")
newRelatedHeight.style.height = document.querySelector("relatedqueries").offsetHeight + 50 + "px"
newRelatedHeight.style.display = "block"
document.getElementById("pod-height").parentNode.appendChild(newRelatedHeight)
document.querySelectorAll("relatedquery").forEach((item) => {
item.setAttribute("onclick", "document.getElementById('equationInput').value = this.innerText; inputSubmit();")
})
}
}
})
}
// WolframAlpha's "lazy" loading of queryresult
if (document.getElementById("pod").querySelector("queryresult").getAttribute("recalculate") != "") {
url = new URL(document.getElementById("pod").querySelector("queryresult").getAttribute("recalculate"))
request(RECALCULATION_URL.format({
domain: url.host,
id: url.searchParams.get("id")
}))
.then((response) => {
if (response) {
let tempElem = document.createElement("temp")
store.xml += response
tempElem.innerHTML = response.replace(/plaintext/g, 'pre').replace(/<pod title../g, '<h2>').replace(/.......scanner/gs, '</h2><!') // same stuff as above
document.getElementById("pod").querySelector("queryresult").innerHTML += tempElem.querySelector("queryresult").innerHTML
parse() // reparse everything to format
// retry once more, just to be sure
if (tempElem.querySelector("queryresult").getAttribute("recalculate") != "") {
url = new URL(tempElem.querySelector("queryresult").getAttribute("recalculate"))
request(RECALCULATION_URL.format({
domain: url.host,
id: url.searchParams.get("id")
}))
.then((response) => {
if (response) {
tempElem = document.createElement("temp")
store.xml += response
tempElem.innerHTML = response.replace(/plaintext/g, 'pre').replace(/<pod title../g, '<h2>').replace(/.......scanner/gs, '</h2><!')
document.getElementById("pod").querySelector("queryresult").innerHTML += tempElem.querySelector("queryresult").innerHTML
parse()
}
})
}
}
})
}
}
}
} else { // xml is null
console.warn("Couldn't get any result")
let newQueryResult = document.createElement("queryresult")
let newTips = document.createElement("tips")
let newTip = document.createElement("tip")
newTip.style.marginBottom = "20px"
newTip.setAttribute("text", "We are very sorry but an error occured on the server or the connection timed out.")
newTips.appendChild(newTip)
newQueryResult.appendChild(newTips)
document.getElementById("pod").innerHTML = ""
document.getElementById("pod").appendChild(newQueryResult)
document.getElementById("pod-height").style.height = document.getElementById("pod").offsetHeight + 50 + "px"
}
})
}
async function resizeHandler() {
if (window.innerWidth <= 700) {
try {
if (document.getElementById('extendedKeyboardContainer').getAttribute('keyboard-type') != 'responsive') {
if (caches.responsiveKeyboard) {
html = caches.responsiveKeyboard
} else {
response = await fetch('/parts/extendedKeyboardResponsive.html')
html = await response.text()
caches.responsiveKeyboard = html
}
document.getElementById('extendedKeyboardContainer').innerHTML = html
document.getElementById('extendedKeyboardContainer').setAttribute('keyboard-type', 'responsive')
}
} catch {
console.warn("Error while handling responsive for the extended keyboard")
}
try {
if (document.getElementById('footerContainer').getAttribute('footer-type') != "responsive") {
if (caches.responsiveFooter) {
html = caches.responsiveFooter
} else {
response = await fetch("/parts/footerResponsive.html")
html = await response.text()
caches.responsiveFooter = html
}
document.getElementById('footerContainer').innerHTML = html
document.getElementById('footerContainer').setAttribute('footer-type', 'responsive')
}
} catch {
console.warn("Error while handling responsive for the footer")
}
try {
if (states.home && document.getElementById('pod').getAttribute('home-type') != "responsive") {
if (caches.responsiveHome) {
html = caches.responsiveHome
} else {
response = await fetch("/parts/homeResponsive.html")
html = await response.text()
caches.responsiveHome = html
}
document.getElementById('pod').innerHTML = html
document.getElementById('pod').setAttribute('home-type', 'responsive')
}
document.getElementById("pod-height").style.height = document.getElementById("pod").offsetHeight + 50 + "px"
} catch {
console.warn("Error while handling responsive for the home")
}
} else {
try {
if (document.getElementById('extendedKeyboardContainer').getAttribute('keyboard-type') != 'normal') {
if (caches.keyboard) {
html = caches.keyboard
} else {
response = await fetch('/parts/extendedKeyboard.html')
html = await response.text()
caches.keyboard = html
}
document.getElementById('extendedKeyboardContainer').innerHTML = html
document.getElementById('extendedKeyboardContainer').setAttribute('keyboard-type', 'normal')
}
} catch {
console.warn("Error while handling responsive for the extended keyboard")
}
try {
if (document.getElementById('footerContainer').getAttribute('footer-type') != 'normal') {
if (caches.footer) {
html = caches.footer
} else {
response = await fetch('/parts/footer.html')
html = await response.text()
caches.footer = html
}
document.getElementById('footerContainer').innerHTML = html
document.getElementById('footerContainer').setAttribute('footer-type', 'normal')
}
} catch {
console.warn("Error while handling responsive for the footer")
}
try {
if (states.home && document.getElementById('pod').getAttribute('home-type') != 'normal') {
if (caches.home) {
html = caches.home
} else {
response = await fetch('/parts/home.html')
html = await response.text()
caches.home = html
}
document.getElementById('pod').innerHTML = html
document.getElementById('pod').setAttribute('home-type', 'normal')
}
document.getElementById("pod-height").style.height = document.getElementById("pod").offsetHeight + 50 + "px"
} catch {
console.warn("Error while handling responsive for the home")
}
}
}
window.addEventListener("load", resizeHandler)
window.addEventListener("load", () => {
hashChange()
.then(() => {
inputSubmit()
resizeHandler()
})
document.getElementById("equationForm").addEventListener("submit", (e) => {
e.preventDefault(); // prevents it from reloading
inputSubmit()
})
document.getElementById("equationInput").addEventListener("keydown", () => {
setTimeout(() => {
autocomplete()
}, 50);
})
document.getElementById("equationInput").addEventListener("focus", () => {
document.getElementById("autocompletionContainer").classList.add("autocompletion-container-shown")
})
document.getElementById("equationInput").addEventListener("blur", () => {
setTimeout(() => {
if (document.activeElement !== document.getElementById("equationInput")) {
document.getElementById("autocompletionContainer").classList.remove("autocompletion-container-shown")
}
}, 100);
})
})
window.addEventListener("hashchange", hashChange)
window.addEventListener("resize", resizeHandler)
/* skeleton.js */
async function createSkeleton() {
let newElem = document.createElement("queryresult")
let newHeader = document.createElement("h2")
newHeader.classList.add("pod-header")
newHeader.classList.add("skeleton-box")
newHeader.style.borderRadius = "8px 8px 0 0"
newElem.appendChild(newHeader)
let newSubPod = document.createElement("subpod")
newSubPod.style.height = "25px"
newElem.appendChild(newSubPod)
newHeader = document.createElement("h2")
newHeader.classList.add("pod-header")
newHeader.classList.add("skeleton-box")
newElem.appendChild(newHeader)
newSubPod = document.createElement("subpod")
newSubPod.style.height = "150px"
newElem.appendChild(newSubPod)
newHeader = document.createElement("h2")
newHeader.classList.add("pod-header")
newHeader.classList.add("skeleton-box")
newElem.appendChild(newHeader)
newSubPod = document.createElement("subpod")
newSubPod.style.height = "35px"
newElem.appendChild(newSubPod)
newHeader = document.createElement("h2")
newHeader.classList.add("pod-header")
newHeader.classList.add("skeleton-box")
newElem.appendChild(newHeader)
newSubPod = document.createElement("subpod")
newSubPod.style.height = "120px"
newElem.appendChild(newSubPod)
for (var i = 0; i < 5; i++) {
newHeader = document.createElement("h2")
newHeader.classList.add("pod-header")
newHeader.classList.add("skeleton-box")
newElem.appendChild(newHeader)
newSubPod = document.createElement("subpod")
newSubPod.style.height = (Math.random() * 200 + 15).toString() + "px"
newElem.appendChild(newSubPod)
}
document.getElementById("pod").innerHTML = ""
document.getElementById("pod").appendChild(newElem)
document.getElementById("pod-height").style.height = document.getElementById("pod").offsetHeight + 50 + "px"
}
/* request.js */
async function request(endpoint) {
try {
let request = await fetch(endpoint)
response = await request.json()
if (response.success) {
response = response.data
} else {
response = null
}
} catch {
response = null
}
return response
}
/* caches.js */
const store = {
"xml": "",
"equation": ""
}
const caches = {
"footer": null,
"responsiveFooter": null,
"keyboard": null,
"responsiveKeyboard": null,
"home": null,
"responsiveHome": null
}
/* home.js */
async function goHome() {
states.home = true;
resizeHandler()
window.location.hash = ""
document.getElementById("equationInput").focus()
document.getElementById("equationInput").blur()
document.getElementById('equationFooter').style.display = "none"
title.innerText = "Wolfram|Alpha: Computational Intelligence"
}
/* states.js */
const states = {
"currentEquation": 0,
"home": false
}
/* autocomplete.js */
async function autocompleteClickHandler(elem) {
document.getElementById("equationInput").value = elem.innerText
inputSubmit()
}
function createAutocompleteElement(complete, query) {
let newListElement = document.createElement("li")
newListElement.classList.add("autocomplete-list-element")
let newAnchor = document.createElement("a")
newAnchor.setAttribute("onclick", 'autocompleteClickHandler(this)')
newAnchor.classList.add("autocomplete-anchor")
let newSpan = document.createElement("span")
let bold = ""
let nonBold = ""
let checkingBold = true
for (var index = 0; index < complete.length; index++) {
if (index < query.length && complete[index].toLowerCase() == query[index].toLowerCase() && checkingBold) {
bold += complete[index]
} else {
checkingBold = false
nonBold += complete[index]
}
}
if (bold.length > 0) {
let newBoldSpan = document.createElement("span")
newBoldSpan.classList.add("autocomplete-bold-span")
newBoldSpan.innerText = bold
newSpan.appendChild(newBoldSpan)
}
newSpan.innerHTML += nonBold
newAnchor.appendChild(newSpan)
newListElement.appendChild(newAnchor)
return newListElement
}
async function autocomplete() {
result = await request(AUTOCOMPLETE_URL.format({
question: encode(document.getElementById("equationInput").value)
}))
if (result) {
let newAutocompleteList = document.createElement("ul")
newAutocompleteList.classList.add("autocomplete-list")
for (index in result.results) {
newAutocompleteList.appendChild(createAutocompleteElement(result.results[index].input, result.query))
}
while (document.getElementById("autocompleteResults").firstElementChild != null) {
document.getElementById("autocompleteResults").firstElementChild.remove()
}
document.getElementById("autocompleteResults").appendChild(newAutocompleteList)
}
}
/* utils.js */
String.prototype.format = function () {
/* C / Python like string formatter --> "Hello {name}".format("world") */
"use strict";
var str = this.toString();
if (arguments.length) {
var t = typeof arguments[0];
var key;
var args = ("string" === t || "number" === t) ?
Array.prototype.slice.call(arguments) :
arguments[0];
for (key in args) {
str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
}
}
return str;
};
async function download() {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/xml;charset=utf-8,' + encodeURIComponent(store.xml));
element.setAttribute('download', store.equation + " - Wolfram|Alpha Result.xml");
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
async function addSpecial(specialCharButton) {
equationInput.value = equationInput.value + specialCharButton.getAttribute("value")
//document.getElementById("inputOutput").innerText = equationInput.value
}
/*
async function addInput() {
document.getElementById("inputOutput").innerText = document.getElementById("equationInput").value
if (equationInput.value.replace(" ", '') == "") {
document.getElementById("inputOutput").innerText = "Enter what you want to calculate or know about"
}
}
*/
function encode(value) {
return encodeURIComponent(String(value)).replace(/[-_.!~*'()]/g, char => '%' + char.charCodeAt(0).toString(16))
}