Add eqeqeq definition to eslint

This commit is contained in:
Rob Garrison 2017-07-16 13:02:00 -05:00
parent 24dd0cb562
commit 417e3b5de3
16 changed files with 240 additions and 238 deletions

View File

@ -82,7 +82,7 @@ rules:
dot-location: [2, property] dot-location: [2, property]
dot-notation: [0] dot-notation: [0]
eol-last: [2] eol-last: [2]
eqeqeq: [0] eqeqeq: [1, always]
func-call-spacing: [2, never] func-call-spacing: [2, never]
func-name-matching: [0] func-name-matching: [0]
func-names: [0] func-names: [0]

View File

@ -33,7 +33,7 @@ chrome.tabs.onAttached.addListener((tabId, data) => {
if (tab.url.startsWith(URLS.ownOrigin + 'edit.html')) { if (tab.url.startsWith(URLS.ownOrigin + 'edit.html')) {
chrome.windows.get(tab.windowId, {populate: true}, win => { chrome.windows.get(tab.windowId, {populate: true}, win => {
// If there's only one tab in this window, it's been dragged to new window // If there's only one tab in this window, it's been dragged to new window
prefs.set('openEditInWindow', win.tabs.length == 1); prefs.set('openEditInWindow', win.tabs.length === 1);
}); });
} }
}); });
@ -59,13 +59,13 @@ updateIcon({id: undefined}, {});
const manifest = chrome.runtime.getManifest(); const manifest = chrome.runtime.getManifest();
// Open FAQs page once after installation to guide new users. // Open FAQs page once after installation to guide new users.
// Do not display it in development mode. // Do not display it in development mode.
if (reason == 'install' && manifest.update_url) { if (reason === 'install' && manifest.update_url) {
setTimeout(openURL, 100, { setTimeout(openURL, 100, {
url: 'http://add0n.com/stylus.html' url: 'http://add0n.com/stylus.html'
}); });
} }
// reset L10N cache on update // reset L10N cache on update
if (reason == 'update') { if (reason === 'update') {
localStorage.L10N = JSON.stringify({ localStorage.L10N = JSON.stringify({
browserUIlanguage: chrome.i18n.getUILanguage(), browserUIlanguage: chrome.i18n.getUILanguage(),
}); });
@ -138,7 +138,7 @@ contextMenus = Object.assign({
const item = Object.assign({id}, contextMenus[id]); const item = Object.assign({id}, contextMenus[id]);
const prefValue = prefs.readOnlyValues[id]; const prefValue = prefs.readOnlyValues[id];
item.title = chrome.i18n.getMessage(item.title); item.title = chrome.i18n.getMessage(item.title);
if (!item.type && typeof prefValue == 'boolean') { if (!item.type && typeof prefValue === 'boolean') {
item.type = 'checkbox'; item.type = 'checkbox';
item.checked = prefValue; item.checked = prefValue;
} }
@ -151,7 +151,7 @@ contextMenus = Object.assign({
}; };
createContextMenus(); createContextMenus();
prefs.subscribe((id, checked) => { prefs.subscribe((id, checked) => {
if (id == 'editor.contextDelete') { if (id === 'editor.contextDelete') {
if (checked) { if (checked) {
createContextMenus([id]); createContextMenus([id]);
} else { } else {
@ -160,7 +160,7 @@ contextMenus = Object.assign({
} else { } else {
chrome.contextMenus.update(id, {checked}, ignoreChromeError); chrome.contextMenus.update(id, {checked}, ignoreChromeError);
} }
}, Object.keys(contextMenus).filter(key => typeof prefs.readOnlyValues[key] == 'boolean')); }, Object.keys(contextMenus).filter(key => typeof prefs.readOnlyValues[key] === 'boolean'));
} }
// ************************************************************************* // *************************************************************************
@ -176,7 +176,7 @@ contextMenus = Object.assign({
.replace(/\*/g, '.*?'), flags); .replace(/\*/g, '.*?'), flags);
for (const cs of contentScripts) { for (const cs of contentScripts) {
cs.matches = cs.matches.map(m => ( cs.matches = cs.matches.map(m => (
m == ALL_URLS ? m : wildcardAsRegExp(m) m === ALL_URLS ? m : wildcardAsRegExp(m)
)); ));
} }
@ -191,8 +191,8 @@ contextMenus = Object.assign({
const pingCS = (cs, {id, url}) => { const pingCS = (cs, {id, url}) => {
cs.matches.some(match => { cs.matches.some(match => {
if ((match == ALL_URLS || url.match(match)) if ((match === ALL_URLS || url.match(match))
&& (!url.startsWith('chrome') || url == NTP)) { && (!url.startsWith('chrome') || url === NTP)) {
chrome.tabs.sendMessage(id, PING, pong => { chrome.tabs.sendMessage(id, PING, pong => {
if (!pong) { if (!pong) {
injectCS(cs, id); injectCS(cs, id);
@ -229,7 +229,7 @@ function webNavigationListener(method, {url, tabId, frameId}) {
}); });
} }
// main page frame id is 0 // main page frame id is 0
if (frameId == 0) { if (frameId === 0) {
updateIcon({id: tabId, url}, styles); updateIcon({id: tabId, url}, styles);
} }
}); });
@ -258,7 +258,7 @@ function updateIcon(tab, styles) {
} }
} }
const disableAll = 'disableAll' in styles ? styles.disableAll : prefs.get('disableAll'); const disableAll = 'disableAll' in styles ? styles.disableAll : prefs.get('disableAll');
const postfix = disableAll ? 'x' : numStyles == 0 ? 'w' : ''; const postfix = disableAll ? 'x' : numStyles === 0 ? 'w' : '';
const color = prefs.get(disableAll ? 'badgeDisabled' : 'badgeNormal'); const color = prefs.get(disableAll ? 'badgeDisabled' : 'badgeNormal');
const text = prefs.get('show-badge') && numStyles ? String(numStyles) : ''; const text = prefs.get('show-badge') && numStyles ? String(numStyles) : '';
const iconset = ['', 'light/'][prefs.get('iconset')] || ''; const iconset = ['', 'light/'][prefs.get('iconset')] || '';

View File

@ -63,7 +63,7 @@ function dbExec(method, data) {
reject(event); reject(event);
}, },
onupgradeneeded(event) { onupgradeneeded(event) {
if (event.oldVersion == 0) { if (event.oldVersion === 0) {
event.target.result.createObjectStore('styles', { event.target.result.createObjectStore('styles', {
keyPath: 'id', keyPath: 'id',
autoIncrement: true, autoIncrement: true,
@ -111,15 +111,17 @@ function filterStyles({
asHash = null, asHash = null,
strictRegexp = true, // used by the popup to detect bad regexps strictRegexp = true, // used by the popup to detect bad regexps
} = {}) { } = {}) {
enabled = enabled === null || typeof enabled == 'boolean' ? enabled : enabled = enabled === null || typeof enabled === 'boolean' ? enabled :
typeof enabled == 'string' ? enabled == 'true' : null; typeof enabled === 'string' ? enabled === 'true' : null;
id = id === null ? null : Number(id); id = id === null ? null : Number(id);
if (enabled === null if (
&& url === null enabled === null &&
&& id === null url === null &&
&& matchUrl === null id === null &&
&& asHash != true) { matchUrl === null &&
asHash !== true
) {
return cachedStyles.list; return cachedStyles.list;
} }
const blankHash = asHash && { const blankHash = asHash && {
@ -191,9 +193,9 @@ function filterStylesInternal({
let style; let style;
for (let i = 0; (style = styles[i]); i++) { for (let i = 0; (style = styles[i]); i++) {
if ((enabled === null || style.enabled == enabled) if ((enabled === null || style.enabled === enabled)
&& (url === null || style.url == url) && (url === null || style.url === url)
&& (id === null || style.id == id)) { && (id === null || style.id === id)) {
const sections = needSections && const sections = needSections &&
getApplicableSections({style, matchUrl, strictRegexp, stopOnFirst: !asHash}); getApplicableSections({style, matchUrl, strictRegexp, stopOnFirst: !asHash});
if (asHash) { if (asHash) {
@ -233,16 +235,16 @@ function saveStyle(style) {
} }
let existed; let existed;
let codeIsUpdated; let codeIsUpdated;
if (reason == 'update' || reason == 'update-digest') { if (reason === 'update' || reason === 'update-digest') {
return calcStyleDigest(style).then(digest => { return calcStyleDigest(style).then(digest => {
style.originalDigest = digest; style.originalDigest = digest;
return decide(); return decide();
}); });
} }
if (reason == 'import') { if (reason === 'import') {
style.originalDigest = style.originalDigest || style.styleDigest; // TODO: remove in the future style.originalDigest = style.originalDigest || style.styleDigest; // TODO: remove in the future
delete style.styleDigest; // TODO: remove in the future delete style.styleDigest; // TODO: remove in the future
if (typeof style.originalDigest != 'string' || style.originalDigest.length != 40) { if (typeof style.originalDigest !== 'string' || style.originalDigest.length !== 40) {
delete style.originalDigest; delete style.originalDigest;
} }
} }
@ -255,7 +257,7 @@ function saveStyle(style) {
return dbExec('get', id).then((event, store) => { return dbExec('get', id).then((event, store) => {
const oldStyle = event.target.result; const oldStyle = event.target.result;
existed = Boolean(oldStyle); existed = Boolean(oldStyle);
if (reason == 'update-digest' && oldStyle.originalDigest == style.originalDigest) { if (reason === 'update-digest' && oldStyle.originalDigest === style.originalDigest) {
return style; return style;
} }
codeIsUpdated = !existed || 'sections' in style && !styleSectionsEqual(style, oldStyle); codeIsUpdated = !existed || 'sections' in style && !styleSectionsEqual(style, oldStyle);
@ -289,7 +291,7 @@ function saveStyle(style) {
} }
function done(event) { function done(event) {
if (reason == 'update-digest') { if (reason === 'update-digest') {
return style; return style;
} }
style.id = style.id || event.target.result; style.id = style.id || event.target.result;
@ -367,14 +369,14 @@ function getApplicableSections({style, matchUrl, strictRegexp = true, stopOnFirs
function arraySomeMatches(array, matchUrl, strictRegexp) { function arraySomeMatches(array, matchUrl, strictRegexp) {
for (const regexp of array) { for (const regexp of array) {
for (let pass = 1; pass <= (strictRegexp ? 1 : 2); pass++) { for (let pass = 1; pass <= (strictRegexp ? 1 : 2); pass++) {
const cacheKey = pass == 1 ? regexp : SLOPPY_REGEXP_PREFIX + regexp; const cacheKey = pass === 1 ? regexp : SLOPPY_REGEXP_PREFIX + regexp;
let rx = cachedStyles.regexps.get(cacheKey); let rx = cachedStyles.regexps.get(cacheKey);
if (rx == false) { if (rx === false) {
// invalid regexp // invalid regexp
break; break;
} }
if (!rx) { if (!rx) {
const anchored = pass == 1 ? '^(?:' + regexp + ')$' : '^' + regexp + '$'; const anchored = pass === 1 ? '^(?:' + regexp + ')$' : '^' + regexp + '$';
rx = tryRegExp(anchored); rx = tryRegExp(anchored);
cachedStyles.regexps.set(cacheKey, rx || false); cachedStyles.regexps.set(cacheKey, rx || false);
if (!rx) { if (!rx) {
@ -415,7 +417,7 @@ function styleSectionsEqual({sections: a}, {sections: b}) {
if (!a || !b) { if (!a || !b) {
return undefined; return undefined;
} }
if (a.length != b.length) { if (a.length !== b.length) {
return false; return false;
} }
const checkedInB = []; const checkedInB = [];
@ -432,16 +434,16 @@ function styleSectionsEqual({sections: a}, {sections: b}) {
return false; return false;
} }
} }
return equalOrEmpty(secA.code, secB.code, 'substr', (a, b) => a == b); return equalOrEmpty(secA.code, secB.code, 'substr', (a, b) => a === b);
} }
function equalOrEmpty(a, b, telltale, comparator) { function equalOrEmpty(a, b, telltale, comparator) {
const typeA = a && typeof a[telltale] == 'function'; const typeA = a && typeof a[telltale] === 'function';
const typeB = b && typeof b[telltale] == 'function'; const typeB = b && typeof b[telltale] === 'function';
return ( return (
(a === null || a === undefined || (typeA && !a.length)) && (a === null || a === undefined || (typeA && !a.length)) &&
(b === null || b === undefined || (typeB && !b.length)) (b === null || b === undefined || (typeB && !b.length))
) || typeA && typeB && a.length == b.length && comparator(a, b); ) || typeA && typeB && a.length === b.length && comparator(a, b);
} }
function arrayMirrors(array1, array2) { function arrayMirrors(array1, array2) {
@ -525,12 +527,12 @@ function cleanupCachedFilters({force = false} = {}) {
function getDomains(url) { function getDomains(url) {
if (url.indexOf('file:') == 0) { if (url.indexOf('file:') === 0) {
return []; return [];
} }
let d = /.*?:\/*([^/:]+)/.exec(url)[1]; let d = /.*?:\/*([^/:]+)/.exec(url)[1];
const domains = [d]; const domains = [d];
while (d.indexOf('.') != -1) { while (d.indexOf('.') !== -1) {
d = d.substring(d.indexOf('.') + 1); d = d.substring(d.indexOf('.') + 1);
domains.push(d); domains.push(d);
} }

View File

@ -68,17 +68,17 @@ var updater = {
}); });
function maybeFetchMd5(digest) { function maybeFetchMd5(digest) {
if (!ignoreDigest && style.originalDigest && style.originalDigest != digest) { if (!ignoreDigest && style.originalDigest && style.originalDigest !== digest) {
return Promise.reject(updater.EDITED); return Promise.reject(updater.EDITED);
} }
return download(style.md5Url); return download(style.md5Url);
} }
function maybeFetchCode(md5) { function maybeFetchCode(md5) {
if (!md5 || md5.length != 32) { if (!md5 || md5.length !== 32) {
return Promise.reject(updater.ERROR_MD5); return Promise.reject(updater.ERROR_MD5);
} }
if (md5 == style.originalMd5 && style.originalDigest && !ignoreDigest) { if (md5 === style.originalMd5 && style.originalDigest && !ignoreDigest) {
return Promise.reject(updater.SAME_MD5); return Promise.reject(updater.SAME_MD5);
} }
return download(style.updateUrl); return download(style.updateUrl);
@ -109,8 +109,8 @@ var updater = {
return json return json
&& json.sections && json.sections
&& json.sections.length && json.sections.length
&& typeof json.sections.every == 'function' && typeof json.sections.every === 'function'
&& typeof json.sections[0].code == 'string'; && typeof json.sections[0].code === 'string';
} }
}, },

View File

@ -28,7 +28,7 @@ function requestStyles(options, callback = applyStyles) {
// dynamic about: and javascript: iframes don't have an URL yet // dynamic about: and javascript: iframes don't have an URL yet
// so we'll try the parent frame which is guaranteed to have a real URL // so we'll try the parent frame which is guaranteed to have a real URL
try { try {
if (window != parent) { if (window !== parent) {
matchUrl = parent.location.href; matchUrl = parent.location.href;
} }
} catch (e) {} } catch (e) {}
@ -49,7 +49,7 @@ function requestStyles(options, callback = applyStyles) {
function applyOnMessage(request, sender, sendResponse) { function applyOnMessage(request, sender, sendResponse) {
if (request.styles == 'DIY') { if (request.styles === 'DIY') {
// Do-It-Yourself tells our built-in pages to fetch the styles directly // Do-It-Yourself tells our built-in pages to fetch the styles directly
// which is faster because IPC messaging JSON-ifies everything internally // which is faster because IPC messaging JSON-ifies everything internally
requestStyles({}, styles => { requestStyles({}, styles => {
@ -114,7 +114,7 @@ function doDisableAll(disable = disableAll) {
disableAll = disable; disableAll = disable;
Array.prototype.forEach.call(document.styleSheets, stylesheet => { Array.prototype.forEach.call(document.styleSheets, stylesheet => {
if (stylesheet.ownerNode.matches(`STYLE.stylus[id^="${ID_PREFIX}"]`) if (stylesheet.ownerNode.matches(`STYLE.stylus[id^="${ID_PREFIX}"]`)
&& stylesheet.disabled != disable) { && stylesheet.disabled !== disable) {
stylesheet.disabled = disable; stylesheet.disabled = disable;
} }
}); });
@ -122,14 +122,14 @@ function doDisableAll(disable = disableAll) {
function doExposeIframes(state = exposeIframes) { function doExposeIframes(state = exposeIframes) {
if (state === exposeIframes || window == parent) { if (state === exposeIframes || window === parent) {
return; return;
} }
exposeIframes = state; exposeIframes = state;
const attr = document.documentElement.getAttribute('stylus-iframe'); const attr = document.documentElement.getAttribute('stylus-iframe');
if (state && attr != '') { if (state && attr !== '') {
document.documentElement.setAttribute('stylus-iframe', ''); document.documentElement.setAttribute('stylus-iframe', '');
} else if (!state && attr == '') { } else if (!state && attr === '') {
document.documentElement.removeAttribute('stylus-iframe'); document.documentElement.removeAttribute('stylus-iframe');
} }
} }
@ -193,7 +193,7 @@ function applyStyles(styles) {
} }
if (document.head if (document.head
&& document.head.firstChild && document.head.firstChild
&& document.head.firstChild.id == 'xml-viewer-style') { && document.head.firstChild.id === 'xml-viewer-style') {
// when site response is application/xml Chrome displays our style elements // when site response is application/xml Chrome displays our style elements
// under document.documentElement as plain text so we need to move them into HEAD // under document.documentElement as plain text so we need to move them into HEAD
// which is already autogenerated at this moment // which is already autogenerated at this moment
@ -293,7 +293,7 @@ function initDocRewriteObserver() {
for (let m = mutations.length; --m >= 0;) { for (let m = mutations.length; --m >= 0;) {
const added = mutations[m].addedNodes; const added = mutations[m].addedNodes;
for (let n = added.length; --n >= 0;) { for (let n = added.length; --n >= 0;) {
if (added[n].localName == 'html') { if (added[n].localName === 'html') {
reinjectStyles(); reinjectStyles();
return; return;
} }
@ -303,7 +303,7 @@ function initDocRewriteObserver() {
docRewriteObserver.observe(document, {childList: true}); docRewriteObserver.observe(document, {childList: true});
// detect dynamic iframes rewritten after creation by the embedder i.e. externally // detect dynamic iframes rewritten after creation by the embedder i.e. externally
setTimeout(() => { setTimeout(() => {
if (document.documentElement != ROOT) { if (document.documentElement !== ROOT) {
reinjectStyles(); reinjectStyles();
} }
}); });

View File

@ -15,7 +15,7 @@ document.addEventListener('stylishInstallOpera', onInstallClicked);
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// orphaned content script check // orphaned content script check
if (msg.method == 'ping') { if (msg.method === 'ping') {
sendResponse(true); sendResponse(true);
} }
}); });
@ -32,7 +32,7 @@ document.documentElement.appendChild(document.createElement('script')).text = '(
Response.prototype.json = function (...args) { Response.prototype.json = function (...args) {
return originalResponseJson.call(this, ...args).then(json => { return originalResponseJson.call(this, ...args).then(json => {
Response.prototype.json = originalResponseJson; Response.prototype.json = originalResponseJson;
if (!settings || typeof ((json || {}).style_settings || {}).every != 'function') { if (!settings || typeof ((json || {}).style_settings || {}).every !== 'function') {
return json; return json;
} }
const images = new Map(); const images = new Map();
@ -46,18 +46,18 @@ document.documentElement.appendChild(document.createElement('script')).text = '(
if (value.startsWith('ik-')) { if (value.startsWith('ik-')) {
value = value.replace(/^ik-/, ''); value = value.replace(/^ik-/, '');
const defaultItem = jsonSetting.style_setting_options.find(item => item.default); const defaultItem = jsonSetting.style_setting_options.find(item => item.default);
if (!defaultItem || defaultItem.install_key != value) { if (!defaultItem || defaultItem.install_key !== value) {
if (defaultItem) { if (defaultItem) {
defaultItem.default = false; defaultItem.default = false;
} }
jsonSetting.style_setting_options.some(item => { jsonSetting.style_setting_options.some(item => {
if (item.install_key == value) { if (item.install_key === value) {
item.default = true; item.default = true;
return true; return true;
} }
}); });
} }
} else if (jsonSetting.setting_type == 'image') { } else if (jsonSetting.setting_type === 'image') {
jsonSetting.style_setting_options.some(item => { jsonSetting.style_setting_options.some(item => {
if (item.default) { if (item.default) {
item.default = false; item.default = false;
@ -67,7 +67,7 @@ document.documentElement.appendChild(document.createElement('script')).text = '(
images.set(jsonSetting.install_key, value); images.set(jsonSetting.install_key, value);
} else { } else {
const item = jsonSetting.style_setting_options[0]; const item = jsonSetting.style_setting_options[0];
if (item.value !== value && item.install_key == 'placeholder') { if (item.value !== value && item.install_key === 'placeholder') {
item.value = value; item.value = value;
} }
} }
@ -151,7 +151,7 @@ function checkUpdatability([installedStyle]) {
const md5Url = getMeta('stylish-md5-url'); const md5Url = getMeta('stylish-md5-url');
if (md5Url && installedStyle.md5Url && installedStyle.originalMd5) { if (md5Url && installedStyle.md5Url && installedStyle.originalMd5) {
getResource(md5Url).then(md5 => { getResource(md5Url).then(md5 => {
reportUpdatable(md5 != installedStyle.originalMd5); reportUpdatable(md5 !== installedStyle.originalMd5);
}); });
} else { } else {
getResource(getStyleURL()).then(code => { getResource(getStyleURL()).then(code => {
@ -180,7 +180,7 @@ function sendEvent(type, detail = null) {
type = type.replace('Chrome', 'Opera'); type = type.replace('Chrome', 'Opera');
} }
detail = {detail}; detail = {detail};
if (typeof cloneInto != 'undefined') { if (typeof cloneInto !== 'undefined') {
// Firefox requires explicit cloning, however USO can't process our messages anyway // Firefox requires explicit cloning, however USO can't process our messages anyway
// because USO tries to use a global "event" variable deprecated in Firefox // because USO tries to use a global "event" variable deprecated in Firefox
detail = cloneInto(detail, document); // eslint-disable-line no-undef detail = cloneInto(detail, document); // eslint-disable-line no-undef
@ -227,7 +227,7 @@ function saveStyleCode(message, name, addProps) {
reason: 'update', reason: 'update',
}), }),
style => { style => {
if (message == 'styleUpdate' && style.updateUrl.includes('?')) { if (message === 'styleUpdate' && style.updateUrl.includes('?')) {
enableUpdateButton(true); enableUpdateButton(true);
} else { } else {
sendEvent('styleInstalledChrome'); sendEvent('styleInstalledChrome');
@ -269,7 +269,7 @@ function styleSectionsEqual({sections: a}, {sections: b}) {
if (!a || !b) { if (!a || !b) {
return undefined; return undefined;
} }
if (a.length != b.length) { if (a.length !== b.length) {
return false; return false;
} }
const checkedInB = []; const checkedInB = [];
@ -286,16 +286,16 @@ function styleSectionsEqual({sections: a}, {sections: b}) {
return false; return false;
} }
} }
return equalOrEmpty(secA.code, secB.code, 'substr', (a, b) => a == b); return equalOrEmpty(secA.code, secB.code, 'substr', (a, b) => a === b);
} }
function equalOrEmpty(a, b, telltale, comparator) { function equalOrEmpty(a, b, telltale, comparator) {
const typeA = a && typeof a[telltale] == 'function'; const typeA = a && typeof a[telltale] === 'function';
const typeB = b && typeof b[telltale] == 'function'; const typeB = b && typeof b[telltale] === 'function';
return ( return (
(a === null || a === undefined || (typeA && !a.length)) && (a === null || a === undefined || (typeA && !a.length)) &&
(b === null || b === undefined || (typeB && !b.length)) (b === null || b === undefined || (typeB && !b.length))
) || typeA && typeB && a.length == b.length && comparator(a, b); ) || typeA && typeB && a.length === b.length && comparator(a, b);
} }
function arrayMirrors(array1, array2) { function arrayMirrors(array1, array2) {
@ -315,7 +315,7 @@ function styleSectionsEqual({sections: a}, {sections: b}) {
function onDOMready() { function onDOMready() {
if (document.readyState != 'loading') { if (document.readyState !== 'loading') {
return Promise.resolve(); return Promise.resolve();
} }
return new Promise(resolve => { return new Promise(resolve => {

View File

@ -45,7 +45,7 @@ Object.defineProperty(Array.prototype, 'last', {get: function () { return this[t
new MutationObserver((mutations, observer) => { new MutationObserver((mutations, observer) => {
const themeElement = document.getElementById('cm-theme'); const themeElement = document.getElementById('cm-theme');
if (themeElement) { if (themeElement) {
themeElement.href = prefs.get('editor.theme') == 'default' ? '' themeElement.href = prefs.get('editor.theme') === 'default' ? ''
: 'vendor/codemirror/theme/' + prefs.get('editor.theme') + '.css'; : 'vendor/codemirror/theme/' + prefs.get('editor.theme') + '.css';
observer.disconnect(); observer.disconnect();
} }
@ -68,8 +68,8 @@ const hotkeyRerouter = {
eventHandler: event => { eventHandler: event => {
const keyName = CodeMirror.keyName(event); const keyName = CodeMirror.keyName(event);
if ( if (
CodeMirror.lookupKey(keyName, CodeMirror.getOption('keyMap'), handleCommand) == 'handled' || CodeMirror.lookupKey(keyName, CodeMirror.getOption('keyMap'), handleCommand) === 'handled' ||
CodeMirror.lookupKey(keyName, CodeMirror.defaults.extraKeys, handleCommand) == 'handled' CodeMirror.lookupKey(keyName, CodeMirror.defaults.extraKeys, handleCommand) === 'handled'
) { ) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
@ -90,7 +90,7 @@ function onChange(event) {
setCleanItem(node, node.savedValue === currentValue); setCleanItem(node, node.savedValue === currentValue);
} else { } else {
// the manually added section's applies-to is dirty only when the value is non-empty // the manually added section's applies-to is dirty only when the value is non-empty
setCleanItem(node, node.localName != 'input' || !node.value.trim()); setCleanItem(node, node.localName !== 'input' || !node.value.trim());
delete node.savedValue; // only valid when actually saved delete node.savedValue; // only valid when actually saved
} }
updateTitle(); updateTitle();
@ -122,7 +122,7 @@ function setCleanItem(node, isClean) {
} }
function isCleanGlobal() { function isCleanGlobal() {
const clean = Object.keys(dirty).length == 0; const clean = Object.keys(dirty).length === 0;
setDirtyClass(document.body, !clean); setDirtyClass(document.body, !clean);
// let saveBtn = document.getElementById('save-button') // let saveBtn = document.getElementById('save-button')
// if (clean){ // if (clean){
@ -270,7 +270,7 @@ function initCodeMirror() {
} else { } else {
// Chrome is starting up and shows our edit.html, but the background page isn't loaded yet // Chrome is starting up and shows our edit.html, but the background page isn't loaded yet
const theme = prefs.get('editor.theme'); const theme = prefs.get('editor.theme');
themeControl.innerHTML = optionsHtmlFromArray([theme == 'default' ? t('defaultTheme') : theme]); themeControl.innerHTML = optionsHtmlFromArray([theme === 'default' ? t('defaultTheme') : theme]);
getCodeMirrorThemes().then(() => { getCodeMirrorThemes().then(() => {
const themes = (localStorage.codeMirrorThemes || '').split(/\s+/); const themes = (localStorage.codeMirrorThemes || '').split(/\s+/);
themeControl.innerHTML = optionsHtmlFromArray(themes); themeControl.innerHTML = optionsHtmlFromArray(themes);
@ -292,7 +292,7 @@ function acmeEventListener(event) {
console.error('acmeEventListener: no "cm_option" %O', el); console.error('acmeEventListener: no "cm_option" %O', el);
return; return;
} }
let value = el.type == 'checkbox' ? el.checked : el.value; let value = el.type === 'checkbox' ? el.checked : el.value;
switch (option) { switch (option) {
case 'tabSize': case 'tabSize':
CodeMirror.setOption('indentUnit', Number(value)); CodeMirror.setOption('indentUnit', Number(value));
@ -300,9 +300,9 @@ function acmeEventListener(event) {
case 'theme': { case 'theme': {
const themeLink = document.getElementById('cm-theme'); const themeLink = document.getElementById('cm-theme');
// use non-localized 'default' internally // use non-localized 'default' internally
if (!value || value == 'default' || value == t('defaultTheme')) { if (!value || value === 'default' || value === t('defaultTheme')) {
value = 'default'; value = 'default';
if (prefs.get(el.id) != value) { if (prefs.get(el.id) !== value) {
prefs.set(el.id, value); prefs.set(el.id, value);
} }
themeLink.href = ''; themeLink.href = '';
@ -310,7 +310,7 @@ function acmeEventListener(event) {
break; break;
} }
const url = chrome.runtime.getURL('vendor/codemirror/theme/' + value + '.css'); const url = chrome.runtime.getURL('vendor/codemirror/theme/' + value + '.css');
if (themeLink.href == url) { // preloaded in initCodeMirror() if (themeLink.href === url) { // preloaded in initCodeMirror()
break; break;
} }
// avoid flicker: wait for the second stylesheet to load, then apply the theme // avoid flicker: wait for the second stylesheet to load, then apply the theme
@ -337,7 +337,7 @@ function acmeEventListener(event) {
case 'token': case 'token':
case 'selection': case 'selection':
document.body.dataset[option] = value; document.body.dataset[option] = value;
value = {showToken: value == 'token' && /[#.\-\w]/, annotateScrollbar: true}; value = {showToken: value === 'token' && /[#.\-\w]/, annotateScrollbar: true};
break; break;
default: default:
value = null; value = null;
@ -372,7 +372,7 @@ function setupCodeMirror(textarea, index) {
let lastClickTime = 0; let lastClickTime = 0;
const resizeGrip = wrapper.appendChild(template.resizeGrip.cloneNode(true)); const resizeGrip = wrapper.appendChild(template.resizeGrip.cloneNode(true));
resizeGrip.onmousedown = event => { resizeGrip.onmousedown = event => {
if (event.button != 0) { if (event.button !== 0) {
return; return;
} }
event.preventDefault(); event.preventDefault();
@ -390,7 +390,7 @@ function setupCodeMirror(textarea, index) {
function resize(e) { function resize(e) {
const cmPageY = wrapper.getBoundingClientRect().top + window.scrollY; const cmPageY = wrapper.getBoundingClientRect().top + window.scrollY;
const height = Math.max(minHeight, e.pageY - cmPageY); const height = Math.max(minHeight, e.pageY - cmPageY);
if (height != wrapper.clientHeight) { if (height !== wrapper.clientHeight) {
cm.setSize(null, height); cm.setSize(null, height);
} }
} }
@ -449,7 +449,7 @@ queryTabs({currentWindow: true}).then(tabs => {
// window was reopened via Ctrl-Shift-T etc. // window was reopened via Ctrl-Shift-T etc.
chrome.windows.update(windowId, prefs.get('windowPosition')); chrome.windows.update(windowId, prefs.get('windowPosition'));
} }
if (tabs.length == 1 && window.history.length == 1) { if (tabs.length === 1 && window.history.length === 1) {
chrome.windows.getAll(windows => { chrome.windows.getAll(windows => {
if (windows.length > 1) { if (windows.length > 1) {
sessionStorageHash('saveSizeOnClose').set(windowId, true); sessionStorageHash('saveSizeOnClose').set(windowId, true);
@ -462,14 +462,14 @@ queryTabs({currentWindow: true}).then(tabs => {
} }
chrome.tabs.onRemoved.addListener((tabId, info) => { chrome.tabs.onRemoved.addListener((tabId, info) => {
sessionStorageHash('manageStylesHistory').unset(tabId); sessionStorageHash('manageStylesHistory').unset(tabId);
if (info.windowId == windowId && info.isWindowClosing) { if (info.windowId === windowId && info.isWindowClosing) {
sessionStorageHash('saveSizeOnClose').unset(windowId); sessionStorageHash('saveSizeOnClose').unset(windowId);
} }
}); });
}); });
getActiveTab().then(tab => { getActiveTab().then(tab => {
useHistoryBack = sessionStorageHash('manageStylesHistory').value[tab.id] == location.href; useHistoryBack = sessionStorageHash('manageStylesHistory').value[tab.id] === location.href;
}); });
function goBackToManage(event) { function goBackToManage(event) {
@ -483,10 +483,10 @@ function goBackToManage(event) {
} }
function isWindowMaximized() { function isWindowMaximized() {
return window.screenLeft == 0 && return window.screenLeft === 0 &&
window.screenTop == 0 && window.screenTop === 0 &&
window.outerWidth == screen.availWidth && window.outerWidth === screen.availWidth &&
window.outerHeight == screen.availHeight; window.outerHeight === screen.availHeight;
} }
window.onbeforeunload = () => { window.onbeforeunload = () => {
@ -568,13 +568,13 @@ function addSection(event, section) {
function toggleTestRegExpVisibility() { function toggleTestRegExpVisibility() {
const show = [...appliesTo.children].some(item => const show = [...appliesTo.children].some(item =>
!item.matches('.applies-to-everything') && !item.matches('.applies-to-everything') &&
item.querySelector('.applies-type').value == 'regexp' && item.querySelector('.applies-type').value === 'regexp' &&
item.querySelector('.applies-value').value.trim()); item.querySelector('.applies-value').value.trim());
div.classList.toggle('has-regexp', show); div.classList.toggle('has-regexp', show);
appliesTo.oninput = appliesTo.oninput || show && (event => { appliesTo.oninput = appliesTo.oninput || show && (event => {
if ( if (
event.target.matches('.applies-value') && event.target.matches('.applies-value') &&
event.target.parentElement.querySelector('.applies-type').value == 'regexp' event.target.parentElement.querySelector('.applies-type').value === 'regexp'
) { ) {
showRegExpTester(null, div); showRegExpTester(null, div);
} }
@ -666,7 +666,7 @@ function setupGlobalSearch() {
let curState; // cm.state.search for last used 'find' let curState; // cm.state.search for last used 'find'
function shouldIgnoreCase(query) { // treat all-lowercase non-regexp queries as case-insensitive function shouldIgnoreCase(query) { // treat all-lowercase non-regexp queries as case-insensitive
return typeof query == 'string' && query == query.toLowerCase(); return typeof query === 'string' && query === query.toLowerCase();
} }
function updateState(cm, newState) { function updateState(cm, newState) {
@ -701,7 +701,7 @@ function setupGlobalSearch() {
function focusClosestCM(activeCM) { function focusClosestCM(activeCM) {
editors.lastActive = activeCM; editors.lastActive = activeCM;
const cm = getEditorInSight(); const cm = getEditorInSight();
if (cm != activeCM) { if (cm !== activeCM) {
cm.focus(); cm.focus();
} }
return cm; return cm;
@ -712,16 +712,16 @@ function setupGlobalSearch() {
customizeOpenDialog(activeCM, template.find, function (query) { customizeOpenDialog(activeCM, template.find, function (query) {
this(query); this(query);
curState = activeCM.state.search; curState = activeCM.state.search;
if (editors.length == 1 || !curState.query) { if (editors.length === 1 || !curState.query) {
return; return;
} }
editors.forEach(cm => { editors.forEach(cm => {
if (cm != activeCM) { if (cm !== activeCM) {
cm.execCommand('clearSearch'); cm.execCommand('clearSearch');
updateState(cm, curState); updateState(cm, curState);
} }
}); });
if (CodeMirror.cmpPos(curState.posFrom, curState.posTo) == 0) { if (CodeMirror.cmpPos(curState.posFrom, curState.posTo) === 0) {
findNext(activeCM); findNext(activeCM);
} }
}); });
@ -737,12 +737,12 @@ function setupGlobalSearch() {
let pos = activeCM.getCursor(reverse ? 'from' : 'to'); let pos = activeCM.getCursor(reverse ? 'from' : 'to');
activeCM.setSelection(activeCM.getCursor()); // clear the selection, don't move the cursor activeCM.setSelection(activeCM.getCursor()); // clear the selection, don't move the cursor
const rxQuery = typeof state.query == 'object' const rxQuery = typeof state.query === 'object'
? state.query : stringAsRegExp(state.query, shouldIgnoreCase(state.query) ? 'i' : ''); ? state.query : stringAsRegExp(state.query, shouldIgnoreCase(state.query) ? 'i' : '');
if ( if (
document.activeElement && document.activeElement &&
document.activeElement.name == 'applies-value' && document.activeElement.name === 'applies-value' &&
searchAppliesTo(activeCM) searchAppliesTo(activeCM)
) { ) {
return; return;
@ -864,7 +864,7 @@ function setupGlobalSearch() {
wrapAround |= cmp <= 0; wrapAround |= cmp <= 0;
const dlg = cm.getWrapperElement().querySelector('.CodeMirror-dialog'); const dlg = cm.getWrapperElement().querySelector('.CodeMirror-dialog');
if (!dlg || cmp == 0 || wrapAround && CodeMirror.cmpPos(cm.getCursor(), origPos) >= 0) { if (!dlg || cmp === 0 || wrapAround && CodeMirror.cmpPos(cm.getCursor(), origPos) >= 0) {
if (dlg) { if (dlg) {
dlg.remove(); dlg.remove();
} }
@ -1006,7 +1006,7 @@ function getEditorInSight(nearbyElement) {
} }
function updateLintReport(cm, delay) { function updateLintReport(cm, delay) {
if (delay == 0) { if (delay === 0) {
// immediately show pending csslint messages in onbeforeunload and save // immediately show pending csslint messages in onbeforeunload and save
update(cm); update(cm);
return; return;
@ -1024,7 +1024,7 @@ function updateLintReport(cm, delay) {
// or update it as soon as possible (default: 500ms lint + 100ms) in case an existing issue was just fixed // or update it as soon as possible (default: 500ms lint + 100ms) in case an existing issue was just fixed
clearTimeout(state.reportTimeout); clearTimeout(state.reportTimeout);
state.reportTimeout = setTimeout(update, state.options.delay + 100, cm); state.reportTimeout = setTimeout(update, state.options.delay + 100, cm);
state.postponeNewIssues = delay == undefined || delay === null; state.postponeNewIssues = delay === undefined || delay === null;
function update(cm) { function update(cm) {
const scope = cm ? [cm] : editors; const scope = cm ? [cm] : editors;
@ -1034,16 +1034,16 @@ function updateLintReport(cm, delay) {
const scopedState = cm.state.lint || {}; const scopedState = cm.state.lint || {};
const oldMarkers = scopedState.markedLast || {}; const oldMarkers = scopedState.markedLast || {};
const newMarkers = {}; const newMarkers = {};
const html = !scopedState.marked || scopedState.marked.length == 0 ? '' : '<tbody>' + const html = !scopedState.marked || scopedState.marked.length === 0 ? '' : '<tbody>' +
scopedState.marked.map(mark => { scopedState.marked.map(mark => {
const info = mark.__annotation; const info = mark.__annotation;
const isActiveLine = info.from.line == cm.getCursor().line; const isActiveLine = info.from.line === cm.getCursor().line;
const pos = isActiveLine ? 'cursor' : (info.from.line + ',' + info.from.ch); const pos = isActiveLine ? 'cursor' : (info.from.line + ',' + info.from.ch);
let message = escapeHtml(info.message.replace(/ at line \d.+$/, '')); let message = escapeHtml(info.message.replace(/ at line \d.+$/, ''));
if (message.length > 100) { if (message.length > 100) {
message = message.substr(0, 100) + '...'; message = message.substr(0, 100) + '...';
} }
if (isActiveLine || oldMarkers[pos] == message) { if (isActiveLine || oldMarkers[pos] === message) {
delete oldMarkers[pos]; delete oldMarkers[pos];
} }
newMarkers[pos] = message; newMarkers[pos] = message;
@ -1057,7 +1057,7 @@ function updateLintReport(cm, delay) {
}).join('') + '</tbody>'; }).join('') + '</tbody>';
scopedState.markedLast = newMarkers; scopedState.markedLast = newMarkers;
fixedOldIssues |= scopedState.reportDisplayed && Object.keys(oldMarkers).length > 0; fixedOldIssues |= scopedState.reportDisplayed && Object.keys(oldMarkers).length > 0;
if (scopedState.html != html) { if (scopedState.html !== html) {
scopedState.html = html; scopedState.html = html;
changed = true; changed = true;
} }
@ -1094,12 +1094,12 @@ function renderLintReport(someBlockChanged) {
issueCount += newBlock.rows.length; issueCount += newBlock.rows.length;
const block = content.children[newContent.children.length - 1]; const block = content.children[newContent.children.length - 1];
const blockChanged = !block || cm != block.cm || html != block.innerHTML; const blockChanged = !block || cm !== block.cm || html !== block.innerHTML;
someBlockChanged |= blockChanged; someBlockChanged |= blockChanged;
cm.state.lint.reportDisplayed = blockChanged; cm.state.lint.reportDisplayed = blockChanged;
} }
}); });
if (someBlockChanged || newContent.children.length != content.children.length) { if (someBlockChanged || newContent.children.length !== content.children.length) {
document.getElementById('issue-count').textContent = issueCount; document.getElementById('issue-count').textContent = issueCount;
container.replaceChild(newContent, content); container.replaceChild(newContent, content);
container.style.display = newContent.children.length ? 'block' : 'none'; container.style.display = newContent.children.length ? 'block' : 'none';
@ -1112,7 +1112,7 @@ function resizeLintReport(event, content) {
if (content.children.length) { if (content.children.length) {
const bounds = content.getBoundingClientRect(); const bounds = content.getBoundingClientRect();
const newMaxHeight = bounds.bottom <= innerHeight ? '' : (innerHeight - bounds.top) + 'px'; const newMaxHeight = bounds.bottom <= innerHeight ? '' : (innerHeight - bounds.top) + 'px';
if (newMaxHeight != content.style.maxHeight) { if (newMaxHeight !== content.style.maxHeight) {
content.style.maxHeight = newMaxHeight; content.style.maxHeight = newMaxHeight;
} }
} }
@ -1167,7 +1167,7 @@ function beautify(event) {
'<div><button role="undo"></button></div>'); '<div><button role="undo"></button></div>');
const undoButton = document.querySelector('#help-popup button[role="undo"]'); const undoButton = document.querySelector('#help-popup button[role="undo"]');
undoButton.textContent = t(scope.length == 1 ? 'undo' : 'undoGlobal'); undoButton.textContent = t(scope.length === 1 ? 'undo' : 'undoGlobal');
undoButton.addEventListener('click', () => { undoButton.addEventListener('click', () => {
let undoable = false; let undoable = false;
scope.forEach(cm => { scope.forEach(cm => {
@ -1188,7 +1188,7 @@ function beautify(event) {
[Object.assign({}, r.anchor), Object.assign({}, r.head)])); [Object.assign({}, r.anchor), Object.assign({}, r.head)]));
const text = cm.getValue(); const text = cm.getValue();
const newText = exports.css_beautify(text, options); const newText = exports.css_beautify(text, options);
if (newText != text) { if (newText !== text) {
if (!cm.beautifyChange || !cm.beautifyChange[cm.changeGeneration()]) { if (!cm.beautifyChange || !cm.beautifyChange[cm.changeGeneration()]) {
// clear the list if last change wasn't a css-beautify // clear the list if last change wasn't a css-beautify
cm.beautifyChange = {}; cm.beautifyChange = {};
@ -1206,7 +1206,7 @@ function beautify(event) {
}); });
document.querySelector('.beautify-options').onchange = ({target}) => { document.querySelector('.beautify-options').onchange = ({target}) => {
const value = target.type == 'checkbox' ? target.checked : target.selectedIndex > 0; const value = target.type === 'checkbox' ? target.checked : target.selectedIndex > 0;
prefs.set('editor.beautify', Object.assign(options, {[target.dataset.option]: value})); prefs.set('editor.beautify', Object.assign(options, {[target.dataset.option]: value}));
if (target.parentNode.hasAttribute('newline')) { if (target.parentNode.hasAttribute('newline')) {
target.parentNode.setAttribute('newline', value.toString()); target.parentNode.setAttribute('newline', value.toString());
@ -1264,7 +1264,7 @@ function init() {
window.onload = null; window.onload = null;
initWithStyle({style}); initWithStyle({style});
}; };
if (document.readyState != 'loading') { if (document.readyState !== 'loading') {
window.onload(); window.onload();
} }
}); });
@ -1346,10 +1346,10 @@ function initHooks() {
function toggleContextMenuDelete(event) { function toggleContextMenuDelete(event) {
if (event.button == 2 && prefs.get('editor.contextDelete')) { if (event.button === 2 && prefs.get('editor.contextDelete')) {
chrome.contextMenus.update('editor.contextDelete', { chrome.contextMenus.update('editor.contextDelete', {
enabled: Boolean( enabled: Boolean(
this.selectionStart != this.selectionEnd || this.selectionStart !== this.selectionEnd ||
this.somethingSelected && this.somethingSelected() this.somethingSelected && this.somethingSelected()
), ),
}, ignoreChromeError); }, ignoreChromeError);
@ -1412,20 +1412,20 @@ function updateTitle() {
function validate() { function validate() {
const name = document.getElementById('name').value; const name = document.getElementById('name').value;
if (name == '') { if (name === '') {
return t('styleMissingName'); return t('styleMissingName');
} }
// validate the regexps // validate the regexps
if (document.querySelectorAll('.applies-to-list').some(list => { if (document.querySelectorAll('.applies-to-list').some(list => {
list.childNodes.some(li => { list.childNodes.some(li => {
if (li.className == template.appliesToEverything.className) { if (li.className === template.appliesToEverything.className) {
return false; return false;
} }
const valueElement = li.querySelector('[name=applies-value]'); const valueElement = li.querySelector('[name=applies-value]');
const type = li.querySelector('[name=applies-type]').value; const type = li.querySelector('[name=applies-type]').value;
const value = valueElement.value; const value = valueElement.value;
if (type && value) { if (type && value) {
if (type == 'regexp') { if (type === 'regexp') {
try { try {
new RegExp(value); new RegExp(value);
} catch (ex) { } catch (ex) {
@ -1472,7 +1472,7 @@ function getSectionsHashes() {
getSections().forEach(div => { getSections().forEach(div => {
const meta = getMeta(div); const meta = getMeta(div);
const code = div.CodeMirror.getValue(); const code = div.CodeMirror.getValue();
if (/^\s*$/.test(code) && Object.keys(meta).length == 0) { if (/^\s*$/.test(code) && Object.keys(meta).length === 0) {
return; return;
} }
meta.code = code; meta.code = code;
@ -1484,7 +1484,7 @@ function getSectionsHashes() {
function getMeta(e) { function getMeta(e) {
const meta = {urls: [], urlPrefixes: [], domains: [], regexps: []}; const meta = {urls: [], urlPrefixes: [], domains: [], regexps: []};
e.querySelector('.applies-to-list').childNodes.forEach(li => { e.querySelector('.applies-to-list').childNodes.forEach(li => {
if (li.className == template.appliesToEverything.className) { if (li.className === template.appliesToEverything.className) {
return; return;
} }
const type = li.querySelector('[name=applies-type]').value; const type = li.querySelector('[name=applies-type]').value;
@ -1502,7 +1502,7 @@ function saveComplete(style) {
setCleanGlobal(); setCleanGlobal();
// Go from new style URL to edit style URL // Go from new style URL to edit style URL
if (location.href.indexOf('id=') == -1) { if (location.href.indexOf('id=') === -1) {
history.replaceState({}, document.title, 'edit.html?id=' + style.id); history.replaceState({}, document.title, 'edit.html?id=' + style.id);
tE('heading', 'editStyleHeading', null, false); tE('heading', 'editStyleHeading', null, false);
} }
@ -1551,7 +1551,7 @@ function fromMozillaFormat() {
}); });
function doImport() { function doImport() {
const replaceOldStyle = this.name == 'import-replace'; const replaceOldStyle = this.name === 'import-replace';
popup.querySelector('.dismiss').onclick(); popup.querySelector('.dismiss').onclick();
const mozStyle = trimNewLines(popup.codebox.getValue()); const mozStyle = trimNewLines(popup.codebox.getValue());
const parser = new parserlib.css.Parser(); const parser = new parserlib.css.Parser();
@ -1578,7 +1578,7 @@ function fromMozillaFormat() {
e.functions.forEach(f => { e.functions.forEach(f => {
const m = f.match(/^(url|url-prefix|domain|regexp)\((['"]?)(.+?)\2?\)$/); const m = f.match(/^(url|url-prefix|domain|regexp)\((['"]?)(.+?)\2?\)$/);
const aType = CssToProperty[m[1]]; const aType = CssToProperty[m[1]];
const aValue = aType != 'regexps' ? m[3] : m[3].replace(/\\\\/g, '\\'); const aValue = aType !== 'regexps' ? m[3] : m[3].replace(/\\\\/g, '\\');
(section[aType] = section[aType] || []).push(aValue); (section[aType] = section[aType] || []).push(aValue);
}); });
sectionStack.push(section); sectionStack.push(section);
@ -1600,7 +1600,7 @@ function fromMozillaFormat() {
delete maximizeCodeHeight.stats; delete maximizeCodeHeight.stats;
editors.forEach(cm => { editors.forEach(cm => {
maximizeCodeHeight(cm.getSection(), cm == editors.last); maximizeCodeHeight(cm.getSection(), cm === editors.last);
}); });
makeSectionVisible(firstAddedCM); makeSectionVisible(firstAddedCM);
@ -1622,7 +1622,7 @@ function fromMozillaFormat() {
const C1 = start.col - 1; const C1 = start.col - 1;
const L2 = end.line - 1; const L2 = end.line - 1;
const C2 = end.col - 1; const C2 = end.col - 1;
if (L1 == L2) { if (L1 === L2) {
return lines[L1].substr(C1, C2 - C1 + 1); return lines[L1].substr(C1, C2 - C1 + 1);
} else { } else {
const middle = lines.slice(L1 + 1, L2).join('\n'); const middle = lines.slice(L1 + 1, L2).join('\n');
@ -1673,7 +1673,7 @@ function fromMozillaFormat() {
function backtrackTo(parser, tokenType, startEnd) { function backtrackTo(parser, tokenType, startEnd) {
const tokens = parser._tokenStream._lt; const tokens = parser._tokenStream._lt;
for (let i = parser._tokenStream._ltIndex - 1; i >= 0; --i) { for (let i = parser._tokenStream._ltIndex - 1; i >= 0; --i) {
if (tokens[i].type == tokenType) { if (tokens[i].type === tokenType) {
return {line: tokens[i][startEnd + 'Line'], col: tokens[i][startEnd + 'Col']}; return {line: tokens[i][startEnd + 'Line'], col: tokens[i][startEnd + 'Col']};
} }
} }
@ -1704,7 +1704,7 @@ function showKeyMapHelp() {
const keyMapSorted = Object.keys(keyMap) const keyMapSorted = Object.keys(keyMap)
.map(key => ({key: key, cmd: keyMap[key]})) .map(key => ({key: key, cmd: keyMap[key]}))
.concat([{key: 'Shift-Ctrl-Wheel', cmd: 'scrollWindow'}]) .concat([{key: 'Shift-Ctrl-Wheel', cmd: 'scrollWindow'}])
.sort((a, b) => (a.cmd < b.cmd || (a.cmd == b.cmd && a.key < b.key) ? -1 : 1)); .sort((a, b) => (a.cmd < b.cmd || (a.cmd === b.cmd && a.key < b.key) ? -1 : 1));
showHelp(t('cm_keyMap') + ': ' + prefs.get('editor.keyMap'), showHelp(t('cm_keyMap') + ': ' + prefs.get('editor.keyMap'),
'<table class="keymap-list">' + '<table class="keymap-list">' +
'<thead><tr><th><input placeholder="' + t('helpKeyMapHotkey') + '" type="search"></th>' + '<thead><tr><th><input placeholder="' + t('helpKeyMapHotkey') + '" type="search"></th>' +
@ -1724,7 +1724,7 @@ function showKeyMapHelp() {
function hotkeyHandler(event) { function hotkeyHandler(event) {
const keyName = CodeMirror.keyName(event); const keyName = CodeMirror.keyName(event);
if (keyName == 'Esc' || keyName == 'Tab' || keyName == 'Shift-Tab') { if (keyName === 'Esc' || keyName === 'Tab' || keyName === 'Shift-Tab') {
return; return;
} }
event.preventDefault(); event.preventDefault();
@ -1754,14 +1754,14 @@ function showKeyMapHelp() {
} }
function mergeKeyMaps(merged, ...more) { function mergeKeyMaps(merged, ...more) {
more.forEach(keyMap => { more.forEach(keyMap => {
if (typeof keyMap == 'string') { if (typeof keyMap === 'string') {
keyMap = CodeMirror.keyMap[keyMap]; keyMap = CodeMirror.keyMap[keyMap];
} }
Object.keys(keyMap).forEach(key => { Object.keys(keyMap).forEach(key => {
let cmd = keyMap[key]; let cmd = keyMap[key];
// filter out '...', 'attach', etc. (hotkeys start with an uppercase letter) // filter out '...', 'attach', etc. (hotkeys start with an uppercase letter)
if (!merged[key] && !key.match(/^[a-z]/) && cmd != '...') { if (!merged[key] && !key.match(/^[a-z]/) && cmd !== '...') {
if (typeof cmd == 'function') { if (typeof cmd === 'function') {
// for 'emacs' keymap: provide at least something meaningful (hotkeys and the function body) // for 'emacs' keymap: provide at least something meaningful (hotkeys and the function body)
// for 'vim*' keymaps: almost nothing as it doesn't rely on CM keymap mechanism // for 'vim*' keymaps: almost nothing as it doesn't rely on CM keymap mechanism
cmd = cmd.toString().replace(/^function.*?\{[\s\r\n]*([\s\S]+?)[\s\r\n]*\}$/, '$1'); cmd = cmd.toString().replace(/^function.*?\{[\s\r\n]*([\s\S]+?)[\s\r\n]*\}$/, '$1');
@ -1795,7 +1795,7 @@ function showRegExpTester(event, section = getSectionForChild(this)) {
const regexps = [...section.querySelector('.applies-to-list').children] const regexps = [...section.querySelector('.applies-to-list').children]
.map(item => .map(item =>
!item.matches('.applies-to-everything') && !item.matches('.applies-to-everything') &&
item.querySelector('.applies-type').value == 'regexp' && item.querySelector('.applies-type').value === 'regexp' &&
item.querySelector('.applies-value').value.trim()) item.querySelector('.applies-value').value.trim())
.filter(item => item) .filter(item => item)
.map(text => { .map(text => {
@ -1857,7 +1857,7 @@ function showRegExpTester(event, section = getSectionForChild(this)) {
? OWN_ICON ? OWN_ICON
: GET_FAVICON_URL + new URL(url).hostname; : GET_FAVICON_URL + new URL(url).hostname;
const icon = `<img src="${faviconUrl}">`; const icon = `<img src="${faviconUrl}">`;
if (match.length == url.length) { if (match.length === url.length) {
full.push(`<div>${icon + url}</div>`); full.push(`<div>${icon + url}</div>`);
} else { } else {
partial.push(`<div>${icon}<mark>${match}</mark>` + partial.push(`<div>${icon}<mark>${match}</mark>` +
@ -1898,7 +1898,7 @@ function showHelp(title, text) {
div.querySelector('.contents').innerHTML = text; div.querySelector('.contents').innerHTML = text;
div.querySelector('.title').innerHTML = title; div.querySelector('.title').innerHTML = title;
if (getComputedStyle(div).display == 'none') { if (getComputedStyle(div).display === 'none') {
document.addEventListener('keydown', closeHelp); document.addEventListener('keydown', closeHelp);
div.querySelector('.dismiss').onclick = closeHelp; // avoid chaining on multiple showHelp() calls div.querySelector('.dismiss').onclick = closeHelp; // avoid chaining on multiple showHelp() calls
} }
@ -1909,8 +1909,8 @@ function showHelp(title, text) {
function closeHelp(e) { function closeHelp(e) {
if ( if (
!e || !e ||
e.type == 'click' || e.type === 'click' ||
((e.keyCode || e.which) == 27 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) ((e.keyCode || e.which) === 27 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey)
) { ) {
div.style.display = ''; div.style.display = '';
document.querySelector('.contents').innerHTML = ''; document.querySelector('.contents').innerHTML = '';
@ -1944,7 +1944,7 @@ function showCodeMirrorPopup(title, html, options) {
function getParams() { function getParams() {
const params = {}; const params = {};
const urlParts = location.href.split('?', 2); const urlParts = location.href.split('?', 2);
if (urlParts.length == 1) { if (urlParts.length === 1) {
return params; return params;
} }
urlParts[1].split('&').forEach(keyValue => { urlParts[1].split('&').forEach(keyValue => {
@ -1959,7 +1959,7 @@ chrome.runtime.onMessage.addListener(onRuntimeMessage);
function onRuntimeMessage(request) { function onRuntimeMessage(request) {
switch (request.method) { switch (request.method) {
case 'styleUpdated': case 'styleUpdated':
if (styleId && styleId == request.style.id && request.reason != 'editSave') { if (styleId && styleId === request.style.id && request.reason !== 'editSave') {
if ((request.style.sections[0] || {}).code === null) { if ((request.style.sections[0] || {}).code === null) {
// the code-less style came from notifyAllTabs // the code-less style came from notifyAllTabs
onBackgroundReady().then(() => { onBackgroundReady().then(() => {
@ -1972,7 +1972,7 @@ function onRuntimeMessage(request) {
} }
break; break;
case 'styleDeleted': case 'styleDeleted':
if (styleId && styleId == request.id) { if (styleId && styleId === request.id) {
window.onbeforeunload = () => {}; window.onbeforeunload = () => {};
window.close(); window.close();
break; break;

View File

@ -27,7 +27,7 @@ navigator.userAgent.includes('Firefox') && setTimeout(() => {
function onDOMready() { function onDOMready() {
if (document.readyState != 'loading') { if (document.readyState !== 'loading') {
return Promise.resolve(); return Promise.resolve();
} }
return new Promise(resolve => { return new Promise(resolve => {
@ -79,9 +79,9 @@ function enforceInputRange(element) {
const max = Number(element.max); const max = Number(element.max);
const doNotify = () => element.dispatchEvent(new Event('change', {bubbles: true})); const doNotify = () => element.dispatchEvent(new Event('change', {bubbles: true}));
const onChange = ({type}) => { const onChange = ({type}) => {
if (type == 'input' && element.checkValidity()) { if (type === 'input' && element.checkValidity()) {
doNotify(); doNotify();
} else if (type == 'change' && !element.checkValidity()) { } else if (type === 'change' && !element.checkValidity()) {
element.value = Math.max(min, Math.min(max, Number(element.value))); element.value = Math.max(min, Math.min(max, Number(element.value)));
doNotify(); doNotify();
} }
@ -113,7 +113,7 @@ function $element(opt) {
? opt.tag.split('#') ? opt.tag.split('#')
: [null, opt.tag]; : [null, opt.tag];
const element = ns const element = ns
? document.createElementNS(ns == 'SVG' || ns == 'svg' ? 'http://www.w3.org/2000/svg' : ns, tag) ? document.createElementNS(ns === 'SVG' || ns === 'svg' ? 'http://www.w3.org/2000/svg' : ns, tag)
: document.createElement(tag || 'div'); : document.createElement(tag || 'div');
(opt.appendChild instanceof Array ? opt.appendChild : [opt.appendChild]) (opt.appendChild instanceof Array ? opt.appendChild : [opt.appendChild])
.forEach(child => child && element.appendChild(child)); .forEach(child => child && element.appendChild(child));

View File

@ -7,7 +7,7 @@ tDocLoader();
function t(key, params) { function t(key, params) {
const cache = !params && t.cache[key]; const cache = !params && t.cache[key];
const s = cache || chrome.i18n.getMessage(key, params); const s = cache || chrome.i18n.getMessage(key, params);
if (s == '') { if (s === '') {
throw `Missing string "${key}"`; throw `Missing string "${key}"`;
} }
if (!params && !cache) { if (!params && !cache) {
@ -20,7 +20,7 @@ function t(key, params) {
function tE(id, key, attr, esc) { function tE(id, key, attr, esc) {
if (attr) { if (attr) {
document.getElementById(id).setAttribute(attr, t(key)); document.getElementById(id).setAttribute(attr, t(key));
} else if (typeof esc == 'undefined' || esc) { } else if (typeof esc === 'undefined' || esc) {
document.getElementById(id).appendChild(document.createTextNode(t(key))); document.getElementById(id).appendChild(document.createTextNode(t(key)));
} else { } else {
document.getElementById(id).innerHTML = t(key); document.getElementById(id).innerHTML = t(key);
@ -43,10 +43,10 @@ function tNodeList(nodes) {
for (let n = nodes.length; --n >= 0;) { for (let n = nodes.length; --n >= 0;) {
const node = nodes[n]; const node = nodes[n];
// skip non-ELEMENT_NODE // skip non-ELEMENT_NODE
if (node.nodeType != 1) { if (node.nodeType !== 1) {
continue; continue;
} }
if (node.localName == 'template') { if (node.localName === 'template') {
const elements = node.content.querySelectorAll('*'); const elements = node.content.querySelectorAll('*');
tNodeList(elements); tNodeList(elements);
template[node.dataset.id] = elements[0]; template[node.dataset.id] = elements[0];
@ -94,7 +94,7 @@ function tDocLoader() {
// reset L10N cache on UI language change // reset L10N cache on UI language change
const UIlang = chrome.i18n.getUILanguage(); const UIlang = chrome.i18n.getUILanguage();
if (t.cache.browserUIlanguage != UIlang) { if (t.cache.browserUIlanguage !== UIlang) {
t.cache = {browserUIlanguage: UIlang}; t.cache = {browserUIlanguage: UIlang};
localStorage.L10N = JSON.stringify(t.cache); localStorage.L10N = JSON.stringify(t.cache);
} }
@ -114,7 +114,7 @@ function tDocLoader() {
const onLoad = () => { const onLoad = () => {
tDocLoader.stop(); tDocLoader.stop();
process(observer.takeRecords()); process(observer.takeRecords());
if (cacheLength != Object.keys(t.cache).length) { if (cacheLength !== Object.keys(t.cache).length) {
localStorage.L10N = JSON.stringify(t.cache); localStorage.L10N = JSON.stringify(t.cache);
} }
}; };

View File

@ -35,7 +35,7 @@ const URLS = {
let BG = chrome.extension.getBackgroundPage(); let BG = chrome.extension.getBackgroundPage();
if (!BG || BG != window) { if (!BG || BG !== window) {
document.documentElement.classList.toggle('firefox', FIREFOX); document.documentElement.classList.toggle('firefox', FIREFOX);
document.documentElement.classList.toggle('opera', OPERA); document.documentElement.classList.toggle('opera', OPERA);
// TODO: remove once our manifest's minimum_chrome_version is 50+ // TODO: remove once our manifest's minimum_chrome_version is 50+
@ -47,7 +47,7 @@ if (!BG || BG != window) {
function notifyAllTabs(msg) { function notifyAllTabs(msg) {
const originalMessage = msg; const originalMessage = msg;
if (msg.method == 'styleUpdated' || msg.method == 'styleAdded') { if (msg.method === 'styleUpdated' || msg.method === 'styleAdded') {
// apply/popup/manage use only meta for these two methods, // apply/popup/manage use only meta for these two methods,
// editor may need the full code but can fetch it directly, // editor may need the full code but can fetch it directly,
// so we send just the meta to avoid spamming lots of tabs with huge styles // so we send just the meta to avoid spamming lots of tabs with huge styles
@ -86,11 +86,11 @@ function notifyAllTabs(msg) {
}); });
} }
// notify self: the message no longer is sent to the origin in new Chrome // notify self: the message no longer is sent to the origin in new Chrome
if (typeof onRuntimeMessage != 'undefined') { if (typeof onRuntimeMessage !== 'undefined') {
onRuntimeMessage(originalMessage); onRuntimeMessage(originalMessage);
} }
// notify apply.js on own pages // notify apply.js on own pages
if (typeof applyOnMessage != 'undefined') { if (typeof applyOnMessage !== 'undefined') {
applyOnMessage(originalMessage); applyOnMessage(originalMessage);
} }
// notify background page and all open popups // notify background page and all open popups
@ -134,7 +134,7 @@ function getActiveTabRealURL() {
function getTabRealURL(tab) { function getTabRealURL(tab) {
return new Promise(resolve => { return new Promise(resolve => {
if (tab.url != 'chrome://newtab/') { if (tab.url !== 'chrome://newtab/') {
resolve(tab.url); resolve(tab.url);
} else { } else {
chrome.webNavigation.getFrame({tabId: tab.id, frameId: 0, processId: -1}, frame => { chrome.webNavigation.getFrame({tabId: tab.id, frameId: 0, processId: -1}, frame => {
@ -159,13 +159,13 @@ function openURL({url, currentWindow = true}) {
const urlQuery = url.startsWith('moz-extension') ? undefined : url.replace(/#.*/, ''); const urlQuery = url.startsWith('moz-extension') ? undefined : url.replace(/#.*/, '');
queryTabs({url: urlQuery, currentWindow}).then(tabs => { queryTabs({url: urlQuery, currentWindow}).then(tabs => {
for (const tab of tabs) { for (const tab of tabs) {
if (tab.url == url) { if (tab.url === url) {
activateTab(tab).then(resolve); activateTab(tab).then(resolve);
return; return;
} }
} }
getActiveTab().then(tab => { getActiveTab().then(tab => {
if (tab && tab.url == 'chrome://newtab/' if (tab && tab.url === 'chrome://newtab/'
// prevent redirecting incognito NTP to a chrome URL as it crashes Chrome // prevent redirecting incognito NTP to a chrome URL as it crashes Chrome
&& (!url.startsWith('chrome') || !tab.incognito)) { && (!url.startsWith('chrome') || !tab.incognito)) {
chrome.tabs.update({url}, resolve); chrome.tabs.update({url}, resolve);
@ -250,14 +250,14 @@ const debounce = Object.assign((fn, delay, ...args) => {
function deepCopy(obj) { function deepCopy(obj) {
return obj !== null && obj !== undefined && typeof obj == 'object' return obj !== null && obj !== undefined && typeof obj === 'object'
? deepMerge(typeof obj.slice == 'function' ? [] : {}, obj) ? deepMerge(typeof obj.slice === 'function' ? [] : {}, obj)
: obj; : obj;
} }
function deepMerge(target, ...args) { function deepMerge(target, ...args) {
const isArray = typeof target.slice == 'function'; const isArray = typeof target.slice === 'function';
for (const obj of args) { for (const obj of args) {
if (isArray && obj !== null && obj !== undefined) { if (isArray && obj !== null && obj !== undefined) {
for (const element of obj) { for (const element of obj) {
@ -267,7 +267,7 @@ function deepMerge(target, ...args) {
} }
for (const k in obj) { for (const k in obj) {
const value = obj[k]; const value = obj[k];
if (k in target && typeof value == 'object' && value !== null) { if (k in target && typeof value === 'object' && value !== null) {
deepMerge(target[k], value); deepMerge(target[k], value);
} else { } else {
target[k] = deepCopy(value); target[k] = deepCopy(value);
@ -346,7 +346,7 @@ function download(url) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.timeout = 10e3; xhr.timeout = 10e3;
xhr.onloadend = () => (xhr.status == 200 xhr.onloadend = () => (xhr.status === 200
? resolve(xhr.responseText) ? resolve(xhr.responseText)
: reject(xhr.status)); : reject(xhr.status));
const [mainUrl, query] = url.split('?'); const [mainUrl, query] = url.split('?');

View File

@ -115,10 +115,10 @@ var prefs = new function Prefs() {
defineReadonlyProperty(this.readOnlyValues, key, value); defineReadonlyProperty(this.readOnlyValues, key, value);
const hasChanged = !equal(value, oldValue); const hasChanged = !equal(value, oldValue);
if (!fromBroadcast) { if (!fromBroadcast) {
if (BG && BG != window) { if (BG && BG !== window) {
BG.prefs.set(key, BG.deepCopy(value), {broadcast, sync}); BG.prefs.set(key, BG.deepCopy(value), {broadcast, sync});
} else { } else {
localStorage[key] = typeof defaults[key] == 'object' localStorage[key] = typeof defaults[key] === 'object'
? JSON.stringify(value) ? JSON.stringify(value)
: value; : value;
if (broadcast && hasChanged) { if (broadcast && hasChanged) {
@ -166,7 +166,7 @@ var prefs = new function Prefs() {
for (const key in defaults) { for (const key in defaults) {
const defaultValue = defaults[key]; const defaultValue = defaults[key];
let value = localStorage[key]; let value = localStorage[key];
if (typeof value == 'string') { if (typeof value === 'string') {
switch (typeof defaultValue) { switch (typeof defaultValue) {
case 'boolean': case 'boolean':
value = value.toLowerCase() === 'true'; value = value.toLowerCase() === 'true';
@ -181,7 +181,7 @@ var prefs = new function Prefs() {
} else { } else {
value = defaultValue; value = defaultValue;
} }
if (BG == window) { if (BG === window) {
// when in bg page, .set() will write to localStorage // when in bg page, .set() will write to localStorage
this.set(key, value, {broadcast: false, sync: false}); this.set(key, value, {broadcast: false, sync: false});
} else { } else {
@ -190,13 +190,13 @@ var prefs = new function Prefs() {
} }
} }
if (!BG || BG == window) { if (!BG || BG === window) {
affectsIcon.forEach(key => this.broadcast(key, values[key], {sync: false})); affectsIcon.forEach(key => this.broadcast(key, values[key], {sync: false}));
getSync().get('settings', ({settings: synced} = {}) => { getSync().get('settings', ({settings: synced} = {}) => {
if (synced) { if (synced) {
for (const key in defaults) { for (const key in defaults) {
if (key == 'popupWidth' && synced[key] != values.popupWidth) { if (key === 'popupWidth' && synced[key] !== values.popupWidth) {
// this is a fix for the period when popupWidth wasn't synced // this is a fix for the period when popupWidth wasn't synced
// TODO: remove it in a couple of months // TODO: remove it in a couple of months
continue; continue;
@ -209,7 +209,7 @@ var prefs = new function Prefs() {
}); });
chrome.storage.onChanged.addListener((changes, area) => { chrome.storage.onChanged.addListener((changes, area) => {
if (area == 'sync' && 'settings' in changes) { if (area === 'sync' && 'settings' in changes) {
const synced = changes.settings.newValue; const synced = changes.settings.newValue;
if (synced) { if (synced) {
for (const key in defaults) { for (const key in defaults) {
@ -283,21 +283,21 @@ var prefs = new function Prefs() {
function defineReadonlyProperty(obj, key, value) { function defineReadonlyProperty(obj, key, value) {
const copy = deepCopy(value); const copy = deepCopy(value);
if (typeof copy == 'object') { if (typeof copy === 'object') {
Object.freeze(copy); Object.freeze(copy);
} }
Object.defineProperty(obj, key, {value: copy, configurable: true}); Object.defineProperty(obj, key, {value: copy, configurable: true});
} }
function equal(a, b) { function equal(a, b) {
if (!a || !b || typeof a != 'object' || typeof b != 'object') { if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {
return a === b; return a === b;
} }
if (Object.keys(a).length != Object.keys(b).length) { if (Object.keys(a).length !== Object.keys(b).length) {
return false; return false;
} }
for (const k in a) { for (const k in a) {
if (typeof a[k] == 'object') { if (typeof a[k] === 'object') {
if (!equal(a[k], b[k])) { if (!equal(a[k], b[k])) {
return false; return false;
} }
@ -315,7 +315,7 @@ var prefs = new function Prefs() {
// Chrome and co. // Chrome and co.
/Safari\/[\d.]+$/.test(navigator.userAgent) && /Safari\/[\d.]+$/.test(navigator.userAgent) &&
// skip forks with Flash as those are likely to have the menu e.g. CentBrowser // skip forks with Flash as those are likely to have the menu e.g. CentBrowser
!Array.from(navigator.plugins).some(p => p.name == 'Shockwave Flash') !Array.from(navigator.plugins).some(p => p.name === 'Shockwave Flash')
); );
} }
}(); }();
@ -330,7 +330,7 @@ function setupLivePrefs(
const checkedProps = {}; const checkedProps = {};
for (const id of IDs) { for (const id of IDs) {
const element = document.getElementById(id); const element = document.getElementById(id);
checkedProps[id] = element.type == 'checkbox' ? 'checked' : 'value'; checkedProps[id] = element.type === 'checkbox' ? 'checked' : 'value';
updateElement({id, element, force: true}); updateElement({id, element, force: true});
element.addEventListener('change', onChange); element.addEventListener('change', onChange);
} }
@ -338,7 +338,7 @@ function setupLivePrefs(
function onChange() { function onChange() {
const value = this[checkedProps[this.id]]; const value = this[checkedProps[this.id]];
if (prefs.get(this.id) != value) { if (prefs.get(this.id) !== value) {
prefs.set(this.id, value); prefs.set(this.id, value);
} }
} }
@ -349,7 +349,7 @@ function setupLivePrefs(
force, force,
}) { }) {
const prop = checkedProps[id]; const prop = checkedProps[id];
if (force || element[prop] != value) { if (force || element[prop] !== value) {
element[prop] = value; element[prop] = value;
element.dispatchEvent(new Event('change', {bubbles: true, cancelable: true})); element.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
} }

View File

@ -53,7 +53,7 @@ function importFromString(jsonString) {
} }
// create objects in background context // create objects in background context
const json = BG.tryJSONparse(jsonString) || []; const json = BG.tryJSONparse(jsonString) || [];
if (typeof json.slice != 'function') { if (typeof json.slice !== 'function') {
json.length = 0; json.length = 0;
} }
const oldStyles = json.length && BG.deepCopy(BG.cachedStyles.list || []); const oldStyles = json.length && BG.deepCopy(BG.cachedStyles.list || []);
@ -94,8 +94,8 @@ function importFromString(jsonString) {
} }
function analyze(item) { function analyze(item) {
if (!item || !item.name || !item.name.trim() || typeof item != 'object' if (!item || !item.name || !item.name.trim() || typeof item !== 'object'
|| (item.sections && typeof item.sections.slice != 'function')) { || (item.sections && typeof item.sections.slice !== 'function')) {
stats.invalid.names.push(`#${index}: ${limitString(item && item.name || '')}`); stats.invalid.names.push(`#${index}: ${limitString(item && item.name || '')}`);
return; return;
} }
@ -117,8 +117,8 @@ function importFromString(jsonString) {
} }
const oldStyleKeys = oldStyle && Object.keys(oldStyle); const oldStyleKeys = oldStyle && Object.keys(oldStyle);
const metaEqual = oldStyleKeys && const metaEqual = oldStyleKeys &&
oldStyleKeys.length == Object.keys(item).length && oldStyleKeys.length === Object.keys(item).length &&
oldStyleKeys.every(k => k == 'sections' || oldStyle[k] === item[k]); oldStyleKeys.every(k => k === 'sections' || oldStyle[k] === item[k]);
const codeEqual = oldStyle && BG.styleSectionsEqual(oldStyle, item); const codeEqual = oldStyle && BG.styleSectionsEqual(oldStyle, item);
if (metaEqual && codeEqual) { if (metaEqual && codeEqual) {
stats.unchanged.names.push(oldStyle.name); stats.unchanged.names.push(oldStyle.name);
@ -131,7 +131,7 @@ function importFromString(jsonString) {
function sameStyle(oldStyle, newStyle) { function sameStyle(oldStyle, newStyle) {
return oldStyle.name.trim() === newStyle.name.trim() || return oldStyle.name.trim() === newStyle.name.trim() ||
['updateUrl', 'originalMd5', 'originalDigest'] ['updateUrl', 'originalMd5', 'originalDigest']
.some(field => oldStyle[field] && oldStyle[field] == newStyle[field]); .some(field => oldStyle[field] && oldStyle[field] === newStyle[field]);
} }
function account({style, info, resolve}) { function account({style, info, resolve}) {
@ -196,7 +196,7 @@ function importFromString(jsonString) {
buttons: [t('confirmOK'), numChanged && t('undo')], buttons: [t('confirmOK'), numChanged && t('undo')],
onshow: bindClick, onshow: bindClick,
}).then(({button, enter, esc}) => { }).then(({button, enter, esc}) => {
if (button == 1) { if (button === 1) {
undo(); undo();
} }
}); });
@ -224,7 +224,7 @@ function importFromString(jsonString) {
buttons: [t('confirmOK')], buttons: [t('confirmOK')],
})); }));
function undoNextId() { function undoNextId() {
if (index == newIds.length) { if (index === newIds.length) {
resolve(); resolve();
return; return;
} }
@ -250,7 +250,7 @@ function importFromString(jsonString) {
} }
}; };
for (const block of $$('details')) { for (const block of $$('details')) {
if (block.dataset.id != 'invalid') { if (block.dataset.id !== 'invalid') {
block.style.cursor = 'pointer'; block.style.cursor = 'pointer';
block.onclick = highlightElement; block.onclick = highlightElement;
} }
@ -262,7 +262,7 @@ function importFromString(jsonString) {
} }
function reportNameChange(oldStyle, newStyle) { function reportNameChange(oldStyle, newStyle) {
return newStyle.name != oldStyle.name return newStyle.name !== oldStyle.name
? oldStyle.name + ' —> ' + newStyle.name ? oldStyle.name + ' —> ' + newStyle.name
: oldStyle.name; : oldStyle.name;
} }
@ -278,21 +278,21 @@ function importFromString(jsonString) {
for (const tab of tabs) { for (const tab of tabs) {
// skip lazy-loaded aka unloaded tabs that seem to start loading on message in FF // skip lazy-loaded aka unloaded tabs that seem to start loading on message in FF
if (FIREFOX && !tab.width) { if (FIREFOX && !tab.width) {
if (tab == lastTab) { if (tab === lastTab) {
resolve(); resolve();
} }
continue; continue;
} }
getStylesSafe({matchUrl: tab.url, enabled: true, asHash: true}).then(styles => { getStylesSafe({matchUrl: tab.url, enabled: true, asHash: true}).then(styles => {
const message = {method: 'styleReplaceAll', styles}; const message = {method: 'styleReplaceAll', styles};
if (tab.id == ownTab.id) { if (tab.id === ownTab.id) {
applyOnMessage(message); applyOnMessage(message);
} else { } else {
invokeOrPostpone(tab.id == activeTab.id, invokeOrPostpone(tab.id === activeTab.id,
chrome.tabs.sendMessage, tab.id, message, ignoreChromeError); chrome.tabs.sendMessage, tab.id, message, ignoreChromeError);
} }
setTimeout(BG.updateIcon, 0, tab, styles); setTimeout(BG.updateIcon, 0, tab, styles);
if (tab == lastTab) { if (tab === lastTab) {
resolve(); resolve();
} }
}); });
@ -359,7 +359,7 @@ $('#unfile-all-styles').onclick = () => {
Object.assign(document.body, { Object.assign(document.body, {
ondragover(event) { ondragover(event) {
const hasFiles = event.dataTransfer.types.includes('Files'); const hasFiles = event.dataTransfer.types.includes('Files');
event.dataTransfer.dropEffect = hasFiles || event.target.type == 'search' ? 'copy' : 'none'; event.dataTransfer.dropEffect = hasFiles || event.target.type === 'search' ? 'copy' : 'none';
this.classList.toggle('dropzone', hasFiles); this.classList.toggle('dropzone', hasFiles);
if (hasFiles) { if (hasFiles) {
event.preventDefault(); event.preventDefault();

View File

@ -73,7 +73,7 @@ function initGlobalEvents() {
// focus search field on / key // focus search field on / key
document.onkeypress = event => { document.onkeypress = event => {
if ((event.keyCode || event.which) == 47 if ((event.keyCode || event.which) === 47
&& !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey
&& !event.target.matches('[type="text"], [type="search"]')) { && !event.target.matches('[type="text"], [type="search"]')) {
event.preventDefault(); event.preventDefault();
@ -114,7 +114,7 @@ function initGlobalEvents() {
function showStyles(styles = []) { function showStyles(styles = []) {
const sorted = styles const sorted = styles
.map(style => ({name: style.name.toLocaleLowerCase(), style})) .map(style => ({name: style.name.toLocaleLowerCase(), style}))
.sort((a, b) => (a.name < b.name ? -1 : a.name == b.name ? 0 : 1)); .sort((a, b) => (a.name < b.name ? -1 : a.name === b.name ? 0 : 1));
let index = 0; let index = 0;
const scrollY = (history.state || {}).scrollY; const scrollY = (history.state || {}).scrollY;
const shouldRenderAll = scrollY > window.innerHeight || sessionStorage.justEditedStyleId; const shouldRenderAll = scrollY > window.innerHeight || sessionStorage.justEditedStyleId;
@ -228,18 +228,18 @@ function createStyleTargetsElement({entry, style, postponeFavicons}) {
displayed.add(targetValue); displayed.add(targetValue);
const element = template.appliesToTarget.cloneNode(true); const element = template.appliesToTarget.cloneNode(true);
if (!newUI.enabled) { if (!newUI.enabled) {
if (numTargets == 10) { if (numTargets === 10) {
container = container.appendChild(template.extraAppliesTo.cloneNode(true)); container = container.appendChild(template.extraAppliesTo.cloneNode(true));
} else if (numTargets > 1) { } else if (numTargets > 1) {
container.appendChild(template.appliesToSeparator.cloneNode(true)); container.appendChild(template.appliesToSeparator.cloneNode(true));
} }
} else if (newUI.favicons) { } else if (newUI.favicons) {
let favicon = ''; let favicon = '';
if (type == 'domains') { if (type === 'domains') {
favicon = GET_FAVICON_URL + targetValue; favicon = GET_FAVICON_URL + targetValue;
} else if (targetValue.startsWith('chrome-extension:')) { } else if (targetValue.startsWith('chrome-extension:')) {
favicon = OWN_ICON; favicon = OWN_ICON;
} else if (type != 'regexps') { } else if (type !== 'regexps') {
favicon = targetValue.includes('://') && targetValue.match(/^.*?:\/\/([^/]+)/); favicon = targetValue.includes('://') && targetValue.match(/^.*?:\/\/([^/]+)/);
favicon = favicon ? GET_FAVICON_URL + favicon[1] : ''; favicon = favicon ? GET_FAVICON_URL + favicon[1] : '';
} }
@ -292,7 +292,7 @@ Object.assign(handleEvent, {
const target = event.target; const target = event.target;
const entry = target.closest('.entry'); const entry = target.closest('.entry');
for (const selector in handleEvent.ENTRY_ROUTES) { for (const selector in handleEvent.ENTRY_ROUTES) {
for (let el = target; el && el != entry; el = el.parentElement) { for (let el = target; el && el !== entry; el = el.parentElement) {
if (el.matches(selector)) { if (el.matches(selector)) {
const handler = handleEvent.ENTRY_ROUTES[selector]; const handler = handleEvent.ENTRY_ROUTES[selector];
return handleEvent[handler].call(el, event, entry); return handleEvent[handler].call(el, event, entry);
@ -307,8 +307,8 @@ Object.assign(handleEvent, {
} }
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
const left = event.button == 0; const left = event.button === 0;
const middle = event.button == 1; const middle = event.button === 1;
const shift = event.shiftKey; const shift = event.shiftKey;
const ctrl = event.ctrlKey; const ctrl = event.ctrlKey;
const openWindow = left && shift && !ctrl; const openWindow = left && shift && !ctrl;
@ -361,7 +361,7 @@ Object.assign(handleEvent, {
buttons: [t('confirmDelete'), t('confirmCancel')], buttons: [t('confirmDelete'), t('confirmCancel')],
}) })
.then(({button, enter, esc}) => { .then(({button, enter, esc}) => {
if (button == 0 || enter) { if (button === 0 || enter) {
deleteStyleSafe({id}); deleteStyleSafe({id});
} }
}); });
@ -386,10 +386,10 @@ Object.assign(handleEvent, {
}, },
filterOnChange({target: el, forceRefilter}) { filterOnChange({target: el, forceRefilter}) {
const getValue = el => (el.type == 'checkbox' ? el.checked : el.value.trim()); const getValue = el => (el.type === 'checkbox' ? el.checked : el.value.trim());
if (!forceRefilter) { if (!forceRefilter) {
const value = getValue(el); const value = getValue(el);
if (value == el.lastValue) { if (value === el.lastValue) {
return; return;
} }
el.lastValue = value; el.lastValue = value;
@ -415,22 +415,22 @@ Object.assign(handleEvent, {
function handleUpdate(style, {reason, method} = {}) { function handleUpdate(style, {reason, method} = {}) {
let entry; let entry;
let oldEntry = $(ENTRY_ID_PREFIX + style.id); let oldEntry = $(ENTRY_ID_PREFIX + style.id);
if (oldEntry && method == 'styleUpdated') { if (oldEntry && method === 'styleUpdated') {
handleToggledOrCodeOnly(); handleToggledOrCodeOnly();
} }
entry = entry || createStyleElement({style}); entry = entry || createStyleElement({style});
if (oldEntry) { if (oldEntry) {
if (oldEntry.styleNameLowerCase == entry.styleNameLowerCase) { if (oldEntry.styleNameLowerCase === entry.styleNameLowerCase) {
installed.replaceChild(entry, oldEntry); installed.replaceChild(entry, oldEntry);
} else { } else {
oldEntry.remove(); oldEntry.remove();
} }
} }
if (reason == 'update' && entry.matches('.updatable')) { if (reason === 'update' && entry.matches('.updatable')) {
handleUpdateInstalled(); handleUpdateInstalled();
} }
filterAndAppend({entry}); filterAndAppend({entry});
if (!entry.matches('.hidden') && reason != 'import') { if (!entry.matches('.hidden') && reason !== 'import') {
animateElement(entry); animateElement(entry);
scrollElementIntoView(entry); scrollElementIntoView(entry);
} }
@ -438,12 +438,12 @@ function handleUpdate(style, {reason, method} = {}) {
function handleToggledOrCodeOnly() { function handleToggledOrCodeOnly() {
const newStyleMeta = getStyleWithNoCode(style); const newStyleMeta = getStyleWithNoCode(style);
const diff = objectDiff(oldEntry.styleMeta, newStyleMeta); const diff = objectDiff(oldEntry.styleMeta, newStyleMeta);
if (diff.length == 0) { if (diff.length === 0) {
// only code was modified // only code was modified
entry = oldEntry; entry = oldEntry;
oldEntry = null; oldEntry = null;
} }
if (diff.length == 1 && diff[0].key == 'enabled') { if (diff.length === 1 && diff[0].key === 'enabled') {
oldEntry.classList.toggle('enabled', style.enabled); oldEntry.classList.toggle('enabled', style.enabled);
oldEntry.classList.toggle('disabled', !style.enabled); oldEntry.classList.toggle('disabled', !style.enabled);
$$('.checker', oldEntry).forEach(el => (el.checked = style.enabled)); $$('.checker', oldEntry).forEach(el => (el.checked = style.enabled));
@ -481,8 +481,8 @@ function switchUI({styleOnly} = {}) {
// ensure the global option is processed first // ensure the global option is processed first
for (const el of [$('#manage.newUI'), ...$$('[id^="manage.newUI."]')]) { for (const el of [$('#manage.newUI'), ...$$('[id^="manage.newUI."]')]) {
const id = el.id.replace(/^manage\.newUI\.?/, '') || 'enabled'; const id = el.id.replace(/^manage\.newUI\.?/, '') || 'enabled';
const value = el.type == 'checkbox' ? el.checked : Number(el.value); const value = el.type === 'checkbox' ? el.checked : Number(el.value);
const valueChanged = value !== newUI[id] && (id == 'enabled' || current.enabled); const valueChanged = value !== newUI[id] && (id === 'enabled' || current.enabled);
current[id] = value; current[id] = value;
changed[id] = valueChanged; changed[id] = valueChanged;
someChanged |= valueChanged; someChanged |= valueChanged;
@ -568,7 +568,7 @@ function checkUpdateAll() {
$('#apply-all-updates').classList.add('hidden'); $('#apply-all-updates').classList.add('hidden');
$('#update-all-no-updates').classList.add('hidden'); $('#update-all-no-updates').classList.add('hidden');
const ignoreDigest = this && this.id == 'check-all-updates-force'; const ignoreDigest = this && this.id === 'check-all-updates-force';
$$('.updatable:not(.can-update)' + (ignoreDigest ? '' : ':not(.update-problem)')) $$('.updatable:not(.can-update)' + (ignoreDigest ? '' : ':not(.update-problem)'))
.map(el => checkUpdate(el, {single: false})); .map(el => checkUpdate(el, {single: false}));
@ -585,7 +585,7 @@ function checkUpdateAll() {
total = value; total = value;
break; break;
case BG.updater.UPDATED: case BG.updater.UPDATED:
if (++updated == 1) { if (++updated === 1) {
$('#apply-all-updates').disabled = true; $('#apply-all-updates').disabled = true;
$('#apply-all-updates').classList.remove('hidden'); $('#apply-all-updates').classList.remove('hidden');
} }
@ -593,7 +593,7 @@ function checkUpdateAll() {
// fallthrough // fallthrough
case BG.updater.SKIPPED: case BG.updater.SKIPPED:
checked++; checked++;
if (details == BG.updater.EDITED || details == BG.updater.MAYBE_EDITED) { if (details === BG.updater.EDITED || details === BG.updater.MAYBE_EDITED) {
skippedEdited++; skippedEdited++;
} }
reportUpdateState(state, value, details); reportUpdateState(state, value, details);
@ -606,13 +606,13 @@ function checkUpdateAll() {
function done() { function done() {
document.body.classList.remove('update-in-progress'); document.body.classList.remove('update-in-progress');
$('#check-all-updates').disabled = total == 0; $('#check-all-updates').disabled = total === 0;
$('#apply-all-updates').disabled = false; $('#apply-all-updates').disabled = false;
renderUpdatesOnlyFilter({check: updated + skippedEdited > 0}); renderUpdatesOnlyFilter({check: updated + skippedEdited > 0});
if (!updated) { if (!updated) {
$('#update-all-no-updates').dataset.skippedEdited = skippedEdited > 0; $('#update-all-no-updates').dataset.skippedEdited = skippedEdited > 0;
$('#update-all-no-updates').classList.remove('hidden'); $('#update-all-no-updates').classList.remove('hidden');
$('#check-all-updates-force').classList.toggle('hidden', skippedEdited == 0); $('#check-all-updates-force').classList.toggle('hidden', skippedEdited === 0);
} }
} }
} }
@ -648,16 +648,16 @@ function reportUpdateState(state, style, details) {
if (entry.classList.contains('can-update')) { if (entry.classList.contains('can-update')) {
break; break;
} }
const same = details == BG.updater.SAME_MD5 || details == BG.updater.SAME_CODE; const same = details === BG.updater.SAME_MD5 || details === BG.updater.SAME_CODE;
const edited = details == BG.updater.EDITED || details == BG.updater.MAYBE_EDITED; const edited = details === BG.updater.EDITED || details === BG.updater.MAYBE_EDITED;
entry.dataset.details = details; entry.dataset.details = details;
if (!details) { if (!details) {
details = t('updateCheckFailServerUnreachable'); details = t('updateCheckFailServerUnreachable');
} else if (typeof details == 'number') { } else if (typeof details === 'number') {
details = t('updateCheckFailBadResponseCode', [details]); details = t('updateCheckFailBadResponseCode', [details]);
} else if (details == BG.updater.EDITED) { } else if (details === BG.updater.EDITED) {
details = t('updateCheckSkippedLocallyEdited') + '\n' + t('updateCheckManualUpdateHint'); details = t('updateCheckSkippedLocallyEdited') + '\n' + t('updateCheckManualUpdateHint');
} else if (details == BG.updater.MAYBE_EDITED) { } else if (details === BG.updater.MAYBE_EDITED) {
details = t('updateCheckSkippedMaybeLocallyEdited') + '\n' + t('updateCheckManualUpdateHint'); details = t('updateCheckSkippedMaybeLocallyEdited') + '\n' + t('updateCheckManualUpdateHint');
} }
const message = same ? t('updateCheckSucceededNoUpdate') : details; const message = same ? t('updateCheckSucceededNoUpdate') : details;
@ -719,7 +719,7 @@ function searchStyles({immediately, container}) {
const searchElement = $('#search'); const searchElement = $('#search');
const query = searchElement.value.toLocaleLowerCase(); const query = searchElement.value.toLocaleLowerCase();
const queryPrev = searchElement.lastValue || ''; const queryPrev = searchElement.lastValue || '';
if (query == queryPrev && !immediately && !container) { if (query === queryPrev && !immediately && !container) {
return; return;
} }
if (!immediately) { if (!immediately) {
@ -741,7 +741,7 @@ function searchStyles({immediately, container}) {
style.url && isMatchingText(style.url) || style.url && isMatchingText(style.url) ||
isMatchingStyle(style))); isMatchingStyle(style)));
} }
if (entry.classList.contains('not-matching') != !isMatching) { if (entry.classList.contains('not-matching') !== !isMatching) {
entry.classList.toggle('not-matching', !isMatching); entry.classList.toggle('not-matching', !isMatching);
needsRefilter = true; needsRefilter = true;
} }
@ -850,7 +850,7 @@ function reapplyFilter(container = installed) {
shuffle(false); shuffle(false);
setTimeout(shuffle, 0, true); setTimeout(shuffle, 0, true);
// single-element job from handleEvent(): add the last wraith // single-element job from handleEvent(): add the last wraith
if (toHide.length == 1 && toHide[0].parentElement != installed) { if (toHide.length === 1 && toHide[0].parentElement !== installed) {
installed.appendChild(toHide[0]); installed.appendChild(toHide[0]);
} }
return; return;
@ -885,7 +885,7 @@ function reapplyFilter(container = installed) {
const skipGroup = state => { const skipGroup = state => {
const start = i; const start = i;
const first = entry; const first = entry;
while (entry && entry.classList.contains('hidden') == state) { while (entry && entry.classList.contains('hidden') === state) {
entry = entry.nextElementSibling; entry = entry.nextElementSibling;
i++; i++;
} }
@ -978,19 +978,19 @@ function objectDiff(first, second, path = '') {
diff.push({path, key, values: [a], type: 'removed'}); diff.push({path, key, values: [a], type: 'removed'});
continue; continue;
} }
if (a && typeof a.filter == 'function' && b && typeof b.filter == 'function') { if (a && typeof a.filter === 'function' && b && typeof b.filter === 'function') {
if ( if (
a.length != b.length || a.length !== b.length ||
a.some((el, i) => { a.some((el, i) => {
const result = !el || typeof el != 'object' const result = !el || typeof el !== 'object'
? el != b[i] ? el !== b[i]
: objectDiff(el, b[i], path + key + '[' + i + '].').length; : objectDiff(el, b[i], path + key + '[' + i + '].').length;
return result; return result;
}) })
) { ) {
diff.push({path, key, values: [a, b], type: 'changed'}); diff.push({path, key, values: [a, b], type: 'changed'});
} }
} else if (typeof a == 'object' && typeof b == 'object') { } else if (typeof a === 'object' && typeof b === 'object') {
diff.push(...objectDiff(a, b, path + key + '.')); diff.push(...objectDiff(a, b, path + key + '.'));
} else { } else {
diff.push({path, key, values: [a, b], type: 'changed'}); diff.push({path, key, values: [a, b], type: 'changed'});

View File

@ -30,9 +30,9 @@ function messageBox({
key(event) { key(event) {
const keyCode = event.keyCode || event.which; const keyCode = event.keyCode || event.which;
if (!event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey if (!event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey
&& (keyCode == 13 || keyCode == 27)) { && (keyCode === 13 || keyCode === 27)) {
event.preventDefault(); event.preventDefault();
resolveWith(keyCode == 13 ? {enter: true} : {esc: true}); resolveWith(keyCode === 13 ? {enter: true} : {esc: true});
} }
}, },
scroll() { scroll() {
@ -52,7 +52,7 @@ function messageBox({
unbindAndRemoveSelf(); unbindAndRemoveSelf();
} }
const id = 'message-box'; const id = 'message-box';
const putAs = typeof contents == 'string' ? 'innerHTML' : 'appendChild'; const putAs = typeof contents === 'string' ? 'innerHTML' : 'appendChild';
messageBox.element = $element({id, className, appendChild: [ messageBox.element = $element({id, className, appendChild: [
$element({appendChild: [ $element({appendChild: [
$element({id: `${id}-title`, innerHTML: title}), $element({id: `${id}-title`, innerHTML: title}),

View File

@ -67,7 +67,7 @@ function setupRadioButtons() {
const sets = {}; const sets = {};
const onChange = function () { const onChange = function () {
const newValue = sets[this.name].indexOf(this); const newValue = sets[this.name].indexOf(this);
if (newValue >= 0 && prefs.get(this.name) != newValue) { if (newValue >= 0 && prefs.get(this.name) !== newValue) {
prefs.set(this.name, newValue); prefs.set(this.name, newValue);
} }
}; };

View File

@ -278,7 +278,7 @@ Object.assign(handleEvent, {
toggle(event) { toggle(event) {
saveStyleSafe({ saveStyleSafe({
id: handleEvent.getClickedStyleId(event), id: handleEvent.getClickedStyleId(event),
enabled: this.type == 'checkbox' ? this.checked : this.matches('.enable'), enabled: this.type === 'checkbox' ? this.checked : this.matches('.enable'),
}); });
}, },
@ -293,9 +293,9 @@ Object.assign(handleEvent, {
window.onkeydown = event => { window.onkeydown = event => {
const keyCode = event.keyCode || event.which; const keyCode = event.keyCode || event.which;
if (!event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey if (!event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey
&& (keyCode == 13 || keyCode == 27)) { && (keyCode === 13 || keyCode === 27)) {
event.preventDefault(); event.preventDefault();
confirm(keyCode == 13); confirm(keyCode === 13);
} }
}; };
function confirm(ok) { function confirm(ok) {
@ -342,9 +342,9 @@ Object.assign(handleEvent, {
maybeEdit(event) { maybeEdit(event) {
if (!( if (!(
event.button == 0 && (event.ctrlKey || event.metaKey) || event.button === 0 && (event.ctrlKey || event.metaKey) ||
event.button == 1 || event.button === 1 ||
event.button == 2)) { event.button === 2)) {
return; return;
} }
// open an editor on middleclick // open an editor on middleclick
@ -401,10 +401,10 @@ function detectSloppyRegexps({entry, style}) {
for (const section of style.sections) { for (const section of style.sections) {
for (const regexp of section.regexps) { for (const regexp of section.regexps) {
for (let pass = 1; pass <= 2; pass++) { for (let pass = 1; pass <= 2; pass++) {
const cacheKey = pass == 1 ? regexp : BG.SLOPPY_REGEXP_PREFIX + regexp; const cacheKey = pass === 1 ? regexp : BG.SLOPPY_REGEXP_PREFIX + regexp;
if (!rxCache.has(cacheKey)) { if (!rxCache.has(cacheKey)) {
// according to CSS4 @document specification the entire URL must match // according to CSS4 @document specification the entire URL must match
const anchored = pass == 1 ? '^(?:' + regexp + ')$' : '^' + regexp + '$'; const anchored = pass === 1 ? '^(?:' + regexp + ')$' : '^' + regexp + '$';
const rx = tryRegExp(anchored); const rx = tryRegExp(anchored);
rxCache.set(cacheKey, rx || false); rxCache.set(cacheKey, rx || false);
} }