-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
334 lines (302 loc) · 10.5 KB
/
index.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
const endpoint = "https://todo.hackrpi.com";
const addListElement = document.getElementById("add-list");
const listContainerElement = document.getElementById('list-container');
const newListInputElement = document.getElementById('new-list-input');
const API_KEY = "2be3095525d52048f21cc456f6b4b584";
//Get status with /status GET endpoint
async function getStatus() {
try {
const response = await fetch(endpoint+'/status', {
method: 'GET',
headers: {
'authorization': API_KEY,
'Content-Type': 'application/json'
}
})
const status = await response.json();
document.getElementById("status").innerText = status.message;
} catch(e){
console.error('Error getting status:' + e);
}
}
//Event listeners for menu
addListElement.addEventListener("click", function(){
addList();
});
newListInputElement.onkeydown = function(e){
if(e.key === "Enter"){
addList();
}
};
//Get all items from server and runs the renderLists function
async function fetchLists() {
try {
let lists = [];
const getListResponse = await loopRequest("");
async function loopRequest(newToken){
//Query parameters include the next token if it is available form the previous request
const response = await fetch(`${endpoint}/GetLists/` + (newToken !== "" ? "?"+new URLSearchParams({
nextToken: newToken
}) :""), {
method: 'GET',
headers: {
'authorization':API_KEY,
'Content-Type': 'application/json',
}
});
const newLists = await response.json();
if(newLists.status == "200"){
lists = lists.concat(newLists.lists);
}
if (newLists.nextToken && newLists.nextToken !== "NULL" ){
return loopRequest(newLists.nextToken);
} else {
return lists;
}
};
await renderLists(getListResponse);
} catch (error) {
console.error('Error fetching lists:', error);
}
}
//Adds list through /AddList POST endpoint.
async function addList() {
const title = newListInputElement.value.trim();
if (title) {
try {
const response = await fetch(endpoint+'/AddList', {
method: 'POST',
headers:{
'authorization':API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
listName: title
})
});
const newList = await response.json();
//Render list if successful
if(newList.status == "200"){
renderList({
id: newList.list.id,
listName: newList.list.listName,
items: []
});
}
newListInputElement.value = '';
} catch (error) {
console.error('Error adding list:', error);
}
}
}
//Deletes list through /DeleteList DELETE endpoint
async function deleteList(listIdParam) {
try {
await fetch(`${endpoint}/DeleteList?` + new URLSearchParams({
listId: listIdParam,
}), {
method: 'DELETE',
headers: {
'authorization':API_KEY,
'Content-Type': 'application/json',
}
});
const listElement = document.getElementById(`list-${listIdParam}`);
listElement.classList.add("fadeOut");
setTimeout(function(){
listElement.remove();
}, 500);
} catch (error) {
console.error('Error deleting list:', error);
}
}
//Renders each list given an array of list objects
async function renderLists(lists) {
//To preserve the sequence of lists, use for loop instead of forEach (which would run functions in parallel)
let listItems;
for (const e of lists){
listItems = await getListItems(e.id);
renderList({
id: e.id,
listName: e.listName,
items: listItems
});
}
let loadingEl=document.getElementById('loading');
if(loadingEl!==null) loadingEl.remove();
}
//Get all list items using GetListItems GET endpoint until next token is exhausted
async function getListItems(listIdParam){
try {
let listItems = [];
const getListResponse = await loopRequest("");
async function loopRequest(newToken){
//Query parameters include the next token if it is available form the previous request
const response = await fetch(`${endpoint}/GetListItems/?` + (newToken !== "" ? new URLSearchParams({
listId: listIdParam,
nextToken: newToken
}) : new URLSearchParams({
listId: listIdParam
})), {
method: 'GET',
headers: {
'authorization':API_KEY,
'Content-Type': 'application/json',
}
});
const newItems = await response.json();
if(newItems.status == "200"){
listItems = listItems.concat(newItems.listItems);
}
if (newItems.nextToken && newItems.nextToken !== "NULL" ){
return loopRequest(newItems.nextToken);
} else {
return listItems;
}
}
return getListResponse;
} catch (error) {
console.error('Error getting list items:', error);
}
return null;
}
const listHTML = `
<div class="list">
<h2 class="list-header"></h2>
<input type="text">
<button>Add</button>
<button>Delete List</button>
<div class="item-list"></div>
</div>
`;
//Renders list
function renderList(list) {
let tempHTML = `
<div id="list-${list.id}" class="list">
<h2 class="list-header">${list.listName}</h2>
<input id="task-input-${list.id}" type="text" value="" class="text-input">
<button id="add-items-${list.id}">Add</button>
<button id="delete-list-${list.id}">Delete List</button>
<div class="item-list"></div>
</div>
`;
let loadingEl=document.getElementById('loading');
if(loadingEl!==null) loadingEl.remove();
document.getElementById("list-container").insertAdjacentHTML("afterbegin", tempHTML);
document.getElementById(`delete-list-${list.id}`).onclick = () => deleteList(list.id);
document.getElementById(`add-items-${list.id}`).onclick = () => addTask(list.id);
document.getElementById(`task-input-${list.id}`).onkeydown = (e) => {
if(e.key === "Enter"){
addTask(list.id)
}
};
list.items.forEach(task => {
createTaskElement(task, list.id);
});
}
//Renders each to-do task
function createTaskElement(task, listId) {
let tempHTML = `
<div id="task-${task.id}" class="item${task.checked ? " completed":""}">
<label class="checkbox-label">
<input id="checkbox-${task.id}" type="checkbox" ${task.checked ? "checked":""}>
<div class="checkbox-display"></div>
</label>
<input id="input-${task.id}" "type="text" value="${task.itemName}" class="text-input task-input">
<button id="delete-${task.id}">Delete Item</button>
</div>
`;
document.getElementById("list-"+listId).querySelector(".item-list").insertAdjacentHTML("afterbegin", tempHTML);
document.getElementById(`input-${task.id}`).onchange = (e) => {
renameTask(task.id, document.getElementById(`input-${task.id}`).value);
};
document.getElementById(`checkbox-${task.id}`).onchange = function(e){
document.getElementById(`task-${task.id}`).classList.toggle('completed', e.target.checked);
setCheckedTask(task.id, e.target.checked);
};
document.getElementById(`delete-${task.id}`).onclick = () => deleteTask(task.id);
}
//Adds task through /AddListItem POST endpoint
async function addTask(listIdParam) {
const taskInput = document.getElementById(`task-input-${listIdParam}`);
const description = taskInput.value.trim();
if (description) {
try {
const response = await fetch(`${endpoint}/AddListItem/`, {
method: 'POST',
headers: {
'authorization':API_KEY,
'Content-Type': 'application/json',
},
body: JSON.stringify({
listId: listIdParam,
itemName: description
})
});
const newTask = await response.json();
if(newTask.status == "200"){
createTaskElement(newTask.listItem, listIdParam);
}
taskInput.value = '';
} catch (error) {
console.error('Error adding task:', error);
}
}
}
//Rename task through /RenameItem/ PATCH endpoint
async function renameTask(thisItemId, newName) {
try {
await fetch(`${endpoint}/RenameItem/?${new URLSearchParams({
itemId: thisItemId,
newItemName: newName
})}`, {
method: 'PATCH',
headers: {
'authorization':API_KEY,
'Content-Type': 'application/json',
}
});
} catch (error) {
console.error('Error updating task:', error);
}
}
//Set checked task through /SetChecked/ PATCH endpoint
async function setCheckedTask(thisItemId, newChecked) {
try {
const response = await fetch(`${endpoint}/SetChecked/?${new URLSearchParams({
itemId: thisItemId,
checked: newChecked
})}`, {
method: 'PATCH',
headers:{
'authorization':API_KEY,
'Content-Type': 'application/json',
}
});
} catch (error) {
console.error('Error updating task:', error);
}
}
//Deletes task through /DeleteListItem/ DELETE endpoint
async function deleteTask(taskId) {
try {
await fetch(`${endpoint}/DeleteListItem/?${new URLSearchParams({
itemId: taskId,
})}`, {
method: 'DELETE',
headers:{
'authorization':API_KEY,
'Content-Type': 'application/json',
},
});
const taskElement = document.getElementById(`task-${taskId}`);
taskElement.classList.add("fadeOut");
setTimeout(function(){
taskElement.remove();
}, 500);
} catch (error) {
console.error('Error deleting task:', error);
}
}
fetchLists();
getStatus();