0
0
mirror of https://github.com/neon-mmd/websurfx.git synced 2024-11-22 05:58:21 -05:00

Added detailed documentation to JS functions and fixed a mistake while loading css from cookie.

This commit is contained in:
Sam sunder 2023-06-04 14:31:02 +00:00
parent ef7567b454
commit 3cbe1cbf00
2 changed files with 170 additions and 100 deletions

View File

@ -1,116 +1,186 @@
// UI: Method for selecting all search engines /*
UI: Method for selecting all search engines
This function is called when user click on
`select all` and `deselect all` toogle element.
- If select all is pressed toggle all options and insert all value
joined with comma to input which is saved in cookie.
then changes text to `deselect all`.
eg value: 'ddg,searx,'
- If deselect all is pressed uncheck all options and insert empty
value to input which is saved in cookie.
*/
function selectAllHandler(elem) { function selectAllHandler(elem) {
let span = elem.parentElement.querySelector('span'); let span = elem.parentElement.querySelector("span");
let mainInput = document.getElementsByName('searchEng')[0]; let mainInput = document.getElementsByName("searchEng")[0];
let prevStateSelectAll = span.innerText == 'Select all' ? true : false; let prevStateSelectAll = span.innerText == "Select all" ? true : false;
document.querySelectorAll('.searchEng-elem').forEach(engine => { document.querySelectorAll(".searchEng-elem").forEach((engine) => {
if (prevStateSelectAll) { if (prevStateSelectAll) {
engine.querySelector('input[type="checkbox"]').checked = true; engine.querySelector('input[type="checkbox"]').checked = true;
} else { } else {
engine.querySelector('input[type="checkbox"]').checked = false; engine.querySelector('input[type="checkbox"]').checked = false;
} }
}) });
if (prevStateSelectAll) { if (prevStateSelectAll) {
let getValues = () => { let getValues = () => {
let value = "" let value = "";
document.querySelectorAll('[data-isCheckbox]:not([data-value="all"])').forEach(elem => { document
.querySelectorAll('[data-isCheckbox]:not([data-value="all"])')
.forEach((elem) => {
value += elem.getAttribute("data-value") + ","; value += elem.getAttribute("data-value") + ",";
}); });
return value; return value;
} };
mainInput.value = getValues(); mainInput.value = getValues();
} else { } else {
mainInput.value = ''; mainInput.value = "";
} }
span.innerText = prevStateSelectAll ? 'Deselect all' : 'Select all'; span.innerText = prevStateSelectAll ? "Deselect all" : "Select all";
} }
/*
UI: Filter settings as per category
// UI: Filter settings as per category There are two elements one is `category` and `detail`.
document.querySelectorAll('.settings-sidebar .set-name').forEach(filter => { Category contains `data-id` when a user click it
let target = filter.getAttribute('data-detailId'); we need to show detail element having
filter.addEventListener('click', () => { `data-detailId` whose value is same as `data-id`.
try {document.querySelector('.set-name.active').classList.remove('active');} catch(e){}
filter.classList.add('active'); When a user clicks on a category on sidebar, view
if (target == 'all') { settings containing `data-id` of sidebar element's `data-detailId`
document.querySelectorAll('.set-item').forEach((elem) => { and hide other settings
elem.style.display = 'block';
}) - if `all` is clicked then show all settings.
*/
document.querySelectorAll(".settings-sidebar .set-name").forEach((filter) => {
let target = filter.getAttribute("data-detailId");
filter.addEventListener("click", () => {
try {
document.querySelector(".set-name.active").classList.remove("active");
} catch (e) {}
filter.classList.add("active");
if (target == "all") {
document.querySelectorAll(".set-item").forEach((elem) => {
elem.style.display = "block";
});
return; return;
} }
document.querySelectorAll('.set-item[data-id="'+target+'"]').forEach((elem) => { document
elem.style.display = 'block' .querySelectorAll('.set-item[data-id="' + target + '"]')
}) .forEach((elem) => {
document.querySelectorAll('.set-item:not([data-id="'+target+'"])').forEach((elem) => { elem.style.display = "block";
elem.style.display = 'none' });
}) document
}) .querySelectorAll('.set-item:not([data-id="' + target + '"])')
}) .forEach((elem) => {
elem.style.display = "none";
});
});
});
// On settings form submit /*
This function is called when a user click on submit button
it validates all user inputs and saves to a cookie.
- if input having `required` attr and is empty it generates a
error text and insert above the setting element
- else store setttings to a cookie.
*/
function submitSettings() { function submitSettings() {
let form = document.settings; let form = document.settings;
let stopProceeding = false; let stopProceeding = false;
document.querySelectorAll('.errTxt').forEach(e => e.remove()); document.querySelectorAll(".errTxt").forEach((e) => e.remove());
for(let i = 0; i < form.elements.length; i++) { for (let i = 0; i < form.elements.length; i++) {
let input = form.elements[i]; let input = form.elements[i];
if (input.value == "" && input.hasAttribute('required')) { if (input.value == "" && input.hasAttribute("required")) {
stopProceeding = true; stopProceeding = true;
let elem = input.parentElement.querySelector('[takeInput]') let elem = input.parentElement.querySelector("[takeInput]");
let errTxt = document.createElement('p') let errTxt = document.createElement("p");
errTxt.classList.add('errTxt') errTxt.classList.add("errTxt");
errTxt.innerText = 'This setting can\'t be empty!!' errTxt.innerText = "This setting can't be empty!!";
elem.classList.add('invalid'); elem.classList.add("invalid");
elem.parentElement.insertBefore(errTxt, elem); elem.parentElement.insertBefore(errTxt, elem);
let sidebarElement = input.closest('.set-item').getAttribute('data-id') let sidebarElement = input.closest(".set-item").getAttribute("data-id");
document.querySelector(`.settings-sidebar .set-name[data-detailId="${sidebarElement}`).click(); document
.querySelector(
`.settings-sidebar .set-name[data-detailId="${sidebarElement}`
)
.click();
stopProceeding = true; stopProceeding = true;
} }
} }
if (!stopProceeding) { if (!stopProceeding) {
var expiration_date = new Date(); var expiration_date = new Date();
expiration_date.setFullYear(expiration_date.getFullYear() + 1); expiration_date.setFullYear(expiration_date.getFullYear() + 1);
let formData = new FormData(document.querySelector('form')); let formData = new FormData(document.querySelector("form"));
for (var [key, value] of formData.entries()) { for (var [key, value] of formData.entries()) {
document.cookie = `${key}=${value}; expires=${expiration_date.toUTCString()}` document.cookie = `${key}=${value}; expires=${expiration_date.toUTCString()}`;
}
} else {
return false;
} }
} else { return false; }
// On settings saved successfully // On settings saved successfully
alert("Settings saved succssfully!"); alert("Settings saved succssfully!");
window.location.reload(); window.location.reload();
} }
// Autoload existing settings
/*
This function will be called on page ready.
it iterates over saved cookies and if cookie name is
in the list of valid cookies then load it.
- if cookie is searchEng(type=toggle/checkbox) we deselect
all checkboxes and select those which are stored in cookie.
- if cookie is of type `select` we deselect default selected
option and then select option which is stored in cookie.
*/
function loadUserSettings() { function loadUserSettings() {
let inputs = ["searchEng", "theme", "color-sch"] let inputs = ["searchEng", "theme", "color-sch"];
var keyValuePairs = document.cookie.split(';'); var keyValuePairs = document.cookie.split(";");
for(var i = 0; i < keyValuePairs.length; i++) { for (var i = 0; i < keyValuePairs.length; i++) {
var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('=')); var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf("="));
var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1); var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf("=") + 1);
name = name.trim(); name = name.trim();
if (!inputs.includes(name)) { return; } if (!inputs.includes(name)) {
continue;
}
let input = document.getElementsByName(name)[0]; let input = document.getElementsByName(name)[0];
input.value = value; input.value = value;
if (name == "searchEng") { if (name == "searchEng") {
// Unload all checked engine // Unload all checked engines
document.querySelectorAll(".searchEng-elem input[type=checkbox]").forEach(e => { document
.querySelectorAll(".searchEng-elem input[type=checkbox]")
.forEach((e) => {
e.checked = false; e.checked = false;
}) });
value = value.replace(" ", ""); value = value.replace(" ", "");
value.split(",").forEach(val => { value.split(",").forEach((val) => {
if (!val) {return} if (!val) {
document.querySelector(`[data-isCheckbox][data-value="${val}"]`). return;
parentElement.querySelector('input').checked = true }
}) document
.querySelector(`[data-isCheckbox][data-value="${val}"]`)
.parentElement.querySelector("input").checked = true;
});
} else { } else {
// Unload all selected options // Unload all selected options
document.querySelector(`[data-input="${name}"] .options span[data-value="${value}"]`). document
removeAttribute('selected'); .querySelector(
singleSelectClickHandler(document.querySelector(`.options span[data-value="${value}"]`)); `[data-input="${name}"] .options span[data-value="${value}"]`
)
.removeAttribute("selected");
singleSelectClickHandler(
document.querySelector(`.options span[data-value="${value}"]`)
);
} }
} }
} }
// Code where settings are loaded from cookie.
loadUserSettings(); loadUserSettings();

View File

@ -24,6 +24,6 @@
head.appendChild(link); head.appendChild(link);
} }
addCss('static/themes/'+ (cookies["theme"] || {{theme}}) + '.css'); addCss('static/themes/'+ (cookies["theme"] || '{{theme}}') + '.css');
addCss('static/colorschemes/'+ (cookies["color-sch"] || {{colorscheme}}) + '.css'); addCss('static/colorschemes/'+ (cookies["color-sch"] || '{{colorscheme}}') + '.css');
</script> </script>