diff options
Diffstat (limited to 'ext')
41 files changed, 2135 insertions, 1049 deletions
diff --git a/ext/bg/css/settings.css b/ext/bg/css/settings.css index 63cead6b..815a88fa 100644 --- a/ext/bg/css/settings.css +++ b/ext/bg/css/settings.css @@ -187,6 +187,23 @@ input[type=checkbox].storage-button-checkbox { margin: 0; } +.error-data-show-button { + display: inline-block; + margin-left: 0.5em; + cursor: pointer; +} +.error-data-show-button:after { + content: "\2026"; + font-weight: bold; +} + +.error-data-container { + margin-top: 0.25em; + font-family: 'Courier New', Courier, monospace; + white-space: pre; + overflow-x: auto; +} + [data-show-for-browser], [data-show-for-operating-system] { display: none; diff --git a/ext/bg/data/options-schema.json b/ext/bg/data/options-schema.json index c086052b..a20a0619 100644 --- a/ext/bg/data/options-schema.json +++ b/ext/bg/data/options-schema.json @@ -65,6 +65,7 @@ "general", "audio", "scanning", + "translation", "dictionaries", "parsing", "anki" @@ -91,6 +92,9 @@ "popupVerticalOffset2", "popupHorizontalTextPosition", "popupVerticalTextPosition", + "popupScalingFactor", + "popupScaleRelativeToPageZoom", + "popupScaleRelativeToVisualViewport", "showGuide", "compactTags", "compactGlossaries", @@ -166,6 +170,18 @@ "enum": ["default", "before", "after", "left", "right"], "default": "before" }, + "popupScalingFactor": { + "type": "number", + "default": 1 + }, + "popupScaleRelativeToPageZoom": { + "type": "boolean", + "default": false + }, + "popupScaleRelativeToVisualViewport": { + "type": "boolean", + "default": true + }, "showGuide": { "type": "boolean", "default": true @@ -335,6 +351,43 @@ } } }, + "translation": { + "type": "object", + "required": [ + "convertHalfWidthCharacters", + "convertNumericCharacters", + "convertAlphabeticCharacters", + "convertHiraganaToKatakana", + "convertKatakanaToHiragana" + ], + "properties": { + "convertHalfWidthCharacters": { + "type": "string", + "enum": ["false", "true", "variant"], + "default": "false" + }, + "convertNumericCharacters": { + "type": "string", + "enum": ["false", "true", "variant"], + "default": "false" + }, + "convertAlphabeticCharacters": { + "type": "string", + "enum": ["false", "true", "variant"], + "default": "false" + }, + "convertHiraganaToKatakana": { + "type": "string", + "enum": ["false", "true", "variant"], + "default": "false" + }, + "convertKatakanaToHiragana": { + "type": "string", + "enum": ["false", "true", "variant"], + "default": "variant" + } + } + }, "dictionaries": { "type": "object", "additionalProperties": { @@ -366,6 +419,7 @@ "enableScanningParser", "enableMecabParser", "selectedParser", + "termSpacing", "readingMode" ], "properties": { @@ -381,9 +435,13 @@ "type": ["string", "null"], "default": null }, + "termSpacing": { + "type": "boolean", + "default": true + }, "readingMode": { "type": "string", - "enum": ["hiragana", "katakana", "romaji"], + "enum": ["hiragana", "katakana", "romaji", "none"], "default": "hiragana" } } diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js index 906aaa30..285b8016 100644 --- a/ext/bg/js/api.js +++ b/ext/bg/js/api.js @@ -25,6 +25,10 @@ function apiAudioGetUrl(definition, source, optionsContext) { return _apiInvoke('audioGetUrl', {definition, source, optionsContext}); } +function apiGetDisplayTemplatesHtml() { + return _apiInvoke('getDisplayTemplatesHtml'); +} + function _apiInvoke(action, params={}) { const data = {action, params}; return new Promise((resolve, reject) => { diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 28b0201e..eeab68a5 100644 --- a/ext/bg/js/backend.js +++ b/ext/bg/js/backend.js @@ -51,9 +51,12 @@ class Backend { this.onOptionsUpdated('background'); - if (chrome.commands !== null && typeof chrome.commands === 'object') { + if (isObject(chrome.commands) && isObject(chrome.commands.onCommand)) { chrome.commands.onCommand.addListener((command) => this._runCommand(command)); } + if (isObject(chrome.tabs) && isObject(chrome.tabs.onZoomChange)) { + chrome.tabs.onZoomChange.addListener((info) => this._onZoomChange(info)); + } chrome.runtime.onMessage.addListener(this.onMessage.bind(this)); const options = this.getOptionsSync(this.optionsContext); @@ -94,6 +97,11 @@ class Backend { } } + _onZoomChange({tabId, oldZoomFactor, newZoomFactor}) { + const callback = () => this.checkLastError(chrome.runtime.lastError); + chrome.tabs.sendMessage(tabId, {action: 'zoomChanged', params: {oldZoomFactor, newZoomFactor}}, callback); + } + applyOptions() { const options = this.getOptionsSync(this.optionsContext); if (!options.general.enable) { @@ -299,8 +307,8 @@ class Backend { const [definitions, sourceLength] = await this.translator.findTermsInternal( text.substring(0, options.scanning.length), dictEnabledSet(options), - options.scanning.alphanumeric, - {} + {}, + options ); if (definitions.length > 0) { dictTermsSort(definitions); @@ -522,6 +530,38 @@ class Backend { return result; } + async _onApiGetDisplayTemplatesHtml() { + const url = chrome.runtime.getURL('/mixed/display-templates.html'); + return await requestText(url, 'GET'); + } + + _onApiGetZoom(params, sender) { + if (!sender || !sender.tab) { + return Promise.reject(new Error('Invalid tab')); + } + + return new Promise((resolve, reject) => { + const tabId = sender.tab.id; + if (!( + chrome.tabs !== null && + typeof chrome.tabs === 'object' && + typeof chrome.tabs.getZoom === 'function' + )) { + // Not supported + resolve({zoomFactor: 1.0}); + return; + } + chrome.tabs.getZoom(tabId, (zoomFactor) => { + const e = chrome.runtime.lastError; + if (e) { + reject(new Error(e.message)); + } else { + resolve({zoomFactor}); + } + }); + }); + } + // Command handlers async _onCommandSearch(params) { @@ -735,7 +775,9 @@ Backend._messageHandlers = new Map([ ['frameInformationGet', (self, ...args) => self._onApiFrameInformationGet(...args)], ['injectStylesheet', (self, ...args) => self._onApiInjectStylesheet(...args)], ['getEnvironmentInfo', (self, ...args) => self._onApiGetEnvironmentInfo(...args)], - ['clipboardGet', (self, ...args) => self._onApiClipboardGet(...args)] + ['clipboardGet', (self, ...args) => self._onApiClipboardGet(...args)], + ['getDisplayTemplatesHtml', (self, ...args) => self._onApiGetDisplayTemplatesHtml(...args)], + ['getZoom', (self, ...args) => self._onApiGetZoom(...args)] ]); Backend._commandHandlers = new Map([ diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index 42a143f3..e87cc64b 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -225,7 +225,7 @@ class Database { } async findTermMetaBulk(termList, titles) { - return this.findGenericBulk('termMeta', 'expression', termList, titles, Database.createMeta); + return this.findGenericBulk('termMeta', 'expression', termList, titles, Database.createTermMeta); } async findKanjiBulk(kanjiList, titles) { @@ -233,7 +233,7 @@ class Database { } async findKanjiMetaBulk(kanjiList, titles) { - return this.findGenericBulk('kanjiMeta', 'character', kanjiList, titles, Database.createMeta); + return this.findGenericBulk('kanjiMeta', 'character', kanjiList, titles, Database.createKanjiMeta); } async findGenericBulk(tableName, indexName, indexValueList, titles, createResult) { @@ -632,13 +632,12 @@ class Database { }; } - static createMeta(row, index) { - return { - index, - mode: row.mode, - data: row.data, - dictionary: row.dictionary - }; + static createTermMeta({expression, mode, data, dictionary}, index) { + return {expression, mode, data, dictionary, index}; + } + + static createKanjiMeta({character, mode, data, dictionary}, index) { + return {character, mode, data, dictionary, index}; } static getAll(dbIndex, query, context, processRow) { diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js index 92adc532..67128725 100644 --- a/ext/bg/js/dictionary.js +++ b/ext/bg/js/dictionary.js @@ -67,7 +67,7 @@ function dictTermsSort(definitions, dictionaries=null) { i = v2.source.length - v1.source.length; if (i !== 0) { return i; } - i = v2.reasons.length - v1.reasons.length; + i = v1.reasons.length - v2.reasons.length; if (i !== 0) { return i; } i = v2.score - v1.score; @@ -147,8 +147,9 @@ function dictTermsGroup(definitions, dictionaries) { definitions: groupDefs, expression: firstDef.expression, reading: firstDef.reading, + furiganaSegments: firstDef.furiganaSegments, reasons: firstDef.reasons, - termTags: groupDefs[0].termTags, + termTags: firstDef.termTags, score: groupDefs.reduce((p, v) => v.score > p ? v.score : p, Number.MIN_SAFE_INTEGER), source: firstDef.source }); diff --git a/ext/bg/js/handlebars.js b/ext/bg/js/handlebars.js index 6d1581be..62f89ee4 100644 --- a/ext/bg/js/handlebars.js +++ b/ext/bg/js/handlebars.js @@ -61,7 +61,7 @@ function handlebarsFuriganaPlain(options) { function handlebarsKanjiLinks(options) { let result = ''; for (const c of options.fn(this)) { - if (jpIsKanji(c)) { + if (jpIsCharCodeKanji(c.charCodeAt(0))) { result += `<a href="#" class="kanji-link">${c}</a>`; } else { result += c; diff --git a/ext/bg/js/mecab.js b/ext/bg/js/mecab.js index 8bcbb91c..34ecd728 100644 --- a/ext/bg/js/mecab.js +++ b/ext/bg/js/mecab.js @@ -20,7 +20,7 @@ class Mecab { constructor() { this.port = null; - this.listeners = {}; + this.listeners = new Map(); this.sequence = 0; } @@ -55,17 +55,18 @@ class Mecab { if (this.port === null) { return; } this.port.disconnect(); this.port = null; - this.listeners = {}; + this.listeners.clear(); this.sequence = 0; } onNativeMessage({sequence, data}) { - if (hasOwn(this.listeners, sequence)) { - const {callback, timer} = this.listeners[sequence]; - clearTimeout(timer); - callback(data); - delete this.listeners[sequence]; - } + const listener = this.listeners.get(sequence); + if (typeof listener === 'undefined') { return; } + + const {callback, timer} = listener; + clearTimeout(timer); + callback(data); + this.listeners.delete(sequence); } invoke(action, params) { @@ -75,13 +76,13 @@ class Mecab { return new Promise((resolve, reject) => { const sequence = this.sequence++; - this.listeners[sequence] = { + this.listeners.set(sequence, { callback: resolve, timer: setTimeout(() => { - delete this.listeners[sequence]; + this.listeners.delete(sequence); reject(new Error(`Mecab invoke timed out in ${Mecab.timeout} ms`)); }, Mecab.timeout) - }; + }); this.port.postMessage({action, params, sequence}); }); diff --git a/ext/bg/js/options.js b/ext/bg/js/options.js index 8021672b..d93862bf 100644 --- a/ext/bg/js/options.js +++ b/ext/bg/js/options.js @@ -279,6 +279,9 @@ function profileOptionsCreateDefaults() { popupVerticalOffset2: 0, popupHorizontalTextPosition: 'below', popupVerticalTextPosition: 'before', + popupScalingFactor: 1, + popupScaleRelativeToPageZoom: false, + popupScaleRelativeToVisualViewport: true, showGuide: true, compactTags: false, compactGlossaries: false, @@ -316,12 +319,21 @@ function profileOptionsCreateDefaults() { enableOnSearchPage: true }, + translation: { + convertHalfWidthCharacters: 'false', + convertNumericCharacters: 'false', + convertAlphabeticCharacters: 'false', + convertHiraganaToKatakana: 'false', + convertKatakanaToHiragana: 'variant' + }, + dictionaries: {}, parsing: { enableScanningParser: true, enableMecabParser: false, selectedParser: null, + termSpacing: true, readingMode: 'hiragana' }, diff --git a/ext/bg/js/request.js b/ext/bg/js/request.js index b584c9a9..02eed6fb 100644 --- a/ext/bg/js/request.js +++ b/ext/bg/js/request.js @@ -17,10 +17,10 @@ */ -function requestJson(url, action, params) { +function requestText(url, action, params) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); - xhr.overrideMimeType('application/json'); + xhr.overrideMimeType('text/plain'); xhr.addEventListener('load', () => resolve(xhr.responseText)); xhr.addEventListener('error', () => reject(new Error('Failed to connect'))); xhr.open(action, url); @@ -29,12 +29,16 @@ function requestJson(url, action, params) { } else { xhr.send(); } - }).then((responseText) => { - try { - return JSON.parse(responseText); - } - catch (e) { - return Promise.reject(new Error('Invalid response')); - } }); } + +async function requestJson(url, action, params) { + const responseText = await requestText(url, action, params); + try { + return JSON.parse(responseText); + } catch (e) { + const error = new Error(`Invalid response (${e.message || e})`); + error.data = {url, action, params, responseText}; + throw error; + } +} diff --git a/ext/bg/js/search-frontend.js b/ext/bg/js/search-frontend.js index 2fe50a13..e453ccef 100644 --- a/ext/bg/js/search-frontend.js +++ b/ext/bg/js/search-frontend.js @@ -27,7 +27,7 @@ async function searchFrontendSetup() { const ignoreNodes = ['.scan-disable', '.scan-disable *']; if (!options.scanning.enableOnPopupExpressions) { - ignoreNodes.push('.expression-scan-toggle', '.expression-scan-toggle *'); + ignoreNodes.push('.source-text', '.source-text *'); } window.frontendInitializationData = {depth: 1, ignoreNodes, proxy: false}; diff --git a/ext/bg/js/search-query-parser.js b/ext/bg/js/search-query-parser.js index 0b3eccbd..e8e6d11f 100644 --- a/ext/bg/js/search-query-parser.js +++ b/ext/bg/js/search-query-parser.js @@ -17,73 +17,47 @@ */ -class QueryParser { +class QueryParser extends TextScanner { constructor(search) { + super(document.querySelector('#query-parser'), [], [], []); this.search = search; - this.pendingLookup = false; - this.clickScanPrevent = false; this.parseResults = []; this.selectedParser = null; this.queryParser = document.querySelector('#query-parser'); this.queryParserSelect = document.querySelector('#query-parser-select'); - - this.queryParser.addEventListener('mousedown', (e) => this.onMouseDown(e)); - this.queryParser.addEventListener('mouseup', (e) => this.onMouseUp(e)); } onError(error) { logError(error, false); } - onMouseDown(e) { - if (DOM.isMouseButtonPressed(e, 'primary')) { - this.clickScanPrevent = false; - } + onClick(e) { + super.onClick(e); + this.searchAt(e.clientX, e.clientY, 'click'); } - onMouseUp(e) { - if ( - this.search.options.scanning.enablePopupSearch && - !this.clickScanPrevent && - DOM.isMouseButtonPressed(e, 'primary') - ) { - const selectText = this.search.options.scanning.selectText; - this.onTermLookup(e, {disableScroll: true, selectText}); - } - } + async onSearchSource(textSource, cause) { + if (textSource === null) { return null; } - onMouseMove(e) { - if (this.pendingLookup || DOM.isMouseButtonDown(e, 'primary')) { - return; - } + this.setTextSourceScanLength(textSource, this.search.options.scanning.length); + const searchText = textSource.text(); + if (searchText.length === 0) { return; } - const scanningOptions = this.search.options.scanning; - const scanningModifier = scanningOptions.modifier; - if (!( - TextScanner.isScanningModifierPressed(scanningModifier, e) || - (scanningOptions.middleMouse && DOM.isMouseButtonDown(e, 'auxiliary')) - )) { - return; - } + const {definitions, length} = await apiTermsFind(searchText, {}, this.search.getOptionsContext()); + if (definitions.length === 0) { return null; } - const selectText = this.search.options.scanning.selectText; - this.onTermLookup(e, {disableScroll: true, disableHistory: true, selectText}); - } + textSource.setEndOffset(length); - onMouseLeave(e) { - this.clickScanPrevent = true; - clearTimeout(e.target.dataset.timer); - delete e.target.dataset.timer; - } + this.search.setContent('terms', {definitions, context: { + focus: false, + disableHistory: cause === 'mouse' ? true : false, + sentence: {text: searchText, offset: 0}, + url: window.location.href + }}); - onTermLookup(e, params) { - this.pendingLookup = true; - (async () => { - await this.search.onTermLookup(e, params); - this.pendingLookup = false; - })(); + return {definitions, type: 'terms'}; } onParserChange(e) { @@ -93,6 +67,32 @@ class QueryParser { this.renderParseResult(this.getParseResult()); } + getMouseEventListeners() { + return [ + [this.node, 'click', this.onClick.bind(this)], + [this.node, 'mousedown', this.onMouseDown.bind(this)], + [this.node, 'mousemove', this.onMouseMove.bind(this)], + [this.node, 'mouseover', this.onMouseOver.bind(this)], + [this.node, 'mouseout', this.onMouseOut.bind(this)] + ]; + } + + getTouchEventListeners() { + return [ + [this.node, 'auxclick', this.onAuxClick.bind(this)], + [this.node, 'touchstart', this.onTouchStart.bind(this)], + [this.node, 'touchend', this.onTouchEnd.bind(this)], + [this.node, 'touchcancel', this.onTouchCancel.bind(this)], + [this.node, 'touchmove', this.onTouchMove.bind(this), {passive: false}], + [this.node, 'contextmenu', this.onContextMenu.bind(this)] + ]; + } + + setOptions(options) { + super.setOptions(options); + this.queryParser.dataset.termSpacing = `${options.parsing.termSpacing}`; + } + refreshSelectedParser() { if (this.parseResults.length > 0) { if (this.selectedParser === null) { @@ -156,10 +156,6 @@ class QueryParser { terms: previewTerms, preview: true }); - - for (const charElement of this.queryParser.querySelectorAll('.query-parser-char')) { - this.activateScanning(charElement); - } } renderParserSelect() { @@ -190,27 +186,6 @@ class QueryParser { 'query-parser.html', {terms: QueryParser.processParseResultForDisplay(parseResult.parsedText)} ); - - for (const charElement of this.queryParser.querySelectorAll('.query-parser-char')) { - this.activateScanning(charElement); - } - } - - activateScanning(element) { - element.addEventListener('mousemove', (e) => { - clearTimeout(e.target.dataset.timer); - if (this.search.options.scanning.modifier === 'none') { - e.target.dataset.timer = setTimeout(() => { - this.onMouseMove(e); - delete e.target.dataset.timer; - }, this.search.options.scanning.delay); - } else { - this.onMouseMove(e); - } - }); - element.addEventListener('mouseleave', (e) => { - this.onMouseLeave(e); - }); } static processParseResultForDisplay(result) { diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index a4103ef2..f5c641a8 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -220,12 +220,12 @@ class DisplaySearch extends Display { this.updateSearchButton(); if (valid) { const {definitions} = await apiTermsFind(query, details, this.optionsContext); - this.setContentTerms(definitions, { + this.setContent('terms', {definitions, context: { focus: false, disableHistory: true, sentence: {text: query, offset: 0}, url: window.location.href - }); + }}); } else { this.container.textContent = ''; } @@ -236,6 +236,11 @@ class DisplaySearch extends Display { } } + async updateOptions(options) { + await super.updateOptions(options); + this.queryParser.setOptions(this.options); + } + initClipboardMonitor() { // ignore copy from search page window.addEventListener('copy', () => { @@ -260,7 +265,7 @@ class DisplaySearch extends Display { text !== this.clipboardPreviousText ) { this.clipboardPreviousText = text; - if (jpIsJapaneseText(text)) { + if (jpIsStringPartiallyJapanese(text)) { this.setQuery(this.isWanakanaEnabled() ? window.wanakana.toKana(text) : text); window.history.pushState(null, '', `${window.location.pathname}?query=${encodeURIComponent(text)}`); this.onSearchQueryUpdated(this.query.value, true); diff --git a/ext/bg/js/settings/anki.js b/ext/bg/js/settings/anki.js index 5f7989b8..9adb2f2a 100644 --- a/ext/bg/js/settings/anki.js +++ b/ext/bg/js/settings/anki.js @@ -37,13 +37,35 @@ function _ankiSetError(error) { if (error) { node.hidden = false; node.textContent = `${error}`; - } - else { + _ankiSetErrorData(node, error); + } else { node.hidden = true; node.textContent = ''; } } +function _ankiSetErrorData(node, error) { + const data = error.data; + let message = ''; + if (typeof data !== 'undefined') { + message += `${JSON.stringify(data, null, 4)}\n\n`; + } + message += `${error.stack}`.trimRight(); + + const button = document.createElement('a'); + button.className = 'error-data-show-button'; + + const content = document.createElement('div'); + content.className = 'error-data-container'; + content.textContent = message; + content.hidden = true; + + button.addEventListener('click', () => content.hidden = !content.hidden, false); + + node.appendChild(button); + node.appendChild(content); +} + function _ankiSetDropdownOptions(dropdown, optionValues) { const fragment = document.createDocumentFragment(); for (const optionValue of optionValues) { diff --git a/ext/bg/js/settings/main.js b/ext/bg/js/settings/main.js index 56828a15..3bf65eda 100644 --- a/ext/bg/js/settings/main.js +++ b/ext/bg/js/settings/main.js @@ -44,6 +44,9 @@ async function formRead(options) { options.general.popupVerticalOffset = parseInt($('#popup-vertical-offset').val(), 10); options.general.popupHorizontalOffset2 = parseInt($('#popup-horizontal-offset2').val(), 0); options.general.popupVerticalOffset2 = parseInt($('#popup-vertical-offset2').val(), 10); + options.general.popupScalingFactor = parseInt($('#popup-scaling-factor').val(), 10); + options.general.popupScaleRelativeToPageZoom = $('#popup-scale-relative-to-page-zoom').prop('checked'); + options.general.popupScaleRelativeToVisualViewport = $('#popup-scale-relative-to-visual-viewport').prop('checked'); options.general.popupTheme = $('#popup-theme').val(); options.general.popupOuterTheme = $('#popup-outer-theme').val(); options.general.customPopupCss = $('#custom-popup-css').val(); @@ -69,8 +72,15 @@ async function formRead(options) { options.scanning.modifier = $('#scan-modifier-key').val(); options.scanning.popupNestingMaxDepth = parseInt($('#popup-nesting-max-depth').val(), 10); + options.translation.convertHalfWidthCharacters = $('#translation-convert-half-width-characters').val(); + options.translation.convertNumericCharacters = $('#translation-convert-numeric-characters').val(); + options.translation.convertAlphabeticCharacters = $('#translation-convert-alphabetic-characters').val(); + options.translation.convertHiraganaToKatakana = $('#translation-convert-hiragana-to-katakana').val(); + options.translation.convertKatakanaToHiragana = $('#translation-convert-katakana-to-hiragana').val(); + options.parsing.enableScanningParser = $('#parsing-scan-enable').prop('checked'); options.parsing.enableMecabParser = $('#parsing-mecab-enable').prop('checked'); + options.parsing.termSpacing = $('#parsing-term-spacing').prop('checked'); options.parsing.readingMode = $('#parsing-reading-mode').val(); const optionsAnkiEnableOld = options.anki.enable; @@ -109,6 +119,9 @@ async function formWrite(options) { $('#popup-vertical-offset').val(options.general.popupVerticalOffset); $('#popup-horizontal-offset2').val(options.general.popupHorizontalOffset2); $('#popup-vertical-offset2').val(options.general.popupVerticalOffset2); + $('#popup-scaling-factor').val(options.general.popupScalingFactor); + $('#popup-scale-relative-to-page-zoom').prop('checked', options.general.popupScaleRelativeToPageZoom); + $('#popup-scale-relative-to-visual-viewport').prop('checked', options.general.popupScaleRelativeToVisualViewport); $('#popup-theme').val(options.general.popupTheme); $('#popup-outer-theme').val(options.general.popupOuterTheme); $('#custom-popup-css').val(options.general.customPopupCss); @@ -134,8 +147,15 @@ async function formWrite(options) { $('#scan-modifier-key').val(options.scanning.modifier); $('#popup-nesting-max-depth').val(options.scanning.popupNestingMaxDepth); + $('#translation-convert-half-width-characters').val(options.translation.convertHalfWidthCharacters); + $('#translation-convert-numeric-characters').val(options.translation.convertNumericCharacters); + $('#translation-convert-alphabetic-characters').val(options.translation.convertAlphabeticCharacters); + $('#translation-convert-hiragana-to-katakana').val(options.translation.convertHiraganaToKatakana); + $('#translation-convert-katakana-to-hiragana').val(options.translation.convertKatakanaToHiragana); + $('#parsing-scan-enable').prop('checked', options.parsing.enableScanningParser); $('#parsing-mecab-enable').prop('checked', options.parsing.enableMecabParser); + $('#parsing-term-spacing').prop('checked', options.parsing.termSpacing); $('#parsing-reading-mode').val(options.parsing.readingMode); $('#anki-enable').prop('checked', options.anki.enable); diff --git a/ext/bg/js/settings/popup-preview-frame.js b/ext/bg/js/settings/popup-preview-frame.js index 2b727cbd..37a4b416 100644 --- a/ext/bg/js/settings/popup-preview-frame.js +++ b/ext/bg/js/settings/popup-preview-frame.js @@ -35,7 +35,6 @@ class SettingsPopupPreview { async prepare() { // Setup events - window.addEventListener('resize', (e) => this.onWindowResize(e), false); window.addEventListener('message', (e) => this.onMessage(e), false); const themeDarkCheckbox = document.querySelector('#theme-dark-checkbox'); @@ -96,16 +95,6 @@ class SettingsPopupPreview { return result; } - onWindowResize() { - if (this.frontend === null) { return; } - const textSource = this.textSource; - if (textSource === null) { return; } - - const elementRect = textSource.getRect(); - const writingMode = textSource.getWritingMode(); - this.frontend.popup.showContent(elementRect, writingMode); - } - onMessage(e) { const {action, params} = e.data; const handler = SettingsPopupPreview._messageHandlers.get(action); @@ -159,10 +148,11 @@ class SettingsPopupPreview { const range = document.createRange(); range.selectNode(textNode); - const source = new TextSourceRange(range, range.toString(), null); + const source = new TextSourceRange(range, range.toString(), null, null); try { await this.frontend.onSearchSource(source, 'script'); + this.frontend.setCurrentTextSource(source); } finally { source.cleanup(); } diff --git a/ext/bg/js/templates.js b/ext/bg/js/templates.js index eae4e014..2f65be31 100644 --- a/ext/bg/js/templates.js +++ b/ext/bg/js/templates.js @@ -1,178 +1,5 @@ (function() { var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; -templates['kanji.html'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"if","hash":{},"fn":container.program(2, data, 0),"inverse":container.program(8, data, 0),"data":data})) != null ? stack1 : ""); -},"2":function(container,depth0,helpers,partials,data) { - var stack1; - - return "<table class=\"info-output\">\n" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.data : depth0),{"name":"each","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</table>\n"; -},"3":function(container,depth0,helpers,partials,data) { - var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return " <tr>\n <th>" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.notes : depth0),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.program(6, data, 0),"data":data})) != null ? stack1 : "") - + "</th>\n <td>" - + container.escapeExpression(((helper = (helper = helpers.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(alias1,{"name":"value","hash":{},"data":data}) : helper))) - + "</td>\n </tr>\n"; -},"4":function(container,depth0,helpers,partials,data) { - var helper; - - return container.escapeExpression(((helper = (helper = helpers.notes || (depth0 != null ? depth0.notes : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"notes","hash":{},"data":data}) : helper))); -},"6":function(container,depth0,helpers,partials,data) { - var helper; - - return container.escapeExpression(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"name","hash":{},"data":data}) : helper))); -},"8":function(container,depth0,helpers,partials,data) { - return "No data found\n"; -},"10":function(container,depth0,helpers,partials,data) { - var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return "<div class=\"entry\" data-type=\"kanji\">\n <div class=\"actions\">\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.addable : depth0),{"name":"if","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " <img src=\"/mixed/img/entry-current.svg\" class=\"current\" title=\"Current entry (Alt + Up/Down/Home/End/PgUp/PgDn)\" alt>\n </div>\n\n <div class=\"glyph expression-scan-toggle\">" - + container.escapeExpression(((helper = (helper = helpers.character || (depth0 != null ? depth0.character : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(alias1,{"name":"character","hash":{},"data":data}) : helper))) - + "</div>\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.frequencies : depth0),{"name":"if","hash":{},"fn":container.program(13, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.tags : depth0),{"name":"if","hash":{},"fn":container.program(16, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n <table class=\"table table-condensed glyph-data\">\n <tr>\n <th>Glossary</th>\n <th>Readings</th>\n <th>Statistics</th>\n </tr>\n <tr>\n <td class=\"glossary\">\n" - + ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.glossary : depth0)) != null ? stack1["1"] : stack1),{"name":"if","hash":{},"fn":container.program(19, data, 0),"inverse":container.program(22, data, 0),"data":data})) != null ? stack1 : "") - + " </td>\n <td class=\"reading\">\n " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.onyomi : depth0),{"name":"if","hash":{},"fn":container.program(24, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.kunyomi : depth0),{"name":"if","hash":{},"fn":container.program(27, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n </td>\n <td>" - + ((stack1 = container.invokePartial(partials.table,depth0,{"name":"table","hash":{"data":((stack1 = (depth0 != null ? depth0.stats : depth0)) != null ? stack1.misc : stack1)},"data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "") - + "</td>\n </tr>\n <tr>\n <th colspan=\"3\">Classifications</th>\n </tr>\n <tr>\n <td colspan=\"3\">" - + ((stack1 = container.invokePartial(partials.table,depth0,{"name":"table","hash":{"data":((stack1 = (depth0 != null ? depth0.stats : depth0)) != null ? stack1["class"] : stack1)},"data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "") - + "</td>\n </tr>\n <tr>\n <th colspan=\"3\">Codepoints</th>\n </tr>\n <tr>\n <td colspan=\"3\">" - + ((stack1 = container.invokePartial(partials.table,depth0,{"name":"table","hash":{"data":((stack1 = (depth0 != null ? depth0.stats : depth0)) != null ? stack1.code : stack1)},"data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "") - + "</td>\n </tr>\n <tr>\n <th colspan=\"3\">Dictionary Indices</th>\n </tr>\n <tr>\n <td colspan=\"3\">" - + ((stack1 = container.invokePartial(partials.table,depth0,{"name":"table","hash":{"data":((stack1 = (depth0 != null ? depth0.stats : depth0)) != null ? stack1.index : stack1)},"data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "") - + "</td>\n </tr>\n </table>\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.debug : depth0),{"name":"if","hash":{},"fn":container.program(29, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</div>\n"; -},"11":function(container,depth0,helpers,partials,data) { - return " <a href=\"#\" class=\"action-view-note pending disabled\"><img src=\"/mixed/img/view-note.svg\" title=\"View added note (Alt + V)\" alt></a>\n <a href=\"#\" class=\"action-add-note pending disabled\" data-mode=\"kanji\"><img src=\"/mixed/img/add-term-kanji.svg\" title=\"Add Kanji (Alt + K)\" alt></a>\n"; -},"13":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <div>\n" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.frequencies : depth0),{"name":"each","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </div>\n"; -},"14":function(container,depth0,helpers,partials,data) { - var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; - - return " <span class=\"label label-default tag-frequency\">" - + alias4(((helper = (helper = helpers.dictionary || (depth0 != null ? depth0.dictionary : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"dictionary","hash":{},"data":data}) : helper))) - + ":" - + alias4(((helper = (helper = helpers.frequency || (depth0 != null ? depth0.frequency : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"frequency","hash":{},"data":data}) : helper))) - + "</span>\n"; -},"16":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <div>\n" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.tags : depth0),{"name":"each","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </div>\n"; -},"17":function(container,depth0,helpers,partials,data) { - var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; - - return " <span class=\"label label-default tag-" - + alias4(((helper = (helper = helpers.category || (depth0 != null ? depth0.category : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"category","hash":{},"data":data}) : helper))) - + "\" title=\"" - + alias4(((helper = (helper = helpers.notes || (depth0 != null ? depth0.notes : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"notes","hash":{},"data":data}) : helper))) - + "\">" - + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper))) - + "</span>\n"; -},"19":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <ol>" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.glossary : depth0),{"name":"each","hash":{},"fn":container.program(20, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</ol>\n"; -},"20":function(container,depth0,helpers,partials,data) { - return "<li><span class=\"glossary-item\">" - + container.escapeExpression(container.lambda(depth0, depth0)) - + "</span></li>"; -},"22":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <span class=\"glossary-item\">" - + container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.glossary : depth0)) != null ? stack1["0"] : stack1), depth0)) - + "</span>\n"; -},"24":function(container,depth0,helpers,partials,data) { - var stack1; - - return "<dl>" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.onyomi : depth0),{"name":"each","hash":{},"fn":container.program(25, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</dl>"; -},"25":function(container,depth0,helpers,partials,data) { - return "<dd>" - + container.escapeExpression(container.lambda(depth0, depth0)) - + "</dd>"; -},"27":function(container,depth0,helpers,partials,data) { - var stack1; - - return "<dl>" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.kunyomi : depth0),{"name":"each","hash":{},"fn":container.program(25, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</dl>"; -},"29":function(container,depth0,helpers,partials,data) { - var stack1, helper, options, buffer = - " <pre>"; - stack1 = ((helper = (helper = helpers.dumpObject || (depth0 != null ? depth0.dumpObject : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"dumpObject","hash":{},"fn":container.program(30, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),options) : helper)); - if (!helpers.dumpObject) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { buffer += stack1; } - return buffer + "</pre>\n"; -},"30":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = container.lambda(depth0, depth0)) != null ? stack1 : ""); -},"32":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return "<div class=\"term-navigation\">\n <a href=\"#\" " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.source : depth0),{"name":"if","hash":{},"fn":container.program(33, data, 0, blockParams, depths),"inverse":container.program(35, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "") - + "><img src=\"/mixed/img/source-term.svg\" title=\"Source term (Alt + B)\" alt></a>\n <a href=\"#\" " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.next : depth0),{"name":"if","hash":{},"fn":container.program(37, data, 0, blockParams, depths),"inverse":container.program(39, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "") - + "><img src=\"/mixed/img/source-term.svg\" style=\"transform: scaleX(-1);\" title=\"Next term (Alt + F)\" alt></a>\n</div>\n" - + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.definitions : depth0),{"name":"each","hash":{},"fn":container.program(41, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"33":function(container,depth0,helpers,partials,data) { - return "class=\"source-term\""; -},"35":function(container,depth0,helpers,partials,data) { - return "class=\"source-term invisible\""; -},"37":function(container,depth0,helpers,partials,data) { - return "class=\"next-term\""; -},"39":function(container,depth0,helpers,partials,data) { - return "class=\"next-term invisible\""; -},"41":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return ((stack1 = helpers.unless.call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.first),{"name":"unless","hash":{},"fn":container.program(42, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = container.invokePartial(partials.kanji,depth0,{"name":"kanji","hash":{"root":(depths[1] != null ? depths[1].root : depths[1]),"addable":(depths[1] != null ? depths[1].addable : depths[1]),"debug":(depths[1] != null ? depths[1].debug : depths[1])},"data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : ""); -},"42":function(container,depth0,helpers,partials,data) { - return "<hr>"; -},"44":function(container,depth0,helpers,partials,data) { - return "<p class=\"note\">No results found</p>\n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return "\n\n" - + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.definitions : depth0),{"name":"if","hash":{},"fn":container.program(32, data, 0, blockParams, depths),"inverse":container.program(44, data, 0, blockParams, depths),"data":data})) != null ? stack1 : ""); -},"main_d": function(fn, props, container, depth0, data, blockParams, depths) { - - var decorators = container.decorators; - - fn = decorators.inline(fn,props,container,{"name":"inline","hash":{},"fn":container.program(1, data, 0, blockParams, depths),"inverse":container.noop,"args":["table"],"data":data}) || fn; - fn = decorators.inline(fn,props,container,{"name":"inline","hash":{},"fn":container.program(10, data, 0, blockParams, depths),"inverse":container.noop,"args":["kanji"],"data":data}) || fn; - return fn; - } - -,"useDecorators":true,"usePartial":true,"useData":true,"useDepths":true}); templates['query-parser.html'] = template({"1":function(container,depth0,helpers,partials,data) { var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}); @@ -225,300 +52,4 @@ templates['query-parser.html'] = template({"1":function(container,depth0,helpers } ,"useDecorators":true,"usePartial":true,"useData":true,"useDepths":true}); -templates['terms.html'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), buffer = - "<div class=\"dict-"; - stack1 = ((helper = (helper = helpers.sanitizeCssClass || (depth0 != null ? depth0.sanitizeCssClass : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"sanitizeCssClass","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(alias1,options) : helper)); - if (!helpers.sanitizeCssClass) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { buffer += stack1; } - return buffer + "\">\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.definitionTags : depth0),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.only : depth0),{"name":"if","hash":{},"fn":container.program(9, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ((stack1 = helpers["if"].call(alias1,((stack1 = (depth0 != null ? depth0.glossary : depth0)) != null ? stack1["1"] : stack1),{"name":"if","hash":{},"fn":container.program(13, data, 0),"inverse":container.program(19, data, 0),"data":data})) != null ? stack1 : "") - + "</div>\n"; -},"2":function(container,depth0,helpers,partials,data) { - var helper; - - return container.escapeExpression(((helper = (helper = helpers.dictionary || (depth0 != null ? depth0.dictionary : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"dictionary","hash":{},"data":data}) : helper))); -},"4":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return " <div " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.compactGlossaries : depth0),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ">\n" - + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.definitionTags : depth0),{"name":"each","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </div>\n"; -},"5":function(container,depth0,helpers,partials,data) { - return "class=\"compact-info\""; -},"7":function(container,depth0,helpers,partials,data) { - var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; - - return " <span class=\"label label-default tag-" - + alias4(((helper = (helper = helpers.category || (depth0 != null ? depth0.category : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"category","hash":{},"data":data}) : helper))) - + "\" title=\"" - + alias4(((helper = (helper = helpers.notes || (depth0 != null ? depth0.notes : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"notes","hash":{},"data":data}) : helper))) - + "\">" - + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper))) - + "</span>\n"; -},"9":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return " <div " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.compactGlossaries : depth0),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ">\n (" - + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.only : depth0),{"name":"each","hash":{},"fn":container.program(10, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " only)\n </div>\n"; -},"10":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = container.lambda(depth0, depth0)) != null ? stack1 : "") - + ((stack1 = helpers.unless.call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.last),{"name":"unless","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n"; -},"11":function(container,depth0,helpers,partials,data) { - return ", "; -},"13":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return " <ul " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.compactGlossaries : depth0),{"name":"if","hash":{},"fn":container.program(14, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ">\n" - + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.glossary : depth0),{"name":"each","hash":{},"fn":container.program(16, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </ul>\n"; -},"14":function(container,depth0,helpers,partials,data) { - return "class=\"compact-glossary\""; -},"16":function(container,depth0,helpers,partials,data) { - var stack1, helper, options, buffer = - " <li><span class=\"glossary-item\">"; - stack1 = ((helper = (helper = helpers.multiLine || (depth0 != null ? depth0.multiLine : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"multiLine","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),options) : helper)); - if (!helpers.multiLine) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { buffer += stack1; } - return buffer + "</span></li>\n"; -},"17":function(container,depth0,helpers,partials,data) { - return container.escapeExpression(container.lambda(depth0, depth0)); -},"19":function(container,depth0,helpers,partials,data) { - var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), buffer = - " <div class=\"glossary-item " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.compactGlossaries : depth0),{"name":"if","hash":{},"fn":container.program(20, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\">"; - stack1 = ((helper = (helper = helpers.multiLine || (depth0 != null ? depth0.multiLine : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"multiLine","hash":{},"fn":container.program(22, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(alias1,options) : helper)); - if (!helpers.multiLine) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { buffer += stack1; } - return buffer + "</div>\n"; -},"20":function(container,depth0,helpers,partials,data) { - return "compact-glossary"; -},"22":function(container,depth0,helpers,partials,data) { - var stack1; - - return container.escapeExpression(container.lambda(((stack1 = (depth0 != null ? depth0.glossary : depth0)) != null ? stack1["0"] : stack1), depth0)); -},"24":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return "<div class=\"entry\" data-type=\"term\">\n <div class=\"actions\">\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.addable : depth0),{"name":"if","hash":{},"fn":container.program(25, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ((stack1 = helpers.unless.call(alias1,(depth0 != null ? depth0.merged : depth0),{"name":"unless","hash":{},"fn":container.program(27, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " <img src=\"/mixed/img/entry-current.svg\" class=\"current\" title=\"Current entry (Alt + Up/Down/Home/End/PgUp/PgDn)\" alt>\n </div>\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.merged : depth0),{"name":"if","hash":{},"fn":container.program(30, data, 0, blockParams, depths),"inverse":container.program(45, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.reasons : depth0),{"name":"if","hash":{},"fn":container.program(48, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.frequencies : depth0),{"name":"if","hash":{},"fn":container.program(52, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n <div class=\"glossary\">\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.grouped : depth0),{"name":"if","hash":{},"fn":container.program(55, data, 0, blockParams, depths),"inverse":container.program(61, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "") - + " </div>\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.debug : depth0),{"name":"if","hash":{},"fn":container.program(64, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</div>\n"; -},"25":function(container,depth0,helpers,partials,data) { - return " <a href=\"#\" class=\"action-view-note pending disabled\"><img src=\"/mixed/img/view-note.svg\" title=\"View added note (Alt + V)\" alt></a>\n <a href=\"#\" class=\"action-add-note pending disabled\" data-mode=\"term-kanji\"><img src=\"/mixed/img/add-term-kanji.svg\" title=\"Add expression (Alt + E)\" alt></a>\n <a href=\"#\" class=\"action-add-note pending disabled\" data-mode=\"term-kana\"><img src=\"/mixed/img/add-term-kana.svg\" title=\"Add reading (Alt + R)\" alt></a>\n"; -},"27":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.playback : depth0),{"name":"if","hash":{},"fn":container.program(28, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"28":function(container,depth0,helpers,partials,data) { - return " <a href=\"#\" class=\"action-play-audio\"><img src=\"/mixed/img/play-audio.svg\" title=\"Play audio (Alt + P)\" alt></a>\n"; -},"30":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.expressions : depth0),{"name":"each","hash":{},"fn":container.program(31, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"31":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", buffer = - "<div class=\"expression expression-scan-toggle\"><span class=\"expression-" - + container.escapeExpression(((helper = (helper = helpers.termFrequency || (depth0 != null ? depth0.termFrequency : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"termFrequency","hash":{},"data":data}) : helper))) - + "\">"; - stack1 = ((helper = (helper = helpers.kanjiLinks || (depth0 != null ? depth0.kanjiLinks : depth0)) != null ? helper : alias2),(options={"name":"kanjiLinks","hash":{},"fn":container.program(32, data, 0, blockParams, depths),"inverse":container.noop,"data":data}),(typeof helper === alias3 ? helper.call(alias1,options) : helper)); - if (!helpers.kanjiLinks) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { buffer += stack1; } - return buffer + "</span><div class=\"peek-wrapper\">" - + ((stack1 = helpers["if"].call(alias1,(depths[1] != null ? depths[1].playback : depths[1]),{"name":"if","hash":{},"fn":container.program(35, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.termTags : depth0),{"name":"if","hash":{},"fn":container.program(37, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.frequencies : depth0),{"name":"if","hash":{},"fn":container.program(40, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</div><span class=\"" - + ((stack1 = helpers["if"].call(alias1,(data && data.last),{"name":"if","hash":{},"fn":container.program(43, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\">、</span></div>"; -},"32":function(container,depth0,helpers,partials,data) { - var stack1, helper, options; - - stack1 = ((helper = (helper = helpers.furigana || (depth0 != null ? depth0.furigana : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"furigana","hash":{},"fn":container.program(33, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),options) : helper)); - if (!helpers.furigana) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { return stack1; } - else { return ''; } -},"33":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = container.lambda(depth0, depth0)) != null ? stack1 : ""); -},"35":function(container,depth0,helpers,partials,data) { - return "<a href=\"#\" class=\"action-play-audio\"><img src=\"/mixed/img/play-audio.svg\" title=\"Play audio\" alt></a>"; -},"37":function(container,depth0,helpers,partials,data) { - var stack1; - - return "<div class=\"tags\">" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.termTags : depth0),{"name":"each","hash":{},"fn":container.program(38, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</div>"; -},"38":function(container,depth0,helpers,partials,data) { - var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; - - return " <span class=\"label label-default tag-" - + alias4(((helper = (helper = helpers.category || (depth0 != null ? depth0.category : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"category","hash":{},"data":data}) : helper))) - + "\" title=\"" - + alias4(((helper = (helper = helpers.notes || (depth0 != null ? depth0.notes : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"notes","hash":{},"data":data}) : helper))) - + "\">" - + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper))) - + "</span>\n"; -},"40":function(container,depth0,helpers,partials,data) { - var stack1; - - return "<div class=\"frequencies\">" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.frequencies : depth0),{"name":"each","hash":{},"fn":container.program(41, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "</div>"; -},"41":function(container,depth0,helpers,partials,data) { - var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; - - return " <span class=\"label label-default tag-frequency\">" - + alias4(((helper = (helper = helpers.dictionary || (depth0 != null ? depth0.dictionary : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"dictionary","hash":{},"data":data}) : helper))) - + ":" - + alias4(((helper = (helper = helpers.frequency || (depth0 != null ? depth0.frequency : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"frequency","hash":{},"data":data}) : helper))) - + "</span>\n"; -},"43":function(container,depth0,helpers,partials,data) { - return "invisible"; -},"45":function(container,depth0,helpers,partials,data) { - var stack1, helper, options, alias1=depth0 != null ? depth0 : (container.nullContext || {}), buffer = - " <div class=\"expression expression-scan-toggle\">"; - stack1 = ((helper = (helper = helpers.kanjiLinks || (depth0 != null ? depth0.kanjiLinks : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"kanjiLinks","hash":{},"fn":container.program(32, 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; } - return buffer + "</div>\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.termTags : depth0),{"name":"if","hash":{},"fn":container.program(46, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"46":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <div style=\"display: inline-block;\">\n" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.termTags : depth0),{"name":"each","hash":{},"fn":container.program(7, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </div>\n"; -},"48":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <div class=\"reasons\">\n" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.reasons : depth0),{"name":"each","hash":{},"fn":container.program(49, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </div>\n"; -},"49":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <span class=\"reasons\">" - + container.escapeExpression(container.lambda(depth0, depth0)) - + "</span> " - + ((stack1 = helpers.unless.call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.last),{"name":"unless","hash":{},"fn":container.program(50, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n"; -},"50":function(container,depth0,helpers,partials,data) { - return "«"; -},"52":function(container,depth0,helpers,partials,data) { - var stack1; - - return " <div>\n" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.frequencies : depth0),{"name":"each","hash":{},"fn":container.program(53, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </div>\n"; -},"53":function(container,depth0,helpers,partials,data) { - var helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}), alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; - - return " <span class=\"label label-default tag-frequency\">" - + alias4(((helper = (helper = helpers.dictionary || (depth0 != null ? depth0.dictionary : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"dictionary","hash":{},"data":data}) : helper))) - + ":" - + alias4(((helper = (helper = helpers.frequency || (depth0 != null ? depth0.frequency : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"frequency","hash":{},"data":data}) : helper))) - + "</span>\n"; -},"55":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),((stack1 = (depth0 != null ? depth0.definitions : depth0)) != null ? stack1["1"] : stack1),{"name":"if","hash":{},"fn":container.program(56, data, 0, blockParams, depths),"inverse":container.program(59, data, 0, blockParams, depths),"data":data})) != null ? stack1 : ""); -},"56":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return " <ol>\n" - + ((stack1 = helpers.each.call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.definitions : depth0),{"name":"each","hash":{},"fn":container.program(57, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " </ol>\n"; -},"57":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return " <li>" - + ((stack1 = container.invokePartial(partials.definition,depth0,{"name":"definition","hash":{"compactGlossaries":(depths[1] != null ? depths[1].compactGlossaries : depths[1])},"data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "") - + "</li>\n"; -},"59":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = container.invokePartial(partials.definition,((stack1 = (depth0 != null ? depth0.definitions : depth0)) != null ? stack1["0"] : stack1),{"name":"definition","hash":{"compactGlossaries":(depth0 != null ? depth0.compactGlossaries : depth0)},"data":data,"indent":" ","helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : ""); -},"61":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.merged : depth0),{"name":"if","hash":{},"fn":container.program(55, data, 0, blockParams, depths),"inverse":container.program(62, data, 0, blockParams, depths),"data":data})) != null ? stack1 : ""); -},"62":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = container.invokePartial(partials.definition,depth0,{"name":"definition","hash":{"compactGlossaries":(depth0 != null ? depth0.compactGlossaries : depth0)},"data":data,"indent":" ","helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : "") - + " "; -},"64":function(container,depth0,helpers,partials,data) { - var stack1, helper, options, buffer = - " <pre>"; - stack1 = ((helper = (helper = helpers.dumpObject || (depth0 != null ? depth0.dumpObject : depth0)) != null ? helper : helpers.helperMissing),(options={"name":"dumpObject","hash":{},"fn":container.program(33, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),options) : helper)); - if (!helpers.dumpObject) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { buffer += stack1; } - return buffer + "</pre>\n"; -},"66":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1, alias1=depth0 != null ? depth0 : (container.nullContext || {}); - - return "<div class=\"term-navigation\">\n <a href=\"#\" " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.source : depth0),{"name":"if","hash":{},"fn":container.program(67, data, 0, blockParams, depths),"inverse":container.program(69, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "") - + "><img src=\"/mixed/img/source-term.svg\" title=\"Source term (Alt + B)\" alt></a>\n <a href=\"#\" " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.next : depth0),{"name":"if","hash":{},"fn":container.program(71, data, 0, blockParams, depths),"inverse":container.program(73, data, 0, blockParams, depths),"data":data})) != null ? stack1 : "") - + "><img src=\"/mixed/img/source-term.svg\" style=\"transform: scaleX(-1);\" title=\"Next term (Alt + F)\" alt></a>\n</div>\n" - + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.definitions : depth0),{"name":"each","hash":{},"fn":container.program(75, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"67":function(container,depth0,helpers,partials,data) { - return "class=\"source-term\""; -},"69":function(container,depth0,helpers,partials,data) { - return "class=\"source-term invisible\""; -},"71":function(container,depth0,helpers,partials,data) { - return "class=\"next-term\""; -},"73":function(container,depth0,helpers,partials,data) { - return "class=\"next-term invisible\""; -},"75":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return ((stack1 = helpers.unless.call(depth0 != null ? depth0 : (container.nullContext || {}),(data && data.first),{"name":"unless","hash":{},"fn":container.program(76, data, 0, blockParams, depths),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = container.invokePartial(partials.term,depth0,{"name":"term","hash":{"compactGlossaries":(depths[1] != null ? depths[1].compactGlossaries : depths[1]),"playback":(depths[1] != null ? depths[1].playback : depths[1]),"addable":(depths[1] != null ? depths[1].addable : depths[1]),"merged":(depths[1] != null ? depths[1].merged : depths[1]),"grouped":(depths[1] != null ? depths[1].grouped : depths[1]),"debug":(depths[1] != null ? depths[1].debug : depths[1])},"data":data,"helpers":helpers,"partials":partials,"decorators":container.decorators})) != null ? stack1 : ""); -},"76":function(container,depth0,helpers,partials,data) { - return "<hr>"; -},"78":function(container,depth0,helpers,partials,data) { - return "<p class=\"note\">No results found.</p>\n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams,depths) { - var stack1; - - return "\n\n" - + ((stack1 = helpers["if"].call(depth0 != null ? depth0 : (container.nullContext || {}),(depth0 != null ? depth0.definitions : depth0),{"name":"if","hash":{},"fn":container.program(66, data, 0, blockParams, depths),"inverse":container.program(78, data, 0, blockParams, depths),"data":data})) != null ? stack1 : ""); -},"main_d": function(fn, props, container, depth0, data, blockParams, depths) { - - var decorators = container.decorators; - - fn = decorators.inline(fn,props,container,{"name":"inline","hash":{},"fn":container.program(1, data, 0, blockParams, depths),"inverse":container.noop,"args":["definition"],"data":data}) || fn; - fn = decorators.inline(fn,props,container,{"name":"inline","hash":{},"fn":container.program(24, data, 0, blockParams, depths),"inverse":container.noop,"args":["term"],"data":data}) || fn; - return fn; - } - -,"useDecorators":true,"usePartial":true,"useData":true,"useDepths":true}); })();
\ No newline at end of file diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index 7473c6ad..dfec54ac 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -121,16 +121,10 @@ class Translator { dictTermsSort(result.definitions, dictionaries); const expressions = []; - for (const expression of result.expressions.keys()) { - for (const reading of result.expressions.get(expression).keys()) { - const termTags = result.expressions.get(expression).get(reading); + for (const [expression, readingMap] of result.expressions.entries()) { + for (const [reading, termTags] of readingMap.entries()) { const score = termTags.map((tag) => tag.score).reduce((p, v) => p + v, 0); - expressions.push({ - expression: expression, - reading: reading, - termTags: dictTagsSort(termTags), - termFrequency: Translator.scoreToTermFrequency(score) - }); + expressions.push(Translator.createExpression(expression, reading, dictTagsSort(termTags), Translator.scoreToTermFrequency(score))); } } @@ -157,10 +151,10 @@ class Translator { async findTermsGrouped(text, details, options) { const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); - const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, details, options); const definitionsGrouped = dictTermsGroup(definitions, dictionaries); - await this.buildTermFrequencies(definitionsGrouped, titles); + await this.buildTermMeta(definitionsGrouped, titles); if (options.general.compactTags) { for (const definition of definitionsGrouped) { @@ -175,7 +169,7 @@ class Translator { const dictionaries = dictEnabledSet(options); const secondarySearchTitles = Object.keys(options.dictionaries).filter((dict) => options.dictionaries[dict].allowSecondarySearches); const titles = Object.keys(dictionaries); - const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, details, options); const {sequencedDefinitions, defaultDefinitions} = await this.getSequencedDefinitions(definitions, options.general.mainDictionary); const definitionsMerged = []; const mergedByTermIndices = new Set(); @@ -194,11 +188,11 @@ class Translator { const strayDefinitions = defaultDefinitions.filter((definition, index) => !mergedByTermIndices.has(index)); for (const groupedDefinition of dictTermsGroup(strayDefinitions, dictionaries)) { - groupedDefinition.expressions = [{expression: groupedDefinition.expression, reading: groupedDefinition.reading}]; + groupedDefinition.expressions = [Translator.createExpression(groupedDefinition.expression, groupedDefinition.reading)]; definitionsMerged.push(groupedDefinition); } - await this.buildTermFrequencies(definitionsMerged, titles); + await this.buildTermMeta(definitionsMerged, titles); if (options.general.compactTags) { for (const definition of definitionsMerged) { @@ -212,26 +206,24 @@ class Translator { async findTermsSplit(text, details, options) { const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); - const [definitions, length] = await this.findTermsInternal(text, dictionaries, options.scanning.alphanumeric, details); + const [definitions, length] = await this.findTermsInternal(text, dictionaries, details, options); - await this.buildTermFrequencies(definitions, titles); + await this.buildTermMeta(definitions, titles); return [definitions, length]; } - async findTermsInternal(text, dictionaries, alphanumeric, details) { - if (!alphanumeric && text.length > 0) { - const c = text[0]; - if (!jpIsKana(c) && !jpIsKanji(c)) { - return [[], 0]; - } + async findTermsInternal(text, dictionaries, details, options) { + text = Translator.getSearchableText(text, options); + if (text.length === 0) { + return [[], 0]; } const titles = Object.keys(dictionaries); const deinflections = ( details.wildcard ? await this.findTermWildcard(text, titles, details.wildcard) : - await this.findTermDeinflections(text, titles) + await this.findTermDeinflections(text, titles, options) ); let definitions = []; @@ -241,14 +233,19 @@ class Translator { definitionTags.push(dictTagBuildSource(definition.dictionary)); const termTags = await this.expandTags(definition.termTags, definition.dictionary); + const {expression, reading} = definition; + const furiganaSegments = jpDistributeFurigana(expression, reading); + definitions.push({ source: deinflection.source, + rawSource: deinflection.rawSource, reasons: deinflection.reasons, score: definition.score, id: definition.id, dictionary: definition.dictionary, - expression: definition.expression, - reading: definition.reading, + expression, + reading, + furiganaSegments, glossary: definition.glossary, definitionTags: dictTagsSort(definitionTags), termTags: dictTagsSort(termTags), @@ -262,7 +259,7 @@ class Translator { let length = 0; for (const definition of definitions) { - length = Math.max(length, definition.source.length); + length = Math.max(length, definition.rawSource.length); } return [definitions, length]; @@ -276,6 +273,7 @@ class Translator { return [{ source: text, + rawSource: text, term: text, rules: 0, definitions, @@ -283,9 +281,8 @@ class Translator { }]; } - async findTermDeinflections(text, titles) { - const text2 = jpKatakanaToHiragana(text); - const deinflections = (text === text2 ? this.getDeinflections(text) : this.getDeinflections2(text, text2)); + async findTermDeinflections(text, titles, options) { + const deinflections = this.getAllDeinflections(text, options); if (deinflections.length === 0) { return []; @@ -293,17 +290,15 @@ class Translator { const uniqueDeinflectionTerms = []; const uniqueDeinflectionArrays = []; - const uniqueDeinflectionsMap = {}; + const uniqueDeinflectionsMap = new Map(); for (const deinflection of deinflections) { const term = deinflection.term; - let deinflectionArray; - if (hasOwn(uniqueDeinflectionsMap, term)) { - deinflectionArray = uniqueDeinflectionsMap[term]; - } else { + let deinflectionArray = uniqueDeinflectionsMap.get(term); + if (typeof deinflectionArray === 'undefined') { deinflectionArray = []; uniqueDeinflectionTerms.push(term); uniqueDeinflectionArrays.push(deinflectionArray); - uniqueDeinflectionsMap[term] = deinflectionArray; + uniqueDeinflectionsMap.set(term, deinflectionArray); } deinflectionArray.push(deinflection); } @@ -323,30 +318,77 @@ class Translator { return deinflections.filter((e) => e.definitions.length > 0); } - getDeinflections(text) { + getAllDeinflections(text, options) { + const translationOptions = options.translation; + const textOptionVariantArray = [ + Translator.getTextOptionEntryVariants(translationOptions.convertHalfWidthCharacters), + Translator.getTextOptionEntryVariants(translationOptions.convertNumericCharacters), + Translator.getTextOptionEntryVariants(translationOptions.convertAlphabeticCharacters), + Translator.getTextOptionEntryVariants(translationOptions.convertHiraganaToKatakana), + Translator.getTextOptionEntryVariants(translationOptions.convertKatakanaToHiragana) + ]; + const deinflections = []; + const used = new Set(); + for (const [halfWidth, numeric, alphabetic, katakana, hiragana] of Translator.getArrayVariants(textOptionVariantArray)) { + let text2 = text; + let sourceMapping = null; + if (halfWidth) { + if (sourceMapping === null) { sourceMapping = Translator.createTextSourceMapping(text2); } + text2 = jpConvertHalfWidthKanaToFullWidth(text2, sourceMapping); + } + if (numeric) { + text2 = jpConvertNumericTofullWidth(text2); + } + if (alphabetic) { + if (sourceMapping === null) { sourceMapping = Translator.createTextSourceMapping(text2); } + text2 = jpConvertAlphabeticToKana(text2, sourceMapping); + } + if (katakana) { + text2 = jpHiraganaToKatakana(text2); + } + if (hiragana) { + text2 = jpKatakanaToHiragana(text2); + } - for (let i = text.length; i > 0; --i) { - const textSubstring = text.substring(0, i); - deinflections.push(...this.deinflector.deinflect(textSubstring)); + for (let i = text2.length; i > 0; --i) { + const text2Substring = text2.substring(0, i); + if (used.has(text2Substring)) { break; } + used.add(text2Substring); + for (const deinflection of this.deinflector.deinflect(text2Substring)) { + deinflection.rawSource = Translator.getDeinflectionRawSource(text, i, sourceMapping); + deinflections.push(deinflection); + } + } } - return deinflections; } - getDeinflections2(text1, text2) { - const deinflections = []; + static getTextOptionEntryVariants(value) { + switch (value) { + case 'true': return [true]; + case 'variant': return [false, true]; + default: return [false]; + } + } - for (let i = text1.length; i > 0; --i) { - const text1Substring = text1.substring(0, i); - const text2Substring = text2.substring(0, i); - deinflections.push(...this.deinflector.deinflect(text1Substring)); - if (text1Substring !== text2Substring) { - deinflections.push(...this.deinflector.deinflect(text2Substring)); - } + static getDeinflectionRawSource(source, length, sourceMapping) { + if (sourceMapping === null) { + return source.substring(0, length); } - return deinflections; + let result = ''; + let index = 0; + for (let i = 0; i < length; ++i) { + const c = sourceMapping[i]; + result += source.substring(index, index + c); + index += c; + } + return result; + } + + static createTextSourceMapping(text) { + return new Array(text.length).fill(1); } async findKanji(text, options) { @@ -370,31 +412,23 @@ class Translator { definitions.sort((a, b) => a.index - b.index); } - const kanjiList2 = []; for (const definition of definitions) { - kanjiList2.push(definition.character); - const tags = await this.expandTags(definition.tags, definition.dictionary); tags.push(dictTagBuildSource(definition.dictionary)); + dictTagsSort(tags); - definition.tags = dictTagsSort(tags); - definition.stats = await this.expandStats(definition.stats, definition.dictionary); - definition.frequencies = []; - } + const stats = await this.expandStats(definition.stats, definition.dictionary); - for (const meta of await this.database.findKanjiMetaBulk(kanjiList2, titles)) { - if (meta.mode !== 'freq') { continue; } - definitions[meta.index].frequencies.push({ - character: meta.character, - frequency: meta.data, - dictionary: meta.dictionary - }); + definition.tags = tags; + definition.stats = stats; } + await this.buildKanjiMeta(definitions, titles); + return definitions; } - async buildTermFrequencies(definitions, titles) { + async buildTermMeta(definitions, titles) { const terms = []; for (const definition of definitions) { if (definition.expressions) { @@ -411,34 +445,48 @@ class Translator { // Create mapping of unique terms const expressionsUnique = []; const termsUnique = []; - const termsUniqueMap = {}; + const termsUniqueMap = new Map(); for (let i = 0, ii = terms.length; i < ii; ++i) { const term = terms[i]; const expression = term.expression; - term.frequencies = []; - - if (hasOwn(termsUniqueMap, expression)) { - termsUniqueMap[expression].push(term); - } else { - const termList = [term]; + let termList = termsUniqueMap.get(expression); + if (typeof termList === 'undefined') { + termList = []; expressionsUnique.push(expression); termsUnique.push(termList); termsUniqueMap[expression] = termList; } + termList.push(term); + + // New data + term.frequencies = []; } const metas = await this.database.findTermMetaBulk(expressionsUnique, titles); - for (const meta of metas) { - if (meta.mode !== 'freq') { - continue; + for (const {expression, mode, data, dictionary, index} of metas) { + switch (mode) { + case 'freq': + for (const term of termsUnique[index]) { + term.frequencies.push({expression, frequency: data, dictionary}); + } + break; } + } + } - for (const term of termsUnique[meta.index]) { - term.frequencies.push({ - expression: meta.expression, - frequency: meta.data, - dictionary: meta.dictionary - }); + async buildKanjiMeta(definitions, titles) { + const kanjiList = []; + for (const definition of definitions) { + kanjiList.push(definition.character); + definition.frequencies = []; + } + + const metas = await this.database.findKanjiMetaBulk(kanjiList, titles); + for (const {character, mode, data, dictionary, index} of metas) { + switch (mode) { + case 'freq': + definitions[index].frequencies.push({character, frequency: data, dictionary}); + break; } } } @@ -504,6 +552,17 @@ class Translator { return tagMetaList; } + static createExpression(expression, reading, termTags=null, termFrequency=null) { + const furiganaSegments = jpDistributeFurigana(expression, reading); + return { + expression, + reading, + furiganaSegments, + termTags, + termFrequency + }; + } + static scoreToTermFrequency(score) { if (score > 0) { return 'popular'; @@ -518,4 +577,38 @@ class Translator { const pos = name.indexOf(':'); return (pos >= 0 ? name.substring(0, pos) : name); } + + static *getArrayVariants(arrayVariants) { + const ii = arrayVariants.length; + + let total = 1; + for (let i = 0; i < ii; ++i) { + total *= arrayVariants[i].length; + } + + for (let a = 0; a < total; ++a) { + const variant = []; + let index = a; + for (let i = 0; i < ii; ++i) { + const entryVariants = arrayVariants[i]; + variant.push(entryVariants[index % entryVariants.length]); + index = Math.floor(index / entryVariants.length); + } + yield variant; + } + } + + static getSearchableText(text, options) { + if (!options.scanning.alphanumeric) { + const ii = text.length; + for (let i = 0; i < ii; ++i) { + if (!jpIsCharCodeJapanese(text.charCodeAt(i))) { + text = text.substring(0, i); + break; + } + } + } + + return text; + } } diff --git a/ext/bg/search.html b/ext/bg/search.html index 409243dd..74afbb68 100644 --- a/ext/bg/search.html +++ b/ext/bg/search.html @@ -43,9 +43,7 @@ </span> </form> - <div id="spinner"> - <img src="/mixed/img/spinner.gif"> - </div> + <div id="spinner" hidden><img src="/mixed/img/spinner.gif"></div> <div class="scan-disable"> <div id="query-parser-select" class="input-group"></div> @@ -54,7 +52,18 @@ <hr> + <div id="navigation-header" class="navigation-header" hidden><div class="navigation-header-actions"> + <button class="action-button action-previous"><img src="/mixed/img/source-term.svg" class="icon-image" title="Source term (Alt + B)" alt></button> + <button class="action-button action-next"><img src="/mixed/img/source-term.svg" class="icon-image" title="Next term (Alt + F)" alt></button> + </div></div><div class="navigation-header-spacer"></div> + <div id="content"></div> + + <div id="no-results" hidden> + <div class="entry"> + <p>No results found.</p> + </div> + </div> </div> <script src="/mixed/lib/handlebars.min.js"></script> @@ -72,6 +81,7 @@ <script src="/mixed/js/audio.js"></script> <script src="/mixed/js/display-context.js"></script> <script src="/mixed/js/display.js"></script> + <script src="/mixed/js/display-generator.js"></script> <script src="/mixed/js/japanese.js"></script> <script src="/mixed/js/scroll.js"></script> <script src="/mixed/js/text-scanner.js"></script> diff --git a/ext/bg/settings.html b/ext/bg/settings.html index 4c973674..3e06d4b5 100644 --- a/ext/bg/settings.html +++ b/ext/bg/settings.html @@ -151,6 +151,14 @@ </div> <div class="checkbox options-advanced"> + <label><input type="checkbox" id="popup-scale-relative-to-page-zoom"> Change popup size relative to page zoom level</label> + </div> + + <div class="checkbox options-advanced"> + <label><input type="checkbox" id="popup-scale-relative-to-visual-viewport"> Change popup size relative to page viewport</label> + </div> + + <div class="checkbox options-advanced"> <label><input type="checkbox" id="show-debug-info"> Show debug information</label> </div> @@ -171,6 +179,11 @@ </select> </div> + <div class="form-group"> + <label for="popup-scaling-factor">Popup size multiplier</label> + <input type="number" min="0" id="popup-scaling-factor" class="form-control"> + </div> + <div class="form-group options-advanced"> <label for="max-displayed-results">Maximum displayed results</label> <input type="number" min="1" id="max-displayed-results" class="form-control"> @@ -384,6 +397,81 @@ </div> </div> + <div> + <h3>Translation Options</h3> + + <p class="help-block"> + The following options can be used during the translation process to provide alternate versions of the input text to search for. + This can be helpful when the input text doesn't exactly match the term or expression found in the database. + </p> + + <p class="help-block"> + The conversion options below are listed in the order that the conversions are applied to the input text. + Each conversion has three possible values: + </p> + + <ul class="help-block"> + <li> + <strong>Disabled</strong><br> + This conversion will never be applied to the input text. + </li> + <li> + <strong>Enabled</strong><br> + This conversion will always be applied to the input text. + </li> + <li> + <strong>Use both variants</strong><br> + The translator will check the database for two variations: the raw input text and the converted input text. + When multiple options use variants, the translator will search for combinations of the converted text. + </li> + </ul> + + <div class="form-group"> + <label for="translation-convert-half-width-characters">Convert half width characters to full width <span class="label-light">(ヨミチャン → ヨミチャン)</span></label> + <select class="form-control" id="translation-convert-half-width-characters"> + <option value="false">Disabled</option> + <option value="true">Enabled</option> + <option value="variant">Use both variants</option> + </select> + </div> + + <div class="form-group"> + <label for="translation-convert-numeric-characters">Convert numeric characters to full width <span class="label-light">(1234 → 1234)</span></label> + <select class="form-control" id="translation-convert-numeric-characters"> + <option value="false">Disabled</option> + <option value="true">Enabled</option> + <option value="variant">Use both variants</option> + </select> + </div> + + <div class="form-group"> + <label for="translation-convert-alphabetic-characters">Convert alphabetic characters to hiragana <span class="label-light">(yomichan → よみちゃん)</span></label> + <select class="form-control" id="translation-convert-alphabetic-characters"> + <option value="false">Disabled</option> + <option value="true">Enabled</option> + <option value="variant">Use both variants</option> + </select> + </div> + + <div class="form-group"> + <label for="translation-convert-hiragana-to-katakana">Convert hiragana to katakana <span class="label-light">(よみちゃん → ヨミチャン)</span></label> + <select class="form-control" id="translation-convert-hiragana-to-katakana"> + <option value="false">Disabled</option> + <option value="true">Enabled</option> + <option value="variant">Use both variants</option> + </select> + </div> + + <div class="form-group"> + <label for="translation-convert-katakana-to-hiragana">Convert katakana to hiragana <span class="label-light">(ヨミチャン → よみちゃん)</span></label> + <select class="form-control" id="translation-convert-katakana-to-hiragana"> + <option value="false">Disabled</option> + <option value="true">Enabled</option> + <option value="variant">Use both variants</option> + </select> + </div> + </div> + <div id="popup-content-scanning"> <h3>Popup Content Scanning Options</h3> @@ -438,12 +526,17 @@ <label><input type="checkbox" id="parsing-mecab-enable"> Enable text parsing using MeCab</label> </div> + <div class="checkbox"> + <label><input type="checkbox" id="parsing-term-spacing"> Enable small spaces between parsed words</label> + </div> + <div class="form-group"> <label for="parsing-reading-mode">Reading mode</label> <select class="form-control" id="parsing-reading-mode"> <option value="hiragana">ひらがな</option> <option value="katakana">カタカナ</option> <option value="romaji">Romaji</option> + <option value="none">Disabled</option> </select> </div> </div> diff --git a/ext/fg/css/client.css b/ext/fg/css/client.css index b9c59da7..5720d8ac 100644 --- a/ext/fg/css/client.css +++ b/ext/fg/css/client.css @@ -39,21 +39,14 @@ iframe.yomichan-float[data-yomichan-theme=auto][data-yomichan-site-color=dark] { iframe.yomichan-float.yomichan-float-full-width { border-left: none; border-right: none; - left: 0 !important; - right: 0 !important; - width: 100% !important; box-sizing: border-box; resize: none; } iframe.yomichan-float.yomichan-float-full-width:not(.yomichan-float-above) { border-bottom: none; - top: auto !important; - bottom: 0 !important; } iframe.yomichan-float.yomichan-float-full-width.yomichan-float-above { border-top: none; - top: 0 !important; - bottom: auto !important; } diff --git a/ext/fg/float.html b/ext/fg/float.html index 886e5e8b..bec5ae68 100644 --- a/ext/fg/float.html +++ b/ext/fg/float.html @@ -15,14 +15,23 @@ <link rel="stylesheet alternate" type="text/css" href="/mixed/css/display-dark.css" data-yomichan-theme-name="dark"> </head> <body> - <div id="spinner"> - <img src="/mixed/img/spinner.gif"> - </div> + <div id="spinner" hidden><img src="/mixed/img/spinner.gif"></div> + + <div id="navigation-header" class="navigation-header" hidden><div class="navigation-header-actions"> + <button class="action-button action-previous"><img src="/mixed/img/source-term.svg" class="icon-image" title="Source term (Alt + B)" alt></button> + <button class="action-button action-next"><img src="/mixed/img/source-term.svg" class="icon-image" title="Next term (Alt + F)" alt></button> + </div></div><div class="navigation-header-spacer"></div> <div id="definitions"></div> - <div id="error-orphaned"> - <div class="container-fluid"> + <div id="no-results" hidden> + <div class="entry"> + <p>No results found.</p> + </div> + </div> + + <div id="error-orphaned" hidden> + <div class="entry"> <h1>Yomichan Updated!</h1> <p> The Yomichan extension has been updated to a new version! In order to continue @@ -40,6 +49,7 @@ <script src="/mixed/js/audio.js"></script> <script src="/mixed/js/display-context.js"></script> <script src="/mixed/js/display.js"></script> + <script src="/mixed/js/display-generator.js"></script> <script src="/mixed/js/scroll.js"></script> <script src="/fg/js/float.js"></script> diff --git a/ext/fg/js/document.js b/ext/fg/js/document.js index e068e3ba..71654b29 100644 --- a/ext/fg/js/document.js +++ b/ext/fg/js/document.js @@ -110,6 +110,7 @@ function docRangeFromPoint(x, y, deepDomScan) { const elements = docElementsFromPoint(x, y, deepDomScan); let imposter = null; let imposterContainer = null; + let imposterSourceElement = null; if (elements.length > 0) { const element = elements[0]; switch (element.nodeName.toUpperCase()) { @@ -117,9 +118,11 @@ function docRangeFromPoint(x, y, deepDomScan) { case 'BUTTON': return new TextSourceElement(element); case 'INPUT': + imposterSourceElement = element; [imposter, imposterContainer] = docImposterCreate(element, false); break; case 'TEXTAREA': + imposterSourceElement = element; [imposter, imposterContainer] = docImposterCreate(element, true); break; } @@ -131,7 +134,7 @@ function docRangeFromPoint(x, y, deepDomScan) { docSetImposterStyle(imposterContainer.style, 'z-index', '-2147483646'); docSetImposterStyle(imposter.style, 'pointer-events', 'none'); } - return new TextSourceRange(range, '', imposterContainer); + return new TextSourceRange(range, '', imposterContainer, imposterSourceElement); } else { if (imposterContainer !== null) { imposterContainer.parentNode.removeChild(imposterContainer); @@ -269,8 +272,14 @@ const caretRangeFromPoint = (() => { const range = document.createRange(); const offset = (node.nodeType === Node.TEXT_NODE ? position.offset : 0); - range.setStart(node, offset); - range.setEnd(node, offset); + try { + range.setStart(node, offset); + range.setEnd(node, offset); + } catch (e) { + // Firefox throws new DOMException("The operation is insecure.") + // when trying to select a node from within a ShadowRoot. + return null; + } return range; }; } diff --git a/ext/fg/js/float.js b/ext/fg/js/float.js index 513d246b..8d61d8f6 100644 --- a/ext/fg/js/float.js +++ b/ext/fg/js/float.js @@ -35,7 +35,7 @@ class DisplayFloat extends Display { onError(error) { if (this._orphaned) { - this.setContentOrphaned(); + this.setContent('orphaned'); } else { logError(error, true); } @@ -89,7 +89,11 @@ class DisplayFloat extends Display { } } - async initialize(options, popupInfo, url, childrenSupported) { + setContentScale(scale) { + document.body.style.fontSize = `${scale}em`; + } + + async initialize(options, popupInfo, url, childrenSupported, scale) { await super.initialize(options); const {id, depth, parentFrameId} = popupInfo; @@ -99,6 +103,8 @@ class DisplayFloat extends Display { if (childrenSupported) { popupNestedInitialize(id, depth, parentFrameId, url); } + + this.setContentScale(scale); } } @@ -116,7 +122,8 @@ DisplayFloat._messageHandlers = new Map([ ['setContent', (self, {type, details}) => self.setContent(type, details)], ['clearAutoPlayTimer', (self) => self.clearAutoPlayTimer()], ['setCustomCss', (self, {css}) => self.setCustomCss(css)], - ['initialize', (self, {options, popupInfo, url, childrenSupported}) => self.initialize(options, popupInfo, url, childrenSupported)] + ['initialize', (self, {options, popupInfo, url, childrenSupported, scale}) => self.initialize(options, popupInfo, url, childrenSupported, scale)], + ['setContentScale', (self, {scale}) => self.setContentScale(scale)] ]); DisplayFloat.instance = new DisplayFloat(); diff --git a/ext/fg/js/frontend.js b/ext/fg/js/frontend.js index 034d9075..2286bf19 100644 --- a/ext/fg/js/frontend.js +++ b/ext/fg/js/frontend.js @@ -34,6 +34,8 @@ class Frontend extends TextScanner { url: popup.url }; + this._pageZoomFactor = 1.0; + this._contentScale = 1.0; this._orphaned = true; this._lastShowPromise = Promise.resolve(); } @@ -41,23 +43,30 @@ class Frontend extends TextScanner { async prepare() { try { await this.updateOptions(); + const {zoomFactor} = await apiGetZoom(); + this._pageZoomFactor = zoomFactor; + + window.addEventListener('resize', this.onResize.bind(this), false); + + const visualViewport = window.visualViewport; + if (visualViewport !== null && typeof visualViewport === 'object') { + window.visualViewport.addEventListener('scroll', this.onVisualViewportScroll.bind(this)); + window.visualViewport.addEventListener('resize', this.onVisualViewportResize.bind(this)); + } yomichan.on('orphaned', () => this.onOrphaned()); yomichan.on('optionsUpdate', () => this.updateOptions()); + yomichan.on('zoomChanged', (e) => this.onZoomChanged(e)); chrome.runtime.onMessage.addListener(this.onRuntimeMessage.bind(this)); + + this._updateContentScale(); } catch (e) { this.onError(e); } } - async onResize() { - const textSource = this.textSourceCurrent; - if (textSource !== null && await this.popup.isVisible()) { - this._lastShowPromise = this.popup.showContent( - textSource.getRect(), - textSource.getWritingMode() - ); - } + onResize() { + this._updatePopupPosition(); } onWindowMessage(e) { @@ -81,18 +90,30 @@ class Frontend extends TextScanner { this._orphaned = true; } + onZoomChanged({newZoomFactor}) { + this._pageZoomFactor = newZoomFactor; + this._updateContentScale(); + } + + onVisualViewportScroll() { + this._updatePopupPosition(); + } + + onVisualViewportResize() { + this._updateContentScale(); + } + getMouseEventListeners() { return [ ...super.getMouseEventListeners(), - [window, 'message', this.onWindowMessage.bind(this)], - [window, 'resize', this.onResize.bind(this)] + [window, 'message', this.onWindowMessage.bind(this)] ]; } async updateOptions() { - this.options = await apiOptionsGet(this.getOptionsContext()); + this.setOptions(await apiOptionsGet(this.getOptionsContext())); await this.popup.setOptions(this.options); - this.setEnabled(this.options.general.enable); + this._updateContentScale(); } async onSearchSource(textSource, cause) { @@ -112,11 +133,7 @@ class Frontend extends TextScanner { } catch (e) { if (this._orphaned) { if (textSource !== null && this.options.scanning.modifier !== 'none') { - this._lastShowPromise = this.popup.showContent( - textSource.getRect(), - textSource.getWritingMode(), - 'orphaned' - ); + this._showPopupContent(textSource, 'orphaned'); } } else { this.onError(e); @@ -133,9 +150,8 @@ class Frontend extends TextScanner { showContent(textSource, focus, definitions, type) { const sentence = docSentenceExtract(textSource, this.options.anki.sentenceExt); const url = window.location.href; - this._lastShowPromise = this.popup.showContent( - textSource.getRect(), - textSource.getWritingMode(), + this._showPopupContent( + textSource, type, {definitions, context: {sentence, url, focus, disableHistory: true}} ); @@ -181,6 +197,44 @@ class Frontend extends TextScanner { this.optionsContext.url = this.popup.url; return this.optionsContext; } + + _showPopupContent(textSource, type=null, details=null) { + this._lastShowPromise = this.popup.showContent( + textSource.getRect(), + textSource.getWritingMode(), + type, + details + ); + return this._lastShowPromise; + } + + _updateContentScale() { + const {popupScalingFactor, popupScaleRelativeToPageZoom, popupScaleRelativeToVisualViewport} = this.options.general; + let contentScale = popupScalingFactor; + if (popupScaleRelativeToPageZoom) { + contentScale /= this._pageZoomFactor; + } + if (popupScaleRelativeToVisualViewport) { + contentScale /= Frontend._getVisualViewportScale(); + } + if (contentScale === this._contentScale) { return; } + + this._contentScale = contentScale; + this.popup.setContentScale(this._contentScale); + this._updatePopupPosition(); + } + + async _updatePopupPosition() { + const textSource = this.getCurrentTextSource(); + if (textSource !== null && await this.popup.isVisible()) { + this._showPopupContent(textSource); + } + } + + static _getVisualViewportScale() { + const visualViewport = window.visualViewport; + return visualViewport !== null && typeof visualViewport === 'object' ? visualViewport.scale : 1.0; + } } Frontend._windowMessageHandlers = new Map([ diff --git a/ext/fg/js/popup-nested.js b/ext/fg/js/popup-nested.js index bacf3b93..3f3c945e 100644 --- a/ext/fg/js/popup-nested.js +++ b/ext/fg/js/popup-nested.js @@ -35,7 +35,7 @@ async function popupNestedInitialize(id, depth, parentFrameId, url) { const ignoreNodes = ['.scan-disable', '.scan-disable *']; if (!options.scanning.enableOnPopupExpressions) { - ignoreNodes.push('.expression-scan-toggle', '.expression-scan-toggle *'); + ignoreNodes.push('.source-text', '.source-text *'); } window.frontendInitializationData = {id, depth, parentFrameId, ignoreNodes, url, proxy: true}; diff --git a/ext/fg/js/popup-proxy-host.js b/ext/fg/js/popup-proxy-host.js index c4f0c6ff..427172c6 100644 --- a/ext/fg/js/popup-proxy-host.js +++ b/ext/fg/js/popup-proxy-host.js @@ -41,7 +41,8 @@ class PopupProxyHost { ['containsPoint', ({id, x, y}) => this._onApiContainsPoint(id, x, y)], ['showContent', ({id, elementRect, writingMode, type, details}) => this._onApiShowContent(id, elementRect, writingMode, type, details)], ['setCustomCss', ({id, css}) => this._onApiSetCustomCss(id, css)], - ['clearAutoPlayTimer', ({id}) => this._onApiClearAutoPlayTimer(id)] + ['clearAutoPlayTimer', ({id}) => this._onApiClearAutoPlayTimer(id)], + ['setContentScale', ({id, scale}) => this._onApiSetContentScale(id, scale)] ])); } @@ -97,6 +98,11 @@ class PopupProxyHost { return popup.clearAutoPlayTimer(); } + async _onApiSetContentScale(id, scale) { + const popup = this._getPopup(id); + return popup.setContentScale(scale); + } + // Private functions _createPopupInternal(parentId, depth) { diff --git a/ext/fg/js/popup-proxy.js b/ext/fg/js/popup-proxy.js index ae0cffad..4cacee53 100644 --- a/ext/fg/js/popup-proxy.js +++ b/ext/fg/js/popup-proxy.js @@ -97,6 +97,11 @@ class PopupProxy { this._invokeHostApi('clearAutoPlayTimer', {id: this._id}); } + async setContentScale(scale) { + const id = await this._getPopupId(); + this._invokeHostApi('setContentScale', {id, scale}); + } + // Private _getPopupId() { diff --git a/ext/fg/js/popup.js b/ext/fg/js/popup.js index 7a0c6133..e7dae93e 100644 --- a/ext/fg/js/popup.js +++ b/ext/fg/js/popup.js @@ -28,10 +28,13 @@ class Popup { this._childrenSupported = true; this._injectPromise = null; this._isInjected = false; + this._isInjectedAndLoaded = false; this._visible = false; this._visibleOverride = null; this._options = null; this._stylesheetInjectedViaApi = false; + this._contentScale = 1.0; + this._containerSizeContentScale = null; this._container = document.createElement('iframe'); this._container.className = 'yomichan-float'; @@ -103,7 +106,7 @@ class Popup { } async showContent(elementRect, writingMode, type=null, details=null) { - if (!this._isInitialized()) { return; } + if (this._options === null) { throw new Error('Options not assigned'); } await this._show(elementRect, writingMode); if (type === null) { return; } this._invokeApi('setContent', {type, details}); @@ -114,11 +117,18 @@ class Popup { } clearAutoPlayTimer() { - if (this._isInjected) { + if (this._isInjectedAndLoaded) { this._invokeApi('clearAutoPlayTimer'); } } + setContentScale(scale) { + this._contentScale = scale; + if (this._isInjectedAndLoaded) { + this._invokeApi('setContentScale', {scale}); + } + } + // Popup-only public functions setParent(parent) { @@ -215,6 +225,7 @@ class Popup { return new Promise((resolve) => { const parentFrameId = (typeof this._frameId === 'number' ? this._frameId : null); this._container.addEventListener('load', () => { + this._isInjectedAndLoaded = true; this._invokeApi('initialize', { options: this._options, popupInfo: { @@ -223,7 +234,8 @@ class Popup { parentFrameId }, url: this.url, - childrenSupported: this._childrenSupported + childrenSupported: this._childrenSupported, + scale: this._contentScale }); resolve(); }); @@ -234,10 +246,6 @@ class Popup { }); } - _isInitialized() { - return this._options !== null; - } - async _show(elementRect, writingMode) { await this._inject(); @@ -250,18 +258,30 @@ class Popup { Popup._getPositionForVerticalText ); - const [x, y, width, height, below] = getPosition( + const viewport = Popup._getViewport(optionsGeneral.popupScaleRelativeToVisualViewport); + const scale = this._contentScale; + const scaleRatio = this._containerSizeContentScale === null ? 1.0 : scale / this._containerSizeContentScale; + this._containerSizeContentScale = scale; + let [x, y, width, height, below] = getPosition( elementRect, - Math.max(containerRect.width, optionsGeneral.popupWidth), - Math.max(containerRect.height, optionsGeneral.popupHeight), - document.body.clientWidth, - window.innerHeight, + Math.max(containerRect.width * scaleRatio, optionsGeneral.popupWidth * scale), + Math.max(containerRect.height * scaleRatio, optionsGeneral.popupHeight * scale), + viewport, + scale, optionsGeneral, writingMode ); - container.classList.toggle('yomichan-float-full-width', optionsGeneral.popupDisplayMode === 'full-width'); + const fullWidth = (optionsGeneral.popupDisplayMode === 'full-width'); + container.classList.toggle('yomichan-float-full-width', fullWidth); container.classList.toggle('yomichan-float-above', !below); + + if (optionsGeneral.popupDisplayMode === 'full-width') { + x = viewport.left; + y = below ? viewport.bottom - height : viewport.top; + width = viewport.right - viewport.left; + } + container.style.left = `${x}px`; container.style.top = `${y}px`; container.style.width = `${width}px`; @@ -307,6 +327,9 @@ class Popup { } _invokeApi(action, params={}) { + if (!this._isInjectedAndLoaded) { + throw new Error('Frame not loaded'); + } this._container.contentWindow.postMessage({action, params}, '*'); } @@ -338,49 +361,49 @@ class Popup { } } - static _getPositionForHorizontalText(elementRect, width, height, maxWidth, maxHeight, optionsGeneral) { - let x = elementRect.left + optionsGeneral.popupHorizontalOffset; - const overflowX = Math.max(x + width - maxWidth, 0); - if (overflowX > 0) { - if (x >= overflowX) { - x -= overflowX; - } else { - width = maxWidth; - x = 0; - } - } - + static _getPositionForHorizontalText(elementRect, width, height, viewport, offsetScale, optionsGeneral) { const preferBelow = (optionsGeneral.popupHorizontalTextPosition === 'below'); + const horizontalOffset = optionsGeneral.popupHorizontalOffset * offsetScale; + const verticalOffset = optionsGeneral.popupVerticalOffset * offsetScale; - const verticalOffset = optionsGeneral.popupVerticalOffset; - const [y, h, below] = Popup._limitGeometry( + const [x, w] = Popup._getConstrainedPosition( + elementRect.right - horizontalOffset, + elementRect.left + horizontalOffset, + width, + viewport.left, + viewport.right, + true + ); + const [y, h, below] = Popup._getConstrainedPositionBinary( elementRect.top - verticalOffset, elementRect.bottom + verticalOffset, height, - maxHeight, + viewport.top, + viewport.bottom, preferBelow ); - - return [x, y, width, h, below]; + return [x, y, w, h, below]; } - static _getPositionForVerticalText(elementRect, width, height, maxWidth, maxHeight, optionsGeneral, writingMode) { + static _getPositionForVerticalText(elementRect, width, height, viewport, offsetScale, optionsGeneral, writingMode) { const preferRight = Popup._isVerticalTextPopupOnRight(optionsGeneral.popupVerticalTextPosition, writingMode); - const horizontalOffset = optionsGeneral.popupHorizontalOffset2; - const verticalOffset = optionsGeneral.popupVerticalOffset2; + const horizontalOffset = optionsGeneral.popupHorizontalOffset2 * offsetScale; + const verticalOffset = optionsGeneral.popupVerticalOffset2 * offsetScale; - const [x, w] = Popup._limitGeometry( + const [x, w] = Popup._getConstrainedPositionBinary( elementRect.left - horizontalOffset, elementRect.right + horizontalOffset, width, - maxWidth, + viewport.left, + viewport.right, preferRight ); - const [y, h, below] = Popup._limitGeometry( + const [y, h, below] = Popup._getConstrainedPosition( elementRect.bottom - verticalOffset, elementRect.top + verticalOffset, height, - maxHeight, + viewport.top, + viewport.bottom, true ); return [x, y, w, h, below]; @@ -409,23 +432,36 @@ class Popup { } } - static _limitGeometry(positionBefore, positionAfter, size, limit, preferAfter) { - let after = preferAfter; - let position = 0; - const overflowBefore = Math.max(0, size - positionBefore); - const overflowAfter = Math.max(0, positionAfter + size - limit); + static _getConstrainedPosition(positionBefore, positionAfter, size, minLimit, maxLimit, after) { + size = Math.min(size, maxLimit - minLimit); + + let position; + if (after) { + position = Math.max(minLimit, positionAfter); + position = position - Math.max(0, (position + size) - maxLimit); + } else { + position = Math.min(maxLimit, positionBefore) - size; + position = position + Math.max(0, minLimit - position); + } + + return [position, size, after]; + } + + static _getConstrainedPositionBinary(positionBefore, positionAfter, size, minLimit, maxLimit, after) { + const overflowBefore = minLimit - (positionBefore - size); + const overflowAfter = (positionAfter + size) - maxLimit; + if (overflowAfter > 0 || overflowBefore > 0) { - if (overflowAfter < overflowBefore) { - size = Math.max(0, size - overflowAfter); - position = positionAfter; - after = true; - } else { - size = Math.max(0, size - overflowBefore); - position = Math.max(0, positionBefore - size); - after = false; - } + after = (overflowAfter < overflowBefore); + } + + let position; + if (after) { + size -= Math.max(0, overflowAfter); + position = Math.max(minLimit, positionAfter); } else { - position = preferAfter ? positionAfter : positionBefore - size; + size -= Math.max(0, overflowBefore); + position = Math.min(maxLimit, positionBefore) - size; } return [position, size, after]; @@ -464,6 +500,39 @@ class Popup { // NOP } } + + static _getViewport(useVisualViewport) { + const visualViewport = window.visualViewport; + if (visualViewport !== null && typeof visualViewport === 'object') { + const left = visualViewport.offsetLeft; + const top = visualViewport.offsetTop; + const width = visualViewport.width; + const height = visualViewport.height; + if (useVisualViewport) { + return { + left, + top, + right: left + width, + bottom: top + height + }; + } else { + const scale = visualViewport.scale; + return { + left: 0, + top: 0, + right: Math.max(left + width, width * scale), + bottom: Math.max(top + height, height * scale) + }; + } + } + + return { + left: 0, + top: 0, + right: document.body.clientWidth, + bottom: window.innerHeight + }; + } } Popup.outerStylesheet = null; diff --git a/ext/fg/js/source.js b/ext/fg/js/source.js index 5cdf47b5..11d3ff0e 100644 --- a/ext/fg/js/source.js +++ b/ext/fg/js/source.js @@ -25,14 +25,16 @@ const IGNORE_TEXT_PATTERN = /\u200c/; */ class TextSourceRange { - constructor(range, content, imposterContainer) { + constructor(range, content, imposterContainer, imposterSourceElement) { this.range = range; + this.rangeStartOffset = range.startOffset; this.content = content; this.imposterContainer = imposterContainer; + this.imposterSourceElement = imposterSourceElement; } clone() { - return new TextSourceRange(this.range.cloneRange(), this.content, this.imposterContainer); + return new TextSourceRange(this.range.cloneRange(), this.content, this.imposterContainer, this.imposterSourceElement); } cleanup() { @@ -55,6 +57,7 @@ class TextSourceRange { setStartOffset(length) { const state = TextSourceRange.seekBackward(this.range.startContainer, this.range.startOffset, length); this.range.setStart(state.node, state.offset); + this.rangeStartOffset = this.range.startOffset; this.content = state.content; return length - state.remainder; } @@ -79,7 +82,17 @@ class TextSourceRange { } equals(other) { - return other && other.range && other.range.compareBoundaryPoints(Range.START_TO_START, this.range) === 0; + if (other === null) { + return false; + } + if (this.imposterSourceElement !== null) { + return ( + this.imposterSourceElement === other.imposterSourceElement && + this.rangeStartOffset === other.rangeStartOffset + ); + } else { + return this.range.compareBoundaryPoints(Range.START_TO_START, other.range) === 0; + } } static shouldEnter(node) { diff --git a/ext/manifest.json b/ext/manifest.json index 5a76157b..31729992 100644 --- a/ext/manifest.json +++ b/ext/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 2, "name": "Yomichan (testing)", - "version": "20.01.04.00", + "version": "20.1.26.0", "description": "Japanese dictionary with Anki integration (testing)", "icons": {"16": "mixed/img/icon16.png", "48": "mixed/img/icon48.png", "128": "mixed/img/icon128.png"}, diff --git a/ext/mixed/css/display-dark.css b/ext/mixed/css/display-dark.css index e26c72aa..088fc741 100644 --- a/ext/mixed/css/display-dark.css +++ b/ext/mixed/css/display-dark.css @@ -19,36 +19,53 @@ body { background-color: #1e1e1e; color: #d4d4d4; } -hr { border-top-color: #2f2f2f; } - -.tag-default { background-color: #69696e; } -.tag-name { background-color: #489148; } -.tag-expression { background-color: #b07f39; } -.tag-popular { background-color: #025caa; } -.tag-frequent { background-color: #4490a7; } -.tag-archaism { background-color: #b04340; } -.tag-dictionary { background-color: #9057ad; } -.tag-frequency { background-color: #489148; } -.tag-partOfSpeech { background-color: #565656; } - -.reasons { color: #888888; } -.glossary li { color: #888888; } -.glossary-item { color: #d4d4d4; } -.label { color: #e1e1e1; } - -.expression .kanji-link { +.navigation-header { + background-color: #1e1e1e; + border-bottom-color: #2f2f2f; +} + +.entry+.entry { border-top-color: #2f2f2f; } + +.kanji-glyph-data>tbody>tr>* { border-top-color: #3f3f3f; } + +.tag { color: #e1e1e1; } +.tag[data-category=default] { background-color: #69696e; } +.tag[data-category=name] { background-color: #489148; } +.tag[data-category=expression] { background-color: #b07f39; } +.tag[data-category=popular] { background-color: #025caa; } +.tag[data-category=frequent] { background-color: #4490a7; } +.tag[data-category=archaism] { background-color: #b04340; } +.tag[data-category=dictionary] { background-color: #9057ad; } +.tag[data-category=frequency] { background-color: #489148; } +.tag[data-category=partOfSpeech] { background-color: #565656; } + +.term-reasons { color: #888888; } + +.term-expression>.term-expression-text .kanji-link { border-bottom-color: #888888; - color: #CCCCCC; + color: #cccccc; } -.expression-popular, .expression-popular .kanji-link { +.term-expression[data-frequency=popular]>.term-expression-text, +.term-expression[data-frequency=popular]>.term-expression-text .kanji-link { color: #0275d8; } -.expression-rare, .expression-rare .kanji-link { +.term-expression[data-frequency=rare]>.term-expression-text, +.term-expression[data-frequency=rare]>.term-expression-text .kanji-link { color: #666666; } +.term-definition-container, +.kanji-glossary-container { + color: #888888; +} + +.term-glossary, +.kanji-glossary { + color: #d4d4d4; +} + .icon-checkbox:checked + label { /* invert colors */ background-color: #d4d4d4; diff --git a/ext/mixed/css/display-default.css b/ext/mixed/css/display-default.css index ac237e79..69141c9d 100644 --- a/ext/mixed/css/display-default.css +++ b/ext/mixed/css/display-default.css @@ -19,36 +19,53 @@ body { background-color: #ffffff; color: #333333; } -hr { border-top-color: #eeeeee; } - -.tag-default { background-color: #8a8a91; } -.tag-name { background-color: #5cb85c; } -.tag-expression { background-color: #f0ad4e; } -.tag-popular { background-color: #0275d8; } -.tag-frequent { background-color: #5bc0de; } -.tag-archaism { background-color: #d9534f; } -.tag-dictionary { background-color: #aa66cc; } -.tag-frequency { background-color: #5cb85c; } -.tag-partOfSpeech { background-color: #565656; } - -.reasons { color: #777777; } -.glossary li { color: #777777; } -.glossary-item { color: #000000; } -.label { color: #ffffff; } - -.expression .kanji-link { +.navigation-header { + background-color: #ffffff; + border-bottom-color: #eeeeee; +} + +.entry+.entry { border-top-color: #eeeeee; } + +.kanji-glyph-data>tbody>tr>* { border-top-color: #dddddd; } + +.tag { color: #ffffff; } +.tag[data-category=default] { background-color: #8a8a91; } +.tag[data-category=name] { background-color: #5cb85c; } +.tag[data-category=expression] { background-color: #f0ad4e; } +.tag[data-category=popular] { background-color: #0275d8; } +.tag[data-category=frequent] { background-color: #5bc0de; } +.tag[data-category=archaism] { background-color: #d9534f; } +.tag[data-category=dictionary] { background-color: #aa66cc; } +.tag[data-category=frequency] { background-color: #5cb85c; } +.tag[data-category=partOfSpeech] { background-color: #565656; } + +.term-reasons { color: #777777; } + +.term-expression>.term-expression-text .kanji-link { border-bottom-color: #777777; color: #333333; } -.expression-popular, .expression-popular .kanji-link { +.term-expression[data-frequency=popular]>.term-expression-text, +.term-expression[data-frequency=popular]>.term-expression-text .kanji-link { color: #0275d8; } -.expression-rare, .expression-rare .kanji-link { +.term-expression[data-frequency=rare]>.term-expression-text, +.term-expression[data-frequency=rare]>.term-expression-text .kanji-link { color: #999999; } +.term-definition-container, +.kanji-glossary-container { + color: #777777; +} + +.term-glossary, +.kanji-glossary { + color: #000000; +} + .icon-checkbox:checked + label { /* invert colors */ background-color: #333333; diff --git a/ext/mixed/css/display.css b/ext/mixed/css/display.css index 7a00bccb..add2583e 100644 --- a/ext/mixed/css/display.css +++ b/ext/mixed/css/display.css @@ -35,37 +35,34 @@ html:root[data-yomichan-page=float]:not([data-yomichan-theme]) body { background-color: transparent; } -body { +:root { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; - line-height: 1.42857143; - margin: 0; - border: 0; - padding: 0; + line-height: 1.42857143; /* 14px => 20px */ } -hr { - padding: 0px; - margin: 0px; +body { + margin: 0; border: 0; - border-top-width: 1px; - border-top-style: solid; + padding: 0; + overflow-y: scroll; /* always show scroll bar */ } ol, ul { margin-top: 0; - margin-bottom: 10px; + margin-bottom: 0.72em; } #spinner { - bottom: 5px; - display: none; position: fixed; - right: 5px; + z-index: 1; + right: 0.36em; + bottom: 0.36em; } -#error-orphaned { - display: none; +#spinner>img { + width: 2.28571428em; /* 14px => 32px */ + height: 2.28571428em; /* 14px => 32px */ } .invisible { @@ -76,10 +73,42 @@ ol, ul { * Navigation */ -.term-navigation { +.navigation-header { + top: 0; + left: 0; + width: 100%; + height: 2.1em; + box-sizing: border-box; + padding: 0.25em 0.5em; + border-bottom-width: 0.07142857em; /* 14px => 1px */ + border-bottom-style: solid; +} + +html:root[data-yomichan-page=search] .navigation-header { + position: sticky; +} + +html:root[data-yomichan-page=float] .navigation-header { position: fixed; - top: 0px; - right: 0px; +} + +html:root[data-yomichan-page=float] .navigation-header:not([hidden])~.navigation-header-spacer { + height: 2.1em; +} + +.navigation-header-actions { + display: flex; +} + +.navigation-header:not([data-has-previous=true]) .navigation-header-actions .action-previous>img, +.navigation-header:not([data-has-next=true]) .navigation-header-actions .action-next>img { + opacity: 0.25; + -webkit-filter: grayscale(100%); + filter: grayscale(100%); +} + +.action-next>img { + transform: scaleX(-1); } @@ -91,24 +120,20 @@ ol, ul { display: none; } -.icon-checkbox + label { +.icon-checkbox+label { cursor: pointer; - font-size: 22px; - padding: 2px; + font-size: 1.6em; + padding: 0.1em; user-select: none; } #query-parser { - margin-top: 10px; - font-size: 24px; -} - -.query-parser-term { - margin-right: 5px; + margin-top: 0.5em; + font-size: 2em; } -html:root[data-yomichan-page=search] body { - overflow-y: scroll; /* always show scroll bar to avoid scanning problems */ +#query-parser[data-term-spacing=true] .query-parser-term { + margin-right: 0.2em; } @@ -116,15 +141,14 @@ html:root[data-yomichan-page=search] body { * Entries */ -.entry, .note { - padding-top: 20px; - padding-bottom: 10px; +.entry { + padding-top: 0.72em; + padding-bottom: 0.72em; } -html:root[data-yomichan-page=float] .entry, -html:root[data-yomichan-page=float] .note { - padding-left: 10px; - padding-right: 10px; +html:root[data-yomichan-page=float] .entry { + padding-left: 0.72em; + padding-right: 0.72em; } .actions .disabled { @@ -143,8 +167,9 @@ html:root[data-yomichan-page=float] .note { } .actions { - display: block; + display: flex; float: right; + margin: -0.25em; } .actions:after { @@ -153,111 +178,289 @@ html:root[data-yomichan-page=float] .note { display: block; } -.expression { +.action-button { display: inline-block; - font-size: 24px; + border: 0; + margin: 0; + padding: 0.3em; + background: transparent; + font-size: inherit; +} + +button.action-button { + cursor: pointer; +} + +.icon-image { + width: 1.14285714em; /* 14px => 16px */ + height: 1.14285714em; /* 14px => 16px */ + display: block; } -.expression .kanji-link { - border-bottom-width: 1px; +.term-expression .kanji-link { + border-bottom-width: 0.03571428em; /* 28px => 1px */ border-bottom-style: dashed; text-decoration: none; } -.expression .peek-wrapper { - font-size: 14px; +.entry:not(.entry-current) .current { + display: none; +} + +.tag { + display: inline; + padding: 0.2em 0.6em 0.3em; + font-size: 75%; + font-weight: 700; + line-height: 1; + text-align: center; white-space: nowrap; + vertical-align: baseline; + border-radius: 0.25em; +} + +.tag-list>.tag+.tag { + margin-left: 0.375em; +} + +.entry-header2, +.entry-header3 { + display: inline; +} + +.term-frequency-separator::before { + content: ":"; +} + +.entry+.entry { + border-top-width: 0.07142857em; /* 14px => 1px */ + border-top-style: solid; +} + +.entry[data-type=term][data-expression-multi=true]:not([data-expression-count="1"]) .actions>.action-play-audio { + display: none; +} + +.term-reasons { + display: inline-block; +} + +.term-reasons>.term-reason+.term-reason:before { + content: " \00AB "; /* The two spaces is not a typo */ + display: inline; +} + +.term-expression-list { + display: inline-block; +} + +.term-expression { + display: inline-block; +} + +.term-expression-text { + display: inline-block; + font-size: 2em; +} + +.term-expression-details { + display: inline; +} + +.term-expression-details>.action-play-audio { + display: none; +} + +.term-expression-details>.tags { + display: inline; +} + +.term-expression-details>.frequencies { + display: none; +} + +.term-expression-list>.term-expression:not(:last-of-type):after { + font-size: 2em; + content: "\3001"; +} + +.term-expression-list>.term-expression:last-of-type:not(:first-of-type):after { + font-size: 2em; + content: "\3000"; + visibility: hidden; +} + +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details { display: inline-block; position: relative; - width: 0px; - height: 0px; + width: 0; + height: 0; visibility: hidden; } -.expression .peek-wrapper .action-play-audio { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression:hover .term-expression-details { + visibility: visible; +} + +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.action-play-audio { position: absolute; - left: 0px; - bottom: 10px; + left: 0; + bottom: 0.5em; +} + +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.action-play-audio { + display: block; } -.expression .peek-wrapper .tags { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.tags { + display: block; position: absolute; - left: 0px; - bottom: -10px; + left: 0; + bottom: -0.5em; + white-space: nowrap; } -.expression .peek-wrapper .frequencies { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.frequencies { + display: block; position: absolute; - left: 0px; - bottom: -30px; + left: 0; + bottom: -1.9em; + white-space: nowrap; } -.expression:hover .peek-wrapper { - visibility: visible; +.term-definition-list { + margin: 0; + padding: 0; + list-style-type: none; } -.reasons { - display: inline-block; +.term-definition-list:not([data-count="0"]):not([data-count="1"]) { + padding-left: 1.4em; + list-style-type: decimal; } -.compact-info { - display: inline-block; +.term-glossary-list { + margin: 0; + padding: 0; + list-style-type: none; } -.glossary ol, .glossary ul { +.term-glossary-list:not([data-count="0"]):not([data-count="1"]) { padding-left: 1.4em; + list-style-type: circle; +} + +.term-definition-only-list[data-count="0"] { + display: none; +} + +.term-definition-only-list:before { + content: "("; +} + +.term-definition-only-list:after { + content: " only)"; +} + +.term-definition-only+.term-definition-only:before { + content: ", "; +} + +.debug-info { + display: none; +} + +:root[data-debug=true] .debug-info { + display: block; } -.glossary ul.compact-glossary { +:root[data-anki-enabled=false] .action-view-note, +:root[data-anki-enabled=false] .action-add-note { + display: none; +} + +:root[data-audio-enabled=false] .action-play-audio { + display: none; +} + +:root[data-compact-glossaries=true] .term-definition-tag-list, +:root[data-compact-glossaries=true] .term-definition-only-list:not([data-count="0"]) { + display: inline-block; +} + +:root[data-compact-glossaries=true] .term-glossary-list { display: inline; list-style: none; - padding-left: 0px; + padding-left: 0; } -.glossary .compact-glossary li { +:root[data-compact-glossaries=true] .term-glossary-list>li { display: inline; } -.glossary .compact-glossary li:not(:first-child):before { +:root[data-compact-glossaries=true] .term-glossary-list>li:not(:first-child):before { content: " | "; } -div.glossary-item.compact-glossary { - display: inline; -} +/* + * Kanji + */ -.glyph { +.kanji-glyph { font-family: kanji-stroke-orders; - font-size: 120px; - line-height: 120px; + font-size: 8.5em; + line-height: 1; padding: 0.01em; vertical-align: top; } -.glyph-data { - margin-top: 10px; +.kanji-glyph-data { + margin-top: 0.75em; + border-spacing: 0; + border-collapse: collapse; } -.info-output { +.kanji-glyph-data>tbody>tr>* { + border-top-width: 0.07142857em; /* 14px => 1px */ + border-top-style: solid; + text-align: left; + vertical-align: top; + padding: 0.36em; + margin: 0; +} + +.kanji-info-table { width: 100%; } -.info-output td { +.kanji-info-table>tbody>tr>th, +.kanji-info-table>tbody>tr>td { + text-align: left; + vertical-align: top; + padding: 0; + margin: 0; +} + +.kanji-info-table>tbody>tr>td { text-align: right; } -.entry:not(.entry-current) .current { - display: none; +.kanji-glyph-data dl { + margin-top: 0; + margin-bottom: 1.4em; } -.label { - display: inline; - padding: 0.2em 0.6em 0.3em; - font-size: 75%; - font-weight: 700; - line-height: 1; - text-align: center; - white-space: nowrap; - vertical-align: baseline; - border-radius: 0.25em; +.kanji-glyph-data dd { + margin-left: 0; +} + +.kanji-glossary-list { + margin: 0; + padding: 0; + list-style-type: none; +} + +.kanji-glossary-list:not([data-count="0"]):not([data-count="1"]) { + padding-left: 1.4em; + list-style-type: decimal; } diff --git a/ext/mixed/display-templates.html b/ext/mixed/display-templates.html new file mode 100644 index 00000000..62f3c69c --- /dev/null +++ b/ext/mixed/display-templates.html @@ -0,0 +1,81 @@ +<!DOCTYPE html><html><head></head><body> + +<template id="term-entry-template"><div class="entry" data-type="term"> + <div class="entry-header1"> + <div class="entry-header2"> + <div class="entry-header3"> + <div class="actions"> + <button class="action-button action-view-note pending disabled"><img src="/mixed/img/view-note.svg" class="icon-image" title="View added note (Alt + V)" alt></button> + <button class="action-button action-add-note pending disabled" data-mode="term-kanji"><img src="/mixed/img/add-term-kanji.svg" class="icon-image" title="Add expression (Alt + E)" alt></button> + <button class="action-button action-add-note pending disabled" data-mode="term-kana"><img src="/mixed/img/add-term-kana.svg" class="icon-image" title="Add reading (Alt + R)" alt></button> + <button class="action-button action-play-audio"><img src="/mixed/img/play-audio.svg" class="icon-image" title="Play audio (Alt + P)" alt></button> + <span class="action-button action-current-indicator"><img src="/mixed/img/entry-current.svg" class="icon-image current" title="Current entry (Alt + Up/Down/Home/End/PgUp/PgDn)" alt></span> + </div> + <div class="term-expression-list"></div> + </div> + <div class="term-reasons"></div> + </div> + <div class="frequencies"></div> + </div> + <div class="term-definition-container"><ol class="term-definition-list"></ol></div> + <pre class="debug-info"></pre> +</div></template> +<template id="term-expression-template"><div class="term-expression"><span class="term-expression-text source-text"></span><div class="term-expression-details"> + <button class="action-button action-play-audio"><img src="/mixed/img/play-audio.svg" class="icon-image" title="Play audio" alt></button> + <div class="tags tag-list"></div> + <div class="frequencies tag-list"></div> +</div></div></template> +<template id="term-definition-item-template"><li class="term-definition-item"> + <div class="term-definition-tag-list tag-list"></div> + <div class="term-definition-only-list"></div> + <ul class="term-glossary-list"></ul> +</li></template> +<template id="term-definition-only-template"><span class="term-definition-only"></span></template> +<template id="term-glossary-item-template"><li class="term-glossary-item"><span class="term-glossary"></span></li></template> +<template id="term-reason-template"><span class="term-reason"></span></template> + +<template id="kanji-entry-template"><div class="entry" data-type="kanji"> + <div class="entry-header1"> + <div class="entry-header2"> + <div class="entry-header3"> + <div class="actions"> + <button class="action-button action-view-note pending disabled"><img src="/mixed/img/view-note.svg" class="icon-image" title="View added note (Alt + V)" alt></button> + <button class="action-button action-add-note pending disabled" data-mode="kanji"><img src="/mixed/img/add-term-kanji.svg" class="icon-image" title="Add Kanji (Alt + K)" alt></button> + <span class="action-button action-current-indicator"><img src="/mixed/img/entry-current.svg" class="icon-image current" title="Current entry (Alt + Up/Down/Home/End/PgUp/PgDn)" alt></span> + </div> + <div class="kanji-glyph source-text"></div> + </div> + </div> + <div class="frequencies"></div> + </div> + <div class="tags tag-list"></div> + <table class="kanji-glyph-data"><tbody> + <tr> + <th>Glossary</th> + <th>Readings</th> + <th>Statistics</th> + </tr> + <tr> + <td class="kanji-glossary-container"><ol class="kanji-glossary-list"></ol></td> + <td class="kanji-readings"><dl class="kanji-readings-chinese"></dl><dl class="kanji-readings-japanese"></dl></td> + <td class="kanji-statistics"></td> + </tr> + <tr><th colspan="3">Classifications</th></tr> + <tr><td colspan="3" class="kanji-classifications"></td></tr> + <tr><th colspan="3">Codepoints</th></tr> + <tr><td colspan="3" class="kanji-codepoints"></td></tr> + <tr><th colspan="3">Dictionary Indices</th></tr> + <tr><td colspan="3" class="kanji-dictionary-indices"></td></tr> + </tbody></table> + <pre class="debug-info"></pre> +</div></template> +<template id="kanji-info-table-template"><table class="kanji-info-table"><tbody class="kanji-info-table-body"></tbody></table></template> +<template id="kanji-info-table-item-template"><tr class="kanji-info-table-item"><th class="kanji-info-table-item-header"></th><td class="kanji-info-table-item-value"></td></tr></template> +<template id="kanji-info-table-empty-template"><tr class="kanji-info-table-item kanji-info-table-item-empty"><td class="kanji-info-table-item-value-empty">No data found</td></tr class="kanji-info-table-item"></template> +<template id="kanji-glossary-item-template"><li class="kanji-glossary-item"><span class="kanji-glossary"></span></li></template> +<template id="kanji-reading-template"><dd class="kanji-reading"></dd></template> + +<template id="tag-template"><span class="tag"></span></template> +<template id="tag-frequency-template"><span class="tag" data-category="frequency"><span class="term-frequency-dictionary-name"></span><span class="term-frequency-separator"></span><span class="term-frequency-value"></span></template> + +</body></html> diff --git a/ext/mixed/js/api.js b/ext/mixed/js/api.js index 8ed1d996..5ec93b01 100644 --- a/ext/mixed/js/api.js +++ b/ext/mixed/js/api.js @@ -101,6 +101,14 @@ function apiClipboardGet() { return _apiInvoke('clipboardGet'); } +function apiGetDisplayTemplatesHtml() { + return _apiInvoke('getDisplayTemplatesHtml'); +} + +function apiGetZoom() { + return _apiInvoke('getZoom'); +} + function _apiInvoke(action, params={}) { const data = {action, params}; return new Promise((resolve, reject) => { diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js index 54e8a9d2..0142d594 100644 --- a/ext/mixed/js/core.js +++ b/ext/mixed/js/core.js @@ -56,7 +56,8 @@ function errorToJson(error) { return { name: error.name, message: error.message, - stack: error.stack + stack: error.stack, + data: error.data }; } @@ -64,6 +65,7 @@ function jsonToError(jsonError) { const error = new Error(jsonError.message); error.name = jsonError.name; error.stack = jsonError.stack; + error.data = jsonError.data; return error; } @@ -74,7 +76,11 @@ function logError(error, alert) { const errorString = `${error.toString ? error.toString() : error}`; const stack = `${error.stack}`.trimRight(); - errorMessage += (!stack.startsWith(errorString) ? `${errorString}\n${stack}` : `${stack}`); + if (!stack.startsWith(errorString)) { errorMessage += `${errorString}\n`; } + errorMessage += stack; + + const data = error.data; + if (typeof data !== 'undefined') { errorMessage += `\nData: ${JSON.stringify(data, null, 4)}`; } errorMessage += '\n\nIssues can be reported at https://github.com/FooSoft/yomichan/issues'; @@ -238,7 +244,8 @@ const yomichan = (() => { this._messageHandlers = new Map([ ['getUrl', this._onMessageGetUrl.bind(this)], - ['optionsUpdate', this._onMessageOptionsUpdate.bind(this)] + ['optionsUpdate', this._onMessageOptionsUpdate.bind(this)], + ['zoomChanged', this._onMessageZoomChanged.bind(this)] ]); chrome.runtime.onMessage.addListener(this._onMessage.bind(this)); @@ -268,6 +275,10 @@ const yomichan = (() => { _onMessageOptionsUpdate({source}) { this.trigger('optionsUpdate', {source}); } + + _onMessageZoomChanged({oldZoomFactor, newZoomFactor}) { + this.trigger('zoomChanged', {oldZoomFactor, newZoomFactor}); + } } return new Yomichan(); diff --git a/ext/mixed/js/display-generator.js b/ext/mixed/js/display-generator.js new file mode 100644 index 00000000..e1710488 --- /dev/null +++ b/ext/mixed/js/display-generator.js @@ -0,0 +1,379 @@ +/* + * Copyright (C) 2019-2020 Alex Yatskov <alex@foosoft.net> + * Author: Alex Yatskov <alex@foosoft.net> + * + * 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 <http://www.gnu.org/licenses/>. + */ + + +class DisplayGenerator { + constructor() { + this._isInitialized = false; + this._initializationPromise = null; + + this._termEntryTemplate = null; + this._termExpressionTemplate = null; + this._termDefinitionItemTemplate = null; + this._termDefinitionOnlyTemplate = null; + this._termGlossaryItemTemplate = null; + this._termReasonTemplate = null; + + this._kanjiEntryTemplate = null; + this._kanjiInfoTableTemplate = null; + this._kanjiInfoTableItemTemplate = null; + this._kanjiInfoTableEmptyTemplate = null; + this._kanjiGlossaryItemTemplate = null; + this._kanjiReadingTemplate = null; + + this._tagTemplate = null; + this._tagFrequencyTemplate = null; + } + + isInitialized() { + return this._isInitialized; + } + + initialize() { + if (this._isInitialized) { + return Promise.resolve(); + } + if (this._initializationPromise === null) { + this._initializationPromise = this._initializeInternal(); + } + return this._initializationPromise; + } + + createTermEntry(details) { + const node = DisplayGenerator._instantiateTemplate(this._termEntryTemplate); + + const expressionsContainer = node.querySelector('.term-expression-list'); + const reasonsContainer = node.querySelector('.term-reasons'); + const frequenciesContainer = node.querySelector('.frequencies'); + const definitionsContainer = node.querySelector('.term-definition-list'); + const debugInfoContainer = node.querySelector('.debug-info'); + + const expressionMulti = Array.isArray(details.expressions); + const definitionMulti = Array.isArray(details.definitions); + + node.dataset.expressionMulti = `${expressionMulti}`; + node.dataset.definitionMulti = `${definitionMulti}`; + node.dataset.expressionCount = `${expressionMulti ? details.expressions.length : 1}`; + node.dataset.definitionCount = `${definitionMulti ? details.definitions.length : 1}`; + + DisplayGenerator._appendMultiple(expressionsContainer, this.createTermExpression.bind(this), details.expressions, [details]); + DisplayGenerator._appendMultiple(reasonsContainer, this.createTermReason.bind(this), details.reasons); + DisplayGenerator._appendMultiple(frequenciesContainer, this.createFrequencyTag.bind(this), details.frequencies); + DisplayGenerator._appendMultiple(definitionsContainer, this.createTermDefinitionItem.bind(this), details.definitions, [details]); + + if (debugInfoContainer !== null) { + debugInfoContainer.textContent = JSON.stringify(details, null, 4); + } + + return node; + } + + createTermExpression(details) { + const node = DisplayGenerator._instantiateTemplate(this._termExpressionTemplate); + + const expressionContainer = node.querySelector('.term-expression-text'); + const tagContainer = node.querySelector('.tags'); + const frequencyContainer = node.querySelector('.frequencies'); + + if (details.termFrequency) { + node.dataset.frequency = details.termFrequency; + } + + if (expressionContainer !== null) { + let furiganaSegments = details.furiganaSegments; + if (!Array.isArray(furiganaSegments)) { + // This case should not occur + furiganaSegments = [{text: details.expression, furigana: details.reading}]; + } + DisplayGenerator._appendFurigana(expressionContainer, furiganaSegments, this._appendKanjiLinks.bind(this)); + } + + DisplayGenerator._appendMultiple(tagContainer, this.createTag.bind(this), details.termTags); + DisplayGenerator._appendMultiple(frequencyContainer, this.createFrequencyTag.bind(this), details.frequencies); + + return node; + } + + createTermReason(reason) { + const node = DisplayGenerator._instantiateTemplate(this._termReasonTemplate); + node.textContent = reason; + node.dataset.reason = reason; + return node; + } + + createTermDefinitionItem(details) { + const node = DisplayGenerator._instantiateTemplate(this._termDefinitionItemTemplate); + + const tagListContainer = node.querySelector('.term-definition-tag-list'); + const onlyListContainer = node.querySelector('.term-definition-only-list'); + const glossaryContainer = node.querySelector('.term-glossary-list'); + + node.dataset.dictionary = details.dictionary; + + DisplayGenerator._appendMultiple(tagListContainer, this.createTag.bind(this), details.definitionTags); + DisplayGenerator._appendMultiple(onlyListContainer, this.createTermOnly.bind(this), details.only); + DisplayGenerator._appendMultiple(glossaryContainer, this.createTermGlossaryItem.bind(this), details.glossary); + + return node; + } + + createTermGlossaryItem(glossary) { + const node = DisplayGenerator._instantiateTemplate(this._termGlossaryItemTemplate); + const container = node.querySelector('.term-glossary'); + if (container !== null) { + DisplayGenerator._appendMultilineText(container, glossary); + } + return node; + } + + createTermOnly(only) { + const node = DisplayGenerator._instantiateTemplate(this._termDefinitionOnlyTemplate); + node.dataset.only = only; + node.textContent = only; + return node; + } + + createKanjiLink(character) { + const node = document.createElement('a'); + node.href = '#'; + node.className = 'kanji-link'; + node.textContent = character; + return node; + } + + createKanjiEntry(details) { + const node = DisplayGenerator._instantiateTemplate(this._kanjiEntryTemplate); + + const glyphContainer = node.querySelector('.kanji-glyph'); + const frequenciesContainer = node.querySelector('.frequencies'); + const tagContainer = node.querySelector('.tags'); + const glossaryContainer = node.querySelector('.kanji-glossary-list'); + const chineseReadingsContainer = node.querySelector('.kanji-readings-chinese'); + const japaneseReadingsContainer = node.querySelector('.kanji-readings-japanese'); + const statisticsContainer = node.querySelector('.kanji-statistics'); + const classificationsContainer = node.querySelector('.kanji-classifications'); + const codepointsContainer = node.querySelector('.kanji-codepoints'); + const dictionaryIndicesContainer = node.querySelector('.kanji-dictionary-indices'); + const debugInfoContainer = node.querySelector('.debug-info'); + + if (glyphContainer !== null) { + glyphContainer.textContent = details.character; + } + + DisplayGenerator._appendMultiple(frequenciesContainer, this.createFrequencyTag.bind(this), details.frequencies); + DisplayGenerator._appendMultiple(tagContainer, this.createTag.bind(this), details.tags); + DisplayGenerator._appendMultiple(glossaryContainer, this.createKanjiGlossaryItem.bind(this), details.glossary); + DisplayGenerator._appendMultiple(chineseReadingsContainer, this.createKanjiReading.bind(this), details.onyomi); + DisplayGenerator._appendMultiple(japaneseReadingsContainer, this.createKanjiReading.bind(this), details.kunyomi); + + if (statisticsContainer !== null) { + statisticsContainer.appendChild(this.createKanjiInfoTable(details.stats.misc)); + } + if (classificationsContainer !== null) { + classificationsContainer.appendChild(this.createKanjiInfoTable(details.stats.class)); + } + if (codepointsContainer !== null) { + codepointsContainer.appendChild(this.createKanjiInfoTable(details.stats.code)); + } + if (dictionaryIndicesContainer !== null) { + dictionaryIndicesContainer.appendChild(this.createKanjiInfoTable(details.stats.index)); + } + + if (debugInfoContainer !== null) { + debugInfoContainer.textContent = JSON.stringify(details, null, 4); + } + + return node; + } + + createKanjiGlossaryItem(glossary) { + const node = DisplayGenerator._instantiateTemplate(this._kanjiGlossaryItemTemplate); + const container = node.querySelector('.kanji-glossary'); + if (container !== null) { + DisplayGenerator._appendMultilineText(container, glossary); + } + return node; + } + + createKanjiReading(reading) { + const node = DisplayGenerator._instantiateTemplate(this._kanjiReadingTemplate); + node.textContent = reading; + return node; + } + + createKanjiInfoTable(details) { + const node = DisplayGenerator._instantiateTemplate(this._kanjiInfoTableTemplate); + + const container = node.querySelector('.kanji-info-table-body'); + + if (container !== null) { + const count = DisplayGenerator._appendMultiple(container, this.createKanjiInfoTableItem.bind(this), details); + if (count === 0) { + const n = this.createKanjiInfoTableItemEmpty(); + container.appendChild(n); + } + } + + return node; + } + + createKanjiInfoTableItem(details) { + const node = DisplayGenerator._instantiateTemplate(this._kanjiInfoTableItemTemplate); + const nameNode = node.querySelector('.kanji-info-table-item-header'); + const valueNode = node.querySelector('.kanji-info-table-item-value'); + if (nameNode !== null) { + nameNode.textContent = details.notes || details.name; + } + if (valueNode !== null) { + valueNode.textContent = details.value; + } + return node; + } + + createKanjiInfoTableItemEmpty() { + return DisplayGenerator._instantiateTemplate(this._kanjiInfoTableEmptyTemplate); + } + + createTag(details) { + const node = DisplayGenerator._instantiateTemplate(this._tagTemplate); + + node.title = details.notes; + node.textContent = details.name; + node.dataset.category = details.category; + + return node; + } + + createFrequencyTag(details) { + const node = DisplayGenerator._instantiateTemplate(this._tagFrequencyTemplate); + + let n = node.querySelector('.term-frequency-dictionary-name'); + if (n !== null) { + n.textContent = details.dictionary; + } + + n = node.querySelector('.term-frequency-value'); + if (n !== null) { + n.textContent = `${details.frequency}`; + } + + node.dataset.dictionary = details.dictionary; + node.dataset.frequency = details.frequency; + + return node; + } + + async _initializeInternal() { + const html = await apiGetDisplayTemplatesHtml(); + const doc = new DOMParser().parseFromString(html, 'text/html'); + this._setTemplates(doc); + } + + _setTemplates(doc) { + this._termEntryTemplate = doc.querySelector('#term-entry-template'); + this._termExpressionTemplate = doc.querySelector('#term-expression-template'); + this._termDefinitionItemTemplate = doc.querySelector('#term-definition-item-template'); + this._termDefinitionOnlyTemplate = doc.querySelector('#term-definition-only-template'); + this._termGlossaryItemTemplate = doc.querySelector('#term-glossary-item-template'); + this._termReasonTemplate = doc.querySelector('#term-reason-template'); + + this._kanjiEntryTemplate = doc.querySelector('#kanji-entry-template'); + this._kanjiInfoTableTemplate = doc.querySelector('#kanji-info-table-template'); + this._kanjiInfoTableItemTemplate = doc.querySelector('#kanji-info-table-item-template'); + this._kanjiInfoTableEmptyTemplate = doc.querySelector('#kanji-info-table-empty-template'); + this._kanjiGlossaryItemTemplate = doc.querySelector('#kanji-glossary-item-template'); + this._kanjiReadingTemplate = doc.querySelector('#kanji-reading-template'); + + this._tagTemplate = doc.querySelector('#tag-template'); + this._tagFrequencyTemplate = doc.querySelector('#tag-frequency-template'); + } + + _appendKanjiLinks(container, text) { + let part = ''; + for (const c of text) { + if (DisplayGenerator._isCharacterKanji(c)) { + if (part.length > 0) { + container.appendChild(document.createTextNode(part)); + part = ''; + } + + const link = this.createKanjiLink(c); + container.appendChild(link); + } else { + part += c; + } + } + if (part.length > 0) { + container.appendChild(document.createTextNode(part)); + } + } + + static _isCharacterKanji(c) { + const code = c.charCodeAt(0); + return ( + code >= 0x4e00 && code < 0x9fb0 || + code >= 0x3400 && code < 0x4dc0 + ); + } + + static _appendMultiple(container, createItem, detailsArray, fallback=[]) { + if (container === null) { return 0; } + + const isArray = Array.isArray(detailsArray); + if (!isArray) { detailsArray = fallback; } + + container.dataset.multi = `${isArray}`; + container.dataset.count = `${detailsArray.length}`; + + for (const details of detailsArray) { + const item = createItem(details); + if (item === null) { continue; } + container.appendChild(item); + } + + return detailsArray.length; + } + + static _appendFurigana(container, segments, addText) { + for (const {text, furigana} of segments) { + if (furigana) { + const ruby = document.createElement('ruby'); + const rt = document.createElement('rt'); + addText(ruby, text); + ruby.appendChild(rt); + rt.appendChild(document.createTextNode(furigana)); + container.appendChild(ruby); + } else { + addText(container, text); + } + } + } + + static _appendMultilineText(container, text) { + const parts = text.split('\n'); + container.appendChild(document.createTextNode(parts[0])); + for (let i = 1, ii = parts.length; i < ii; ++i) { + container.appendChild(document.createElement('br')); + container.appendChild(document.createTextNode(parts[i])); + } + } + + static _instantiateTemplate(template) { + return document.importNode(template.content.firstChild, true); + } +} diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index e756f948..c4be02f2 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -24,7 +24,6 @@ class Display { this.definitions = []; this.options = null; this.context = null; - this.sequence = 0; this.index = 0; this.audioPlaying = null; this.audioFallback = null; @@ -36,7 +35,9 @@ class Display { this.interactive = false; this.eventListenersActive = false; this.clickScanPrevent = false; + this.setContentToken = null; + this.displayGenerator = new DisplayGenerator(); this.windowScroll = new WindowScroll(); this.setInteractive(true); @@ -76,7 +77,7 @@ class Display { }; const definitions = await apiKanjiFind(link.textContent, this.getOptionsContext()); - this.setContentKanji(definitions, context); + this.setContent('kanji', {definitions, context}); } catch (error) { this.onError(error); } @@ -130,7 +131,7 @@ class Display { }); } - this.setContentTerms(definitions, context); + this.setContent('terms', {definitions, context}); if (selectText) { textSource.select(); @@ -174,7 +175,7 @@ class Display { const link = e.currentTarget; const entry = link.closest('.entry'); const definitionIndex = this.entryIndexFind(entry); - const expressionIndex = Display.indexOf(entry.querySelectorAll('.expression .action-play-audio'), link); + const expressionIndex = Display.indexOf(entry.querySelectorAll('.term-expression .action-play-audio'), link); this.audioPlay(this.definitions[definitionIndex], expressionIndex, definitionIndex); } @@ -240,11 +241,20 @@ class Display { async updateOptions(options) { this.options = options ? options : await apiOptionsGet(this.getOptionsContext()); + this.updateDocumentOptions(this.options); this.updateTheme(this.options.general.popupTheme); this.setCustomCss(this.options.general.customPopupCss); audioPrepareTextToSpeech(this.options); } + updateDocumentOptions(options) { + const data = document.documentElement.dataset; + data.ankiEnabled = `${options.anki.enable}`; + data.audioEnabled = `${options.audio.enable}`; + data.compactGlossaries = `${options.general.compactGlossaries}`; + data.debug = `${options.general.debugInfo}`; + } + updateTheme(themeName) { document.documentElement.dataset.yomichanTheme = themeName; @@ -277,6 +287,9 @@ class Display { if (interactive) { Display.addEventListener(this.persistentEventListeners, document, 'keydown', this.onKeyDown.bind(this), false); Display.addEventListener(this.persistentEventListeners, document, 'wheel', this.onWheel.bind(this), {passive: false}); + Display.addEventListener(this.persistentEventListeners, document.querySelector('.action-previous'), 'click', this.onSourceTermView.bind(this)); + Display.addEventListener(this.persistentEventListeners, document.querySelector('.action-next'), 'click', this.onNextTermView.bind(this)); + Display.addEventListener(this.persistentEventListeners, document.querySelector('.navigation-header'), 'wheel', this.onHistoryWheel.bind(this), {passive: false}); } else { Display.clearEventListeners(this.persistentEventListeners); } @@ -293,9 +306,6 @@ class Display { this.addEventListeners('.action-view-note', 'click', this.onNoteView.bind(this)); this.addEventListeners('.action-play-audio', 'click', this.onAudioPlay.bind(this)); this.addEventListeners('.kanji-link', 'click', this.onKanjiLookup.bind(this)); - this.addEventListeners('.source-term', 'click', this.onSourceTermView.bind(this)); - this.addEventListeners('.next-term', 'click', this.onNextTermView.bind(this)); - this.addEventListeners('.term-navigation', 'wheel', this.onHistoryWheel.bind(this), {passive: false}); if (this.options.scanning.enablePopupSearch) { this.addEventListeners('.glossary-item', 'mouseup', this.onGlossaryMouseUp.bind(this)); this.addEventListeners('.glossary-item', 'mousedown', this.onGlossaryMouseDown.bind(this)); @@ -312,138 +322,178 @@ class Display { } } - setContent(type, details) { - switch (type) { - case 'terms': - return this.setContentTerms(details.definitions, details.context); - case 'kanji': - return this.setContentKanji(details.definitions, details.context); - case 'orphaned': - return this.setContentOrphaned(); - default: - return Promise.resolve(); + async setContent(type, details) { + const token = {}; // Unique identifier token + this.setContentToken = token; + try { + switch (type) { + case 'terms': + await this.setContentTerms(details.definitions, details.context, token); + break; + case 'kanji': + await this.setContentKanji(details.definitions, details.context, token); + break; + case 'orphaned': + this.setContentOrphaned(); + break; + } + } catch (e) { + this.onError(e); + } finally { + if (this.setContentToken === token) { + this.setContentToken = null; + } } } - async setContentTerms(definitions, context) { + async setContentTerms(definitions, context, token) { if (!context) { throw new Error('Context expected'); } if (!this.isInitialized()) { return; } - try { - const options = this.options; + this.setEventListenersActive(false); - this.setEventListenersActive(false); + if (context.focus !== false) { + window.focus(); + } - if (context.focus !== false) { - window.focus(); - } + if (!this.displayGenerator.isInitialized()) { + await this.displayGenerator.initialize(); + if (this.setContentToken !== token) { return; } + } - this.definitions = definitions; - if (context.disableHistory) { - delete context.disableHistory; - this.context = new DisplayContext('terms', definitions, context); - } else { - this.context = DisplayContext.push(this.context, 'terms', definitions, context); - } + this.definitions = definitions; + if (context.disableHistory) { + delete context.disableHistory; + this.context = new DisplayContext('terms', definitions, context); + } else { + this.context = DisplayContext.push(this.context, 'terms', definitions, context); + } - const sequence = ++this.sequence; - const params = { - definitions, - source: !!this.context.previous, - next: !!this.context.next, - addable: options.anki.enable, - grouped: options.general.resultOutputMode === 'group', - merged: options.general.resultOutputMode === 'merge', - playback: options.audio.enabled, - compactGlossaries: options.general.compactGlossaries, - debug: options.general.debugInfo - }; + for (const definition of definitions) { + definition.cloze = Display.clozeBuild(context.sentence, definition.source); + definition.url = context.url; + } - for (const definition of definitions) { - definition.cloze = Display.clozeBuild(context.sentence, definition.source); - definition.url = context.url; - } + this.updateNavigation(this.context.previous, this.context.next); + this.setNoContentVisible(definitions.length === 0); - const content = await apiTemplateRender('terms.html', params); - this.container.innerHTML = content; - const {index, scroll, disableScroll} = context; - if (!disableScroll) { - this.entryScrollIntoView(index || 0, scroll); - } else { - delete context.disableScroll; - this.entrySetCurrent(index || 0); - } + const container = this.container; + container.textContent = ''; - if (options.audio.enabled && options.audio.autoPlay) { - this.autoPlayAudio(); + for (let i = 0, ii = definitions.length; i < ii; ++i) { + if (i > 0) { + await promiseTimeout(1); + if (this.setContentToken !== token) { return; } } - this.setEventListenersActive(true); + const entry = this.displayGenerator.createTermEntry(definitions[i]); + container.appendChild(entry); + } - await this.adderButtonUpdate(['term-kanji', 'term-kana'], sequence); - } catch (e) { - this.onError(e); + const {index, scroll, disableScroll} = context; + if (!disableScroll) { + this.entryScrollIntoView(index || 0, scroll); + } else { + delete context.disableScroll; + this.entrySetCurrent(index || 0); } + + if (this.options.audio.enabled && this.options.audio.autoPlay) { + this.autoPlayAudio(); + } + + this.setEventListenersActive(true); + + const states = await apiDefinitionsAddable(definitions, ['term-kanji', 'term-kana'], this.getOptionsContext()); + if (this.setContentToken !== token) { return; } + + this.updateAdderButtons(states); } - async setContentKanji(definitions, context) { + async setContentKanji(definitions, context, token) { if (!context) { throw new Error('Context expected'); } if (!this.isInitialized()) { return; } - try { - const options = this.options; + this.setEventListenersActive(false); - this.setEventListenersActive(false); + if (context.focus !== false) { + window.focus(); + } - if (context.focus !== false) { - window.focus(); - } + if (!this.displayGenerator.isInitialized()) { + await this.displayGenerator.initialize(); + if (this.setContentToken !== token) { return; } + } - this.definitions = definitions; - if (context.disableHistory) { - delete context.disableHistory; - this.context = new DisplayContext('kanji', definitions, context); - } else { - this.context = DisplayContext.push(this.context, 'kanji', definitions, context); - } + this.definitions = definitions; + if (context.disableHistory) { + delete context.disableHistory; + this.context = new DisplayContext('kanji', definitions, context); + } else { + this.context = DisplayContext.push(this.context, 'kanji', definitions, context); + } - const sequence = ++this.sequence; - const params = { - definitions, - source: !!this.context.previous, - next: !!this.context.next, - addable: options.anki.enable, - debug: options.general.debugInfo - }; + for (const definition of definitions) { + definition.cloze = Display.clozeBuild(context.sentence, definition.character); + definition.url = context.url; + } - for (const definition of definitions) { - definition.cloze = Display.clozeBuild(context.sentence, definition.character); - definition.url = context.url; - } + this.updateNavigation(this.context.previous, this.context.next); + this.setNoContentVisible(definitions.length === 0); - const content = await apiTemplateRender('kanji.html', params); - this.container.innerHTML = content; - const {index, scroll} = context; - this.entryScrollIntoView(index || 0, scroll); + const container = this.container; + container.textContent = ''; - this.setEventListenersActive(true); + for (let i = 0, ii = definitions.length; i < ii; ++i) { + if (i > 0) { + await promiseTimeout(0); + if (this.setContentToken !== token) { return; } + } - await this.adderButtonUpdate(['kanji'], sequence); - } catch (e) { - this.onError(e); + const entry = this.displayGenerator.createKanjiEntry(definitions[i]); + container.appendChild(entry); } + + const {index, scroll} = context; + this.entryScrollIntoView(index || 0, scroll); + + this.setEventListenersActive(true); + + const states = await apiDefinitionsAddable(definitions, ['kanji'], this.getOptionsContext()); + if (this.setContentToken !== token) { return; } + + this.updateAdderButtons(states); } - async setContentOrphaned() { - const definitions = document.querySelector('#definitions'); + setContentOrphaned() { const errorOrphaned = document.querySelector('#error-orphaned'); - if (definitions !== null) { - definitions.style.setProperty('display', 'none', 'important'); + if (this.container !== null) { + this.container.hidden = true; } if (errorOrphaned !== null) { - errorOrphaned.style.setProperty('display', 'block', 'important'); + errorOrphaned.hidden = false; + } + + this.updateNavigation(null, null); + this.setNoContentVisible(false); + } + + setNoContentVisible(visible) { + const noResults = document.querySelector('#no-results'); + + if (noResults !== null) { + noResults.hidden = !visible; + } + } + + updateNavigation(previous, next) { + const navigation = document.querySelector('#navigation-header'); + if (navigation !== null) { + navigation.hidden = !(previous || next); + navigation.dataset.hasPrevious = `${!!previous}`; + navigation.dataset.hasNext = `${!!next}`; } } @@ -451,35 +501,26 @@ class Display { this.audioPlay(this.definitions[0], this.firstExpressionIndex, 0); } - async adderButtonUpdate(modes, sequence) { - try { - const states = await apiDefinitionsAddable(this.definitions, modes, this.getOptionsContext()); - if (!states || sequence !== this.sequence) { - return; - } - - for (let i = 0; i < states.length; ++i) { - const state = states[i]; - let noteId = null; - for (const mode in state) { - const button = this.adderButtonFind(i, mode); - if (button === null) { - continue; - } - - const info = state[mode]; - if (!info.canAdd && noteId === null && info.noteId) { - noteId = info.noteId; - } - button.classList.toggle('disabled', !info.canAdd); - button.classList.remove('pending'); + updateAdderButtons(states) { + for (let i = 0; i < states.length; ++i) { + const state = states[i]; + let noteId = null; + for (const mode in state) { + const button = this.adderButtonFind(i, mode); + if (button === null) { + continue; } - if (noteId !== null) { - this.viewerButtonShow(i, noteId); + + const info = state[mode]; + if (!info.canAdd && noteId === null && info.noteId) { + noteId = info.noteId; } + button.classList.toggle('disabled', !info.canAdd); + button.classList.remove('pending'); + } + if (noteId !== null) { + this.viewerButtonShow(i, noteId); } - } catch (e) { - this.onError(e); } } @@ -511,6 +552,11 @@ class Display { target = scroll; } else { target = this.index === 0 || entry === null ? 0 : Display.getElementTop(entry); + + const header = document.querySelector('#navigation-header'); + if (header !== null) { + target -= header.getBoundingClientRect().height; + } } if (smooth) { @@ -673,7 +719,9 @@ class Display { } setSpinnerVisible(visible) { - this.spinner.style.display = visible ? 'block' : ''; + if (this.spinner !== null) { + this.spinner.hidden = !visible; + } } getEntry(index) { @@ -733,6 +781,7 @@ class Display { } static addEventListener(eventListeners, object, type, listener, options) { + if (object === null) { return; } object.addEventListener(type, listener, options); eventListeners.push([object, type, listener, options]); } diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 23b2bd36..0da822d7 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -17,24 +17,153 @@ */ -function jpIsKanji(c) { - const code = c.charCodeAt(0); - return code >= 0x4e00 && code < 0x9fb0 || code >= 0x3400 && code < 0x4dc0; +const JP_HALFWIDTH_KATAKANA_MAPPING = new Map([ + ['ヲ', 'ヲヺ-'], + ['ァ', 'ァ--'], + ['ィ', 'ィ--'], + ['ゥ', 'ゥ--'], + ['ェ', 'ェ--'], + ['ォ', 'ォ--'], + ['ャ', 'ャ--'], + ['ュ', 'ュ--'], + ['ョ', 'ョ--'], + ['ッ', 'ッ--'], + ['ー', 'ー--'], + ['ア', 'ア--'], + ['イ', 'イ--'], + ['ウ', 'ウヴ-'], + ['エ', 'エ--'], + ['オ', 'オ--'], + ['カ', 'カガ-'], + ['キ', 'キギ-'], + ['ク', 'クグ-'], + ['ケ', 'ケゲ-'], + ['コ', 'コゴ-'], + ['サ', 'サザ-'], + ['シ', 'シジ-'], + ['ス', 'スズ-'], + ['セ', 'セゼ-'], + ['ソ', 'ソゾ-'], + ['タ', 'タダ-'], + ['チ', 'チヂ-'], + ['ツ', 'ツヅ-'], + ['テ', 'テデ-'], + ['ト', 'トド-'], + ['ナ', 'ナ--'], + ['ニ', 'ニ--'], + ['ヌ', 'ヌ--'], + ['ネ', 'ネ--'], + ['ノ', 'ノ--'], + ['ハ', 'ハバパ'], + ['ヒ', 'ヒビピ'], + ['フ', 'フブプ'], + ['ヘ', 'ヘベペ'], + ['ホ', 'ホボポ'], + ['マ', 'マ--'], + ['ミ', 'ミ--'], + ['ム', 'ム--'], + ['メ', 'メ--'], + ['モ', 'モ--'], + ['ヤ', 'ヤ--'], + ['ユ', 'ユ--'], + ['ヨ', 'ヨ--'], + ['ラ', 'ラ--'], + ['リ', 'リ--'], + ['ル', 'ル--'], + ['レ', 'レ--'], + ['ロ', 'ロ--'], + ['ワ', 'ワ--'], + ['ン', 'ン--'] +]); + +const JP_HIRAGANA_RANGE = [0x3040, 0x309f]; +const JP_KATAKANA_RANGE = [0x30a0, 0x30ff]; +const JP_KANA_RANGES = [JP_HIRAGANA_RANGE, JP_KATAKANA_RANGE]; + +const JP_CJK_COMMON_RANGE = [0x4e00, 0x9fff]; +const JP_CJK_RARE_RANGE = [0x3400, 0x4dbf]; +const JP_CJK_RANGES = [JP_CJK_COMMON_RANGE, JP_CJK_RARE_RANGE]; + +const JP_ITERATION_MARK_CHAR_CODE = 0x3005; + +// Japanese character ranges, roughly ordered in order of expected frequency +const JP_JAPANESE_RANGES = [ + JP_HIRAGANA_RANGE, + JP_KATAKANA_RANGE, + + JP_CJK_COMMON_RANGE, + JP_CJK_RARE_RANGE, + + [0xff66, 0xff9f], // Halfwidth katakana + + [0x30fb, 0x30fc], // Katakana punctuation + [0xff61, 0xff65], // Kana punctuation + [0x3000, 0x303f], // CJK punctuation + + [0xff10, 0xff19], // Fullwidth numbers + [0xff21, 0xff3a], // Fullwidth upper case Latin letters + [0xff41, 0xff5a], // Fullwidth lower case Latin letters + + [0xff01, 0xff0f], // Fullwidth punctuation 1 + [0xff1a, 0xff1f], // Fullwidth punctuation 2 + [0xff3b, 0xff3f], // Fullwidth punctuation 3 + [0xff5b, 0xff60], // Fullwidth punctuation 4 + [0xffe0, 0xffee], // Currency markers +]; + + +// Helper functions + +function _jpIsCharCodeInRanges(charCode, ranges) { + for (const [min, max] of ranges) { + if (charCode >= min && charCode <= max) { + return true; + } + } + return false; } -function jpIsKana(c) { - return wanakana.isKana(c); + +// Character code testing functions + +function jpIsCharCodeKanji(charCode) { + return _jpIsCharCodeInRanges(charCode, JP_CJK_RANGES); } -function jpIsJapaneseText(text) { - for (const c of text) { - if (jpIsKanji(c) || jpIsKana(c)) { +function jpIsCharCodeKana(charCode) { + return _jpIsCharCodeInRanges(charCode, JP_KANA_RANGES); +} + +function jpIsCharCodeJapanese(charCode) { + return _jpIsCharCodeInRanges(charCode, JP_JAPANESE_RANGES); +} + + +// String testing functions + +function jpIsStringEntirelyKana(str) { + if (str.length === 0) { return false; } + for (let i = 0, ii = str.length; i < ii; ++i) { + if (!jpIsCharCodeKana(str.charCodeAt(i))) { + return false; + } + } + return true; +} + +function jpIsStringPartiallyJapanese(str) { + if (str.length === 0) { return false; } + for (let i = 0, ii = str.length; i < ii; ++i) { + if (jpIsCharCodeJapanese(str.charCodeAt(i))) { return true; } } return false; } + +// Conversion functions + function jpKatakanaToHiragana(text) { let result = ''; for (const c of text) { @@ -75,11 +204,13 @@ function jpConvertReading(expressionFragment, readingFragment, readingMode) { if (readingFragment) { return jpToRomaji(readingFragment); } else { - if (jpIsKana(expressionFragment)) { + if (jpIsStringEntirelyKana(expressionFragment)) { return jpToRomaji(expressionFragment); } } return readingFragment; + case 'none': + return null; default: return readingFragment; } @@ -132,7 +263,8 @@ function jpDistributeFurigana(expression, reading) { const groups = []; let modePrev = null; for (const c of expression) { - const modeCurr = jpIsKanji(c) || c.charCodeAt(0) === 0x3005 /* noma */ ? 'kanji' : 'kana'; + const charCode = c.charCodeAt(0); + const modeCurr = jpIsCharCodeKanji(charCode) || charCode === JP_ITERATION_MARK_CHAR_CODE ? 'kanji' : 'kana'; if (modeCurr === modePrev) { groups[groups.length - 1].text += c; } else { @@ -175,3 +307,148 @@ function jpDistributeFuriganaInflected(expression, reading, source) { return output; } + +function jpConvertHalfWidthKanaToFullWidth(text, sourceMapping) { + let result = ''; + const ii = text.length; + const hasSourceMapping = Array.isArray(sourceMapping); + + for (let i = 0; i < ii; ++i) { + const c = text[i]; + const mapping = JP_HALFWIDTH_KATAKANA_MAPPING.get(c); + if (typeof mapping !== 'string') { + result += c; + continue; + } + + let index = 0; + switch (text.charCodeAt(i + 1)) { + case 0xff9e: // dakuten + index = 1; + break; + case 0xff9f: // handakuten + index = 2; + break; + } + + let c2 = mapping[index]; + if (index > 0) { + if (c2 === '-') { // invalid + index = 0; + c2 = mapping[0]; + } else { + ++i; + } + } + + if (hasSourceMapping && index > 0) { + index = result.length; + const v = sourceMapping.splice(index + 1, 1)[0]; + sourceMapping[index] += v; + } + result += c2; + } + + return result; +} + +function jpConvertNumericTofullWidth(text) { + let result = ''; + for (let i = 0, ii = text.length; i < ii; ++i) { + let c = text.charCodeAt(i); + if (c >= 0x30 && c <= 0x39) { // ['0', '9'] + c += 0xff10 - 0x30; // 0xff10 = '0' full width + result += String.fromCharCode(c); + } else { + result += text[i]; + } + } + return result; +} + +function jpConvertAlphabeticToKana(text, sourceMapping) { + let part = ''; + let result = ''; + const ii = text.length; + + if (sourceMapping.length === ii) { + sourceMapping.length = ii; + sourceMapping.fill(1); + } + + for (let i = 0; i < ii; ++i) { + // Note: 0x61 is the character code for 'a' + let c = text.charCodeAt(i); + if (c >= 0x41 && c <= 0x5a) { // ['A', 'Z'] + c += (0x61 - 0x41); + } else if (c >= 0x61 && c <= 0x7a) { // ['a', 'z'] + // NOP; c += (0x61 - 0x61); + } else if (c >= 0xff21 && c <= 0xff3a) { // ['A', 'Z'] fullwidth + c += (0x61 - 0xff21); + } else if (c >= 0xff41 && c <= 0xff5a) { // ['a', 'z'] fullwidth + c += (0x61 - 0xff41); + } else if (c === 0x2d || c === 0xff0d) { // '-' or fullwidth dash + c = 0x2d; // '-' + } else { + if (part.length > 0) { + result += jpToHiragana(part, sourceMapping, result.length); + part = ''; + } + result += text[i]; + continue; + } + part += String.fromCharCode(c); + } + + if (part.length > 0) { + result += jpToHiragana(part, sourceMapping, result.length); + } + return result; +} + +function jpToHiragana(text, sourceMapping, sourceMappingStart) { + const result = wanakana.toHiragana(text); + + // Generate source mapping + if (Array.isArray(sourceMapping)) { + if (typeof sourceMappingStart !== 'number') { sourceMappingStart = 0; } + let i = 0; + let resultPos = 0; + const ii = text.length; + while (i < ii) { + // Find smallest matching substring + let iNext = i + 1; + let resultPosNext = result.length; + while (iNext < ii) { + const t = wanakana.toHiragana(text.substring(0, iNext)); + if (t === result.substring(0, t.length)) { + resultPosNext = t.length; + break; + } + ++iNext; + } + + // Merge characters + const removals = iNext - i - 1; + if (removals > 0) { + let sum = 0; + const vs = sourceMapping.splice(sourceMappingStart + 1, removals); + for (const v of vs) { sum += v; } + sourceMapping[sourceMappingStart] += sum; + } + ++sourceMappingStart; + + // Empty elements + const additions = resultPosNext - resultPos - 1; + for (let j = 0; j < additions; ++j) { + sourceMapping.splice(sourceMappingStart, 0, 0); + ++sourceMappingStart; + } + + i = iNext; + resultPos = resultPosNext; + } + } + + return result; +} diff --git a/ext/mixed/js/text-scanner.js b/ext/mixed/js/text-scanner.js index a05dd2ee..88f1e27a 100644 --- a/ext/mixed/js/text-scanner.js +++ b/ext/mixed/js/text-scanner.js @@ -281,6 +281,7 @@ class TextScanner { setOptions(options) { this.options = options; + this.setEnabled(this.options.general.enable); } async searchAt(x, y, cause) { @@ -298,11 +299,11 @@ class TextScanner { } const textSource = docRangeFromPoint(x, y, this.options.scanning.deepDomScan); - if (this.textSourceCurrent !== null && this.textSourceCurrent.equals(textSource)) { - return; - } - try { + if (this.textSourceCurrent !== null && this.textSourceCurrent.equals(textSource)) { + return; + } + this.pendingLookup = true; const result = await this.onSearchSource(textSource, cause); if (result !== null) { |