Commit 10e7e354 authored by Irina Kera Gundersen's avatar Irina Kera Gundersen
Browse files

Refactor code in frontend

parent e2684002
Pipeline #128209 passed with stages
in 2 minutes and 45 seconds
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
}
};
{
"eslint.alwaysShowStatus": true,
"eslint.run": "onSave"
}
\ No newline at end of file
...@@ -4,14 +4,15 @@ let deleteButton; ...@@ -4,14 +4,15 @@ let deleteButton;
let editButton; let editButton;
let oldFormData; let oldFormData;
function disableExerciseForm() {
function handleCancelButtonDuringEdit() {
setReadOnly(true, "#form-exercise"); setReadOnly(true, "#form-exercise");
okButton.className += " hide"; okButton.className += " hide";
deleteButton.className += " hide"; deleteButton.className += " hide";
cancelButton.className += " hide"; cancelButton.className += " hide";
editButton.className = editButton.className.replace(" hide", ""); editButton.className = editButton.className.replace(" hide", "");
}
function handleCancelButtonDuringEdit() {
disableExerciseForm();
cancelButton.removeEventListener("click", handleCancelButtonDuringEdit); cancelButton.removeEventListener("click", handleCancelButtonDuringEdit);
let form = document.querySelector("#form-exercise"); let form = document.querySelector("#form-exercise");
...@@ -19,7 +20,7 @@ function handleCancelButtonDuringEdit() { ...@@ -19,7 +20,7 @@ function handleCancelButtonDuringEdit() {
if (oldFormData.has("description")) form.description.value = oldFormData.get("description"); if (oldFormData.has("description")) form.description.value = oldFormData.get("description");
if (oldFormData.has("category")) form.category.value = oldFormData.get("category"); if (oldFormData.has("category")) form.category.value = oldFormData.get("category");
if (oldFormData.has("unit")) form.unit.value = oldFormData.get("unit"); if (oldFormData.has("unit")) form.unit.value = oldFormData.get("unit");
oldFormData.delete("name"); oldFormData.delete("name");
oldFormData.delete("description"); oldFormData.delete("description");
oldFormData.delete("category"); oldFormData.delete("category");
...@@ -34,10 +35,12 @@ function handleCancelButtonDuringCreate() { ...@@ -34,10 +35,12 @@ function handleCancelButtonDuringCreate() {
async function createExercise() { async function createExercise() {
let form = document.querySelector("#form-exercise"); let form = document.querySelector("#form-exercise");
let formData = new FormData(form); let formData = new FormData(form);
let body = {"name": formData.get("name"), let body = {
"description": formData.get("description"), "name": formData.get("name"),
"category": formData.get("category"), "description": formData.get("description"),
"unit": formData.get("unit")}; "category": formData.get("category"),
"unit": formData.get("unit")
};
let response = await sendRequest("POST", `${HOST}/api/exercises/`, body); let response = await sendRequest("POST", `${HOST}/api/exercises/`, body);
...@@ -83,7 +86,7 @@ async function retrieveExercise(id) { ...@@ -83,7 +86,7 @@ async function retrieveExercise(id) {
let alert = createAlert("Could not retrieve exercise data!", data); let alert = createAlert("Could not retrieve exercise data!", data);
document.body.prepend(alert); document.body.prepend(alert);
} else { } else {
exerciseData = await response.json(); exerciseData = await response.json();
let form = document.querySelector("#form-exercise"); let form = document.querySelector("#form-exercise");
let formData = new FormData(form); let formData = new FormData(form);
...@@ -103,10 +106,12 @@ async function retrieveExercise(id) { ...@@ -103,10 +106,12 @@ async function retrieveExercise(id) {
async function updateExercise(id) { async function updateExercise(id) {
let form = document.querySelector("#form-exercise"); let form = document.querySelector("#form-exercise");
let formData = new FormData(form); let formData = new FormData(form);
let body = {"name": formData.get("name"), let body = {
"description": formData.get("description"), "name": formData.get("name"),
"category": formData.get("category"), "description": formData.get("description"),
"unit": formData.get("unit")}; "category": formData.get("category"),
"unit": formData.get("unit")
};
let response = await sendRequest("PUT", `${HOST}/api/exercises/${id}/`, body); let response = await sendRequest("PUT", `${HOST}/api/exercises/${id}/`, body);
if (!response.ok) { if (!response.ok) {
...@@ -114,16 +119,10 @@ async function updateExercise(id) { ...@@ -114,16 +119,10 @@ async function updateExercise(id) {
let alert = createAlert(`Could not update exercise ${id}`, data); let alert = createAlert(`Could not update exercise ${id}`, data);
document.body.prepend(alert); document.body.prepend(alert);
} else { } else {
// duplicate code from handleCancelButtonDuringEdit disableExerciseForm();
// you should refactor this
setReadOnly(true, "#form-exercise");
okButton.className += " hide";
deleteButton.className += " hide";
cancelButton.className += " hide";
editButton.className = editButton.className.replace(" hide", "");
cancelButton.removeEventListener("click", handleCancelButtonDuringEdit); cancelButton.removeEventListener("click", handleCancelButtonDuringEdit);
oldFormData.delete("name"); oldFormData.delete("name");
oldFormData.delete("description"); oldFormData.delete("description");
oldFormData.delete("category"); oldFormData.delete("category");
...@@ -149,7 +148,7 @@ window.addEventListener("DOMContentLoaded", async () => { ...@@ -149,7 +148,7 @@ window.addEventListener("DOMContentLoaded", async () => {
editButton.addEventListener("click", handleEditExerciseButtonClick); editButton.addEventListener("click", handleEditExerciseButtonClick);
deleteButton.addEventListener("click", (async (id) => await deleteExercise(id)).bind(undefined, exerciseId)); deleteButton.addEventListener("click", (async (id) => await deleteExercise(id)).bind(undefined, exerciseId));
okButton.addEventListener("click", (async (id) => await updateExercise(id)).bind(undefined, exerciseId)); okButton.addEventListener("click", (async (id) => await updateExercise(id)).bind(undefined, exerciseId));
} }
//create //create
else { else {
setReadOnly(false, "#form-exercise"); setReadOnly(false, "#form-exercise");
......
...@@ -17,7 +17,7 @@ async function fetchExerciseTypes(request) { ...@@ -17,7 +17,7 @@ async function fetchExerciseTypes(request) {
h5.textContent = exercise.name; h5.textContent = exercise.name;
const p = exerciseAnchor.querySelector("p"); const p = exerciseAnchor.querySelector("p");
p.textContent = exercise.description; p.textContent = exercise.description;
container.appendChild(exerciseAnchor); container.appendChild(exerciseAnchor);
} }
......
async function login() { async function login() {
let form = document.querySelector("#form-login"); let form = document.querySelector("#form-login");
let formData = new FormData(form); let formData = new FormData(form);
let body = {"username": formData.get("username"), "password": formData.get("password")}; let body = { "username": formData.get("username"), "password": formData.get("password") };
let response = await sendRequest("POST", `${HOST}/api/token/`, body) let response = await sendRequest("POST", `${HOST}/api/token/`, body)
if (response.ok) { if (response.ok) {
...@@ -19,15 +19,15 @@ async function login() { ...@@ -19,15 +19,15 @@ async function login() {
} }
// Sets cookie if remember me checked // Sets cookie if remember me checked
var rememberMe = document.getElementById("rememberMe").checked; let rememberMe = document.getElementById("rememberMe").checked;
if (rememberMe) { if (rememberMe) {
let response = await sendRequest("GET", `${HOST}/api/remember_me/`); let response = await sendRequest("GET", `${HOST}/api/remember_me/`);
if(response.ok) { if (response.ok) {
let data = await response.json(); let data = await response.json();
setCookie("remember_me", data.remember_me, 3000000000, "/"); setCookie("remember_me", data.remember_me, 3000000000, "/");
} }
} }
}; }
// Used for login if remember me cookie exists // Used for login if remember me cookie exists
async function rememberMe() { async function rememberMe() {
...@@ -44,10 +44,10 @@ async function rememberMe() { ...@@ -44,10 +44,10 @@ async function rememberMe() {
let alert = createAlert("Login failed!", data); let alert = createAlert("Login failed!", data);
document.body.prepend(alert); document.body.prepend(alert);
} }
}; }
window.onload = function() { window.onload = function () {
if (getCookieValue('remember_me')){ if (getCookieValue('remember_me')) {
rememberMe(); rememberMe();
} }
}; };
......
...@@ -9,8 +9,6 @@ function isUserAuthenticated() { ...@@ -9,8 +9,6 @@ function isUserAuthenticated() {
} }
function updateNavBar() { function updateNavBar() {
let nav = document.querySelector("nav");
// Emphasize link to current page // Emphasize link to current page
if ( if (
window.location.pathname == "/" || window.location.pathname == "/" ||
......
...@@ -6,32 +6,29 @@ async function fetchWorkouts(ordering) { ...@@ -6,32 +6,29 @@ async function fetchWorkouts(ordering) {
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} else {
let data = await response.json();
let workouts = data.results;
return workouts;
} }
let data = await response.json();
let workouts = data.results;
return workouts;
} }
function isLastWeek(date) { function isLastWeek(date) {
let lastWeek = new Date(); let lastWeek = new Date();
let today = new Date(); const today = new Date();
let past = lastWeek.getDate() - 7; const past = lastWeek.getDate() - 7;
lastWeek.setDate(past); lastWeek.setDate(past);
console.log(today);
return date >= lastWeek && date <= today; return date >= lastWeek && date <= today;
} }
function isLastMonth(date) { function isLastMonth(date) {
let lastMonth = new Date(); let lastMonth = new Date();
let today = new Date(); const today = new Date();
let past = lastMonth.getDate() - 30; const past = lastMonth.getDate() - 30;
lastMonth.setDate(past); lastMonth.setDate(past);
return date >= lastMonth && date <= today; return date >= lastMonth && date <= today;
} }
function isLastYear(date) { function isLastYear(date) {
let lastYear = new Date(); let lastYear = new Date();
let today = new Date(); const today = new Date();
let past = lastYear.getDate() - 365; const past = lastYear.getDate() - 365;
lastYear.setDate(past); lastYear.setDate(past);
return date >= lastYear && date <= today; return date >= lastYear && date <= today;
} }
...@@ -48,15 +45,11 @@ window.addEventListener("DOMContentLoaded", async () => { ...@@ -48,15 +45,11 @@ window.addEventListener("DOMContentLoaded", async () => {
} }
let workouts = await fetchWorkouts(ordering); let workouts = await fetchWorkouts(ordering);
console.log(workouts.length);
for (let i = 0; i < workouts.length; i++) { for (let i = 0; i < workouts.length; i++) {
let workout = workouts[i]; let workout = workouts[i];
let d = workout.date; let d = workout.date;
let wDate = new Date(d.slice(0, 4), d.slice(5, 7) - 1, d.slice(8, 10)); let wDate = new Date(d.slice(0, 4), d.slice(5, 7) - 1, d.slice(8, 10));
console.log("last week", isLastWeek(wDate));
console.log("last month", isLastMonth(wDate));
console.log("last year", isLastYear(wDate));
if (workout.owner == currentUser.url) { if (workout.owner == currentUser.url) {
if (isLastWeek(wDate)) { if (isLastWeek(wDate)) {
...@@ -75,6 +68,5 @@ window.addEventListener("DOMContentLoaded", async () => { ...@@ -75,6 +68,5 @@ window.addEventListener("DOMContentLoaded", async () => {
document.getElementById("month").innerHTML = thirtyDays; document.getElementById("month").innerHTML = thirtyDays;
document.getElementById("year").innerHTML = threeSixtyFive; document.getElementById("year").innerHTML = threeSixtyFive;
console.log(sevenDays, thirtyDays, threeSixtyFive);
} }
}); });
//single_test.js:Jest testing tutorial for Selenium JavaScript Testing
/**
* @jest-environment jest-environment-webdriver
*/
const webdriver = require('selenium-webdriver');
const script = require('jest');
const url = 'https://www.selenium.dev/'
const getElementXpath = async (driver, xpath, timeout = 3000) => {
const el = await driver.wait(until.elementLocated(By.xpath(xpath)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
const getElementName = async (driver, name, timeout = 3000) => {
const el = await driver.wait(until.elementLocated(By.name(name)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
const getElementId = async (driver, id, timeout = 3000) => {
const el = await driver.wait(until.elementLocated(By.id(id)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
// declaring the test group This is our test case scenario that we will execute from our first test script.
describe('executing test scenario on the website www.selenium.dev', () => {
let driver;
driver = new webdriver().build();
// func to get the cloud driver eslint disable next line no undef
await driver.get(
https://www.selenium.dev’,
);
}, 10000);
afterAll(async () => {
await driver.quit();
}, 15000);
test('it performs a validation of title on the home page', async () => {
await browser.get(url)
const title = await browser.findElement(by.tagName('h1')).getText()
expect(title).toContain('SeleniumHQ Browser Automation')
})
test('it performs a validation of the search box on the page', async () => {
const foundAndLoadedCheck = async () => {
await until.elementLocated(by.id('search'))
const value = await browser.findElement(by.id('search')).getText()
return value !== '~'
}
await browser.wait(foundAndLoadedCheck, 3000)
const search = await browser.findElement(by.id('search')).getText()
expect(search).toEqual('')
})
// declaring the test group
describe('it captures a screenshot of the current page on the browser', () => {
test('snap a picture by taking the screenshot', async () => {
// files saved in ./reports/screenshots by default
await browser.get(url)
await browser.takeScreenshot()
})
})
})
\ No newline at end of file
...@@ -20,13 +20,13 @@ async function retrieveWorkout(id) { ...@@ -20,13 +20,13 @@ async function retrieveWorkout(id) {
let selector = `input[name="${key}"], textarea[name="${key}"]`; let selector = `input[name="${key}"], textarea[name="${key}"]`;
let input = form.querySelector(selector); let input = form.querySelector(selector);
let newVal = workoutData[key]; let newVal = workoutData[key];
if (key == "date") { if (key === "date") {
// Creating a valid datetime-local string with the correct local time // Creating a valid datetime-local string with the correct local time
let date = new Date(newVal); let date = new Date(newVal);
date = new Date( date = new Date(
date.getTime() - date.getTimezoneOffset() * 60 * 1000 date.getTime() - date.getTimezoneOffset() * 60 * 1000
).toISOString(); // get ISO format for local time ).toISOString();
newVal = date.substring(0, newVal.length - 1); // remove Z (since this is a local time, not UTC) newVal = date.substring(0, newVal.length - 1);
} }
if (key != "files") { if (key != "files") {
input.value = newVal; input.value = newVal;
...@@ -79,7 +79,7 @@ async function retrieveWorkout(id) { ...@@ -79,7 +79,7 @@ async function retrieveWorkout(id) {
for (let j = 0; j < exerciseTypes.count; j++) { for (let j = 0; j < exerciseTypes.count; j++) {
let option = document.createElement("option"); let option = document.createElement("option");
option.value = exerciseTypes.results[j].id; option.value = exerciseTypes.results[j].id;
if (currentExerciseTypeId == exerciseTypes.results[j].id) { if (currentExerciseTypeId === exerciseTypes.results[j].id) {
currentExerciseType = exerciseTypes.results[j]; currentExerciseType = exerciseTypes.results[j];
} }
option.innerText = exerciseTypes.results[j].name; option.innerText = exerciseTypes.results[j].name;
...@@ -103,7 +103,7 @@ async function retrieveWorkout(id) { ...@@ -103,7 +103,7 @@ async function retrieveWorkout(id) {
let exerciseNumberLabel = divExerciseContainer.querySelector( let exerciseNumberLabel = divExerciseContainer.querySelector(
".exercise-number" ".exercise-number"
); );
(exerciseNumberLabel.for = "for"), `inputNumber${i}`; (exerciseNumberLabel.for = "for")`inputNumber${i}`;
exerciseNumberLabel.innerText = currentExerciseType.unit; exerciseNumberLabel.innerText = currentExerciseType.unit;
let exerciseNumberInput = divExerciseContainer.querySelector( let exerciseNumberInput = divExerciseContainer.querySelector(
...@@ -129,9 +129,8 @@ function athleteChecked() { ...@@ -129,9 +129,8 @@ function athleteChecked() {
let checkBox = document.getElementById("forAthlete"); let checkBox = document.getElementById("forAthlete");
let athletes = document.getElementById("athletes"); let athletes = document.getElementById("athletes");
let myself = document.getElementById("inputOwner"); let myself = document.getElementById("inputOwner");
console.log(checkBox.checked);
if (checkBox.checked == true) { if (checkBox.checked === true) {
athletes.style.display = "block"; athletes.style.display = "block";
myself.style.display = "none"; myself.style.display = "none";
} else { } else {
...@@ -151,7 +150,6 @@ async function athletesInDropdown() { ...@@ -151,7 +150,6 @@ async function athletesInDropdown() {
newElement.text = athlete.username; newElement.text = athlete.username;
ath.add(newElement); ath.add(newElement);
} }
click = true;
} }
function handleEditWorkoutButtonClick() { function handleEditWorkoutButtonClick() {
...@@ -160,7 +158,8 @@ function handleEditWorkoutButtonClick() { ...@@ -160,7 +158,8 @@ function handleEditWorkoutButtonClick() {
setReadOnly(false, "#form-workout"); setReadOnly(false, "#form-workout");
document.querySelector("#inputOwner").readOnly = true; // owner field should still be readonly // owner field should still be readonly
document.querySelector("#inputOwner").readOnly = true;
editWorkoutButton.className += " hide"; editWorkoutButton.className += " hide";
okWorkoutButton.className = okWorkoutButton.className.replace(" hide", ""); okWorkoutButton.className = okWorkoutButton.className.replace(" hide", "");
...@@ -272,8 +271,6 @@ function handleCancelDuringWorkoutCreate() { ...@@ -272,8 +271,6 @@ function handleCancelDuringWorkoutCreate() {
} }
async function createBlankExercise() { async function createBlankExercise() {
let form = document.querySelector("#form-workout");
let exerciseTypeResponse = await sendRequest("GET", `${HOST}/api/exercises/`); let exerciseTypeResponse = await sendRequest("GET", `${HOST}/api/exercises/`);
let exerciseTypes = await exerciseTypeResponse.json(); let exerciseTypes = await exerciseTypeResponse.json();
...@@ -375,7 +372,7 @@ async function retrieveComments(workoutid) { ...@@ -375,7 +372,7 @@ async function retrieveComments(workoutid) {
let comments = data.results; let comments = data.results;
for (let comment of comments) { for (let comment of comments) {
let splitArray = comment.workout.split("/"); let splitArray = comment.workout.split("/");
if (splitArray[splitArray.length - 2] == workoutid) { if (splitArray[splitArray.length - 2] === workoutid) {
addComment(comment.owner, comment.content, comment.timestamp, true); addComment(comment.owner, comment.content, comment.timestamp, true);
} }
} }
...@@ -404,7 +401,7 @@ window.addEventListener("DOMContentLoaded", async () => { ...@@ -404,7 +401,7 @@ window.addEventListener("DOMContentLoaded", async () => {
await retrieveComments(id); await retrieveComments(id);
console.log(currentUser.url); console.log(currentUser.url);
if (workoutData["owner"] == currentUser.url) { if (workoutData["owner"] === currentUser.url) {
editWorkoutButton.classList.remove("hide"); editWorkoutButton.classList.remove("hide");
editWorkoutButton.addEventListener("click", handleEditWorkoutButtonClick); editWorkoutButton.addEventListener("click", handleEditWorkoutButtonClick);
deleteWorkoutButton.addEventListener( deleteWorkoutButton.addEventListener(
......
...@@ -27,13 +27,13 @@ async function fetchWorkouts(ordering) { ...@@ -27,13 +27,13 @@ async function fetchWorkouts(ordering) {
let rows = table.querySelectorAll("tr"); let rows = table.querySelectorAll("tr");
rows[0].querySelectorAll( rows[0].querySelectorAll(
"td" "td"
)[1].textContent = localDate.toLocaleDateString(); // Date )[1].textContent = localDate.toLocaleDateString();
rows[1].querySelectorAll( rows[1].querySelectorAll(
"td" "td"
)[1].textContent = localDate.toLocaleTimeString(); // Time )[1].textContent = localDate.toLocaleTimeString();
rows[2].querySelectorAll("td")[1].textContent = workout.owner_username; //Owner rows[2].querySelectorAll("td")[1].textContent = workout.owner_username;
rows[3].querySelectorAll("td")[1].textContent = rows[3].querySelectorAll("td")[1].textContent =
workout.exercise_instances.length; // Exercises workout.exercise_instances.length;
container.appendChild(aWorkout); container.appendChild(aWorkout);
}); });
...@@ -52,7 +52,6 @@ window.addEventListener("DOMContentLoaded", async () => { ...@@ -52,7 +52,6 @@ window.addEventListener("DOMContentLoaded", async () => {
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has("ordering")) { if (urlParams.has("ordering")) {
let aSort = null;
ordering = urlParams.get("ordering"); ordering = urlParams.get("ordering");
if (ordering == "name" || ordering == "owner" || ordering == "date") { if (ordering == "name" || ordering == "owner" || ordering == "date") {
let aSort = document.querySelector(`a[href="?ordering=${ordering}"`); let aSort = document.querySelector(`a[href="?ordering=${ordering}"`);
...@@ -76,12 +75,9 @@ window.addEventListener("DOMContentLoaded", async () => { ...@@ -76,12 +75,9 @@ window.addEventListener("DOMContentLoaded", async () => {
let tabEls = document.querySelectorAll('a[data-bs-toggle="list"]'); let tabEls = document.querySelectorAll('a[data-bs-toggle="list"]');
for (let i = 0;