From c3b6d083be07da2831bff06496137200547fc947 Mon Sep 17 00:00:00 2001 From: rstular Date: Thu, 14 May 2020 02:39:45 +0200 Subject: Styling fixes, documentation --- js/absences.js | 4 ++-- js/app.js | 10 +++----- js/chats.js | 2 +- js/gradings.js | 8 +++---- js/initialize.js | 7 +----- js/lib/mergedeep.js | 25 ++++++++++---------- js/meals.js | 68 ++++++++++++++++++++++++++++++++++------------------- js/settings.js | 3 ++- js/timetable.js | 29 +++++++++++++++++++++-- 9 files changed, 96 insertions(+), 60 deletions(-) (limited to 'js') diff --git a/js/absences.js b/js/absences.js index 4057dec..9bc4a83 100644 --- a/js/absences.js +++ b/js/absences.js @@ -123,7 +123,7 @@ function displayData() { break; case 1: subject_lesson_icon_i.innerText = "check_circle_outline"; - break; + break; case 2: subject_lesson_icon_i.innerText = "error_outline"; break; @@ -135,7 +135,7 @@ function displayData() { subject_lesson_icon.appendChild(subject_lesson_icon_i); let subject_name = document.createElement("td"); - subject_name.innerText = S(gseAbsenceTypes[absence["subjects"][lesson]["status"]]) + " : " + absence["subjects"][lesson]["subject"]; + subject_name.innerText = `${S(gseAbsenceTypes[absence["subjects"][lesson]["status"]])} : ${absence["subjects"][lesson]["subject"]}`; subject_row.appendChild(subject_lesson_icon); subject_row.appendChild(subject_lesson_text); subject_row.appendChild(subject_name); diff --git a/js/app.js b/js/app.js index 022b946..20cfae4 100644 --- a/js/app.js +++ b/js/app.js @@ -13,21 +13,17 @@ if (navigator.serviceWorker) { }); } -if (location.protocol != 'https:') { - location.href = 'https:' + window.location.href.substring(window.location.protocol.length); -} - async function UIAlert(usermsg, devmsg) { if(true) { // če bo kakšen dev switch? M.toast( { html: usermsg } ); - console.log("[BežiApp UIAlert] "+usermsg+" "+devmsg); + console.log(`[BežiApp UIAlert] ${usermsg} ${devmsg}`); } else { - M.toast( { html: usermsg+" "+devmsg } ); + M.toast( { html: `${usermsg} ${devmsg}` } ); } } function gsecErrorHandlerUI(err) { - console.log("gsecErrorHanderUI: handling "+err); + console.log(`gsecErrorHanderUI: handling ${err}`); if(err == GSEC_ERR_NET || err == GSEC_ERR_NET_POSTBACK_GET || err == GSEC_ERR_NET_POSTBACK_POST) { UIAlert( D("gsecErrNet") ); } else if(err == GSEC_ERR_LOGIN) { diff --git a/js/chats.js b/js/chats.js index 640a2ab..778a2c9 100644 --- a/js/chats.js +++ b/js/chats.js @@ -379,8 +379,8 @@ async function startFetchingMessages() { } } catch (err) { gsecErrorHandlerUI(err); - setLoading(false); } + setLoading(false); } async function startLoadingMessagesForCategory(gsecInstance, category, lastpage) { diff --git a/js/gradings.js b/js/gradings.js index c55e743..747679a 100644 --- a/js/gradings.js +++ b/js/gradings.js @@ -137,10 +137,10 @@ function gradingClickHandler(eventClickInfo) { let grading_date_obj = gradings[grading_id]["date"]; let grading_date = dateString.longFormatted(grading_date_obj); let grading_description = gradings[grading_id]["description"]; - document.getElementById("grading-subject").innerText = grading_subject; - document.getElementById("grading-date").innerText = grading_date; - document.getElementById("grading-description").innerText = grading_description; - const modal = document.querySelectorAll('.side-modal')[0]; + $("#grading-subject").text(grading_subject); + $("#grading-date").text(grading_date); + $("#grading-description").text(grading_description); + const modal = document.querySelectorAll(".side-modal")[0]; M.Sidenav.getInstance(modal).open(); } /* diff --git a/js/initialize.js b/js/initialize.js index 7bd7cd9..cb5d210 100644 --- a/js/initialize.js +++ b/js/initialize.js @@ -1,11 +1,7 @@ function getUrlParameter(sParam) { const url_params = new URLSearchParams(window.location.search); const found_param = url_params.get(sParam); - if (found_param === null) { - return "" - } else { - return found_param - } + return found_param === null ? "" : found_param; } @@ -34,7 +30,6 @@ localforage.getItem("logged_in") } ).catch( function (err) { - // This code runs if there were any errors console.log(err); } ); diff --git a/js/lib/mergedeep.js b/js/lib/mergedeep.js index dfd0dd2..a56aa1d 100644 --- a/js/lib/mergedeep.js +++ b/js/lib/mergedeep.js @@ -5,7 +5,7 @@ * @returns {boolean} */ function isObject(item) { - return (item && typeof item === 'object' && !Array.isArray(item)); + return (item && typeof item === 'object' && !Array.isArray(item)); } /** @@ -14,19 +14,18 @@ function isObject(item) { * @param ...sources */ function mergeDeep(target, ...sources) { - if (!sources.length) return target; - const source = sources.shift(); + if (!sources.length) return target; + const source = sources.shift(); - if (isObject(target) && isObject(source)) { - for (const key in source) { - if (isObject(source[key])) { - if (!target[key]) Object.assign(target, { [key]: {} }); - mergeDeep(target[key], source[key]); - } else { - Object.assign(target, { [key]: source[key] }); - } + if (isObject(target) && isObject(source)) { + for (const key in source) { + if (isObject(source[key])) { + if (!target[key]) Object.assign(target, { [key]: {} }); + mergeDeep(target[key], source[key]); + } else { + Object.assign(target, { [key]: source[key] }); + } + } } - } - return mergeDeep(target, ...sources); } diff --git a/js/meals.js b/js/meals.js index 3423292..a69eac9 100644 --- a/js/meals.js +++ b/js/meals.js @@ -3,11 +3,11 @@ const API_ENDPOINT = "https://lopolis-api.gimb.tk/"; async function checkLogin() { localforage.getItem("logged_in_lopolis").then((value) => { if (value != true) { - document.getElementById("meals-container").hidden = true; - document.getElementById("meals-login").hidden = false; + $("#meals-container").hide(); + $("#meals-login").show(); } else { - document.getElementById("meals-container").hidden = false; - document.getElementById("meals-login").hidden = true; + $("#meals-container").show(); + $("#meals-login").hide(); loadMeals(); } }).catch((err) => { @@ -34,18 +34,23 @@ async function getToken(callback, callbackparams = []) { }) ]; await Promise.all(promises_to_run); + $.ajax({ - url: API_ENDPOINT+"gettoken", + url: API_ENDPOINT + "gettoken", crossDomain: true, contentType: "application/json", - data: JSON.stringify( { "username": username, "password": password } ), + data: JSON.stringify({ + "username": username, + "password": password + }), + dataType: "json", cache: false, type: "POST", + success: (dataauth) => { if(dataauth === null || dataauth.error == true) { UIAlert(D("authenticationError"), "getToken(): response error or null"); - setLoading(false); localforage.setItem("logged_in_lopolis", false).then( function(){ checkLogin(); }); @@ -54,11 +59,10 @@ async function getToken(callback, callbackparams = []) { empty.token = dataauth.data; let argumentsToCallback = [empty].concat(callbackparams); callback(...argumentsToCallback); // poslje token v {token: xxx} - setLoading(false); } else { UIAlert( D("authenticationError"), "getToken(): invalid response, no condition met"); - setLoading(false); } + setLoading(false); }, error: () => { UIAlert( D("lopolisAPIConnectionError"), "getToken(): AJAX error"); @@ -69,22 +73,29 @@ async function getToken(callback, callbackparams = []) { async function getMenus(dataauth, callback, callbackparams = []) { setLoading(true); - let datee = new Date(); + let current_date = new Date(); // naloži za dva meseca vnaprej (če so zadnji dnevi v mesecu) let mealsgathered = {}; let promises_to_wait_for = []; for (let iteration = 1; iteration <= 2; iteration++) { + promises_to_wait_for[iteration] = $.ajax({ url: API_ENDPOINT+"getmenus", crossDomain: true, contentType: "application/json", - data: JSON.stringify({"month": datee.getMonth()+iteration, "year": datee.getFullYear()}), + data: JSON.stringify({ + "month": current_date.getMonth() + iteration, + "year": current_date.getFullYear() + }), + headers: { - "Authorization": "Bearer "+dataauth.token + "Authorization": `Bearer ${dataauth.token}` }, + dataType: "json", cache: false, type: "POST", + success: (meals) => { if(meals === null || meals.error == true) { UIAlert( D("errorGettingMenus"), "getMenus(): response error or null"); @@ -100,6 +111,7 @@ async function getMenus(dataauth, callback, callbackparams = []) { UIAlert( D("errorUnexpectedResponse") , "getMenus(): invalid response, no condition met"); } }, + error: () => { setLoading(false); UIAlert( D("lopolisAPIConnectionError"), "getMenus(): AJAX error"); @@ -112,7 +124,7 @@ async function getMenus(dataauth, callback, callbackparams = []) { let allmeals = {}; let passtocallback = {}; - for(const [index, monthmeals] of Object.entries(mealsgathered)) { // although this is not very javascripty + for (const [index, monthmeals] of Object.entries(mealsgathered)) { // although this is not very javascripty allmeals = mergeDeep(allmeals, monthmeals.data); } @@ -131,7 +143,7 @@ function displayMeals(meals) { // console.log(JSON.stringify(meals)); // debug // dela! let root_element = document.getElementById("meals-collapsible"); - for(const [date, mealzz] of Object.entries(meals.data)) { + for (const [date, mealzz] of Object.entries(meals.data)) { let unabletochoosequestionmark = ""; let readonly = mealzz.readonly; var datum = new Date(date); @@ -148,7 +160,7 @@ function displayMeals(meals) { let subject_header_text = document.createElement("span"); if(mealzz.readonly) { - unabletochoosequestionmark = "*" + S("readOnly") + "*"; + unabletochoosequestionmark = `*${S("readOnly")}*`; } // Use ES6 templates @@ -222,28 +234,33 @@ function refreshMeals(force) { function lopolisLogout() { localforage.setItem("logged_in_lopolis", false); - document.getElementById("meals-collapsible").innerHTML = ""; + $("#meals-collapsible").html(""); checkLogin(); } async function lopolisLogin() { setLoading(true); - var usernameEl = document.getElementById("meals_username"); - var passwordEl = document.getElementById("meals_password"); + var usernameEl = $("#meals_username"); + var passwordEl = $("#meals_password"); $.ajax({ url: API_ENDPOINT+"gettoken", crossDomain: true, contentType: "application/json", - data: JSON.stringify({"username": usernameEl.value, "password": passwordEl.value}), + data: JSON.stringify({ + "username": usernameEl.val(), + "password": passwordEl.val() + }), + dataType: "json", cache: false, type: "POST", + success: async function(data) { if(data == null) { UIAlert( S("requestForAuthenticationFailed"), "lopolisLogin(): date is is null"); setLoading(false); - usernameEl.value = ""; - passwordEl.value = ""; + usernameEl.val(""); + passwordEl.val(""); } else if(data.error == true) { UIAlert( S("loginFailed"), "lopolisLogin(): login failed. data.error is true"); usernameEl.value = ""; @@ -252,14 +269,15 @@ async function lopolisLogin() { } else { let promises_to_run = [ localforage.setItem("logged_in_lopolis", true), - localforage.setItem("lopolis_username", usernameEl.value), - localforage.setItem("lopolis_password", passwordEl.value) + localforage.setItem("lopolis_username", usernameEl.val()), + localforage.setItem("lopolis_password", passwordEl.val()) ]; await Promise.all(promises_to_run); checkLogin(); UIAlert("Credential match!"); } }, + error: () => { UIAlert( D("loginError"), "lopolisLogin(): ajax.error"); setLoading(false); @@ -268,7 +286,8 @@ async function lopolisLogin() { } async function setMenus(currentmeals = 69, toBeSentChoices) { // currentmeals je getMenus response in vsebuje tudi token. - if(currentmeals === 69) { + + if (currentmeals === 69) { getToken(getMenus, [setMenus, toBeSentChoices]); return; } @@ -354,5 +373,6 @@ document.addEventListener("DOMContentLoaded", async () => { showClearBtn: true, format: "dddd, dd. mmmm yyyy" }); + refreshMeals(); }); diff --git a/js/settings.js b/js/settings.js index 5811ee4..fed7fe6 100644 --- a/js/settings.js +++ b/js/settings.js @@ -7,10 +7,11 @@ async function setLanguage(langCode) { } document.addEventListener("DOMContentLoaded", async () => { - $(document).on("click",".settings-language-selector", function () { + $(document).on("click", ".settings-language-selector", () => { let languageToSet = $(this).attr("data-language"); setLanguage(languageToSet); }); + // Setup side menu const menus = document.querySelectorAll(".side-menu"); M.Sidenav.init(menus, { edge: "right", draggable: true }); diff --git a/js/timetable.js b/js/timetable.js index 2b718ad..3f7d4fc 100644 --- a/js/timetable.js +++ b/js/timetable.js @@ -7,7 +7,7 @@ function checkLogin() { localforage.getItem("logged_in").then((value) => { // This code runs once the value has been loaded // from the offline store. - if (value != true) { + if (value !== true) { window.location.replace("/index.html"); } }).catch((err) => { @@ -27,6 +27,13 @@ function setLoading(state) { // ----GET COLOR FROM STRING-------- +/** + * + * Calculate hash code from a string + * @param {string} input_string String to convert to hash + * @returns {string} calculated hash code + * + */ function hashCode(str) { // java String#hashCode var hash = 0; for (var i = 0; i < str.length; i++) { @@ -35,6 +42,13 @@ function hashCode(str) { // java String#hashCode return hash; } +/** + * + * Convert last 3 bytes of an integer to RGB color + * @param {integer} input_integer Integer that will be converted to RGB color + * @returns {string} Hex color code + * + */ function intToRGB(i) { var c = (i & 0x00FFFFFF) .toString(16) @@ -44,6 +58,12 @@ function intToRGB(i) { } // http://www.w3.org/TR/AERT#color-contrast +/** + * + * Calculate the matching foreground color for a given background (improves UX) + * @param {string} background_color Background color of the object + * @returns {string} Forground color that will match background color + */ function getForegroundFromBackground(background_color) { let color_hex = background_color.replace("#", ""); let rgb = [ @@ -59,6 +79,12 @@ function getForegroundFromBackground(background_color) { } } +/** + * + * Convert a given string to hex color + * @param {string} input_string Input string + * @returns {string} Hex RGB color + */ function getHexColorFromString(str) { return "#" + intToRGB(hashCode(str)); } @@ -66,7 +92,6 @@ function getHexColorFromString(str) { // ---------DATE FUNCTION------------- function getDateString(date) { - let year_str = date.getFullYear(); let month_str = date.getMonth() + 1 month_str = month_str.toString().padStart(2, "0"); -- cgit v1.2.3