-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
63 lines (55 loc) · 1.82 KB
/
scripts.js
File metadata and controls
63 lines (55 loc) · 1.82 KB
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
const form = document.querySelector('form');
const queryInput = document.querySelector('#query');
const limitInput = document.querySelector('#limit');
const indentInput = document.querySelector('#indent');
const languageSelect = document.querySelector('#languages');
const resultsDiv = document.querySelector('#results');
let isResultScore = false;
function syntaxHighlight(json) {
if (typeof json !== 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function (match) {
let cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
if (/^"resultScore"/.test(match)) {
isResultScore = true;
} else {
isResultScore = false;
}
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
} else if (isResultScore) {
cls = 'result-score-value';
}
return '<span class="' + cls + '">' + match + '</span>';
}
);
}
form.addEventListener('submit', (event) => {
event.preventDefault();
const query = queryInput.value;
const limit = limitInput.value;
const indent = indentInput.checked;
const language = languageSelect.value;
const url = `api.php?query=${query}&limit=${limit}&indent=${indent}&languages=${language}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const formattedJson = syntaxHighlight(data);
resultsDiv.innerHTML = formattedJson;
})
.catch((error) => {
console.error(error);
});
});