From fa963722a79c26c1642bbf81a2e153bd0c1a3fe8 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Fri, 8 Nov 2019 19:24:33 -0500 Subject: Fix seekForward and seekBackward not handling length=0 case correctly --- ext/fg/js/source.js | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'ext/fg') diff --git a/ext/fg/js/source.js b/ext/fg/js/source.js index c3da9f46..5be521fa 100644 --- a/ext/fg/js/source.js +++ b/ext/fg/js/source.js @@ -108,6 +108,10 @@ class TextSourceRange { static seekForward(node, offset, length) { const state = {node, offset, remainder: length, content: ''}; + if (length <= 0) { + return state; + } + const TEXT_NODE = Node.TEXT_NODE; const ELEMENT_NODE = Node.ELEMENT_NODE; let resetOffset = false; @@ -166,6 +170,10 @@ class TextSourceRange { static seekBackward(node, offset, length) { const state = {node, offset, remainder: length, content: ''}; + if (length <= 0) { + return state; + } + const TEXT_NODE = Node.TEXT_NODE; const ELEMENT_NODE = Node.ELEMENT_NODE; let resetOffset = false; -- cgit v1.2.3 From 25af532ab7750a456f46b37825d8dbe876363d19 Mon Sep 17 00:00:00 2001 From: siikamiika Date: Sat, 9 Nov 2019 12:27:09 +0200 Subject: enable expression scan toggling on search page --- ext/bg/js/search-frontend.js | 4 +++- ext/bg/js/templates.js | 4 ++-- ext/bg/settings.html | 2 +- ext/fg/js/popup-nested.js | 2 +- tmpl/terms.html | 4 ++-- 5 files changed, 9 insertions(+), 7 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/search-frontend.js b/ext/bg/js/search-frontend.js index b21dac17..63ed0724 100644 --- a/ext/bg/js/search-frontend.js +++ b/ext/bg/js/search-frontend.js @@ -25,7 +25,9 @@ async function searchFrontendSetup() { const options = await apiOptionsGet(optionsContext); if (!options.scanning.enableOnSearchPage) { return; } - window.frontendInitializationData = {depth: 1, proxy: false}; + const ignoreNodes = options.scanning.enableOnPopupExpressions ? [] : ['.expression-scan-toggle', '.expression-scan-toggle *']; + + window.frontendInitializationData = {depth: 1, ignoreNodes, proxy: false}; const scriptSrcs = [ '/fg/js/frontend-api-receiver.js', diff --git a/ext/bg/js/templates.js b/ext/bg/js/templates.js index 26d1575f..96aa39cd 100644 --- a/ext/bg/js/templates.js +++ b/ext/bg/js/templates.js @@ -299,7 +299,7 @@ templates['terms.html'] = template({"1":function(container,depth0,helpers,partia return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.expressions : depth0),{"name":"each","hash":{},"fn":container.program(33, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : ""); },"33":function(container,depth0,helpers,partials,data,blockParams,depths) { var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", buffer = - "
"; stack1 = ((helper = (helper = helpers.kanjiLinks || (depth0 != null ? depth0.kanjiLinks : depth0)) != null ? helper : alias2),(options={"name":"kanjiLinks","hash":{},"fn":container.program(34, data, 0, blockParams, depths),"inverse":container.noop,"data":data}),(typeof helper === alias3 ? helper.call(alias1,options) : helper)); @@ -359,7 +359,7 @@ templates['terms.html'] = template({"1":function(container,depth0,helpers,partia return "invisible"; },"47":function(container,depth0,helpers,partials,data) { var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), buffer = - "
"; + "
"; stack1 = ((helper = (helper = helpers.kanjiLinks || (depth0 != null ? depth0.kanjiLinks : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"kanjiLinks","hash":{},"fn":container.program(34, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(alias1,options) : helper)); if (!helpers.kanjiLinks) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} if (stack1 != null) { buffer += stack1; } diff --git a/ext/bg/settings.html b/ext/bg/settings.html index 19449261..86feacf7 100644 --- a/ext/bg/settings.html +++ b/ext/bg/settings.html @@ -401,7 +401,7 @@
- +
diff --git a/ext/fg/js/popup-nested.js b/ext/fg/js/popup-nested.js index cec95aea..1b5ab8f7 100644 --- a/ext/fg/js/popup-nested.js +++ b/ext/fg/js/popup-nested.js @@ -33,7 +33,7 @@ async function popupNestedInitialize(id, depth, parentFrameId, url) { return; } - const ignoreNodes = options.scanning.enableOnPopupExpressions ? [] : [ '.expression', '.expression *' ]; + const ignoreNodes = options.scanning.enableOnPopupExpressions ? [] : ['.expression-scan-toggle', '.expression-scan-toggle *']; window.frontendInitializationData = {id, depth, parentFrameId, ignoreNodes, url, proxy: true}; diff --git a/tmpl/terms.html b/tmpl/terms.html index 3dee43d7..993b5aa0 100644 --- a/tmpl/terms.html +++ b/tmpl/terms.html @@ -49,7 +49,7 @@ {{#if merged}} {{~#each expressions~}} -
{{#kanjiLinks}}{{#furigana}}{{{.}}}{{/furigana}}{{/kanjiLinks}}
+
{{#kanjiLinks}}{{#furigana}}{{{.}}}{{/furigana}}{{/kanjiLinks}}
{{~#if ../playback~}} {{~/if~}} @@ -70,7 +70,7 @@
{{~/each~}} {{else}} -
{{#kanjiLinks}}{{#furigana}}{{{.}}}{{/furigana}}{{/kanjiLinks}}
+
{{#kanjiLinks}}{{#furigana}}{{{.}}}{{/furigana}}{{/kanjiLinks}}
{{#if termTags}}
{{#each termTags}} -- cgit v1.2.3 From 40c8268fd6b32c9918fbebd374723cd17f2e19aa Mon Sep 17 00:00:00 2001 From: siikamiika Date: Sat, 9 Nov 2019 13:01:21 +0200 Subject: always disable scanning IME checkbox label --- ext/bg/js/search-frontend.js | 5 ++++- ext/bg/search.html | 2 +- ext/fg/js/popup-nested.js | 5 ++++- 3 files changed, 9 insertions(+), 3 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/search-frontend.js b/ext/bg/js/search-frontend.js index 63ed0724..6ba8467e 100644 --- a/ext/bg/js/search-frontend.js +++ b/ext/bg/js/search-frontend.js @@ -25,7 +25,10 @@ async function searchFrontendSetup() { const options = await apiOptionsGet(optionsContext); if (!options.scanning.enableOnSearchPage) { return; } - const ignoreNodes = options.scanning.enableOnPopupExpressions ? [] : ['.expression-scan-toggle', '.expression-scan-toggle *']; + const ignoreNodes = ['.scan-disable', '.scan-disable *']; + if (!options.scanning.enableOnPopupExpressions) { + ignoreNodes.push('.expression-scan-toggle', '.expression-scan-toggle *'); + } window.frontendInitializationData = {depth: 1, ignoreNodes, proxy: false}; diff --git a/ext/bg/search.html b/ext/bg/search.html index 91140b95..c7f97712 100644 --- a/ext/bg/search.html +++ b/ext/bg/search.html @@ -27,7 +27,7 @@
-
- - -- cgit v1.2.3 From 820beb7c9338bd81501d1779b10181c7cced9992 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 25 Nov 2019 21:04:34 -0500 Subject: Fix incorrect opacity check --- ext/fg/js/document.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ext/fg') diff --git a/ext/fg/js/document.js b/ext/fg/js/document.js index a168705e..8161c85a 100644 --- a/ext/fg/js/document.js +++ b/ext/fg/js/document.js @@ -359,7 +359,7 @@ function isElementTransparent(element) { } const style = window.getComputedStyle(element); return ( - parseFloat(style.opacity) < 0 || + parseFloat(style.opacity) <= 0 || style.visibility === 'hidden' || (style.backgroundImage === 'none' && isColorTransparent(style.backgroundColor)) ); -- cgit v1.2.3 From 7f9a73135da4244e779f32179c7d19e6984bbc55 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 26 Nov 2019 15:07:11 -0500 Subject: Remove utilAsync --- ext/bg/js/settings-profiles.js | 14 +++++++------- ext/bg/js/settings.js | 8 ++++---- ext/bg/js/util.js | 6 ------ ext/fg/js/util.js | 6 ------ 4 files changed, 11 insertions(+), 23 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/settings-profiles.js b/ext/bg/js/settings-profiles.js index 3ae9db14..357a1b9b 100644 --- a/ext/bg/js/settings-profiles.js +++ b/ext/bg/js/settings-profiles.js @@ -35,16 +35,16 @@ async function profileOptionsSetup() { } function profileOptionsSetupEventListeners() { - $('#profile-target').change(utilAsync(onTargetProfileChanged)); + $('#profile-target').change((e) => onTargetProfileChanged(e)); $('#profile-name').change(onProfileNameChanged); - $('#profile-add').click(utilAsync(onProfileAdd)); - $('#profile-remove').click(utilAsync(onProfileRemove)); - $('#profile-remove-confirm').click(utilAsync(onProfileRemoveConfirm)); - $('#profile-copy').click(utilAsync(onProfileCopy)); - $('#profile-copy-confirm').click(utilAsync(onProfileCopyConfirm)); + $('#profile-add').click((e) => onProfileAdd(e)); + $('#profile-remove').click((e) => onProfileRemove(e)); + $('#profile-remove-confirm').click((e) => onProfileRemoveConfirm(e)); + $('#profile-copy').click((e) => onProfileCopy(e)); + $('#profile-copy-confirm').click((e) => onProfileCopyConfirm(e)); $('#profile-move-up').click(() => onProfileMove(-1)); $('#profile-move-down').click(() => onProfileMove(1)); - $('.profile-form').find('input, select, textarea').not('.profile-form-manual').change(utilAsync(onProfileOptionsChanged)); + $('.profile-form').find('input, select, textarea').not('.profile-form-manual').change((e) => onProfileOptionsChanged(e)); } function tryGetIntegerValue(selector, min, max) { diff --git a/ext/bg/js/settings.js b/ext/bg/js/settings.js index ab267c32..d1f9d0d1 100644 --- a/ext/bg/js/settings.js +++ b/ext/bg/js/settings.js @@ -155,8 +155,8 @@ async function formWrite(options) { } function formSetupEventListeners() { - $('input, select, textarea').not('.anki-model').not('.ignore-form-changes *').change(utilAsync(onFormOptionsChanged)); - $('.anki-model').change(utilAsync(onAnkiModelChanged)); + $('input, select, textarea').not('.anki-model').not('.ignore-form-changes *').change((e) => onFormOptionsChanged(e)); + $('.anki-model').change((e) => onAnkiModelChanged(e)); } function formUpdateVisibility(options) { @@ -219,7 +219,7 @@ async function onReady() { chrome.runtime.onMessage.addListener(onMessage); } -$(document).ready(utilAsync(onReady)); +$(document).ready(() => onReady()); /* @@ -582,7 +582,7 @@ async function ankiFieldsPopulate(element, options) { container.append($(html)); } - tab.find('.anki-field-value').change(utilAsync(onFormOptionsChanged)); + tab.find('.anki-field-value').change((e) => onFormOptionsChanged(e)); tab.find('.marker-link').click(onAnkiMarkerClicked); } diff --git a/ext/bg/js/util.js b/ext/bg/js/util.js index a6126677..b9e602b3 100644 --- a/ext/bg/js/util.js +++ b/ext/bg/js/util.js @@ -16,12 +16,6 @@ * along with this program. If not, see . */ -function utilAsync(func) { - return function(...args) { - func.apply(this, args); - }; -} - function utilIsolate(data) { return JSON.parse(JSON.stringify(data)); } diff --git a/ext/fg/js/util.js b/ext/fg/js/util.js index 9a7968a7..f28bd636 100644 --- a/ext/fg/js/util.js +++ b/ext/fg/js/util.js @@ -17,12 +17,6 @@ */ -function utilAsync(func) { - return function(...args) { - func.apply(this, args); - }; -} - function utilInvoke(action, params={}) { const data = {action, params}; return new Promise((resolve, reject) => { -- cgit v1.2.3 From a14b820a190c561664e8ad451cf2f83c1d98c4ca Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 26 Nov 2019 17:23:55 -0500 Subject: Move utilInvoke into api.js, rename to _apiInvoke --- ext/fg/js/api.js | 64 +++++++++++++++++++++++++++++++++++++++---------------- ext/fg/js/util.js | 46 --------------------------------------- ext/manifest.json | 1 - 3 files changed, 46 insertions(+), 65 deletions(-) delete mode 100644 ext/fg/js/util.js (limited to 'ext/fg') diff --git a/ext/fg/js/api.js b/ext/fg/js/api.js index 92330d9c..f881b23d 100644 --- a/ext/fg/js/api.js +++ b/ext/fg/js/api.js @@ -18,73 +18,101 @@ function apiOptionsGet(optionsContext) { - return utilInvoke('optionsGet', {optionsContext}); + return _apiInvoke('optionsGet', {optionsContext}); } function apiOptionsSet(changedOptions, optionsContext, source) { - return utilInvoke('optionsSet', {changedOptions, optionsContext, source}); + return _apiInvoke('optionsSet', {changedOptions, optionsContext, source}); } function apiTermsFind(text, details, optionsContext) { - return utilInvoke('termsFind', {text, details, optionsContext}); + return _apiInvoke('termsFind', {text, details, optionsContext}); } function apiTextParse(text, optionsContext) { - return utilInvoke('textParse', {text, optionsContext}); + return _apiInvoke('textParse', {text, optionsContext}); } function apiTextParseMecab(text, optionsContext) { - return utilInvoke('textParseMecab', {text, optionsContext}); + return _apiInvoke('textParseMecab', {text, optionsContext}); } function apiKanjiFind(text, optionsContext) { - return utilInvoke('kanjiFind', {text, optionsContext}); + return _apiInvoke('kanjiFind', {text, optionsContext}); } function apiDefinitionAdd(definition, mode, context, optionsContext) { - return utilInvoke('definitionAdd', {definition, mode, context, optionsContext}); + return _apiInvoke('definitionAdd', {definition, mode, context, optionsContext}); } function apiDefinitionsAddable(definitions, modes, optionsContext) { - return utilInvoke('definitionsAddable', {definitions, modes, optionsContext}).catch(() => null); + return _apiInvoke('definitionsAddable', {definitions, modes, optionsContext}).catch(() => null); } function apiNoteView(noteId) { - return utilInvoke('noteView', {noteId}); + return _apiInvoke('noteView', {noteId}); } function apiTemplateRender(template, data, dynamic) { - return utilInvoke('templateRender', {data, template, dynamic}); + return _apiInvoke('templateRender', {data, template, dynamic}); } function apiAudioGetUrl(definition, source, optionsContext) { - return utilInvoke('audioGetUrl', {definition, source, optionsContext}); + return _apiInvoke('audioGetUrl', {definition, source, optionsContext}); } function apiCommandExec(command, params) { - return utilInvoke('commandExec', {command, params}); + return _apiInvoke('commandExec', {command, params}); } function apiScreenshotGet(options) { - return utilInvoke('screenshotGet', {options}); + return _apiInvoke('screenshotGet', {options}); } function apiForward(action, params) { - return utilInvoke('forward', {action, params}); + return _apiInvoke('forward', {action, params}); } function apiFrameInformationGet() { - return utilInvoke('frameInformationGet'); + return _apiInvoke('frameInformationGet'); } function apiInjectStylesheet(css) { - return utilInvoke('injectStylesheet', {css}); + return _apiInvoke('injectStylesheet', {css}); } function apiGetEnvironmentInfo() { - return utilInvoke('getEnvironmentInfo'); + return _apiInvoke('getEnvironmentInfo'); } function apiClipboardGet() { - return utilInvoke('clipboardGet'); + return _apiInvoke('clipboardGet'); +} + +function _apiInvoke(action, params={}) { + const data = {action, params}; + return new Promise((resolve, reject) => { + try { + chrome.runtime.sendMessage(data, (response) => { + _apiCheckLastError(chrome.runtime.lastError); + if (response !== null && typeof response === 'object') { + if (typeof response.error !== 'undefined') { + reject(jsonToError(response.error)); + } else { + resolve(response.result); + } + } else { + const message = response === null ? 'Unexpected null response' : `Unexpected response of type ${typeof response}`; + reject(new Error(`${message} (${JSON.stringify(data)})`)); + } + }); + } catch (e) { + window.yomichan_orphaned = true; + reject(e); + } + }); +} + +function _apiCheckLastError(e) { + // NOP } diff --git a/ext/fg/js/util.js b/ext/fg/js/util.js deleted file mode 100644 index f28bd636..00000000 --- a/ext/fg/js/util.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2016-2017 Alex Yatskov - * Author: Alex Yatskov - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -function utilInvoke(action, params={}) { - const data = {action, params}; - return new Promise((resolve, reject) => { - try { - chrome.runtime.sendMessage(data, (response) => { - utilCheckLastError(chrome.runtime.lastError); - if (response !== null && typeof response === 'object') { - if (typeof response.error !== 'undefined') { - reject(jsonToError(response.error)); - } else { - resolve(response.result); - } - } else { - const message = response === null ? 'Unexpected null response' : `Unexpected response of type ${typeof response}`; - reject(new Error(`${message} (${JSON.stringify(data)})`)); - } - }); - } catch (e) { - window.yomichan_orphaned = true; - reject(e); - } - }); -} - -function utilCheckLastError(e) { - // NOP -} diff --git a/ext/manifest.json b/ext/manifest.json index 4d75cd54..43a887cd 100644 --- a/ext/manifest.json +++ b/ext/manifest.json @@ -24,7 +24,6 @@ "fg/js/frontend-api-receiver.js", "fg/js/popup.js", "fg/js/source.js", - "fg/js/util.js", "fg/js/popup-proxy-host.js", "fg/js/frontend.js", "fg/js/frontend-initialize.js" -- cgit v1.2.3 From 7e94fca7c7a07f94de40ddeb56a3f06e43000e25 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 26 Nov 2019 17:29:52 -0500 Subject: Rename extension.js to core.js to better reflect its use --- ext/bg/background.html | 2 +- ext/bg/context.html | 2 +- ext/bg/search.html | 2 +- ext/bg/settings-popup-preview.html | 2 +- ext/bg/settings.html | 2 +- ext/fg/float.html | 2 +- ext/manifest.json | 2 +- ext/mixed/js/core.js | 150 +++++++++++++++++++++++++++++++++++++ ext/mixed/js/extension.js | 150 ------------------------------------- 9 files changed, 157 insertions(+), 157 deletions(-) create mode 100644 ext/mixed/js/core.js delete mode 100644 ext/mixed/js/extension.js (limited to 'ext/fg') diff --git a/ext/bg/background.html b/ext/bg/background.html index 6e6e7c26..3b337e18 100644 --- a/ext/bg/background.html +++ b/ext/bg/background.html @@ -18,7 +18,7 @@ - + diff --git a/ext/bg/context.html b/ext/bg/context.html index bd62270b..52ca255d 100644 --- a/ext/bg/context.html +++ b/ext/bg/context.html @@ -178,7 +178,7 @@
- + diff --git a/ext/bg/search.html b/ext/bg/search.html index e819ebe6..16074022 100644 --- a/ext/bg/search.html +++ b/ext/bg/search.html @@ -60,7 +60,7 @@ - + diff --git a/ext/bg/settings-popup-preview.html b/ext/bg/settings-popup-preview.html index d27a9a33..574b6707 100644 --- a/ext/bg/settings-popup-preview.html +++ b/ext/bg/settings-popup-preview.html @@ -117,7 +117,7 @@
- + diff --git a/ext/bg/settings.html b/ext/bg/settings.html index 262386e9..b2af3759 100644 --- a/ext/bg/settings.html +++ b/ext/bg/settings.html @@ -864,7 +864,7 @@ - + diff --git a/ext/fg/float.html b/ext/fg/float.html index 73118917..e04c1402 100644 --- a/ext/fg/float.html +++ b/ext/fg/float.html @@ -31,7 +31,7 @@ - + diff --git a/ext/manifest.json b/ext/manifest.json index 43a887cd..69ee0c4f 100644 --- a/ext/manifest.json +++ b/ext/manifest.json @@ -18,7 +18,7 @@ "content_scripts": [{ "matches": ["http://*/*", "https://*/*", "file://*/*"], "js": [ - "mixed/js/extension.js", + "mixed/js/core.js", "fg/js/api.js", "fg/js/document.js", "fg/js/frontend-api-receiver.js", diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js new file mode 100644 index 00000000..12ed9c1f --- /dev/null +++ b/ext/mixed/js/core.js @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2019 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +// toIterable is required on Edge for cross-window origin objects. +function toIterable(value) { + if (typeof Symbol !== 'undefined' && typeof value[Symbol.iterator] !== 'undefined') { + return value; + } + + if (value !== null && typeof value === 'object') { + const length = value.length; + if (typeof length === 'number' && Number.isFinite(length)) { + const array = []; + for (let i = 0; i < length; ++i) { + array.push(value[i]); + } + return array; + } + } + + throw new Error('Could not convert to iterable'); +} + +function extensionHasChrome() { + try { + return typeof chrome === 'object' && chrome !== null; + } catch (e) { + return false; + } +} + +function extensionHasBrowser() { + try { + return typeof browser === 'object' && browser !== null; + } catch (e) { + return false; + } +} + +function errorToJson(error) { + return { + name: error.name, + message: error.message, + stack: error.stack + }; +} + +function jsonToError(jsonError) { + const error = new Error(jsonError.message); + error.name = jsonError.name; + error.stack = jsonError.stack; + return error; +} + +function logError(error, alert) { + const manifest = chrome.runtime.getManifest(); + let errorMessage = `${manifest.name} v${manifest.version} has encountered an error.\n`; + errorMessage += `Originating URL: ${window.location.href}\n`; + + const errorString = `${error.toString ? error.toString() : error}`; + const stack = `${error.stack}`.trimRight(); + errorMessage += (!stack.startsWith(errorString) ? `${errorString}\n${stack}` : `${stack}`); + + errorMessage += '\n\nIssues can be reported at https://github.com/FooSoft/yomichan/issues'; + + console.error(errorMessage); + + if (alert) { + window.alert(`${errorString}\n\nCheck the developer console for more details.`); + } +} + +const EXTENSION_IS_BROWSER_EDGE = ( + extensionHasBrowser() && + (!extensionHasChrome() || (typeof chrome.runtime === 'undefined' && typeof browser.runtime !== 'undefined')) +); + +if (EXTENSION_IS_BROWSER_EDGE) { + // Edge does not have chrome defined. + chrome = browser; +} + +function promiseTimeout(delay, resolveValue) { + if (delay <= 0) { + return Promise.resolve(resolveValue); + } + + let timer = null; + let promiseResolve = null; + let promiseReject = null; + + const complete = (callback, value) => { + if (callback === null) { return; } + if (timer !== null) { + window.clearTimeout(timer); + timer = null; + } + promiseResolve = null; + promiseReject = null; + callback(value); + }; + + const resolve = (value) => complete(promiseResolve, value); + const reject = (value) => complete(promiseReject, value); + + const promise = new Promise((resolve, reject) => { + promiseResolve = resolve; + promiseReject = reject; + }); + timer = window.setTimeout(() => { + timer = null; + resolve(resolveValue); + }, delay); + + promise.resolve = resolve; + promise.reject = reject; + + return promise; +} + +function stringReplaceAsync(str, regex, replacer) { + let match; + let index = 0; + const parts = []; + while ((match = regex.exec(str)) !== null) { + parts.push(str.substring(index, match.index), replacer(...match, match.index, str)); + index = regex.lastIndex; + } + if (parts.length === 0) { + return Promise.resolve(str); + } + parts.push(str.substring(index)); + return Promise.all(parts).then(v => v.join('')); +} diff --git a/ext/mixed/js/extension.js b/ext/mixed/js/extension.js deleted file mode 100644 index 12ed9c1f..00000000 --- a/ext/mixed/js/extension.js +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2019 Alex Yatskov - * Author: Alex Yatskov - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -// toIterable is required on Edge for cross-window origin objects. -function toIterable(value) { - if (typeof Symbol !== 'undefined' && typeof value[Symbol.iterator] !== 'undefined') { - return value; - } - - if (value !== null && typeof value === 'object') { - const length = value.length; - if (typeof length === 'number' && Number.isFinite(length)) { - const array = []; - for (let i = 0; i < length; ++i) { - array.push(value[i]); - } - return array; - } - } - - throw new Error('Could not convert to iterable'); -} - -function extensionHasChrome() { - try { - return typeof chrome === 'object' && chrome !== null; - } catch (e) { - return false; - } -} - -function extensionHasBrowser() { - try { - return typeof browser === 'object' && browser !== null; - } catch (e) { - return false; - } -} - -function errorToJson(error) { - return { - name: error.name, - message: error.message, - stack: error.stack - }; -} - -function jsonToError(jsonError) { - const error = new Error(jsonError.message); - error.name = jsonError.name; - error.stack = jsonError.stack; - return error; -} - -function logError(error, alert) { - const manifest = chrome.runtime.getManifest(); - let errorMessage = `${manifest.name} v${manifest.version} has encountered an error.\n`; - errorMessage += `Originating URL: ${window.location.href}\n`; - - const errorString = `${error.toString ? error.toString() : error}`; - const stack = `${error.stack}`.trimRight(); - errorMessage += (!stack.startsWith(errorString) ? `${errorString}\n${stack}` : `${stack}`); - - errorMessage += '\n\nIssues can be reported at https://github.com/FooSoft/yomichan/issues'; - - console.error(errorMessage); - - if (alert) { - window.alert(`${errorString}\n\nCheck the developer console for more details.`); - } -} - -const EXTENSION_IS_BROWSER_EDGE = ( - extensionHasBrowser() && - (!extensionHasChrome() || (typeof chrome.runtime === 'undefined' && typeof browser.runtime !== 'undefined')) -); - -if (EXTENSION_IS_BROWSER_EDGE) { - // Edge does not have chrome defined. - chrome = browser; -} - -function promiseTimeout(delay, resolveValue) { - if (delay <= 0) { - return Promise.resolve(resolveValue); - } - - let timer = null; - let promiseResolve = null; - let promiseReject = null; - - const complete = (callback, value) => { - if (callback === null) { return; } - if (timer !== null) { - window.clearTimeout(timer); - timer = null; - } - promiseResolve = null; - promiseReject = null; - callback(value); - }; - - const resolve = (value) => complete(promiseResolve, value); - const reject = (value) => complete(promiseReject, value); - - const promise = new Promise((resolve, reject) => { - promiseResolve = resolve; - promiseReject = reject; - }); - timer = window.setTimeout(() => { - timer = null; - resolve(resolveValue); - }, delay); - - promise.resolve = resolve; - promise.reject = reject; - - return promise; -} - -function stringReplaceAsync(str, regex, replacer) { - let match; - let index = 0; - const parts = []; - while ((match = regex.exec(str)) !== null) { - parts.push(str.substring(index, match.index), replacer(...match, match.index, str)); - index = regex.lastIndex; - } - if (parts.length === 0) { - return Promise.resolve(str); - } - parts.push(str.substring(index)); - return Promise.all(parts).then(v => v.join('')); -} -- cgit v1.2.3 From 96aad50340b4d0374979ac981cd1c481cc8dcd94 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 26 Nov 2019 18:47:16 -0500 Subject: Create DOM utility file --- ext/bg/background.html | 1 + ext/bg/context.html | 1 + ext/bg/search.html | 1 + ext/bg/settings-popup-preview.html | 2 ++ ext/bg/settings.html | 1 + ext/fg/float.html | 1 + ext/fg/js/document.js | 19 ++-------------- ext/fg/js/frontend.js | 14 +----------- ext/manifest.json | 1 + ext/mixed/js/dom.js | 46 ++++++++++++++++++++++++++++++++++++++ 10 files changed, 57 insertions(+), 30 deletions(-) create mode 100644 ext/mixed/js/dom.js (limited to 'ext/fg') diff --git a/ext/bg/background.html b/ext/bg/background.html index 3b337e18..5a6970c3 100644 --- a/ext/bg/background.html +++ b/ext/bg/background.html @@ -19,6 +19,7 @@ + diff --git a/ext/bg/context.html b/ext/bg/context.html index 52ca255d..eda09a68 100644 --- a/ext/bg/context.html +++ b/ext/bg/context.html @@ -179,6 +179,7 @@ + diff --git a/ext/bg/search.html b/ext/bg/search.html index 16074022..ef24af89 100644 --- a/ext/bg/search.html +++ b/ext/bg/search.html @@ -61,6 +61,7 @@ + diff --git a/ext/bg/settings-popup-preview.html b/ext/bg/settings-popup-preview.html index 574b6707..9ca59e44 100644 --- a/ext/bg/settings-popup-preview.html +++ b/ext/bg/settings-popup-preview.html @@ -118,6 +118,8 @@ + + diff --git a/ext/bg/settings.html b/ext/bg/settings.html index b2af3759..908c618c 100644 --- a/ext/bg/settings.html +++ b/ext/bg/settings.html @@ -865,6 +865,7 @@ + diff --git a/ext/fg/float.html b/ext/fg/float.html index e04c1402..38439c79 100644 --- a/ext/fg/float.html +++ b/ext/fg/float.html @@ -32,6 +32,7 @@ + diff --git a/ext/fg/js/document.js b/ext/fg/js/document.js index 8161c85a..3dd12a40 100644 --- a/ext/fg/js/document.js +++ b/ext/fg/js/document.js @@ -223,7 +223,7 @@ function isPointInRange(x, y, range) { const {node, offset, content} = TextSourceRange.seekForward(range.endContainer, range.endOffset, 1); range.setEnd(node, offset); - if (!isWhitespace(content) && isPointInAnyRect(x, y, range.getClientRects())) { + if (!isWhitespace(content) && DOM.isPointInAnyRect(x, y, range.getClientRects())) { return true; } } finally { @@ -234,7 +234,7 @@ function isPointInRange(x, y, range) { const {node, offset, content} = TextSourceRange.seekBackward(range.startContainer, range.startOffset, 1); range.setStart(node, offset); - if (!isWhitespace(content) && isPointInAnyRect(x, y, range.getClientRects())) { + if (!isWhitespace(content) && DOM.isPointInAnyRect(x, y, range.getClientRects())) { // This purposefully leaves the starting offset as modified and sets the range length to 0. range.setEnd(node, offset); return true; @@ -248,21 +248,6 @@ function isWhitespace(string) { return string.trim().length === 0; } -function isPointInAnyRect(x, y, rects) { - for (const rect of rects) { - if (isPointInRect(x, y, rect)) { - return true; - } - } - return false; -} - -function isPointInRect(x, y, rect) { - return ( - x >= rect.left && x < rect.right && - y >= rect.top && y < rect.bottom); -} - const caretRangeFromPoint = (() => { if (typeof document.caretRangeFromPoint === 'function') { // Chrome, Edge diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index 6002dfcb..81c159db 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -159,7 +159,7 @@ class Frontend { this.preventNextClick = false; const primaryTouch = e.changedTouches[0]; - if (Frontend.selectionContainsPoint(window.getSelection(), primaryTouch.clientX, primaryTouch.clientY)) { + if (DOM.isPointInSelection(primaryTouch.clientX, primaryTouch.clientY, window.getSelection())) { return; } @@ -456,18 +456,6 @@ class Frontend { return -1; } - static selectionContainsPoint(selection, x, y) { - for (let i = 0; i < selection.rangeCount; ++i) { - const range = selection.getRangeAt(i); - for (const rect of range.getClientRects()) { - if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) { - return true; - } - } - } - return false; - } - setTextSourceScanLength(textSource, length) { textSource.setEndOffset(length); if (this.ignoreNodes === null || !textSource.range) { diff --git a/ext/manifest.json b/ext/manifest.json index 69ee0c4f..dc670633 100644 --- a/ext/manifest.json +++ b/ext/manifest.json @@ -19,6 +19,7 @@ "matches": ["http://*/*", "https://*/*", "file://*/*"], "js": [ "mixed/js/core.js", + "mixed/js/dom.js", "fg/js/api.js", "fg/js/document.js", "fg/js/frontend-api-receiver.js", diff --git a/ext/mixed/js/dom.js b/ext/mixed/js/dom.js new file mode 100644 index 00000000..4525dace --- /dev/null +++ b/ext/mixed/js/dom.js @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2019 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +class DOM { + static isPointInRect(x, y, rect) { + return ( + x >= rect.left && x < rect.right && + y >= rect.top && y < rect.bottom + ); + } + + static isPointInAnyRect(x, y, rects) { + for (const rect of rects) { + if (DOM.isPointInRect(x, y, rect)) { + return true; + } + } + return false; + } + + static isPointInSelection(x, y, selection) { + for (let i = 0; i < selection.rangeCount; ++i) { + const range = selection.getRangeAt(i); + if (DOM.isPointInAnyRect(x, y, range.getClientRects())) { + return true; + } + } + return false; + } +} -- cgit v1.2.3 From 4110a848f5107c697e09c014d3488360fc8219ef Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 26 Nov 2019 18:52:05 -0500 Subject: Move additional utility functions to DOM --- ext/bg/js/search-query-parser.js | 8 ++++---- ext/fg/js/frontend.js | 35 ++--------------------------------- ext/mixed/js/display.js | 4 ++-- ext/mixed/js/dom.js | 20 ++++++++++++++++++++ 4 files changed, 28 insertions(+), 39 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/search-query-parser.js b/ext/bg/js/search-query-parser.js index 42e53989..1a43347c 100644 --- a/ext/bg/js/search-query-parser.js +++ b/ext/bg/js/search-query-parser.js @@ -38,7 +38,7 @@ class QueryParser { } onMouseDown(e) { - if (Frontend.isMouseButton('primary', e)) { + if (DOM.isMouseButtonPressed(e, 'primary')) { this.clickScanPrevent = false; } } @@ -47,7 +47,7 @@ class QueryParser { if ( this.search.options.scanning.clickGlossary && !this.clickScanPrevent && - Frontend.isMouseButton('primary', e) + DOM.isMouseButtonPressed(e, 'primary') ) { const selectText = this.search.options.scanning.selectText; this.onTermLookup(e, {disableScroll: true, selectText}); @@ -55,7 +55,7 @@ class QueryParser { } onMouseMove(e) { - if (this.pendingLookup || Frontend.isMouseButton('primary', e)) { + if (this.pendingLookup || DOM.isMouseButtonDown(e, 'primary')) { return; } @@ -63,7 +63,7 @@ class QueryParser { const scanningModifier = scanningOptions.modifier; if (!( Frontend.isScanningModifierPressed(scanningModifier, e) || - (scanningOptions.middleMouse && Frontend.isMouseButton('auxiliary', e)) + (scanningOptions.middleMouse && DOM.isMouseButtonDown(e, 'auxiliary')) )) { return; } diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index 81c159db..ee653d78 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -80,7 +80,7 @@ class Frontend { onMouseMove(e) { this.popupTimerClear(); - if (this.pendingLookup || Frontend.isMouseButtonDown('primary', e)) { + if (this.pendingLookup || DOM.isMouseButtonDown(e, 'primary')) { return; } @@ -88,7 +88,7 @@ class Frontend { const scanningModifier = scanningOptions.modifier; if (!( Frontend.isScanningModifierPressed(scanningModifier, e) || - (scanningOptions.middleMouse && Frontend.isMouseButtonDown('auxiliary', e)) + (scanningOptions.middleMouse && DOM.isMouseButtonDown(e, 'auxiliary')) )) { return; } @@ -487,37 +487,6 @@ class Frontend { default: return false; } } - - static isMouseButton(button, mouseEvent) { - switch (mouseEvent.type) { - case 'mouseup': - case 'mousedown': - case 'click': - return Frontend.isMouseButtonPressed(button, mouseEvent); - default: - return Frontend.isMouseButtonDown(button, mouseEvent); - } - } - - static isMouseButtonPressed(button, mouseEvent) { - const mouseEventButton = mouseEvent.button; - switch (button) { - case 'primary': return mouseEventButton === 0; - case 'secondary': return mouseEventButton === 2; - case 'auxiliary': return mouseEventButton === 1; - default: return false; - } - } - - static isMouseButtonDown(button, mouseEvent) { - const mouseEventButtons = mouseEvent.buttons; - switch (button) { - case 'primary': return (mouseEventButtons & 0x1) !== 0x0; - case 'secondary': return (mouseEventButtons & 0x2) !== 0x0; - case 'auxiliary': return (mouseEventButtons & 0x4) !== 0x0; - default: return false; - } - } } Frontend.windowMessageHandlers = { diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index cbf8efb7..854418f4 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -85,7 +85,7 @@ class Display { } onGlossaryMouseDown(e) { - if (Frontend.isMouseButtonPressed('primary', e)) { + if (DOM.isMouseButtonPressed(e, 'primary')) { this.clickScanPrevent = false; } } @@ -95,7 +95,7 @@ class Display { } onGlossaryMouseUp(e) { - if (!this.clickScanPrevent && Frontend.isMouseButtonPressed('primary', e)) { + if (!this.clickScanPrevent && DOM.isMouseButtonPressed(e, 'primary')) { this.onTermLookup(e); } } diff --git a/ext/mixed/js/dom.js b/ext/mixed/js/dom.js index 4525dace..4e4d49e3 100644 --- a/ext/mixed/js/dom.js +++ b/ext/mixed/js/dom.js @@ -43,4 +43,24 @@ class DOM { } return false; } + + static isMouseButtonPressed(mouseEvent, button) { + const mouseEventButton = mouseEvent.button; + switch (button) { + case 'primary': return mouseEventButton === 0; + case 'secondary': return mouseEventButton === 2; + case 'auxiliary': return mouseEventButton === 1; + default: return false; + } + } + + static isMouseButtonDown(mouseEvent, button) { + const mouseEventButtons = mouseEvent.buttons; + switch (button) { + case 'primary': return (mouseEventButtons & 0x1) !== 0x0; + case 'secondary': return (mouseEventButtons & 0x2) !== 0x0; + case 'auxiliary': return (mouseEventButtons & 0x4) !== 0x0; + default: return false; + } + } } -- cgit v1.2.3 From 0aed27b66d9c496e4cd57ef95d982c4e634a8666 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 25 Nov 2019 14:19:18 -0500 Subject: Replace hasOwnProperty with simplified hasOwn function --- ext/bg/js/api.js | 4 ++-- ext/bg/js/audio.js | 6 +++--- ext/bg/js/backend.js | 2 +- ext/bg/js/conditions-ui.js | 20 ++++++++++---------- ext/bg/js/conditions.js | 30 +++++++++++++++--------------- ext/bg/js/database.js | 2 +- ext/bg/js/dictionary.js | 4 ++-- ext/bg/js/mecab.js | 2 +- ext/bg/js/options.js | 2 +- ext/bg/js/search.js | 2 +- ext/bg/js/settings-dictionaries.js | 4 ++-- ext/bg/js/settings-popup-preview.js | 2 +- ext/bg/js/translator.js | 12 ++++++------ ext/fg/js/float.js | 4 ++-- ext/fg/js/frontend-api-receiver.js | 2 +- ext/fg/js/frontend-api-sender.js | 6 +++--- ext/fg/js/frontend.js | 4 ++-- ext/fg/js/popup-proxy-host.js | 4 ++-- ext/mixed/js/audio.js | 2 +- ext/mixed/js/core.js | 4 ++++ ext/mixed/js/display.js | 4 ++-- 21 files changed, 63 insertions(+), 59 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index 766fb0ed..12257e92 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -45,7 +45,7 @@ async function apiOptionsSet(changedOptions, optionsContext, source) { function modifyOption(path, value, options) { let pivot = options; for (const key of path.slice(0, -1)) { - if (!pivot.hasOwnProperty(key)) { + if (!hasOwn(pivot, key)) { return false; } pivot = pivot[key]; @@ -236,7 +236,7 @@ async function apiTemplateRender(template, data, dynamic) { async function apiCommandExec(command, params) { const handlers = apiCommandExec.handlers; - if (handlers.hasOwnProperty(command)) { + if (hasOwn(handlers, command)) { const handler = handlers[command]; handler(params); } diff --git a/ext/bg/js/audio.js b/ext/bg/js/audio.js index cd42a158..9bbbf902 100644 --- a/ext/bg/js/audio.js +++ b/ext/bg/js/audio.js @@ -107,12 +107,12 @@ const audioUrlBuilders = { 'custom': async (definition, optionsContext) => { const options = await apiOptionsGet(optionsContext); const customSourceUrl = options.audio.customSourceUrl; - return customSourceUrl.replace(/\{([^\}]*)\}/g, (m0, m1) => (definition.hasOwnProperty(m1) ? `${definition[m1]}` : m0)); + return customSourceUrl.replace(/\{([^\}]*)\}/g, (m0, m1) => (hasOwn(definition, m1) ? `${definition[m1]}` : m0)); } }; async function audioGetUrl(definition, mode, optionsContext, download) { - if (audioUrlBuilders.hasOwnProperty(mode)) { + if (hasOwn(audioUrlBuilders, mode)) { const handler = audioUrlBuilders[mode]; try { return await handler(definition, optionsContext, download); @@ -171,7 +171,7 @@ async function audioInject(definition, fields, sources, optionsContext) { try { let audioSourceDefinition = definition; - if (definition.hasOwnProperty('expressions')) { + if (hasOwn(definition, 'expressions')) { audioSourceDefinition = definition.expressions[0]; } diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 45db9660..4190116b 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -73,7 +73,7 @@ class Backend { onMessage({action, params}, sender, callback) { const handlers = Backend.messageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const promise = handler(params, sender); promise.then( diff --git a/ext/bg/js/conditions-ui.js b/ext/bg/js/conditions-ui.js index 43c6dc08..cc9db087 100644 --- a/ext/bg/js/conditions-ui.js +++ b/ext/bg/js/conditions-ui.js @@ -84,7 +84,7 @@ ConditionsUI.Container = class Container { createDefaultCondition(type) { let operator = ''; let value = ''; - if (this.conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(this.conditionDescriptors, type)) { const conditionDescriptor = this.conditionDescriptors[type]; operator = conditionDescriptor.defaultOperator; ({value} = this.getOperatorDefaultValue(type, operator)); @@ -96,15 +96,15 @@ ConditionsUI.Container = class Container { } getOperatorDefaultValue(type, operator) { - if (this.conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(this.conditionDescriptors, type)) { const conditionDescriptor = this.conditionDescriptors[type]; - if (conditionDescriptor.operators.hasOwnProperty(operator)) { + if (hasOwn(conditionDescriptor.operators, operator)) { const operatorDescriptor = conditionDescriptor.operators[operator]; - if (operatorDescriptor.hasOwnProperty('defaultValue')) { + if (hasOwn(operatorDescriptor, 'defaultValue')) { return {value: operatorDescriptor.defaultValue, fromOperator: true}; } } - if (conditionDescriptor.hasOwnProperty('defaultValue')) { + if (hasOwn(conditionDescriptor, 'defaultValue')) { return {value: conditionDescriptor.defaultValue, fromOperator: false}; } } @@ -219,7 +219,7 @@ ConditionsUI.Condition = class Condition { optionGroup.empty(); const type = this.condition.type; - if (conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(conditionDescriptors, type)) { const conditionDescriptor = conditionDescriptors[type]; const operators = conditionDescriptor.operators; for (const operatorName of Object.keys(operators)) { @@ -240,23 +240,23 @@ ConditionsUI.Condition = class Condition { }; const objects = []; - if (conditionDescriptors.hasOwnProperty(type)) { + if (hasOwn(conditionDescriptors, type)) { const conditionDescriptor = conditionDescriptors[type]; objects.push(conditionDescriptor); - if (conditionDescriptor.operators.hasOwnProperty(operator)) { + if (hasOwn(conditionDescriptor.operators, operator)) { const operatorDescriptor = conditionDescriptor.operators[operator]; objects.push(operatorDescriptor); } } for (const object of objects) { - if (object.hasOwnProperty('placeholder')) { + if (hasOwn(object, 'placeholder')) { props.placeholder = object.placeholder; } if (object.type === 'number') { props.type = 'number'; for (const prop of ['step', 'min', 'max']) { - if (object.hasOwnProperty(prop)) { + if (hasOwn(object, prop)) { props[prop] = object[prop]; } } diff --git a/ext/bg/js/conditions.js b/ext/bg/js/conditions.js index ed4b14f5..c0f0f301 100644 --- a/ext/bg/js/conditions.js +++ b/ext/bg/js/conditions.js @@ -18,14 +18,14 @@ function conditionsValidateOptionValue(object, value) { - if (object.hasOwnProperty('validate') && !object.validate(value)) { + if (hasOwn(object, 'validate') && !object.validate(value)) { throw new Error('Invalid value for condition'); } - if (object.hasOwnProperty('transform')) { + if (hasOwn(object, 'transform')) { value = object.transform(value); - if (object.hasOwnProperty('validateTransformed') && !object.validateTransformed(value)) { + if (hasOwn(object, 'validateTransformed') && !object.validateTransformed(value)) { throw new Error('Invalid value for condition'); } } @@ -34,12 +34,12 @@ function conditionsValidateOptionValue(object, value) { } function conditionsNormalizeOptionValue(descriptors, type, operator, optionValue) { - if (!descriptors.hasOwnProperty(type)) { + if (!hasOwn(descriptors, type)) { throw new Error('Invalid type'); } const conditionDescriptor = descriptors[type]; - if (!conditionDescriptor.operators.hasOwnProperty(operator)) { + if (!hasOwn(conditionDescriptor.operators, operator)) { throw new Error('Invalid operator'); } @@ -48,28 +48,28 @@ function conditionsNormalizeOptionValue(descriptors, type, operator, optionValue let transformedValue = conditionsValidateOptionValue(conditionDescriptor, optionValue); transformedValue = conditionsValidateOptionValue(operatorDescriptor, transformedValue); - if (operatorDescriptor.hasOwnProperty('transformReverse')) { + if (hasOwn(operatorDescriptor, 'transformReverse')) { transformedValue = operatorDescriptor.transformReverse(transformedValue); } return transformedValue; } function conditionsTestValueThrowing(descriptors, type, operator, optionValue, value) { - if (!descriptors.hasOwnProperty(type)) { + if (!hasOwn(descriptors, type)) { throw new Error('Invalid type'); } const conditionDescriptor = descriptors[type]; - if (!conditionDescriptor.operators.hasOwnProperty(operator)) { + if (!hasOwn(conditionDescriptor.operators, operator)) { throw new Error('Invalid operator'); } const operatorDescriptor = conditionDescriptor.operators[operator]; - if (operatorDescriptor.hasOwnProperty('transform')) { - if (operatorDescriptor.hasOwnProperty('transformCache')) { + if (hasOwn(operatorDescriptor, 'transform')) { + if (hasOwn(operatorDescriptor, 'transformCache')) { const key = `${optionValue}`; const transformCache = operatorDescriptor.transformCache; - if (transformCache.hasOwnProperty(key)) { + if (hasOwn(transformCache, key)) { optionValue = transformCache[key]; } else { optionValue = operatorDescriptor.transform(optionValue); @@ -93,23 +93,23 @@ function conditionsTestValue(descriptors, type, operator, optionValue, value) { function conditionsClearCaches(descriptors) { for (const type in descriptors) { - if (!descriptors.hasOwnProperty(type)) { + if (!hasOwn(descriptors, type)) { continue; } const conditionDescriptor = descriptors[type]; - if (conditionDescriptor.hasOwnProperty('transformCache')) { + if (hasOwn(conditionDescriptor, 'transformCache')) { conditionDescriptor.transformCache = {}; } const operatorDescriptors = conditionDescriptor.operators; for (const operator in operatorDescriptors) { - if (!operatorDescriptors.hasOwnProperty(operator)) { + if (!hasOwn(operatorDescriptors, operator)) { continue; } const operatorDescriptor = operatorDescriptors[operator]; - if (operatorDescriptor.hasOwnProperty('transformCache')) { + if (hasOwn(operatorDescriptor, 'transformCache')) { operatorDescriptor.transformCache = {}; } } diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index 9b560f78..c53c9f77 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -137,7 +137,7 @@ class Database { const visited = {}; const results = []; const processRow = (row, index) => { - if (titles.includes(row.dictionary) && !visited.hasOwnProperty(row.id)) { + if (titles.includes(row.dictionary) && !hasOwn(visited, row.id)) { visited[row.id] = true; results.push(Database.createTerm(row, index)); } diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js index 9aa0af9c..affce9e9 100644 --- a/ext/bg/js/dictionary.js +++ b/ext/bg/js/dictionary.js @@ -81,7 +81,7 @@ function dictTermsUndupe(definitions) { const definitionGroups = {}; for (const definition of definitions) { const definitionExisting = definitionGroups[definition.id]; - if (!definitionGroups.hasOwnProperty(definition.id) || definition.expression.length > definitionExisting.expression.length) { + if (!hasOwn(definitionGroups, definition.id) || definition.expression.length > definitionExisting.expression.length) { definitionGroups[definition.id] = definition; } } @@ -131,7 +131,7 @@ function dictTermsGroup(definitions, dictionaries) { } const keyString = key.toString(); - if (groups.hasOwnProperty(keyString)) { + if (hasOwn(groups, keyString)) { groups[keyString].push(definition); } else { groups[keyString] = [definition]; diff --git a/ext/bg/js/mecab.js b/ext/bg/js/mecab.js index 246f8bba..297432e2 100644 --- a/ext/bg/js/mecab.js +++ b/ext/bg/js/mecab.js @@ -60,7 +60,7 @@ class Mecab { } onNativeMessage({sequence, data}) { - if (this.listeners.hasOwnProperty(sequence)) { + if (hasOwn(this.listeners, sequence)) { const {callback, timer} = this.listeners[sequence]; clearTimeout(timer); callback(data); diff --git a/ext/bg/js/options.js b/ext/bg/js/options.js index 63d88789..358a6b45 100644 --- a/ext/bg/js/options.js +++ b/ext/bg/js/options.js @@ -336,7 +336,7 @@ function profileOptionsSetDefaults(options) { const combine = (target, source) => { for (const key in source) { - if (!target.hasOwnProperty(key)) { + if (!hasOwn(target, key)) { target[key] = source[key]; } } diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index 0922d938..16cbfbbd 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -234,7 +234,7 @@ class DisplaySearch extends Display { onRuntimeMessage({action, params}, sender, callback) { const handlers = DisplaySearch.runtimeMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const result = handler(this, params); callback(result); diff --git a/ext/bg/js/settings-dictionaries.js b/ext/bg/js/settings-dictionaries.js index ebd380ac..177379b0 100644 --- a/ext/bg/js/settings-dictionaries.js +++ b/ext/bg/js/settings-dictionaries.js @@ -81,7 +81,7 @@ class SettingsDictionaryListUI { let changed = false; let optionsDictionary; const optionsDictionaries = this.optionsDictionaries; - if (optionsDictionaries.hasOwnProperty(title)) { + if (hasOwn(optionsDictionaries, title)) { optionsDictionary = optionsDictionaries[title]; } else { optionsDictionary = SettingsDictionaryListUI.createDictionaryOptions(); @@ -466,7 +466,7 @@ function dictionaryErrorsShow(errors) { for (let e of errors) { console.error(e); e = dictionaryErrorToString(e); - uniqueErrors[e] = uniqueErrors.hasOwnProperty(e) ? uniqueErrors[e] + 1 : 1; + uniqueErrors[e] = hasOwn(uniqueErrors, e) ? uniqueErrors[e] + 1 : 1; } for (const e in uniqueErrors) { diff --git a/ext/bg/js/settings-popup-preview.js b/ext/bg/js/settings-popup-preview.js index 7d641c46..49409968 100644 --- a/ext/bg/js/settings-popup-preview.js +++ b/ext/bg/js/settings-popup-preview.js @@ -106,7 +106,7 @@ class SettingsPopupPreview { onMessage(e) { const {action, params} = e.data; const handlers = SettingsPopupPreview.messageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; handler(this, params); } diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index e27cbdff..0a0ce663 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -297,7 +297,7 @@ class Translator { for (const deinflection of deinflections) { const term = deinflection.term; let deinflectionArray; - if (uniqueDeinflectionsMap.hasOwnProperty(term)) { + if (hasOwn(uniqueDeinflectionsMap, term)) { deinflectionArray = uniqueDeinflectionsMap[term]; } else { deinflectionArray = []; @@ -355,7 +355,7 @@ class Translator { const kanjiUnique = {}; const kanjiList = []; for (const c of text) { - if (!kanjiUnique.hasOwnProperty(c)) { + if (!hasOwn(kanjiUnique, c)) { kanjiList.push(c); kanjiUnique[c] = true; } @@ -417,7 +417,7 @@ class Translator { const expression = term.expression; term.frequencies = []; - if (termsUniqueMap.hasOwnProperty(expression)) { + if (hasOwn(termsUniqueMap, expression)) { termsUniqueMap[expression].push(term); } else { const termList = [term]; @@ -464,7 +464,7 @@ class Translator { const category = meta.category; const group = ( - stats.hasOwnProperty(category) ? + hasOwn(stats, category) ? stats[category] : (stats[category] = []) ); @@ -484,7 +484,7 @@ class Translator { async getTagMetaList(names, title) { const tagMetaList = []; const cache = ( - this.tagCache.hasOwnProperty(title) ? + hasOwn(this.tagCache, title) ? this.tagCache[title] : (this.tagCache[title] = {}) ); @@ -492,7 +492,7 @@ class Translator { for (const name of names) { const base = Translator.getNameBase(name); - if (cache.hasOwnProperty(base)) { + if (hasOwn(cache, base)) { tagMetaList.push(cache[base]); } else { const tagMeta = await this.database.findTagForTitle(base, title); diff --git a/ext/fg/js/float.js b/ext/fg/js/float.js index 089c9422..ae54be00 100644 --- a/ext/fg/js/float.js +++ b/ext/fg/js/float.js @@ -49,7 +49,7 @@ class DisplayFloat extends Display { onMessage(e) { const {action, params} = e.data; const handlers = DisplayFloat.messageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; handler(this, params); } @@ -58,7 +58,7 @@ class DisplayFloat extends Display { onKeyDown(e) { const key = Display.getKeyFromEvent(e); const handlers = DisplayFloat.onKeyDownHandlers; - if (handlers.hasOwnProperty(key)) { + if (hasOwn(handlers, key)) { const handler = handlers[key]; if (handler(this, e)) { e.preventDefault(); diff --git a/ext/fg/js/frontend-api-receiver.js b/ext/fg/js/frontend-api-receiver.js index fbfb3ab0..bde14646 100644 --- a/ext/fg/js/frontend-api-receiver.js +++ b/ext/fg/js/frontend-api-receiver.js @@ -34,7 +34,7 @@ class FrontendApiReceiver { onMessage(port, {id, action, params, target, senderId}) { if ( target !== this.source || - !this.handlers.hasOwnProperty(action) + !hasOwn(this.handlers, action) ) { return; } diff --git a/ext/fg/js/frontend-api-sender.js b/ext/fg/js/frontend-api-sender.js index c6eeaeb2..af998a8f 100644 --- a/ext/fg/js/frontend-api-sender.js +++ b/ext/fg/js/frontend-api-sender.js @@ -78,7 +78,7 @@ class FrontendApiSender { } onAck(id) { - if (!this.callbacks.hasOwnProperty(id)) { + if (!hasOwn(this.callbacks, id)) { console.warn(`ID ${id} not found for ack`); return; } @@ -95,7 +95,7 @@ class FrontendApiSender { } onResult(id, data) { - if (!this.callbacks.hasOwnProperty(id)) { + if (!hasOwn(this.callbacks, id)) { console.warn(`ID ${id} not found`); return; } @@ -118,7 +118,7 @@ class FrontendApiSender { } onError(id, reason) { - if (!this.callbacks.hasOwnProperty(id)) { return; } + if (!hasOwn(this.callbacks, id)) { return; } const info = this.callbacks[id]; delete this.callbacks[id]; info.timer = null; diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index ee653d78..16302e82 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -237,7 +237,7 @@ class Frontend { onWindowMessage(e) { const action = e.data; const handlers = Frontend.windowMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; handler(this); } @@ -245,7 +245,7 @@ class Frontend { onRuntimeMessage({action, params}, sender, callback) { const handlers = Frontend.runtimeMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const result = handler(this, params); callback(result); diff --git a/ext/fg/js/popup-proxy-host.js b/ext/fg/js/popup-proxy-host.js index d8dec4df..b2f18b97 100644 --- a/ext/fg/js/popup-proxy-host.js +++ b/ext/fg/js/popup-proxy-host.js @@ -50,7 +50,7 @@ class PopupProxyHost { } createPopup(parentId, depth) { - const parent = (typeof parentId === 'string' && this.popups.hasOwnProperty(parentId) ? this.popups[parentId] : null); + const parent = (typeof parentId === 'string' && hasOwn(this.popups, parentId) ? this.popups[parentId] : null); const id = `${this.nextId}`; if (parent !== null) { depth = parent.depth + 1; @@ -70,7 +70,7 @@ class PopupProxyHost { } getPopup(id) { - if (!this.popups.hasOwnProperty(id)) { + if (!hasOwn(this.popups, id)) { throw new Error('Invalid popup ID'); } diff --git a/ext/mixed/js/audio.js b/ext/mixed/js/audio.js index 4e9d04fa..7d5ffedd 100644 --- a/ext/mixed/js/audio.js +++ b/ext/mixed/js/audio.js @@ -113,7 +113,7 @@ function audioGetFromUrl(url, willDownload) { async function audioGetFromSources(expression, sources, optionsContext, willDownload, cache=null) { const key = `${expression.expression}:${expression.reading}`; - if (cache !== null && cache.hasOwnProperty(expression)) { + if (cache !== null && hasOwn(cache, expression)) { return cache[key]; } diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js index 8a8a2368..d82b9b4b 100644 --- a/ext/mixed/js/core.js +++ b/ext/mixed/js/core.js @@ -94,6 +94,10 @@ function isObject(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); } +function hasOwn(object, property) { + return Object.prototype.hasOwnProperty.call(object, property); +} + // toIterable is required on Edge for cross-window origin objects. function toIterable(value) { if (typeof Symbol !== 'undefined' && typeof value[Symbol.iterator] !== 'undefined') { diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index 854418f4..ce43b22c 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -194,7 +194,7 @@ class Display { onKeyDown(e) { const key = Display.getKeyFromEvent(e); const handlers = Display.onKeyDownHandlers; - if (handlers.hasOwnProperty(key)) { + if (hasOwn(handlers, key)) { const handler = handlers[key]; if (handler(this, e)) { e.preventDefault(); @@ -216,7 +216,7 @@ class Display { onRuntimeMessage({action, params}, sender, callback) { const handlers = Display.runtimeMessageHandlers; - if (handlers.hasOwnProperty(action)) { + if (hasOwn(handlers, action)) { const handler = handlers[action]; const result = handler(this, params); callback(result); -- cgit v1.2.3 From 943350a1f66b3576e98c58539cbff277b0069977 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 25 Nov 2019 14:21:19 -0500 Subject: Use single quotes --- ext/bg/js/search.js | 2 +- ext/fg/js/popup.js | 2 +- ext/fg/js/source.js | 4 ++-- ext/mixed/js/display.js | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index 16cbfbbd..ae76c23b 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -324,7 +324,7 @@ class DisplaySearch extends Display { this.intro.style.transition = ''; this.intro.style.height = ''; const size = this.intro.getBoundingClientRect(); - this.intro.style.height = `0px`; + this.intro.style.height = '0px'; this.intro.style.transition = `height ${duration}s ease-in-out 0s`; window.getComputedStyle(this.intro).getPropertyValue('height'); // Commits height so next line can start animation this.intro.style.height = `${size.height}px`; diff --git a/ext/fg/js/popup.js b/ext/fg/js/popup.js index ac96f9e8..df784029 100644 --- a/ext/fg/js/popup.js +++ b/ext/fg/js/popup.js @@ -401,7 +401,7 @@ class Popup { if (Popup.outerStylesheet === null) { if (!css) { return; } Popup.outerStylesheet = document.createElement('style'); - Popup.outerStylesheet.id = "yomichan-popup-outer-stylesheet"; + Popup.outerStylesheet.id = 'yomichan-popup-outer-stylesheet'; } const outerStylesheet = Popup.outerStylesheet; diff --git a/ext/fg/js/source.js b/ext/fg/js/source.js index 5be521fa..886093d7 100644 --- a/ext/fg/js/source.js +++ b/ext/fg/js/source.js @@ -99,9 +99,9 @@ class TextSourceRange { static getRubyElement(node) { node = TextSourceRange.getParentElement(node); - if (node !== null && node.nodeName.toUpperCase() === "RT") { + if (node !== null && node.nodeName.toUpperCase() === 'RT') { node = node.parentNode; - return (node !== null && node.nodeName.toUpperCase() === "RUBY") ? node : null; + return (node !== null && node.nodeName.toUpperCase() === 'RUBY') ? node : null; } return null; } diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index ce43b22c..b454bf59 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -574,7 +574,7 @@ class Display { if (button !== null) { let titleDefault = button.dataset.titleDefault; if (!titleDefault) { - titleDefault = button.title || ""; + titleDefault = button.title || ''; button.dataset.titleDefault = titleDefault; } button.title = `${titleDefault}\n${info}`; -- cgit v1.2.3 From 527595f79bf97bc2d17cb821c8bb6b4e8b6776f9 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 25 Nov 2019 14:25:11 -0500 Subject: Remove unnecessary escapes from regex literals --- ext/bg/js/audio.js | 4 ++-- ext/bg/js/dictionary.js | 2 +- ext/bg/js/search.js | 4 ++-- ext/fg/js/document.js | 2 +- ext/fg/js/popup.js | 2 +- ext/mixed/js/audio.js | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/audio.js b/ext/bg/js/audio.js index 9bbbf902..dc0ba5eb 100644 --- a/ext/bg/js/audio.js +++ b/ext/bg/js/audio.js @@ -107,7 +107,7 @@ const audioUrlBuilders = { 'custom': async (definition, optionsContext) => { const options = await apiOptionsGet(optionsContext); const customSourceUrl = options.audio.customSourceUrl; - return customSourceUrl.replace(/\{([^\}]*)\}/g, (m0, m1) => (hasOwn(definition, m1) ? `${definition[m1]}` : m0)); + return customSourceUrl.replace(/\{([^}]*)\}/g, (m0, m1) => (hasOwn(definition, m1) ? `${definition[m1]}` : m0)); } }; @@ -133,7 +133,7 @@ function audioUrlNormalize(url, baseUrl, basePath) { // Begins with "/" url = baseUrl + url; } - } else if (!/^[a-z][a-z0-9\+\-\.]*:/i.test(url)) { + } else if (!/^[a-z][a-z0-9\-+.]*:/i.test(url)) { // No URI scheme => relative path url = baseUrl + basePath + url; } diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js index affce9e9..409bed85 100644 --- a/ext/bg/js/dictionary.js +++ b/ext/bg/js/dictionary.js @@ -322,7 +322,7 @@ async function dictFieldFormat(field, definition, mode, options, exceptions) { compactGlossaries: options.general.compactGlossaries }; const markers = dictFieldFormat.markers; - const pattern = /\{([\w\-]+)\}/g; + const pattern = /\{([\w-]+)\}/g; return await stringReplaceAsync(field, pattern, async (g0, marker) => { if (!markers.has(marker)) { return g0; diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index ae76c23b..552b7a59 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -207,7 +207,7 @@ class DisplaySearch extends Display { async onSearchQueryUpdated(query, animate) { try { const details = {}; - const match = /[\*\uff0a]+$/.exec(query); + const match = /[*\uff0a]+$/.exec(query); if (match !== null) { details.wildcard = true; query = query.substring(0, query.length - match[0].length); @@ -356,7 +356,7 @@ class DisplaySearch extends Display { } static getSearchQueryFromLocation(url) { - let match = /^[^\?#]*\?(?:[^&#]*&)?query=([^&#]*)/.exec(url); + let match = /^[^?#]*\?(?:[^&#]*&)?query=([^&#]*)/.exec(url); return match !== null ? decodeURIComponent(match[1]) : null; } } diff --git a/ext/fg/js/document.js b/ext/fg/js/document.js index 3dd12a40..10dea7df 100644 --- a/ext/fg/js/document.js +++ b/ext/fg/js/document.js @@ -17,7 +17,7 @@ */ -const REGEX_TRANSPARENT_COLOR = /rgba\s*\([^\)]*,\s*0(?:\.0+)?\s*\)/; +const REGEX_TRANSPARENT_COLOR = /rgba\s*\([^)]*,\s*0(?:\.0+)?\s*\)/; function docSetImposterStyle(style, propertyName, value) { style.setProperty(propertyName, value, 'important'); diff --git a/ext/fg/js/popup.js b/ext/fg/js/popup.js index df784029..c40e5d60 100644 --- a/ext/fg/js/popup.js +++ b/ext/fg/js/popup.js @@ -303,7 +303,7 @@ class Popup { } static getColorInfo(cssColor) { - const m = /^\s*rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d\.]+)\s*)?\)\s*$/.exec(cssColor); + const m = /^\s*rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)\s*$/.exec(cssColor); if (m === null) { return null; } const m4 = m[4]; diff --git a/ext/mixed/js/audio.js b/ext/mixed/js/audio.js index 7d5ffedd..35f283a4 100644 --- a/ext/mixed/js/audio.js +++ b/ext/mixed/js/audio.js @@ -68,7 +68,7 @@ class TextToSpeechAudio { } static createFromUri(ttsUri) { - const m = /^tts:[^#\?]*\?([^#]*)/.exec(ttsUri); + const m = /^tts:[^#?]*\?([^#]*)/.exec(ttsUri); if (m === null) { return null; } const searchParameters = {}; -- cgit v1.2.3 From ef833d2bea07cd2e979dd558eaba141f880063cb Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 25 Nov 2019 14:28:52 -0500 Subject: Use const rather than let where possible --- ext/bg/js/handlebars.js | 2 +- ext/bg/js/search-query-parser.js | 2 +- ext/bg/js/search.js | 2 +- ext/fg/js/frontend.js | 4 ++-- ext/fg/js/source.js | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/handlebars.js b/ext/bg/js/handlebars.js index d6307e1d..8f43cf9a 100644 --- a/ext/bg/js/handlebars.js +++ b/ext/bg/js/handlebars.js @@ -89,7 +89,7 @@ function handlebarsRegexReplace(...args) { let value = args[args.length - 1].fn(this); if (args.length >= 3) { try { - let flags = args.length > 3 ? args[2] : 'g'; + const flags = args.length > 3 ? args[2] : 'g'; const regex = new RegExp(args[0], flags); value = value.replace(regex, args[1]); } catch (e) { diff --git a/ext/bg/js/search-query-parser.js b/ext/bg/js/search-query-parser.js index 1a43347c..2bf24ce3 100644 --- a/ext/bg/js/search-query-parser.js +++ b/ext/bg/js/search-query-parser.js @@ -134,7 +134,7 @@ class QueryParser { }); } if (this.search.options.parsing.enableMecabParser) { - let mecabResults = await apiTextParseMecab(text, this.search.getOptionsContext()); + const mecabResults = await apiTextParseMecab(text, this.search.getOptionsContext()); for (const mecabDictName in mecabResults) { results.push({ name: `MeCab: ${mecabDictName}`, diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index 552b7a59..e5cdf272 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -356,7 +356,7 @@ class DisplaySearch extends Display { } static getSearchQueryFromLocation(url) { - let match = /^[^?#]*\?(?:[^&#]*&)?query=([^&#]*)/.exec(url); + const match = /^[^?#]*\?(?:[^&#]*&)?query=([^&#]*)/.exec(url); return match !== null ? decodeURIComponent(match[1]) : null; } } diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index 16302e82..8297f54d 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -447,8 +447,8 @@ class Frontend { } getIndexOfTouch(touchList, identifier) { - for (let i in touchList) { - let t = touchList[i]; + for (const i in touchList) { + const t = touchList[i]; if (t.identifier === identifier) { return i; } diff --git a/ext/fg/js/source.js b/ext/fg/js/source.js index 886093d7..e6b991c4 100644 --- a/ext/fg/js/source.js +++ b/ext/fg/js/source.js @@ -361,7 +361,7 @@ class TextSourceElement { let consumed = 0; let content = ''; - for (let currentChar of this.content || '') { + for (const currentChar of this.content || '') { if (consumed >= length) { break; } else if (!currentChar.match(IGNORE_TEXT_PATTERN)) { -- cgit v1.2.3 From acb70f126cd87234b442fd599061f1b7539c846b Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 25 Nov 2019 14:35:53 -0500 Subject: Update unused arguments --- ext/bg/js/anki.js | 10 +++++----- ext/bg/js/backend.js | 2 +- ext/bg/js/search.js | 4 ++-- ext/fg/js/api.js | 2 +- ext/fg/js/frontend.js | 4 ++-- ext/fg/js/source.js | 2 +- ext/mixed/js/display.js | 4 ++-- 7 files changed, 14 insertions(+), 14 deletions(-) (limited to 'ext/fg') diff --git a/ext/bg/js/anki.js b/ext/bg/js/anki.js index 9f851f13..ac45784b 100644 --- a/ext/bg/js/anki.js +++ b/ext/bg/js/anki.js @@ -108,11 +108,11 @@ class AnkiConnect { */ class AnkiNull { - async addNote(note) { + async addNote() { return null; } - async canAddNotes(notes) { + async canAddNotes() { return []; } @@ -124,15 +124,15 @@ class AnkiNull { return []; } - async getModelFieldNames(modelName) { + async getModelFieldNames() { return []; } - async guiBrowse(query) { + async guiBrowse() { return []; } - async findNoteIds(notes) { + async findNoteIds() { return []; } } diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 4190116b..73df7cf5 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -177,7 +177,7 @@ class Backend { } } - checkLastError(e) { + checkLastError() { // NOP } } diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index e5cdf272..a98d7a9a 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -167,7 +167,7 @@ class DisplaySearch extends Display { this.onSearchQueryUpdated(query, true); } - onPopState(e) { + onPopState() { const query = DisplaySearch.getSearchQueryFromLocation(window.location.href) || ''; if (this.query !== null) { if (this.isWanakanaEnabled()) { @@ -245,7 +245,7 @@ class DisplaySearch extends Display { initClipboardMonitor() { // ignore copy from search page - window.addEventListener('copy', (e) => { + window.addEventListener('copy', () => { this.clipboardPrevText = document.getSelection().toString().trim(); }); } diff --git a/ext/fg/js/api.js b/ext/fg/js/api.js index f881b23d..0e100b59 100644 --- a/ext/fg/js/api.js +++ b/ext/fg/js/api.js @@ -113,6 +113,6 @@ function _apiInvoke(action, params={}) { }); } -function _apiCheckLastError(e) { +function _apiCheckLastError() { // NOP } diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index 8297f54d..bcdfd152 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -122,7 +122,7 @@ class Frontend { } } - onMouseOut(e) { + onMouseOut() { this.popupTimerClear(); } @@ -135,7 +135,7 @@ class Frontend { } } - onAuxClick(e) { + onAuxClick() { this.preventNextContextMenu = false; } diff --git a/ext/fg/js/source.js b/ext/fg/js/source.js index e6b991c4..a84feed4 100644 --- a/ext/fg/js/source.js +++ b/ext/fg/js/source.js @@ -375,7 +375,7 @@ class TextSourceElement { return this.content.length; } - setStartOffset(length) { + setStartOffset() { return 0; } diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index b454bf59..2396805a 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -42,7 +42,7 @@ class Display { this.setInteractive(true); } - onError(error) { + onError(_error) { throw new Error('Override me'); } @@ -90,7 +90,7 @@ class Display { } } - onGlossaryMouseMove(e) { + onGlossaryMouseMove() { this.clickScanPrevent = true; } -- cgit v1.2.3 From 5a1046bc906a74ca39906a52acc62fc702a658f2 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 26 Nov 2019 22:01:54 -0500 Subject: Update arrow-parens to always --- .eslintrc.json | 2 +- ext/bg/js/anki.js | 2 +- ext/bg/js/api.js | 2 +- ext/bg/js/backend-api-forwarder.js | 4 ++-- ext/bg/js/backend.js | 6 +++--- ext/bg/js/context.js | 2 +- ext/bg/js/database.js | 22 +++++++++++----------- ext/bg/js/dictionary.js | 10 +++++----- ext/bg/js/options.js | 6 +++--- ext/bg/js/profile-conditions.js | 2 +- ext/bg/js/request.js | 2 +- ext/bg/js/search-query-parser.js | 4 ++-- ext/bg/js/settings-dictionaries.js | 10 +++++----- ext/bg/js/settings-profiles.js | 2 +- ext/bg/js/settings.js | 8 ++++---- ext/bg/js/translator.js | 8 ++++---- ext/bg/js/util.js | 4 ++-- ext/fg/js/frontend-api-receiver.js | 4 ++-- ext/fg/js/popup.js | 4 ++-- ext/mixed/js/core.js | 2 +- 20 files changed, 53 insertions(+), 53 deletions(-) (limited to 'ext/fg') diff --git a/.eslintrc.json b/.eslintrc.json index fce4b884..0e3b939a 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -8,7 +8,7 @@ "/ext/bg/js/templates.js" ], "rules": { - "arrow-parens": ["error", "as-needed"], + "arrow-parens": ["error", "always"], "comma-dangle": ["error", "never"], "curly": ["error", "all"], "dot-notation": "error", diff --git a/ext/bg/js/anki.js b/ext/bg/js/anki.js index ac45784b..17b93620 100644 --- a/ext/bg/js/anki.js +++ b/ext/bg/js/anki.js @@ -74,7 +74,7 @@ class AnkiConnect { async findNoteIds(notes) { await this.checkVersion(); - const actions = notes.map(note => ({ + const actions = notes.map((note) => ({ action: 'findNotes', params: { query: `deck:"${AnkiConnect.escapeQuery(note.deckName)}" ${AnkiConnect.fieldsToQuery(note.fields)}` diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index d5256acb..b489b8d2 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -207,7 +207,7 @@ async function apiDefinitionsAddable(definitions, modes, optionsContext) { } if (cannotAdd.length > 0) { - const noteIdsArray = await anki.findNoteIds(cannotAdd.map(e => e[0])); + const noteIdsArray = await anki.findNoteIds(cannotAdd.map((e) => e[0])); for (let i = 0, ii = Math.min(cannotAdd.length, noteIdsArray.length); i < ii; ++i) { const noteIds = noteIdsArray[i]; if (noteIds.length > 0) { diff --git a/ext/bg/js/backend-api-forwarder.js b/ext/bg/js/backend-api-forwarder.js index 979afd16..db4d30b9 100644 --- a/ext/bg/js/backend-api-forwarder.js +++ b/ext/bg/js/backend-api-forwarder.js @@ -37,8 +37,8 @@ class BackendApiForwarder { const forwardPort = chrome.tabs.connect(tabId, {name: 'frontend-api-receiver'}); - port.onMessage.addListener(message => forwardPort.postMessage(message)); - forwardPort.onMessage.addListener(message => port.postMessage(message)); + port.onMessage.addListener((message) => forwardPort.postMessage(message)); + forwardPort.onMessage.addListener((message) => port.postMessage(message)); port.onDisconnect.addListener(() => forwardPort.disconnect()); forwardPort.onDisconnect.addListener(() => port.disconnect()); } diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 73df7cf5..d9f9b586 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -60,7 +60,7 @@ class Backend { this.applyOptions(); const callback = () => this.checkLastError(chrome.runtime.lastError); - chrome.tabs.query({}, tabs => { + chrome.tabs.query({}, (tabs) => { for (const tab of tabs) { chrome.tabs.sendMessage(tab.id, {action: 'optionsUpdate', params: {source}}, callback); } @@ -77,8 +77,8 @@ class Backend { const handler = handlers[action]; const promise = handler(params, sender); promise.then( - result => callback({result}), - error => callback({error: errorToJson(error)}) + (result) => callback({result}), + (error) => callback({error: errorToJson(error)}) ); } diff --git a/ext/bg/js/context.js b/ext/bg/js/context.js index b288a79a..38a82636 100644 --- a/ext/bg/js/context.js +++ b/ext/bg/js/context.js @@ -63,7 +63,7 @@ window.addEventListener('DOMContentLoaded', () => { depth: 0, url: window.location.href }; - apiOptionsGet(optionsContext).then(options => { + apiOptionsGet(optionsContext).then((options) => { const toggle = document.querySelector('#enable-search'); toggle.checked = options.general.enable; toggle.addEventListener('change', () => apiCommandExec('toggle'), false); diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index c53c9f77..a20d5f15 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -257,7 +257,7 @@ class Database { const dbTerms = dbTransaction.objectStore('tagMeta'); const dbIndex = dbTerms.index('name'); const only = IDBKeyRange.only(name); - await Database.getAll(dbIndex, only, null, row => { + await Database.getAll(dbIndex, only, null, (row) => { if (title === row.dictionary) { result = row; } @@ -273,7 +273,7 @@ class Database { const dbTransaction = this.db.transaction(['dictionaries'], 'readonly'); const dbDictionaries = dbTransaction.objectStore('dictionaries'); - await Database.getAll(dbDictionaries, null, null, info => results.push(info)); + await Database.getAll(dbDictionaries, null, null, (info) => results.push(info)); return results; } @@ -308,7 +308,7 @@ class Database { counts.push(null); const index = i; const query2 = IDBKeyRange.only(dictionaryNames[i]); - const countPromise = Database.getCounts(targets, query2).then(v => counts[index] = v); + const countPromise = Database.getCounts(targets, query2).then((v) => counts[index] = v); countPromises.push(countPromise); } await Promise.all(countPromises); @@ -346,7 +346,7 @@ class Database { } }; - const indexDataLoaded = async summary => { + const indexDataLoaded = async (summary) => { if (summary.version > 3) { throw new Error('Unsupported dictionary version'); } @@ -522,13 +522,13 @@ class Database { await indexDataLoaded(summary); - const buildTermBankName = index => `term_bank_${index + 1}.json`; - const buildTermMetaBankName = index => `term_meta_bank_${index + 1}.json`; - const buildKanjiBankName = index => `kanji_bank_${index + 1}.json`; - const buildKanjiMetaBankName = index => `kanji_meta_bank_${index + 1}.json`; - const buildTagBankName = index => `tag_bank_${index + 1}.json`; + const buildTermBankName = (index) => `term_bank_${index + 1}.json`; + const buildTermMetaBankName = (index) => `term_meta_bank_${index + 1}.json`; + const buildKanjiBankName = (index) => `kanji_bank_${index + 1}.json`; + const buildKanjiMetaBankName = (index) => `kanji_meta_bank_${index + 1}.json`; + const buildTagBankName = (index) => `tag_bank_${index + 1}.json`; - const countBanks = namer => { + const countBanks = (namer) => { let count = 0; while (zip.files[namer(count)]) { ++count; @@ -657,7 +657,7 @@ class Database { const counts = {}; for (const [objectStoreName, index] of targets) { const n = objectStoreName; - const countPromise = Database.getCount(index, query).then(count => counts[n] = count); + const countPromise = Database.getCount(index, query).then((count) => counts[n] = count); countPromises.push(countPromise); } return Promise.all(countPromises).then(() => counts); diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js index 409bed85..0b35e32e 100644 --- a/ext/bg/js/dictionary.js +++ b/ext/bg/js/dictionary.js @@ -99,8 +99,8 @@ function dictTermsCompressTags(definitions) { let lastPartOfSpeech = ''; for (const definition of definitions) { - const dictionary = JSON.stringify(definition.definitionTags.filter(tag => tag.category === 'dictionary').map(tag => tag.name).sort()); - const partOfSpeech = JSON.stringify(definition.definitionTags.filter(tag => tag.category === 'partOfSpeech').map(tag => tag.name).sort()); + const dictionary = JSON.stringify(definition.definitionTags.filter((tag) => tag.category === 'dictionary').map((tag) => tag.name).sort()); + const partOfSpeech = JSON.stringify(definition.definitionTags.filter((tag) => tag.category === 'partOfSpeech').map((tag) => tag.name).sort()); const filterOutCategories = []; @@ -117,7 +117,7 @@ function dictTermsCompressTags(definitions) { lastPartOfSpeech = partOfSpeech; } - definition.definitionTags = definition.definitionTags.filter(tag => !filterOutCategories.includes(tag.category)); + definition.definitionTags = definition.definitionTags.filter((tag) => !filterOutCategories.includes(tag.category)); } } @@ -231,7 +231,7 @@ function dictTermsMergeByGloss(result, definitions, appendTo, mergedIndices) { result.reading.add(definition.reading); for (const tag of definition.definitionTags) { - if (!definitionsByGloss[gloss].definitionTags.find(existingTag => existingTag.name === tag.name)) { + if (!definitionsByGloss[gloss].definitionTags.find((existingTag) => existingTag.name === tag.name)) { definitionsByGloss[gloss].definitionTags.push(tag); } } @@ -246,7 +246,7 @@ function dictTermsMergeByGloss(result, definitions, appendTo, mergedIndices) { } for (const tag of definition.termTags) { - if (!result.expressions.get(definition.expression).get(definition.reading).find(existingTag => existingTag.name === tag.name)) { + if (!result.expressions.get(definition.expression).get(definition.reading).find((existingTag) => existingTag.name === tag.name)) { result.expressions.get(definition.expression).get(definition.reading).push(tag); } } diff --git a/ext/bg/js/options.js b/ext/bg/js/options.js index 358a6b45..e53a8a13 100644 --- a/ext/bg/js/options.js +++ b/ext/bg/js/options.js @@ -429,7 +429,7 @@ function optionsUpdateVersion(options, defaultProfileOptions) { function optionsLoad() { return new Promise((resolve, reject) => { - chrome.storage.local.get(['options'], store => { + chrome.storage.local.get(['options'], (store) => { const error = chrome.runtime.lastError; if (error) { reject(new Error(error)); @@ -437,7 +437,7 @@ function optionsLoad() { resolve(store.options); } }); - }).then(optionsStr => { + }).then((optionsStr) => { if (typeof optionsStr === 'string') { const options = JSON.parse(optionsStr); if (isObject(options)) { @@ -447,7 +447,7 @@ function optionsLoad() { return {}; }).catch(() => { return {}; - }).then(options => { + }).then((options) => { return ( Array.isArray(options.profiles) ? optionsUpdateVersion(options, {}) : diff --git a/ext/bg/js/profile-conditions.js b/ext/bg/js/profile-conditions.js index 8272e5dd..ebc6680a 100644 --- a/ext/bg/js/profile-conditions.js +++ b/ext/bg/js/profile-conditions.js @@ -86,7 +86,7 @@ const profileConditionsDescriptor = { placeholder: 'Comma separated list of domains', defaultValue: 'example.com', transformCache: {}, - transform: (optionValue) => optionValue.split(/[,;\s]+/).map(v => v.trim().toLowerCase()).filter(v => v.length > 0), + transform: (optionValue) => optionValue.split(/[,;\s]+/).map((v) => v.trim().toLowerCase()).filter((v) => v.length > 0), transformReverse: (transformedOptionValue) => transformedOptionValue.join(', '), validateTransformed: (transformedOptionValue) => (transformedOptionValue.length > 0), test: ({url}, transformedOptionValue) => _profileConditionTestDomainList(url, transformedOptionValue) diff --git a/ext/bg/js/request.js b/ext/bg/js/request.js index 3afc1506..7d73d49b 100644 --- a/ext/bg/js/request.js +++ b/ext/bg/js/request.js @@ -29,7 +29,7 @@ function requestJson(url, action, params) { } else { xhr.send(); } - }).then(responseText => { + }).then((responseText) => { try { return JSON.parse(responseText); } diff --git a/ext/bg/js/search-query-parser.js b/ext/bg/js/search-query-parser.js index 74ef32d8..c7222212 100644 --- a/ext/bg/js/search-query-parser.js +++ b/ext/bg/js/search-query-parser.js @@ -107,7 +107,7 @@ class QueryParser { } getParseResult() { - return this.parseResults.find(r => r.id === this.selectedParser); + return this.parseResults.find((r) => r.id === this.selectedParser); } async setText(text) { @@ -216,7 +216,7 @@ class QueryParser { static processParseResultForDisplay(result) { return result.map((term) => { - return term.filter(part => part.text.trim()).map((part) => { + return term.filter((part) => part.text.trim()).map((part) => { return { text: Array.from(part.text), reading: part.reading, diff --git a/ext/bg/js/settings-dictionaries.js b/ext/bg/js/settings-dictionaries.js index 177379b0..065a8abc 100644 --- a/ext/bg/js/settings-dictionaries.js +++ b/ext/bg/js/settings-dictionaries.js @@ -62,8 +62,8 @@ class SettingsDictionaryListUI { this.updateDictionaryOrder(); - const titles = this.dictionaryEntries.map(e => e.dictionaryInfo.title); - const removeKeys = Object.keys(this.optionsDictionaries).filter(key => titles.indexOf(key) < 0); + const titles = this.dictionaryEntries.map((e) => e.dictionaryInfo.title); + const removeKeys = Object.keys(this.optionsDictionaries).filter((key) => titles.indexOf(key) < 0); if (removeKeys.length > 0) { for (const key of toIterable(removeKeys)) { delete this.optionsDictionaries[key]; @@ -161,7 +161,7 @@ class SettingsDictionaryListUI { delete n.dataset.dict; $(n).modal('hide'); - const index = this.dictionaryEntries.findIndex(e => e.dictionaryInfo.title === title); + const index = this.dictionaryEntries.findIndex((e) => e.dictionaryInfo.title === title); if (index >= 0) { this.dictionaryEntries[index].deleteDictionary(); } @@ -377,7 +377,7 @@ async function onDatabaseUpdated(options) { updateMainDictionarySelect(options, dictionaries); - const {counts, total} = await utilDatabaseGetDictionaryCounts(dictionaries.map(v => v.title), true); + const {counts, total} = await utilDatabaseGetDictionaryCounts(dictionaries.map((v) => v.title), true); dictionaryUI.setCounts(counts, total); } catch (e) { dictionaryErrorsShow([e]); @@ -564,7 +564,7 @@ async function onDictionaryImport(e) { dictionaryErrorsShow(null); dictionarySpinnerShow(true); - const setProgress = percent => dictProgress.find('.progress-bar').css('width', `${percent}%`); + const setProgress = (percent) => dictProgress.find('.progress-bar').css('width', `${percent}%`); const updateProgress = (total, current) => { setProgress(current / total * 100.0); if (storageEstimate.mostRecent !== null && !storageUpdateStats.isUpdating) { diff --git a/ext/bg/js/settings-profiles.js b/ext/bg/js/settings-profiles.js index 9532e3eb..8c218e97 100644 --- a/ext/bg/js/settings-profiles.js +++ b/ext/bg/js/settings-profiles.js @@ -147,7 +147,7 @@ function profileOptionsCreateCopyName(name, profiles, maxUniqueAttempts) { let i = 0; while (true) { const newName = `${prefix}${space}${index}${suffix}`; - if (i++ >= maxUniqueAttempts || profiles.findIndex(profile => profile.name === newName) < 0) { + if (i++ >= maxUniqueAttempts || profiles.findIndex((profile) => profile.name === newName) < 0) { return newName; } if (typeof index !== 'number') { diff --git a/ext/bg/js/settings.js b/ext/bg/js/settings.js index 48026794..abe6f389 100644 --- a/ext/bg/js/settings.js +++ b/ext/bg/js/settings.js @@ -18,7 +18,7 @@ async function getOptionsArray() { const optionsFull = await apiOptionsGetFull(); - return optionsFull.profiles.map(profile => profile.options); + return optionsFull.profiles.map((profile) => profile.options); } async function formRead(options) { @@ -484,12 +484,12 @@ async function ankiDeckAndModelPopulate(options) { const deckNames = await utilAnkiGetDeckNames(); const ankiDeck = $('.anki-deck'); ankiDeck.find('option').remove(); - deckNames.sort().forEach(name => ankiDeck.append($('