-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
66 lines (57 loc) · 1.86 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
const input = document.querySelector("#typeahead");
const suggestions = document.querySelector("#suggestions");
let selectedIndex = 0;
input.addEventListener("keyup", event => {
const query = event.target.value;
if (event.key === "ArrowDown") {
updateSelectedUser(1);
} else if (event.key === "ArrowUp") {
updateSelectedUser(-1);
} else if (event.key === "ArrowUp") {
const username = document.querySelector(".selected").innerText;
window.open(`http://github.com/${username}`);
} else {
// Makes a GET request to the following endpoint. The second .then()
// provides the response JSON as its first argument.
fetch(`https://api.github.com/search/users?q=${query}`)
.then(response => response.json())
// Shape of JSON: { items: User[] }
.then(json => {
selectedIndex = 0;
suggestions.innerHTML = "";
json.items.forEach((user, index) =>
suggestions.appendChild(buildSuggestionHTML(user, index))
);
});
}
});
function updateSelectedUser(position) {
selectedIndex += position;
document.querySelector(".selected").setAttribute("class", null);
document.querySelectorAll("tr")[selectedIndex].setAttribute("class", "selected");
}
// Creates the following markup:
//
// <tr>
// <td>
// <img src={user.avatar_url} />
// </td>
// <tr>
// {user.login}
// </tr>
// </tr>
function buildSuggestionHTML(user, index) {
const avatarTd = document.createElement("td");
const avatarImg = document.createElement("img");
avatarImg.setAttribute("src", user.avatar_url);
avatarTd.appendChild(avatarImg);
const nameTd = document.createElement("td");
nameTd.textContent = user.login;
const row = document.createElement("tr");
row.appendChild(avatarTd);
row.appendChild(nameTd);
if (index === selectedIndex) {
row.setAttribute("class", "selected");
}
return row;
}