Code cleaning

This commit is contained in:
varjolintu 2020-02-22 21:27:11 +02:00
parent c2cad20dc4
commit c78b002032
18 changed files with 86 additions and 88 deletions

View file

@ -59,13 +59,13 @@ browserAction.removeLevelFromStack = function(tab, level, type, dontShow) {
const newStack = [];
for (const i of page.tabs[tab.id].stack) {
if ((type === '<' && i.level >= level) ||
(type === '<=' && i.level > level) ||
(type === '=' && i.level !== level) ||
(type === '==' && i.level !== level) ||
(type === '!=' && i.level === level) ||
(type === '>' && i.level <= level) ||
(type === '>=' && i.level < level)) {
if ((type === '<' && i.level >= level)
|| (type === '<=' && i.level > level)
|| (type === '=' && i.level !== level)
|| (type === '==' && i.level !== level)
|| (type === '!=' && i.level === level)
|| (type === '>' && i.level <= level)
|| (type === '>=' && i.level < level)) {
newStack.push(i);
}
}

View file

@ -166,7 +166,7 @@ kpxcEvent.onLoginPopup = function(tab, logins) {
kpxcEvent.initHttpAuth = function() {
httpAuth.init();
return Promise.resolve();
}
};
kpxcEvent.onHTTPAuthPopup = function(tab, data) {
const stackData = {
@ -212,7 +212,7 @@ kpxcEvent.pageSetLoginId = function(tab, loginId) {
kpxcEvent.pageClearSubmitted = function() {
page.clearSubmittedCredentials();
return Promise.resolve();
}
};
kpxcEvent.pageGetSubmitted = async function() {
return page.submittedCredentials;

View file

@ -93,8 +93,8 @@ browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
* @param {object} details
*/
browser.webNavigation.onCommitted.addListener((details) => {
if ((details.transitionQualifiers.length > 0 && details.transitionQualifiers[0] === 'client_redirect') ||
details.transitionType === 'form_submit') {
if ((details.transitionQualifiers.length > 0 && details.transitionQualifiers[0] === 'client_redirect')
|| details.transitionType === 'form_submit') {
page.redirectCount += 1;
return;
}

View file

@ -533,7 +533,7 @@ keepass.getDatabaseHash = async function(tab, args = []) {
keepass.setcurrentKeePassXCVersion(parsed.version);
keepass.databaseHash = parsed.hash || '';
if (oldDatabaseHash && oldDatabaseHash != keepass.databaseHash) {
if (oldDatabaseHash && oldDatabaseHash !== keepass.databaseHash) {
keepass.associated.value = false;
keepass.associated.hash = null;
}
@ -1108,8 +1108,8 @@ keepass.decrypt = function(input, nonce) {
keepass.enableAutomaticReconnect = function() {
// Disable for Windows if KeePassXC is older than 2.3.4
if (!page.settings.autoReconnect ||
(navigator.platform.toLowerCase().includes('win') && !keepass.compareVersion('2.3.4', keepass.currentKeePassXC))) {
if (!page.settings.autoReconnect
|| (navigator.platform.toLowerCase().includes('win') && !keepass.compareVersion('2.3.4', keepass.currentKeePassXC))) {
return;
}

View file

@ -101,7 +101,7 @@ page.initSettings = async function() {
if (!('showNotifications' in page.settings)) {
page.settings.showNotifications = defaultSettings.showNotifications;
}
if (!('showOTPIcon' in page.settings)) {
page.settings.showOTPIcon = defaultSettings.showOTPIcon;
}

View file

@ -42,7 +42,7 @@ kpxcAutocomplete.showList = function(inputField) {
kpxcAutocomplete.updatePosition(inputField, div);
div.style.zIndex = '2147483646';
const styleSheet = createStylesheet('css/autocomplete.css');
const colorStyleSheet = createStylesheet('css/colors.css');
const wrapper = kpxcUI.createElement('div');
@ -243,11 +243,11 @@ document.addEventListener('click', function(e) {
return;
}
if (e.target !== kpxcAutocomplete.input &&
!e.target.classList.contains('kpxc-username-icon') &&
e.target.nodeName !== kpxcAutocomplete.input.nodeName) {
if (e.target !== kpxcAutocomplete.input
&& !e.target.classList.contains('kpxc-username-icon')
&& e.target.nodeName !== kpxcAutocomplete.input.nodeName) {
kpxcAutocomplete.closeList(e.target);
if (kpxcAutocomplete.wrapper) {
document.body.removeChild(kpxcAutocomplete.wrapper);
}

View file

@ -120,7 +120,6 @@ kpxcBanner.create = async function(credentials = {}) {
initColorTheme(banner);
const styleSheet = createStylesheet('css/banner.css');
const buttonStyleSheet = createStylesheet('css/button.css');
const colorStyleSheet = createStylesheet('css/colors.css');
@ -149,7 +148,7 @@ kpxcBanner.saveNewCredentials = async function(credentials = {}) {
// Or when default group is not set and defaultGroupAskAlways is disabled -> save to default
if ((result.groups === undefined || (result.groups.length > 0 && result.groups[0].children.length === 0)) ||
(!result.defaultGroupAlwaysAsk && (result.defaultGroup === '' || result.defaultGroup === DEFAULT_BROWSER_GROUP))) {
let args = [ credentials.username, credentials.password, credentials.url ];
const args = [ credentials.username, credentials.password, credentials.url ];
// If root group is defined by the user, and there's no default browser group, save the credentials to the root group
if (result.groups[0].children.length === 0 && result.defaultGroup.toLowerCase() === 'root') {
@ -300,7 +299,7 @@ kpxcBanner.updateCredentials = async function(credentials = {}) {
browser.runtime.sendMessage({
action: 'retrieve_credentials',
args: [ url, '', true ] // Sets triggerUnlock to true
}).then(async (creds) => {
}).then(async creds => {
if (!creds || creds.length !== credentials.list.length) {
kpxcBanner.verifyResult('error');
return;

View file

@ -124,9 +124,9 @@ kpxcDefine.resetSelection = function() {
kpxcDefine.isFieldSelected = function(kpxcId) {
if (kpxcId) {
return (
kpxcId === kpxcDefine.selection.username ||
kpxcId === kpxcDefine.selection.password ||
kpxcId in kpxcDefine.selection.fields
kpxcId === kpxcDefine.selection.username
|| kpxcId === kpxcDefine.selection.password
|| kpxcId in kpxcDefine.selection.fields
);
}
return false;

View file

@ -177,8 +177,8 @@ kpxcForm.getNewPassword = function() {
}
// Just two password fields, current and new
if (kpxcForm.passwordInputs.length === 2 &&
kpxcForm.passwordInputs[0] !== kpxcForm.passwordInputs[1]) {
if (kpxcForm.passwordInputs.length === 2
&& kpxcForm.passwordInputs[0] !== kpxcForm.passwordInputs[1]) {
return kpxcForm.passwordInputs[1].value;
}
@ -262,16 +262,16 @@ kpxcFields.isSearchField = function(target) {
if (closestForm) {
// Check form action
const formAction = closestForm.getAttribute('action');
if (formAction && (formAction.toLowerCase().includes('search') &&
!formAction.toLowerCase().includes('research'))) {
if (formAction && (formAction.toLowerCase().includes('search')
&& !formAction.toLowerCase().includes('research'))) {
return true;
}
// Check form class and id
const closestFormId = closestForm.getAttribute('id');
const closestFormClass = closestForm.className;
if (closestFormClass && (closestForm.className.toLowerCase().includes('search') ||
(closestFormId && closestFormId.toLowerCase().includes('search') && !closestFormId.toLowerCase().includes('research')))) {
if (closestFormClass && (closestForm.className.toLowerCase().includes('search')
|| (closestFormId && closestFormId.toLowerCase().includes('search') && !closestFormId.toLowerCase().includes('research')))) {
return true;
}
}
@ -320,8 +320,8 @@ kpxcFields.getAllFields = function() {
_detectedFields = fields.length;
// Show add username-only option for the site in popup
if (!_singleInputEnabledForPage &&
fields.length === 1 && fields[0].getLowerCaseAttribute('type') !== 'password') {
if (!_singleInputEnabledForPage
&& fields.length === 1 && fields[0].getLowerCaseAttribute('type') !== 'password') {
browser.runtime.sendMessage({
action: 'username_field_detected',
args: true
@ -627,18 +627,18 @@ kpxcObserverHelper.inputTypes = [
'number',
'username', // Note: Not a standard
undefined, // Input field can be without any type. Include this and null to the list.
null
null
];
// Ignores all nodes that doesn't contain elements
kpxcObserverHelper.ignoredNode = function(target) {
if (target.nodeType === Node.ATTRIBUTE_NODE ||
target.nodeType === Node.TEXT_NODE ||
target.nodeType === Node.CDATA_SECTION_NODE ||
target.nodeType === Node.PROCESSING_INSTRUCTION_NODE ||
target.nodeType === Node.COMMENT_NODE ||
target.nodeType === Node.DOCUMENT_TYPE_NODE ||
target.nodeType === Node.NOTATION_NODE) {
if (target.nodeType === Node.ATTRIBUTE_NODE
|| target.nodeType === Node.TEXT_NODE
|| target.nodeType === Node.CDATA_SECTION_NODE
|| target.nodeType === Node.PROCESSING_INSTRUCTION_NODE
|| target.nodeType === Node.COMMENT_NODE
|| target.nodeType === Node.DOCUMENT_TYPE_NODE
|| target.nodeType === Node.NOTATION_NODE) {
return true;
}
return false;
@ -652,7 +652,7 @@ kpxcObserverHelper.getInputs = function(target) {
// Filter out any input fields with type 'hidden' right away
const inputFields = [];
Array.from(target.getElementsByTagName('input')).forEach((e) => {
Array.from(target.getElementsByTagName('input')).forEach(e => {
if (e.type !== 'hidden' && !e.readOnly) {
inputFields.push(e);
}
@ -670,7 +670,7 @@ kpxcObserverHelper.getInputs = function(target) {
// Only include input fields that match with kpxcObserverHelper.inputTypes
const inputs = [];
for (const i of inputFields) {
let type = i.getLowerCaseAttribute('type');
const type = i.getLowerCaseAttribute('type');
if (kpxcObserverHelper.inputTypes.includes(type)) {
kpxcFields.setUniqueId(i);
@ -691,8 +691,8 @@ kpxcObserverHelper.ignoredElement = function(target) {
}
// Ignore KeePassXC-Browser classes
if (target.className && target.className !== undefined &&
target.className.includes('kpxc')) {
if (target.className && target.className !== undefined
&& target.className.includes('kpxc')) {
return true;
}
@ -755,7 +755,6 @@ kpxcObserverHelper.detectURLChange = function() {
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
const kpxc = {};
kpxc.settings = {};
kpxc.u = null;
@ -838,10 +837,10 @@ kpxc.initObserver = function() {
if (mut.target.nodeType === Node.TEXT_NODE) {
continue;
}
// Check document URL change and detect new fields
kpxcObserverHelper.detectURLChange();
// Handle attributes only if CSS display is modified
if (mut.type === 'attributes') {
// Check if some class is changed that folds a form or input field(s)
@ -849,7 +848,7 @@ kpxc.initObserver = function() {
kpxc.initCredentialFields(true);
continue;
}
const newValue = mut.target.getAttribute(mut.attributeName);
if (newValue && (newValue.includes('display') || newValue.includes('z-index'))) {
if (mut.target.style.display !== 'none') {
@ -864,7 +863,7 @@ kpxc.initObserver = function() {
}
}
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
@ -928,7 +927,7 @@ kpxc.siteIgnored = function(condition) {
// Cross-domain security error inspecting window.top.location.href.
// This catches an error when an iframe is being accessed from another (sub)domain -> use the iframe URL instead.
currentLocation = window.self.location.href;
}
}
const currentSetting = condition || IGNORE_FULL;
for (const site of kpxc.settings.sitePreferences) {
@ -1101,7 +1100,7 @@ kpxc.prepareFieldsForCredentials = function(autoFillInForSingle) {
}
if (combination) {
let list = [];
const list = [];
if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[0].stringFields, list)) {
kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
}
@ -1132,16 +1131,16 @@ kpxc.preparePageForMultipleCredentials = function(credentials) {
return text;
}
function getUniqueGroupCount(credentials) {
const groups = credentials.map(c => c.group || '')
const uniqueGroups = new Set(groups)
return uniqueGroups.size
function getUniqueGroupCount(creds) {
const groups = creds.map(c => c.group || '');
const uniqueGroups = new Set(groups);
return uniqueGroups.size;
}
// Add usernames + descriptions to autocomplete-list and popup-list
const usernames = [];
kpxcAutocomplete.elements = [];
const showGroupNameInAutocomplete = kpxc.settings.showGroupNameInAutocomplete && (getUniqueGroupCount(credentials) > 1)
const showGroupNameInAutocomplete = kpxc.settings.showGroupNameInAutocomplete && (getUniqueGroupCount(credentials) > 1);
for (let i = 0; i < credentials.length; i++) {
const loginText = getLoginText(credentials[i], showGroupNameInAutocomplete);
usernames.push(loginText);
@ -1417,7 +1416,7 @@ kpxc.fillWithSpecificLogin = function(id) {
combination = kpxcFields.getCombination('password', kpxc.p);
}
let list = [];
const list = [];
if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[id].stringFields, list)) {
kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
}
@ -1463,7 +1462,7 @@ kpxc.fillIn = function(combination, onlyPassword, suppressWarnings) {
kpxc.setPasswordFilled(true);
}
let list = [];
const list = [];
if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[0].stringFields, list)) {
kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
filledIn = true;
@ -1501,7 +1500,7 @@ kpxc.fillIn = function(combination, onlyPassword, suppressWarnings) {
kpxc.setPasswordFilled(true);
}
let list = [];
const list = [];
if (kpxc.fillInStringFields(combination.fields, kpxc.credentials[combination.loginId].stringFields, list)) {
kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
filledIn = true;
@ -1554,7 +1553,7 @@ kpxc.fillIn = function(combination, onlyPassword, suppressWarnings) {
kpxc.setPasswordFilled(true);
}
let list = [];
const list = [];
if (kpxc.fillInStringFields(combination.fields, valStringFields, list)) {
kpxcForm.destroy(false, { 'password': list.list[0], 'username': list.list[1] });
}

View file

@ -21,7 +21,7 @@ class PasswordIcon extends Icon {
this.initField(field, inputs, pos);
kpxcUI.monitorIconPosition(this);
}
};
}
PasswordIcon.prototype.initField = function(field, inputs, pos) {
if (!field) {
@ -294,8 +294,8 @@ kpxcPasswordDialog.fill = function(e) {
const password = kpxcPasswordDialog.shadowSelector('.kpxc-pwgen-input');
if (field.getAttribute('maxlength')) {
if (password.value.length > field.getAttribute('maxlength')) {
const message = tr('passwordGeneratorErrorTooLong') + '\r\n' +
tr('passwordGeneratorErrorTooLongCut') + '\r\n' + tr('passwordGeneratorErrorTooLongRemember');
const message = tr('passwordGeneratorErrorTooLong') + '\r\n'
+ tr('passwordGeneratorErrorTooLongCut') + '\r\n' + tr('passwordGeneratorErrorTooLongRemember');
message.style.whiteSpace = 'pre';
browser.runtime.sendMessage({
action: 'show_notification',

View file

@ -24,11 +24,11 @@ class TOTPFieldIcon extends Icon {
this.initField(field);
kpxcUI.monitorIconPosition(this);
}
};
}
TOTPFieldIcon.prototype.initField = function(field) {
if (!field
|| field.getAttribute('kpxc-totp-field') === 'true'
|| field.getAttribute('kpxc-totp-field') === 'true'
|| field.offsetWidth < MINIMUM_SIZE
|| field.size < 2
|| (field.maxLength > 0 && field.maxLength < 4)) {

View file

@ -28,12 +28,12 @@ class Icon {
}
if (locked) {
this.icon.style.filter = 'saturate(0%)';
this.icon.style.filter = 'saturate(0%)';
} else {
this.icon.style.filter = 'saturate(100%)';
}
}
};
}
const kpxcUI = {};
kpxcUI.mouseDown = false;
@ -222,7 +222,7 @@ Element.prototype.getLowerCaseAttribute = function(attr) {
Element.prototype._attachShadow = Element.prototype.attachShadow;
Element.prototype.attachShadow = function () {
return this._attachShadow( { mode: 'closed' } );
return this._attachShadow({ mode: 'closed' });
};
Object.prototype.shadowSelector = function(value) {

View file

@ -27,7 +27,7 @@ class UsernameFieldIcon extends Icon {
if (!this.icon) {
return;
}
if (locked) {
this.icon.classList.remove(getIconClassName());
this.icon.classList.add(getIconClassName(true));
@ -38,7 +38,7 @@ class UsernameFieldIcon extends Icon {
this.icon.title = tr('usernameFieldText');
}
}
};
}
UsernameFieldIcon.prototype.initField = function(field) {
if (!field || field.getAttribute('kpxc-username-field') === 'true') {
@ -67,7 +67,7 @@ UsernameFieldIcon.prototype.createIcon = function(target) {
// Size the icon dynamically, but not greater than 24 or smaller than 14
const size = Math.max(Math.min(24, field.offsetHeight - 4), 14);
// Don't create the icon if the input field is too small
if (field.offsetWidth < (size * 1.5) || field.offsetHeight < size) {
this.observer.unobserve(field);

View file

@ -110,4 +110,4 @@ function tr(key, params) {
// Removes everything after '?' from URL
const trimURL = function(url) {
return url.indexOf('?') !== -1 ? url.split('?')[0] : url;
}
};

View file

@ -99,7 +99,7 @@ options.initGeneralSettings = function() {
});
$('#tab-general-settings input[type=range]').val(options.settings['redirectAllowance']);
$('#redirectAllowanceLabel').text(tr('optionsRedirectAllowance',
$('#redirectAllowanceLabel').text(tr('optionsRedirectAllowance',
options.settings['redirectAllowance'] === 11 ? 'Infinite' : String(options.settings['redirectAllowance'])));
$('#tab-general-settings input[type=checkbox]').change(function() {
@ -164,7 +164,7 @@ options.initGeneralSettings = function() {
browser.commands.getAll().then(function(commands) {
commands.forEach(function(command) {
let shortcut = document.getElementById(`${command.name}-shortcut`);
const shortcut = document.getElementById(`${command.name}-shortcut`);
if (!shortcut) {
return;
}
@ -199,19 +199,19 @@ options.initGeneralSettings = function() {
link.setAttribute('type', 'file');
link.onchange = function(e) {
const reader = new FileReader();
if (e.target.files.length > 0) {
reader.readAsText(e.target.files[0]);
}
reader.onloadend = function(e) {
reader.onloadend = function(ev) {
try {
const contents = JSON.parse(e.target.result);
const contents = JSON.parse(ev.target.result);
// A quick check that this is the KeePassXC-Browser settings file
if (contents['checkUpdateKeePassXC'] === undefined ||
contents['autoCompleteUsernames'] === undefined ||
contents['autoFillAndSend'] === undefined) {
if (contents['checkUpdateKeePassXC'] === undefined
|| contents['autoCompleteUsernames'] === undefined
|| contents['autoFillAndSend'] === undefined) {
console.log('Error: Not a KeePassXC-Browser settings file.');
return;
}
@ -224,7 +224,7 @@ options.initGeneralSettings = function() {
$('#dialogImportSettings').on('shown.bs.modal', () => {
$('#dialogImportSettings').find('[autofocus]').focus();
});
} catch (e) {
} catch (err) {
console.log('Error loading JSON settings file.');
}
};
@ -235,7 +235,7 @@ options.initGeneralSettings = function() {
$('#exportSettingsButton').click(function() {
const link = document.createElement('a');
const file = new Blob([ JSON.stringify(options.settings)], { type: 'application/json' });
const file = new Blob([ JSON.stringify(options.settings) ], { type: 'application/json' });
link.href = URL.createObjectURL(file);
link.download = 'keepassxc-browser_settings.json';
link.click();
@ -318,7 +318,7 @@ options.initConnectedDatabases = function() {
const date = (options.keyRing[hash].created) ? new Date(options.keyRing[hash].created).toLocaleDateString() : 'unknown';
tr.children('td:eq(3)').text(date);
$('#tab-connected-databases table tbody:first').append(tr);
}
};
let hashList = options.keyRing;
for (const hash in hashList) {

View file

@ -1,6 +1,6 @@
'use strict';
let tempArray = [];
const tempArray = [];
let keyArray = [];
document.querySelectorAll('input').forEach((b) => {

View file

@ -61,7 +61,7 @@ $(async () => {
});
$('#reconnect-button').click(async () => {
await browser.runtime.sendMessage({
await browser.runtime.sendMessage({
action: 'associate'
});
close();

View file

@ -37,7 +37,7 @@ async function initColorTheme() {
} else {
document.body.setAttribute('data-color-theme', colorTheme);
}
};
}
$(async () => {