Improve JS Logic (#28)

* theme engine fix ugly logic part 1

* remove new lines when gettings css value property

* theme-engine: add process cssvalues

* theme-engine: add getting inputfields value

* theme-engine: validation

* theme-engine: animspeed validation

* theme-engine: animspeed validation 2

* fix #rgbaa validator

* theme-engine:almost finish

* theme-engine: fix codacy errors

* theme-engine: fix missing semicolon

* theme-engine: fix missing semicolon

* weather-settings: use confirm() method

* weather-settings: cleanup, remove some confirm()
This commit is contained in:
Gerome Matilla 2020-06-17 19:03:27 +08:00 committed by GitHub
parent ae6e1254ea
commit 6d6de0f883
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 289 additions and 139 deletions

View File

@ -1,4 +1,4 @@
/*Filter for body's lazy loaded background */
/* Filter for body's lazy loaded background */
#dummyBodyBackground {
background: var(--base-body-bg);

View File

@ -189,7 +189,7 @@
/* mask-image: linear-gradient(to bottom, black 85%, transparent 100%); */
}
/*Stretch list item if screen width < 470px*/
/* Stretch list item if screen width < 470px */
@media screen and (max-width: 470px) {
#webMenuList {
flex-grow: 1;
@ -221,18 +221,18 @@
}
}
/*The a href container/main web menu button container*/
/* The a href container/main web menu button container */
.webMenuLink {
/*Act as div*/
/* Act as div */
display: block;
/*Remove outlines*/
/* Remove outlines */
text-decoration: none;
outline: 0;
border: none;
-moz-outline-style: none;
/*Disable dragging*/
/* Disable dragging */
user-select: none;
-webkit-user-drag: none;
}

View File

@ -164,8 +164,8 @@
<div class='themeEngineGroups' id='themeEngineBackground'>
<label for='backgroundSet' class='themeEngineLabels'>Background Color and Opacity</label>
<div class='backgroundColorSetter'>
<input type='text' maxlength='7' class='themeEngineInputs' id='backgroundSet' autocomplete='off' placeholder='000000'/>
<input type='text' maxlength='2' class='themeEngineInputs' id='backgroundOpacitySet' autocomplete='off' placeholder='FF'/>
<input type='text' maxlength='7' class='themeEngineInputs' id='backgroundSet' autocomplete='off' placeholder='000000' pattern='[a-fA-f0-9#]+'/>
<input type='text' maxlength='2' class='themeEngineInputs' id='backgroundOpacitySet' autocomplete='off' placeholder='FF' pattern='[a-fA-f0-9]+'/>
</div>
</div>
@ -173,21 +173,21 @@
<div class='themeEngineGroups' id='themeEngineForeground'>
<label for='foregroundSet' class='themeEngineLabels'>Foreground Color and Opacity</label>
<div class='foregroundColorSetter'>
<input type='text' maxlength='7' class='themeEngineInputs' id='foregroundSet' autocomplete='off' placeholder='000000'/>
<input type='text' maxlength='2' class='themeEngineInputs' id='foregroundOpacitySet' autocomplete='off' placeholder='FF'/>
<input type='text' maxlength='7' class='themeEngineInputs' id='foregroundSet' autocomplete='off' placeholder='000000' pattern='[a-fA-f0-9#]+'/>
<input type='text' maxlength='2' class='themeEngineInputs' id='foregroundOpacitySet' autocomplete='off' placeholder='FF' pattern='[a-fA-f0-9]+'/>
</div>
</div>
<div class='themeEngineGroups' id='themeEngineBlurStrength'>
<label for='blurSet' class='themeEngineLabels'>Blur Strength in Pixels</label>
<div class='blurSetter'>
<input type='text' class='themeEngineInputs' id='blurSet' autocomplete='off' placeholder='10'/>
<input type='text' class='themeEngineInputs' id='blurSet' autocomplete='off' placeholder='6px' pattern='[0-9px]+'/>
</div>
</div>
<div class='themeEngineGroups' id='themeEngineAnimSpeed'>
<label for='animSpeedSet' class='themeEngineLabels'>Animation Speed</label>
<div class='animSpeedSetter'>
<input type='text' class='themeEngineInputs' id='animSpeedSet' autocomplete='off' placeholder='300ms'/>
<input type='text' class='themeEngineInputs' id='animSpeedSet' autocomplete='off' placeholder='300ms' pattern='[0-9ms]+'/>
</div>
</div>
<button type='button' id='themeEngineReset'>Reset</button>

View File

@ -12,9 +12,6 @@ class SearchEngineSettings {
this._searchEngines = config.getSearchEngines();
this._onClickEvent = this._onClickEvent.bind(this);
this._onChangeEvent = this._onChangeEvent.bind(this);
this._init();
}
@ -22,8 +19,8 @@ class SearchEngineSettings {
this._updateDefaultSearchEngine();
this._createSearchEngineOptions();
this._selectTheEngine();
this._registerOnChangeEvent();
this._registerOnClickEvent();
this._registerSearchEngineSelectOnChangeEvent();
this._registerApplyOnClickEvent();
}
_updateDefaultSearchEngine = () => {
@ -74,18 +71,18 @@ class SearchEngineSettings {
}
// Execute this on change event of <select>
_onChangeEvent = e => {
_searchEngineSelectOnChangeEvent = e => {
const selectedEngine = this._selectSearchEngine.options[this._selectSearchEngine.selectedIndex].value;
this._currentSearchEngine = selectedEngine;
this._selectTheEngine();
}
_registerOnChangeEvent = () => {
this._selectSearchEngine.onchange = this._onChangeEvent;
_registerSearchEngineSelectOnChangeEvent = () => {
this._selectSearchEngine.onchange = this._searchEngineSelectOnChangeEvent;
}
// Apply button callback
_onClickEvent = e => {
_applyOnClickEvent = e => {
// Get selected <options>
const selectCurrentIndex = this._selectSearchEngine.options[this._selectSearchEngine.selectedIndex];
@ -100,8 +97,8 @@ class SearchEngineSettings {
this._updateDefaultSearchEngine();
}
_registerOnClickEvent = () => {
this._selectSearchEngineApply.onclick = this._onClickEvent;
_registerApplyOnClickEvent = () => {
this._selectSearchEngineApply.onclick = this._applyOnClickEvent;
}
}

View File

@ -16,56 +16,90 @@ class ThemeEngine {
this._init();
}
_saveDefaultCSS = () => {
// Get CSS variable value
_getCSSProperty = variable => {
let cssValue = window.getComputedStyle(document.documentElement).getPropertyValue(String(variable));
const origBaseBG = this._localStorage.getItem('origBaseBG');
const origBaseColor = this._localStorage.getItem('origBaseColor');
const origBlurStrength = this._localStorage.getItem('origBlurStrength');
const origAnimSpeed = this._localStorage.getItem('origAnimSpeed');
if ((origBaseBG === null) || (origBaseColor === null) || (origBlurStrength === null) || (origAnimSpeed === null)) {
// Remove whitespaces
// I don't know why getProperty value adds a whitespace(i'm really noob at js)
cssValue = cssValue.replace(/ /g,'');
this._localStorage.setItem(
'origBaseBG',
window.getComputedStyle(document.documentElement).getPropertyValue('--base-bg')
);
this._localStorage.setItem(
'origBaseColor',
window.getComputedStyle(document.documentElement).getPropertyValue('--base-color')
);
this._localStorage.setItem(
'origBlurStrength',
window.getComputedStyle(document.documentElement).getPropertyValue('--blur-strength')
);
this._localStorage.setItem(
'origAnimSpeed',
window.getComputedStyle(document.documentElement).getPropertyValue('--transition-speed')
);
}
return cssValue;
}
// Get localStorage item value
_getStorageItem = item => {
return this._localStorage.getItem(String(item));
}
// Set localStorage item value
_setStorageItem = (item, value) => {
this._localStorage.setItem(
String(item),
this._getCSSProperty(String(value))
);
}
// Set/Save original CSS Value, useful when reseting theme engine
_saveOriginalDefaultCSS = () => {
// Check original default CSS values
const defaultValues = {
'origBaseBG': {
value: this._getStorageItem('origBaseBG'),
cssVariable: '--base-bg'
},
'origBaseColor': {
value: this._getStorageItem('origBaseColor'),
cssVariable: '--base-color'
},
'origBlurStrength': {
value: this._getStorageItem('origBlurStrength'),
cssVariable: '--blur-strength'
},
'origAnimSpeed': {
value: this._getStorageItem('origAnimSpeed'),
cssVariable: '--transition-speed'
}
};
// If original css variable has has no value, set it
Object.keys(defaultValues)
.forEach(item => {
const itemName = item;
const itemValue = defaultValues[String(item)].value;
// If value is null, set
if (!itemValue) {
this._setStorageItem(itemName, defaultValues[String(item)].cssVariable);
}
});
}
// Validate color
_checkColorValidity = colorStr => {
// Check if RGBA - (#RRGGBBAA)
const colorRGBA = /^#[0-9A-F]{8}$/i.test(colorStr);
const colorRGBA = /^#[0-9a-fA-F]{8}$/i.test(colorStr);
// If not RGBA
if (!colorRGBA) {
// If RGB - (#RRGGBB)
if (/^#[0-9A-F]{3}$/i.test(colorStr)) {
if (/^#[0-9a-fA-F]{3}$/i.test(colorStr)) {
// Add completely opaque alpha
return colorStr + 'FF';
// If three-charactered HEX color - (#RGB)
} else if (/^#[0-9A-F]{3}$/i.test(colorStr)) {
// I feel that this is never used lol
} else if (/^#[0-9a-fA-F]{3}$/i.test(colorStr)) {
// Convert it to RRGGBB
return colorStr.replace(/^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/, '#$1$1$2$2$3$3');
// If three-charactered HEX Color(#RGB) with AA - (#RGBAA)
} else if (colorStr.length === 6) {
} else if (/^#[0-9a-fA-F]{3}[0-9a-fA-F]{2}$/i.test(colorStr)) {
const bg = colorStr.slice(0, -2);
const op = colorStr.slice(-2);
@ -73,8 +107,7 @@ class ThemeEngine {
return bg.replace(/^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/, '#$1$1$2$2$3$3') + op;
} else {
alert('Invalid color');
return false;
return null;
}
}
@ -82,6 +115,42 @@ class ThemeEngine {
return colorStr;
}
// Validate color
_checkBlurValidity = blurStr => {
let blurStrength = parseInt(blurStr, 10);
if (String(blurStrength) === 'NaN') {
return null;
} else {
return String(blurStrength) + 'px';
}
}
_checkAnimSpeedValidity = speedStr => {
let animSpeed = parseInt(speedStr, 10);
let timeSuffix;
if (speedStr.endsWith('ms')) {
timeSuffix = 'ms';
} else if (speedStr.endsWith('s')) {
timeSuffix = 's';
}
if(String(animSpeed) === 'NaN') {
return null;
} else {
if (timeSuffix) {
return String(animSpeed) + timeSuffix;
} else {
return String(animSpeed) + 'ms';
}
}
}
// Update textboxes value
_updateTextBoxValues = (bgColor, bgOpacity, fgColor, fgOpacity, blurPower, animSpeed) => {
// Set placeholders
@ -101,57 +170,64 @@ class ThemeEngine {
this._animSpeedTextBox.value = '';
this._animSpeedTextBox.placeholder = animSpeed;
}
_processTheme = () => {
// Get/Update current css value
_getCurrentCSSValues = () => {
// Retrieve custom colors
let baseBG = this._localStorage.getItem('baseBG');
let baseColor = this._localStorage.getItem('baseColor');
let blurStrength = this._localStorage.getItem('blurStrength');
let animSpeed = this._localStorage.getItem('animSpeed');
// Retrieve current css values
let currentValues = {
'baseBG': {
value: this._getStorageItem('baseBG'),
origVariable: 'origBaseBG'
},
'baseColor': {
value: this._getStorageItem('baseColor'),
origVariable: 'origBaseColor'
},
'blurStrength': {
value: this._getStorageItem('blurStrength'),
origVariable: 'origBlurStrength'
},
'animSpeed': {
value: this._getStorageItem('animSpeed'),
origVariable: 'origAnimSpeed'
}
};
// If custom color doesn't exist, use the value in CSS
if (baseBG === null) {
baseBG = this._localStorage.getItem('origBaseBG');
}
// If current css variable has has no value, set it
Object.keys(currentValues)
.forEach(key => {
const cssVar = key;
const cssValue = currentValues[String(cssVar)].value;
if (baseColor === null) {
baseColor = this._localStorage.getItem('origBaseColor');
}
// If value is null, set
if (!cssValue) {
currentValues[String(cssVar)].value = this._getStorageItem(currentValues[String(cssVar)].origVariable);
}
});
if (blurStrength === null) {
blurStrength = this._localStorage.getItem('origBlurStrength');
}
return currentValues;
}
if (animSpeed === null) {
animSpeed = this._localStorage.getItem('origAnimSpeed');
}
// Process css variables to update input fields
_processCurrentCSSValues = () => {
// Remove whitespace
baseBG = baseBG.replace(/ /g,'');
baseColor = baseColor.replace(/ /g,'');
blurStrength = blurStrength.replace(/ /g,'');
animSpeed = animSpeed.replace(/ /g,'');
// Get current css values
const themeObj = this._getCurrentCSSValues();
// Check validity
baseBG = this._checkColorValidity(baseBG);
baseColor = this._checkColorValidity(baseColor);
// Slice to separate RGB and A of background color
// Slice alpha out
const baseBG = themeObj['baseBG'].value;
const backgroundColor = baseBG.slice(0, -2);
// Get alpha
const backgroundOpacity = baseBG.slice(-2);
// Slice to separate RGB and A of foreground color
// Slice alpha out
const baseColor = themeObj['baseColor'].value;
const foregroundColor = baseColor.slice(0, -2);
// Get alpha
const foregroundOpacity = baseColor.slice(-2);
const blurStrength = themeObj['blurStrength'].value;
const animSpeed = themeObj['animSpeed'].value;
// Pass value to update textboxes
this._updateTextBoxValues(
backgroundColor,
backgroundOpacity,
@ -161,29 +237,111 @@ class ThemeEngine {
animSpeed
);
}
// Get input fields values
_getInputFieldsValue = () => {
_updateCSSconstiables = () => {
// Get value from input fields
const background = (this._backgroundTextBox.value || this._backgroundTextBox.placeholder) +
// Get value from the input fields
const backgroundColor = (this._backgroundTextBox.value || this._backgroundTextBox.placeholder) +
(this._backgroundOpacityTextBox.value || this._backgroundOpacityTextBox.placeholder);
const foreground = (this._foregroundTextBox.value || this._foregroundTextBox.placeholder) +
const foregroundColor = (this._foregroundTextBox.value || this._foregroundTextBox.placeholder) +
(this._foregroundOpacityTextBox.value || this._foregroundOpacityTextBox.placeholder);
const blurPower = (this._blurTextBox.value || this._blurTextBox.placeholder);
const animSpeed = (this._animSpeedTextBox.value || this._animSpeedTextBox.placeholder);
const blurStrength = (this._blurTextBox.value || this._blurTextBox.placeholder);
const transitionSpeed = (this._animSpeedTextBox.value || this._animSpeedTextBox.placeholder);
// Check color validity
const bgColor = this._checkColorValidity(background);
const fgColor = this._checkColorValidity(foreground);
const inputFieldValues = {
'background': backgroundColor,
'foreground': foregroundColor,
'blurPower': blurStrength,
'animSpeed': transitionSpeed
};
return inputFieldValues;
}
_updateCSSColors = (bgColor, fgColor, blurPower, animSpeed) => {
// Change CSS colors
document.documentElement.style.setProperty('--base-bg', bgColor);
document.documentElement.style.setProperty('--base-color', fgColor);
document.documentElement.style.setProperty('--blur-strength', blurPower);
document.documentElement.style.setProperty('--transition-speed', animSpeed);
}
// Update css variables and set theme
_updateCSSVariables = () => {
const inputValueObj = this._getInputFieldsValue();
const bgColorRaw = inputValueObj['background'];
const fgColorRaw = inputValueObj['foreground'];
const blurPowerRaw = inputValueObj['blurPower'];
const animSpeedRaw = inputValueObj['animSpeed'];
// Colors data obj
let validatedColorValues = {
'bgColor': {
value: this._checkColorValidity(String(bgColorRaw)),
fallbackVar: 'baseBG',
fallbackOrigVar: 'origBaseBG'
},
'fgColor': {
value: this._checkColorValidity(String(fgColorRaw)),
fallbackVar: 'baseColor',
fallbackOrigVar: 'origBaseColor'
}
};
// Check color validity
Object.keys(validatedColorValues)
.forEach(key => {
let colorVar = key;
let colorValue = validatedColorValues[String(key)].value;
if (!colorValue) {
validatedColorValues[String(key)].value =
this._getStorageItem(validatedColorValues[String(key)].fallbackVar) ||
this._getStorageItem(validatedColorValues[String(key)].fallbackOrigVar);
// console.log('Invalid Color! Will use previous one...')
}
});
// Set valid color to variables
const bgColor = validatedColorValues['bgColor'].value;
const fgColor = validatedColorValues['fgColor'].value;
// Blur data obj
let validatedBlurValue = {
'blurStrength': {
value: this._checkBlurValidity(blurPowerRaw),
fallbackVar: 'blurStrength',
fallbackOrigVar: 'origBlurStrength'
}
};
// Validate and set blur strength
const blurPower = this._checkBlurValidity(blurPowerRaw) ||
this._getStorageItem(validatedBlurValue['blurStrength'].fallbackVar) ||
this._getStorageItem(validatedBlurValue['blurStrength'].fallbackOrigVar);
// Anim speed data obj
let validatedSpeedValue = {
'transitionSpeed' : {
value: this._checkBlurValidity(animSpeedRaw),
fallbackVar: 'animSpeed',
fallbackOrigVar: 'origAnimSpeed'
}
};
// Valudate and set anim speed
const animSpeed = this._checkAnimSpeedValidity(animSpeedRaw) ||
this._getStorageItem(validatedSpeedValue['transitionSpeed'].fallbackVar) ||
this._getStorageItem(validatedSpeedValue['transitionSpeed'].fallbackOrigVar);
// console.log('bg: '+bgColor+'\nfg: '+fgColor+'\nblur: '+blurPower+'\nspeed: '+animSpeed);
// Save custom color
this._localStorage.setItem('baseBG', bgColor);
@ -191,12 +349,24 @@ class ThemeEngine {
this._localStorage.setItem('blurStrength', blurPower);
this._localStorage.setItem('animSpeed', animSpeed);
this._processTheme();
// Update css colors
this._updateCSSColors(bgColor, fgColor, blurPower, animSpeed);
this._processCurrentCSSValues();
}
_reApplyTheme = () => {
this._updateCSSColors(
this._getStorageItem('baseBG') || this._getStorageItem('origBaseBG'),
this._getStorageItem('baseColor') || this._getStorageItem('origBaseColor'),
this._getStorageItem('blurStrength') || this._getStorageItem('origBlurStrength'),
this._getStorageItem('animSpeed') || this._getStorageItem('origAnimSpeed')
);
this._processCurrentCSSValues();
}
_applyOnClickEvent = e => {
this._updateCSSconstiables();
alert('Success!');
this._updateCSSVariables();
}
_registerApplyOnClickEvent = () => {
@ -209,11 +379,8 @@ class ThemeEngine {
this._localStorage.removeItem('blurStrength');
this._localStorage.removeItem('animSpeed');
this._saveDefaultCSS();
this._processTheme();
this._updateCSSconstiables();
alert('Success!');
this._saveOriginalDefaultCSS();
this._reApplyTheme();
}
_registerResetOnClickEvent = () => {
@ -222,13 +389,13 @@ class ThemeEngine {
_init = () => {
this._saveDefaultCSS();
// Save original css variables value
this._saveOriginalDefaultCSS();
// Update
this._processTheme();
// Update settings
this._updateCSSconstiables();
// Process theme
this._reApplyTheme();
// Register events
this._registerApplyOnClickEvent();
this._registerResetOnClickEvent();
}

View File

@ -104,9 +104,8 @@ class WeatherSettings {
// You denied the permission request
_deniedGeolocation = () => {
alert(`Location access denied! If you're on mobile, make sure to`+
confirm(`Location access denied! If you're on mobile, make sure to`+
` enable your GPS and allow the location permission on your browser's settings.`);
}
// Watch
@ -130,13 +129,10 @@ class WeatherSettings {
// Error
_watchGeoError = err => {
// console.warn('ERROR(' + err.code + '): ' + err.message);
if (err.code === err.PERMISSION_DENIED) {
this._deniedGeolocation();
}
}
@ -153,13 +149,10 @@ class WeatherSettings {
if ((result.state === 'prompt') || (result.state === 'granted')) {
this._watchGeoPosition();
} else if (result.state === 'denied') {
alert('Manually enable the geolocation in your browser settings. How? Who knows?');
}
});
}
@ -170,25 +163,17 @@ class WeatherSettings {
if (this._locatorMode === 'geolocation') {
// console.log('geolocation');
this._weatherSettingsCityIDGroup.classList.add('hideWeatherSettings');
} else if (this._locatorMode === 'city') {
// console.log('city');
this._weatherSettingsCityIDGroup.classList.remove('hideWeatherSettings');
}
}
// Register on change event
_registerWeatherSelectLocatorOnChangeEvent = () => {
this._weatherSelectLocator.onchange = this._weatherSelectLocatorOnChangeEvent;
}
// Update weather settings
@ -200,15 +185,12 @@ class WeatherSettings {
if (this._locatorMode === 'geolocation') {
this._weatherSettingsCityIDGroup.classList.add('hideWeatherSettings');
if (navigator.geolocation) {
this._checkGeoPermission();
} else {
alert(`Oof! It seems your browser doesn't support geolocation.`);
}
} else if (this._locatorMode === 'city') {
@ -221,7 +203,6 @@ class WeatherSettings {
// Update weather forecast elements
this._getWeatherDataViaCity(this._appID, this._cityID, this._units);
this._getForecastDataViaCity(this._appID, this._cityID, this._units);
}
this._deleteWeatherSettingsValue();
@ -230,6 +211,7 @@ class WeatherSettings {
// Reset
_weatherResetOnClickEvent = e => {
// Reset keys
this._clearWeatherCredentials();
@ -247,22 +229,26 @@ class WeatherSettings {
} else if (this._locatorMode === 'city') {
this._weatherSettingsCityIDGroup.classList.remove('hideWeatherSettings');
}
alert('Credentials deleted!');
}
// Apply Onclick event
_weatherApplyOnClickEvent = e => {
// Set input field value to variables
const apiKey = this._apiKeySet.value || this._apiKeySet.placeholder;
const cityID = this._cityIDSet.value || this._cityIDSet.placeholder;
const units = this._weatherSelectUnits.options[this._weatherSelectUnits.selectedIndex].value;
const locator = this._weatherSelectLocator.options[this._weatherSelectLocator.selectedIndex].value;
// Update credentials/Settings
this._applyWeatherSettings(
this._apiKeySet.value || this._apiKeySet.placeholder,
this._cityIDSet.value || this._cityIDSet.placeholder,
this._weatherSelectUnits.options[this._weatherSelectUnits.selectedIndex].value,
this._weatherSelectLocator.options[this._weatherSelectLocator.selectedIndex].value
apiKey,
cityID,
units,
locator
);
this._updateWeatherSettings();
alert('Successfully updated!');
}
_registerWeatherResetOnClickEvent = () => {