Skip to content

Week 2 Done #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,6 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

# some screenshots of my projects using vs code carbon extension
carbon
11 changes: 5 additions & 6 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,16 @@
</nav>
<center>
<div class="input-group mb-3 todo-add-task">
<input type="text" class="form-control" placeholder="Enter Task">
<input type="text" class="form-control" placeholder="Enter Task" id="add-task-input">
<div class="input-group-append">
<button type="button" class="btn btn-outline-success" onclick="addTask()">Add Task</button>
<button type="button" class="btn btn-outline-success" id="add-task-btn">Add Task</button>
</div>
</div>
<ul class="list-group todo-available-tasks">
<ul class="list-group todo-available-tasks" id="final-list">
<span class="badge badge-primary badge-pill todo-available-tasks-text">
Available Tasks
</span>


<li class="list-group-item d-flex justify-content-between align-items-center">
<input id="input-button-1" type="text" class="form-control todo-edit-task-input hideme" placeholder="Edit The Task">
<div id="done-button-1" class="input-group-append hideme">
Expand All @@ -75,7 +74,7 @@
</div>

<span id="task-actions-1">
<button style="margin-right:5px;" type="button" onclick="editTask(1)"
<button style="margin-right:5px;" type="button"
class="btn btn-outline-warning">
<img src="https://res.cloudinary.com/nishantwrp/image/upload/v1587486663/CSOC/edit.png"
width="18px" height="20px">
Expand All @@ -98,7 +97,7 @@
Sample Task 2
</div>
<span id="task-actions-2">
<button style="margin-right:5px;" type="button" onclick="editTask(2)"
<button style="margin-right:5px;" type="button"
class="btn btn-outline-warning">
<img src="https://res.cloudinary.com/nishantwrp/image/upload/v1587486663/CSOC/edit.png"
width="18px" height="20px">
Expand Down
2 changes: 1 addition & 1 deletion login/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
<label>Password</label>
<input type="Password" class="form-control" id="inputPassword">
</div>
<button class="btn btn-outline-success my-2 my-sm-0" onclick="login()" type="submit">Log In</button>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="login-btn">Log In</button>
</div>
</body>

Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion register/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
<label for="inputAddress2">Password</label>
<input type="Password" class="form-control" id="inputPassword">
</div>
<button class="btn btn-outline-success my-2 my-sm-0" onclick="register()" type="submit">Register</button>
<button class="btn btn-outline-success my-2 my-sm-0" id="register-btn" type="submit">Register</button>
</div>
</body>

Expand Down
10 changes: 10 additions & 0 deletions src/auth_required.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
/***
* @todo Redirect the user to login page if token is not present.
*/
checkTokenAuthReq();

function checkTokenAuthReq() {
const token = localStorage.getItem("token");

// if the token is empty, redirect
if (!token) {
window.location.href = "/login/"
}
}
60 changes: 59 additions & 1 deletion src/init.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,64 @@
import axios from 'axios';
import mainJsImports from "./main.js";

const API_BASE_URL = 'https://todo-app-csoc.herokuapp.com/';

function createTaskLi(data) {
console.log("createTaskLi is running");

// clearing the previous form
document.querySelector("#final-list").innerHTML = "";

data.data.forEach((element, index) => {

document.querySelector("#final-list").innerHTML +=
`<li class="list-group-item d-flex justify-content-between align-items-center">
<input id="input-button-${element.id}" type="text" class="form-control todo-edit-task-input hideme" placeholder="Edit The Task">
<div id="done-button-${element.id}" class="input-group-append hideme">
<button class="btn btn-outline-secondary todo-update-task" data-id="${element.id}" type="button">Done</button>
</div>
<div id="task-${element.id}" class="todo-task">
${element.title}
</div>

<span id="task-actions-${element.id}">
<button style="margin-right:5px;" type="button"
class="btn btn-outline-warning btn-task-edit" id="" data-id="${element.id}">
<img src="https://res.cloudinary.com/nishantwrp/image/upload/v1587486663/CSOC/edit.png"
width="18px" height="20px">
</button>
<button type="button" class="btn btn-outline-danger btn-task-del" data-id="${element.id}" id="task-${element.id}">
<img src="https://res.cloudinary.com/nishantwrp/image/upload/v1587486661/CSOC/delete.svg"
width="18px" height="22px">
</button>
</span>
</li>`;
});

}

function getTasks() {
/***
* @todo Fetch the tasks created by the user and display them in the dom.
*/

console.log("getTasks hasn't yee'd his last haw yet");

axios({
headers: {
Authorization: "Token " + localStorage.getItem("token"),
},
url: API_BASE_URL + "todo/",
method: 'get',
}).then((data, status) => {
console.log(data);

createTaskLi(data);

mainJsImports.setBtnGrpListeners(".btn-task-del", mainJsImports.deleteTask);
mainJsImports.setBtnGrpListeners(".btn-task-edit", mainJsImports.editTask);
mainJsImports.setBtnGrpListeners(".todo-update-task", mainJsImports.updateTask);
});
}

axios({
Expand All @@ -17,4 +71,8 @@ axios({
document.getElementById('avatar-image').src = 'https://ui-avatars.com/api/?name=' + data.name + '&background=fff&size=33&color=007bff';
document.getElementById('profile-name').innerHTML = data.name;
getTasks();
})
});

const exports = { getTasks: getTasks };

export default exports;
166 changes: 163 additions & 3 deletions src/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,41 @@
import axios from 'axios';
import exports from "./init.js";

setClickListeners();
setBtnGrpListeners(".btn-task-del", deleteTask);
setBtnGrpListeners(".btn-task-edit", editTask);
setBtnGrpListeners(".todo-update-task", updateTask);

function setClickListeners() {
const btnArrays = [];
const btnListenerFuncs = [login, register, addTask];

btnArrays.push(document.querySelector("#login-btn"));
btnArrays.push(document.querySelector("#register-btn"));
btnArrays.push(document.querySelector("#add-task-btn"));

btnArrays.forEach((element, index) => {
if (element !== null) {
console.log(element.id);
element.addEventListener("click", () => {
btnListenerFuncs[index]();
});
}
});
}

// this function sets up event listeners for a group of buttons, like delete or edit buttons of tasks,
// using a 'func' argument function passed in, which operates on the button's dataset.id property
function setBtnGrpListeners(queryString, func) {
const btns = Array.from(document.querySelectorAll(queryString));

btns.forEach((element) => {
element.addEventListener("click", () => {
func(element.dataset.id);
});
});
}

function displaySuccessToast(message) {
iziToast.success({
title: 'Success',
Expand Down Expand Up @@ -39,7 +76,19 @@ function registerFieldsAreValid(firstName, lastName, email, username, password)
return true;
}

// function to validate login fields, uses name similar to regsiterFieldsAreValid to maintain project consistency
function loginFieldsAreValid(username, password) {
if (username === '' || password === '') {
displayErrorToast("Please fill all the fields correctly.");
return false;
}

return true;
}

function register() {
alert("register's still not bitten the dust")

const firstName = document.getElementById('inputFirstName').value.trim();
const lastName = document.getElementById('inputLastName').value.trim();
const email = document.getElementById('inputEmail').value.trim();
Expand All @@ -61,10 +110,10 @@ function register() {
method: 'post',
data: dataForApiRequest,
}).then(function({data, status}) {
localStorage.setItem('token', data.token);
window.location.href = '/';
localStorage.setItem('token', data.token);
window.location.href = '/';
}).catch(function(err) {
displayErrorToast('An account using same email or username is already created');
displayErrorToast('An account using same email or username is already created');
})
}
}
Expand All @@ -75,6 +124,39 @@ function login() {
* @todo 1. Write code for form validation.
* @todo 2. Fetch the auth token from backend, login and direct user to home page.
*/

// testing if the event listeners work
// alert("login event listener didn't get l + ratio'd");

const username = document.getElementById('inputUsername').value.trim();
const password = document.getElementById('inputPassword').value;

console.log(username, password);

if (loginFieldsAreValid(username, password)) {
displayInfoToast("Please wait...");

const loginReqData = {
username: username,
password: password
};

console.log(axios);

axios({
url: API_BASE_URL + "auth/login/",
method: "post",
data: loginReqData
}).then(({data, status}) => {
console.log(status);
console.log("the login promise was done successfully :)");
localStorage.setItem("token", data.token);
window.location.href = '/';
}).catch(err => {
console.log("well shit >:(");
displayErrorToast('An account using same email or username is already created');
});
}
}

function addTask() {
Expand All @@ -83,6 +165,34 @@ function addTask() {
* @todo 1. Send the request to add the task to the backend server.
* @todo 2. Add the task in the dom.
*/

console.log("addTask is trying his best, don't bully it :(");

const newTask = document.querySelector("#add-task-input").value;
console.log(newTask);

const createTaskData = {
title: newTask
};

if (newTask.length > 0) {
axios({
headers: {
Authorization: "Token " + localStorage.getItem("token"),
},
url: API_BASE_URL + "todo/create/",
method: 'post',
data: createTaskData
}).then((data, status) => {
console.log(data, status);
exports.getTasks();
}).catch(err => {

});
}

document.querySelector("#add-task-input").value = "";

}

function editTask(id) {
Expand All @@ -98,6 +208,21 @@ function deleteTask(id) {
* @todo 1. Send the request to delete the task to the backend server.
* @todo 2. Remove the task from the dom.
*/

// console.log(id);
axios({
headers: {
Authorization: "Token " + localStorage.getItem("token"),
},
url: API_BASE_URL + `todo/${id}`,
method: 'delete',
}).then((data, status) => {
console.log(data, status);
displaySuccessToast("The task has been successfully deleted :)");
exports.getTasks();
}).catch(err => {
displayErrorToast("Some error occurred and we could not delete the task :(");
});
}

function updateTask(id) {
Expand All @@ -106,4 +231,39 @@ function updateTask(id) {
* @todo 1. Send the request to update the task to the backend server.
* @todo 2. Update the task in the dom.
*/

console.log("Ayy this is updateTask here :D");

const newVal = document.querySelector(`#input-button-${id}`).value;
const headersForApiRequest = {
Authorization: 'Token ' + localStorage.getItem('token')
}

axios({
headers: headersForApiRequest,
url: API_BASE_URL + `todo/${id}/`,
method: 'put',
data: {
title: newVal
}
}).then(({ data, status }) => {
displaySuccessToast("Task updated");
exports.getTasks();
}).catch((err) => {
displayErrorToast("Failed to update task");
});

document.getElementById('task-' + id).classList.remove('hideme');
document.getElementById('task-actions-' + id).classList.remove('hideme');
document.getElementById('input-button-' + id).classList.add('hideme');
document.getElementById('done-button-' + id).classList.add('hideme');
}

const mainJsExports = {
setBtnGrpListeners,
deleteTask,
editTask,
updateTask
};

export default mainJsExports;
12 changes: 11 additions & 1 deletion src/no_auth_required.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
/***
* @todo Redirect the user to main page if token is present.
*/
*/
checkTokenAuthNotReq();

function checkTokenAuthNotReq() {
const token = localStorage.getItem("token");

// if the token is not empty, redirect to main page
if (token) {
window.location.href = "/";
}
}