From 8292be92d8958fc09dceb7c6bf252ac1c170ed1a Mon Sep 17 00:00:00 2001 From: siikamiika Date: Thu, 16 Jan 2020 23:22:38 +0200 Subject: use TextScanner in QueryParser --- ext/mixed/js/text-scanner.js | 1 + 1 file changed, 1 insertion(+) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/text-scanner.js b/ext/mixed/js/text-scanner.js index a05dd2ee..e037109d 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) { -- cgit v1.2.3 From 56ee7f8df47a3826e10d9b0876f313f5ced4c98e Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 24 Dec 2019 21:45:57 -0500 Subject: Update display content generation to use HTML templates --- ext/bg/search.html | 90 ++++++++++ ext/fg/float.html | 92 +++++++++- ext/mixed/css/display-dark.css | 59 ++++--- ext/mixed/css/display-default.css | 57 +++--- ext/mixed/css/display.css | 359 +++++++++++++++++++++++++++++--------- ext/mixed/js/display-generator.js | 332 +++++++++++++++++++++++++++++++++++ ext/mixed/js/display.js | 87 ++++++--- 7 files changed, 928 insertions(+), 148 deletions(-) create mode 100644 ext/mixed/js/display-generator.js (limited to 'ext/mixed/js') diff --git a/ext/bg/search.html b/ext/bg/search.html index 409243dd..5d9babea 100644 --- a/ext/bg/search.html +++ b/ext/bg/search.html @@ -54,9 +54,98 @@
+ +
+ + + + + + + + + + + + + + + + + + + @@ -72,6 +161,7 @@ + diff --git a/ext/fg/float.html b/ext/fg/float.html index 886e5e8b..f5f56853 100644 --- a/ext/fg/float.html +++ b/ext/fg/float.html @@ -19,10 +19,21 @@ + +
+ +
-
+

Yomichan Updated!

The Yomichan extension has been updated to a new version! In order to continue @@ -31,6 +42,84 @@

+ + + + + + + + + + + + + + + + + @@ -40,6 +129,7 @@ + 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..ff42771a 100644 --- a/ext/mixed/css/display.css +++ b/ext/mixed/css/display.css @@ -38,30 +38,28 @@ html:root[data-yomichan-page=float]:not([data-yomichan-theme]) body { body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; - line-height: 1.42857143; + line-height: 1.42857143; /* 14px => 20px */ margin: 0; border: 0; padding: 0; } -hr { - padding: 0px; - margin: 0px; - border: 0; - border-top-width: 1px; - border-top-style: solid; -} - 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; +} + +#spinner>img { + width: 2.28571428em; /* 14px => 32px */ + height: 2.28571428em; /* 14px => 32px */ } #error-orphaned { @@ -76,10 +74,38 @@ 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=float] .navigation-header { position: fixed; - top: 0px; - right: 0px; +} + +.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,20 +117,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; + margin-top: 0.5em; + font-size: 2em; } .query-parser-term { - margin-right: 5px; + margin-right: 0.2em; } html:root[data-yomichan-page=search] body { @@ -116,15 +142,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 +168,9 @@ html:root[data-yomichan-page=float] .note { } .actions { - display: block; + display: flex; float: right; + margin: -0.25em; } .actions:after { @@ -153,111 +179,286 @@ html:root[data-yomichan-page=float] .note { display: block; } -.expression { +.action-button { display: inline-block; - font-size: 24px; + border: 0; + margin: 0; + padding: 0.25em; + background: transparent; +} + +button.action-button { + cursor: pointer; } -.expression .kanji-link { - border-bottom-width: 1px; +.icon-image { + width: 1.14285714em; /* 14px => 16px */ + height: 1.14285714em; /* 14px => 16px */ + display: block; +} + +.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-multi-expression=true] .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[data-multi=true] .term-expression-details { + visibility: hidden; +} + +.term-expression-list[data-multi=true] .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] .term-expression:hover .term-expression-details { + visibility: visible; +} + +.term-expression-list[data-multi=true] .term-expression-details>.action-play-audio { position: absolute; - left: 0px; - bottom: 10px; + left: 0; + bottom: 0.5em; } -.expression .peek-wrapper .tags { +.term-expression-list[data-multi=true] .term-expression-details>.action-play-audio { + display: block; +} + +.term-expression-list[data-multi=true] .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] .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; +} + +: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; } -.glossary ul.compact-glossary { +: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; +} + +.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; } -.info-output { +.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/js/display-generator.js b/ext/mixed/js/display-generator.js new file mode 100644 index 00000000..37be5041 --- /dev/null +++ b/ext/mixed/js/display-generator.js @@ -0,0 +1,332 @@ +/* + * Copyright (C) 2019-2020 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +class DisplayGenerator { + constructor() { + this._termEntryTemplate = document.querySelector('#term-entry-template'); + this._termExpressionTemplate = document.querySelector('#term-expression-template'); + this._termDefinitionItemTemplate = document.querySelector('#term-definition-item-template'); + this._termDefinitionOnlyTemplate = document.querySelector('#term-definition-only-template'); + this._termGlossaryItemTemplate = document.querySelector('#term-glossary-item-template'); + this._termReasonTemplate = document.querySelector('#term-reason-template'); + + this._kanjiEntryTemplate = document.querySelector('#kanji-entry-template'); + this._kanjiInfoTableTemplate = document.querySelector('#kanji-info-table-template'); + this._kanjiInfoTableItemTemplate = document.querySelector('#kanji-info-table-item-template'); + this._kanjiInfoTableEmptyTemplate = document.querySelector('#kanji-info-table-empty-template'); + this._kanjiGlossaryItemTemplate = document.querySelector('#kanji-glossary-item-template'); + this._kanjiReadingTemplate = document.querySelector('#kanji-reading-template'); + + this._tagTemplate = document.querySelector('#tag-template'); + this._tagFrequencyTemplate = document.querySelector('#tag-frequency-template'); + } + + createTermEntry(details) { + const node = DisplayGenerator._instantiateTemplate(this._termEntryTemplate); + + const expressionsContainer = node.querySelector('.term-expression-list'); + const reasonsContainer = node.querySelector('.reasons'); + const frequenciesContainer = node.querySelector('.frequencies'); + const definitionsContainer = node.querySelector('.term-definition-list'); + const debugInfoContainer = node.querySelector('.debug-info'); + + const multiExpression = Array.isArray(details.expressions); + const multiDefinition = Array.isArray(details.definitions); + + node.dataset.multiExpression = `${multiExpression}`; + node.dataset.multiDefinition = `${multiDefinition}`; + + 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) { + const segments = [{text: details.expression, furigana: details.reading}]; // TODO : Use proper furigana segmentation + DisplayGenerator._appendFurigana(expressionContainer, segments, 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; + } + + _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) { + const content = document.importNode(template.content, true); + return content.firstChild; + } +} diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index e756f948..f61e76b5 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -37,6 +37,7 @@ class Display { this.eventListenersActive = false; this.clickScanPrevent = false; + this.displayGenerator = new DisplayGenerator(); this.windowScroll = new WindowScroll(); this.setInteractive(true); @@ -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)); @@ -347,25 +357,25 @@ class Display { } 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; } - const content = await apiTemplateRender('terms.html', params); - this.container.innerHTML = content; + this.updateNavigation(this.context.previous, this.context.next); + this.setNoContentVisible(definitions.length === 0); + + const fragment = document.createDocumentFragment(); + for (const definition of definitions) { + fragment.appendChild(this.displayGenerator.createTermEntry(definition)); + } + + await Promise.resolve(); // Delay to help avoid forced reflow warnings in Chrome + + this.container.textContent = ''; + this.container.appendChild(fragment); + const {index, scroll, disableScroll} = context; if (!disableScroll) { this.entryScrollIntoView(index || 0, scroll); @@ -391,8 +401,6 @@ class Display { if (!this.isInitialized()) { return; } try { - const options = this.options; - this.setEventListenersActive(false); if (context.focus !== false) { @@ -408,21 +416,25 @@ class Display { } 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; } - const content = await apiTemplateRender('kanji.html', params); - this.container.innerHTML = content; + this.updateNavigation(this.context.previous, this.context.next); + this.setNoContentVisible(definitions.length === 0); + + const fragment = document.createDocumentFragment(); + for (const definition of definitions) { + fragment.appendChild(this.displayGenerator.createKanjiEntry(definition)); + } + + await Promise.resolve(); // Delay to help avoid forced reflow warnings in Chrome + + this.container.textContent = ''; + this.container.appendChild(fragment); + const {index, scroll} = context; this.entryScrollIntoView(index || 0, scroll); @@ -445,6 +457,26 @@ class Display { if (errorOrphaned !== null) { errorOrphaned.style.setProperty('display', 'block', 'important'); } + + 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}`; + } } autoPlayAudio() { @@ -733,6 +765,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]); } -- cgit v1.2.3 From a50e2fb0f12838673543131c02e7ca37fe4b66fb Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Fri, 27 Dec 2019 15:08:55 -0500 Subject: Fix furigana segmentation --- ext/bg/js/dictionary.js | 3 ++- ext/bg/js/translator.js | 33 +++++++++++++++++++++------------ ext/mixed/js/display-generator.js | 8 ++++++-- 3 files changed, 29 insertions(+), 15 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js index ee7ee756..67128725 100644 --- a/ext/bg/js/dictionary.js +++ b/ext/bg/js/dictionary.js @@ -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/translator.js b/ext/bg/js/translator.js index 7473c6ad..e31f9f62 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))); } } @@ -194,7 +188,7 @@ 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(expression, reading)]; definitionsMerged.push(groupedDefinition); } @@ -241,14 +235,18 @@ 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, 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), @@ -504,6 +502,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'; diff --git a/ext/mixed/js/display-generator.js b/ext/mixed/js/display-generator.js index 37be5041..1921a454 100644 --- a/ext/mixed/js/display-generator.js +++ b/ext/mixed/js/display-generator.js @@ -76,8 +76,12 @@ class DisplayGenerator { } if (expressionContainer !== null) { - const segments = [{text: details.expression, furigana: details.reading}]; // TODO : Use proper furigana segmentation - DisplayGenerator._appendFurigana(expressionContainer, segments, this._appendKanjiLinks.bind(this)); + 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); -- cgit v1.2.3 From 24832be63693d8f04797ed45041ffbd3e8ac3f9d Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Fri, 27 Dec 2019 15:10:51 -0500 Subject: Update how spinner visibility is controlled --- ext/bg/search.html | 4 +--- ext/fg/float.html | 4 +--- ext/mixed/css/display.css | 1 - ext/mixed/js/display.js | 4 +++- 4 files changed, 5 insertions(+), 8 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/bg/search.html b/ext/bg/search.html index 5d9babea..819c8505 100644 --- a/ext/bg/search.html +++ b/ext/bg/search.html @@ -43,9 +43,7 @@ -
- -
+
diff --git a/ext/fg/float.html b/ext/fg/float.html index f5f56853..9879ae3e 100644 --- a/ext/fg/float.html +++ b/ext/fg/float.html @@ -15,9 +15,7 @@ -
- -
+ -
+ - - - - - - - - - - - - - - - - - diff --git a/ext/fg/float.html b/ext/fg/float.html index 9cc0dc39..bec5ae68 100644 --- a/ext/fg/float.html +++ b/ext/fg/float.html @@ -40,84 +40,6 @@
- - - - - - - - - - - - - - - - - diff --git a/ext/mixed/display-templates.html b/ext/mixed/display-templates.html new file mode 100644 index 00000000..01cfeffc --- /dev/null +++ b/ext/mixed/display-templates.html @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/ext/mixed/js/api.js b/ext/mixed/js/api.js index 8ed1d996..9f0835b0 100644 --- a/ext/mixed/js/api.js +++ b/ext/mixed/js/api.js @@ -101,6 +101,10 @@ function apiClipboardGet() { return _apiInvoke('clipboardGet'); } +function apiGetDisplayTemplatesHtml() { + return _apiInvoke('getDisplayTemplatesHtml'); +} + function _apiInvoke(action, params={}) { const data = {action, params}; return new Promise((resolve, reject) => { diff --git a/ext/mixed/js/display-generator.js b/ext/mixed/js/display-generator.js index 44b250e7..8eb699e0 100644 --- a/ext/mixed/js/display-generator.js +++ b/ext/mixed/js/display-generator.js @@ -19,22 +19,39 @@ class DisplayGenerator { constructor() { - this._termEntryTemplate = document.querySelector('#term-entry-template'); - this._termExpressionTemplate = document.querySelector('#term-expression-template'); - this._termDefinitionItemTemplate = document.querySelector('#term-definition-item-template'); - this._termDefinitionOnlyTemplate = document.querySelector('#term-definition-only-template'); - this._termGlossaryItemTemplate = document.querySelector('#term-glossary-item-template'); - this._termReasonTemplate = document.querySelector('#term-reason-template'); - - this._kanjiEntryTemplate = document.querySelector('#kanji-entry-template'); - this._kanjiInfoTableTemplate = document.querySelector('#kanji-info-table-template'); - this._kanjiInfoTableItemTemplate = document.querySelector('#kanji-info-table-item-template'); - this._kanjiInfoTableEmptyTemplate = document.querySelector('#kanji-info-table-empty-template'); - this._kanjiGlossaryItemTemplate = document.querySelector('#kanji-glossary-item-template'); - this._kanjiReadingTemplate = document.querySelector('#kanji-reading-template'); - - this._tagTemplate = document.querySelector('#tag-template'); - this._tagFrequencyTemplate = document.querySelector('#tag-frequency-template'); + 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) { @@ -259,6 +276,31 @@ class DisplayGenerator { 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) { diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index eabb73ca..75b43aa0 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -356,6 +356,11 @@ class Display { window.focus(); } + if (!this.displayGenerator.isInitialized()) { + await this.displayGenerator.initialize(); + if (this.setContentToken !== token) { return; } + } + this.definitions = definitions; if (context.disableHistory) { delete context.disableHistory; @@ -415,6 +420,11 @@ class Display { window.focus(); } + if (!this.displayGenerator.isInitialized()) { + await this.displayGenerator.initialize(); + if (this.setContentToken !== token) { return; } + } + this.definitions = definitions; if (context.disableHistory) { delete context.disableHistory; -- cgit v1.2.3 From d4296a34cca1f4eeb84fec53608a7e5c6b9b9fb1 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 28 Dec 2019 23:03:18 -0500 Subject: Fix scroll position when header is visible --- ext/mixed/js/display.js | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index 75b43aa0..50e099f6 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -552,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) { -- cgit v1.2.3 From 6c344b2740ae7ef0bc214d1391c1592d802434ac Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Thu, 16 Jan 2020 20:48:51 -0500 Subject: Fix incorrect selector --- ext/mixed/js/display.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/display.js b/ext/mixed/js/display.js index 50e099f6..c4be02f2 100644 --- a/ext/mixed/js/display.js +++ b/ext/mixed/js/display.js @@ -175,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); } -- cgit v1.2.3 From 9abfd7acde5c917f70db9f2d9e04148862102f57 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Thu, 16 Jan 2020 21:33:58 -0500 Subject: Always show actions when there is only a single term result --- ext/mixed/css/display.css | 16 ++++++++-------- ext/mixed/js/display-generator.js | 10 ++++++---- 2 files changed, 14 insertions(+), 12 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/css/display.css b/ext/mixed/css/display.css index 325cc8e7..808306ca 100644 --- a/ext/mixed/css/display.css +++ b/ext/mixed/css/display.css @@ -233,7 +233,7 @@ button.action-button { border-top-style: solid; } -.entry[data-type=term][data-multi-expression=true] .actions>.action-play-audio { +.entry[data-type=term][data-expression-multi=true]:not([data-expression-count="1"]) .actions>.action-play-audio { display: none; } @@ -280,11 +280,11 @@ button.action-button { content: "\3001"; } -.term-expression-list[data-multi=true] .term-expression-details { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details { visibility: hidden; } -.term-expression-list[data-multi=true] .term-expression-details { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details { display: inline-block; position: relative; width: 0; @@ -292,21 +292,21 @@ button.action-button { visibility: hidden; } -.term-expression-list[data-multi=true] .term-expression:hover .term-expression-details { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression:hover .term-expression-details { visibility: visible; } -.term-expression-list[data-multi=true] .term-expression-details>.action-play-audio { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.action-play-audio { position: absolute; left: 0; bottom: 0.5em; } -.term-expression-list[data-multi=true] .term-expression-details>.action-play-audio { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.action-play-audio { display: block; } -.term-expression-list[data-multi=true] .term-expression-details>.tags { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.tags { display: block; position: absolute; left: 0; @@ -314,7 +314,7 @@ button.action-button { white-space: nowrap; } -.term-expression-list[data-multi=true] .term-expression-details>.frequencies { +.term-expression-list[data-multi=true]:not([data-count="1"]) .term-expression-details>.frequencies { display: block; position: absolute; left: 0; diff --git a/ext/mixed/js/display-generator.js b/ext/mixed/js/display-generator.js index 8eb699e0..63e7a8b5 100644 --- a/ext/mixed/js/display-generator.js +++ b/ext/mixed/js/display-generator.js @@ -63,11 +63,13 @@ class DisplayGenerator { const definitionsContainer = node.querySelector('.term-definition-list'); const debugInfoContainer = node.querySelector('.debug-info'); - const multiExpression = Array.isArray(details.expressions); - const multiDefinition = Array.isArray(details.definitions); + const expressionMulti = Array.isArray(details.expressions); + const definitionMulti = Array.isArray(details.definitions); - node.dataset.multiExpression = `${multiExpression}`; - node.dataset.multiDefinition = `${multiDefinition}`; + 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); -- cgit v1.2.3 From 1fd568ab8e7c909010e843654540162baeab9e1e Mon Sep 17 00:00:00 2001 From: siikamiika Date: Sun, 19 Jan 2020 03:04:45 +0200 Subject: fix term reason selector --- ext/mixed/js/display-generator.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/display-generator.js b/ext/mixed/js/display-generator.js index 63e7a8b5..e1710488 100644 --- a/ext/mixed/js/display-generator.js +++ b/ext/mixed/js/display-generator.js @@ -58,7 +58,7 @@ class DisplayGenerator { const node = DisplayGenerator._instantiateTemplate(this._termEntryTemplate); const expressionsContainer = node.querySelector('.term-expression-list'); - const reasonsContainer = node.querySelector('.reasons'); + const reasonsContainer = node.querySelector('.term-reasons'); const frequenciesContainer = node.querySelector('.frequencies'); const definitionsContainer = node.querySelector('.term-definition-list'); const debugInfoContainer = node.querySelector('.debug-info'); -- cgit v1.2.3 From 26ea278c29dbb19d003dddda2e60559c502d0cc3 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 21 Jan 2020 19:08:56 -0500 Subject: Improve debug logging --- ext/bg/css/settings.css | 17 +++++++++++++++++ ext/bg/js/request.js | 7 ++++--- ext/bg/js/settings/anki.js | 26 ++++++++++++++++++++++++-- ext/mixed/js/core.js | 10 ++++++++-- 4 files changed, 53 insertions(+), 7 deletions(-) (limited to 'ext/mixed/js') 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/js/request.js b/ext/bg/js/request.js index 778f933b..02eed6fb 100644 --- a/ext/bg/js/request.js +++ b/ext/bg/js/request.js @@ -36,8 +36,9 @@ async function requestJson(url, action, params) { const responseText = await requestText(url, action, params); try { return JSON.parse(responseText); - } - catch (e) { - throw new Error('Invalid response'); + } 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/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/mixed/js/core.js b/ext/mixed/js/core.js index 54e8a9d2..7fc01c94 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'; -- cgit v1.2.3 From 8ef57936d7ab25c723d4da2d655b742cdcf8c84a Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Mon, 23 Dec 2019 11:59:47 -0500 Subject: Add functionality for getting and observing zoom factor --- ext/bg/js/backend.js | 31 +++++++++++++++++++++++++++++-- ext/mixed/js/api.js | 4 ++++ ext/mixed/js/core.js | 7 ++++++- 3 files changed, 39 insertions(+), 3 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js index 391d6243..4e6c59df 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) { @@ -527,6 +535,24 @@ class Backend { 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; + 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) { @@ -741,7 +767,8 @@ Backend._messageHandlers = new Map([ ['injectStylesheet', (self, ...args) => self._onApiInjectStylesheet(...args)], ['getEnvironmentInfo', (self, ...args) => self._onApiGetEnvironmentInfo(...args)], ['clipboardGet', (self, ...args) => self._onApiClipboardGet(...args)], - ['getDisplayTemplatesHtml', (self, ...args) => self._onApiGetDisplayTemplatesHtml(...args)] + ['getDisplayTemplatesHtml', (self, ...args) => self._onApiGetDisplayTemplatesHtml(...args)], + ['getZoom', (self, ...args) => self._onApiGetZoom(...args)] ]); Backend._commandHandlers = new Map([ diff --git a/ext/mixed/js/api.js b/ext/mixed/js/api.js index 9f0835b0..5ec93b01 100644 --- a/ext/mixed/js/api.js +++ b/ext/mixed/js/api.js @@ -105,6 +105,10 @@ 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 7fc01c94..0142d594 100644 --- a/ext/mixed/js/core.js +++ b/ext/mixed/js/core.js @@ -244,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)); @@ -274,6 +275,10 @@ const yomichan = (() => { _onMessageOptionsUpdate({source}) { this.trigger('optionsUpdate', {source}); } + + _onMessageZoomChanged({oldZoomFactor, newZoomFactor}) { + this.trigger('zoomChanged', {oldZoomFactor, newZoomFactor}); + } } return new Yomichan(); -- cgit v1.2.3 From aa5a044dade6a6b4caaa368215b96add53a312b4 Mon Sep 17 00:00:00 2001 From: siikamiika Date: Sat, 25 Jan 2020 02:56:14 +0200 Subject: query parser: add reading mode 'none' --- ext/bg/data/options-schema.json | 2 +- ext/bg/settings.html | 1 + ext/mixed/js/japanese.js | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) (limited to 'ext/mixed/js') diff --git a/ext/bg/data/options-schema.json b/ext/bg/data/options-schema.json index 3cb25218..224b93f8 100644 --- a/ext/bg/data/options-schema.json +++ b/ext/bg/data/options-schema.json @@ -398,7 +398,7 @@ }, "readingMode": { "type": "string", - "enum": ["hiragana", "katakana", "romaji"], + "enum": ["hiragana", "katakana", "romaji", "none"], "default": "hiragana" } } diff --git a/ext/bg/settings.html b/ext/bg/settings.html index a283335c..4b73e02c 100644 --- a/ext/bg/settings.html +++ b/ext/bg/settings.html @@ -457,6 +457,7 @@ +
diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 23b2bd36..c9bc7b87 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -80,6 +80,8 @@ function jpConvertReading(expressionFragment, readingFragment, readingMode) { } } return readingFragment; + case 'none': + return null; default: return readingFragment; } -- cgit v1.2.3 From 73cc64fb5c055a95c0c26a1cb173269cdeac8659 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sun, 22 Dec 2019 14:07:30 -0500 Subject: Implement new translation options --- ext/bg/js/translator.js | 56 +++++++++++-- ext/mixed/js/japanese.js | 201 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 252 insertions(+), 5 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/bg/js/translator.js b/ext/bg/js/translator.js index bb78d46d..88a5c6e8 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -240,6 +240,7 @@ class Translator { definitions.push({ source: deinflection.source, + rawSource: deinflection.rawSource, reasons: deinflection.reasons, score: definition.score, id: definition.id, @@ -260,7 +261,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]; @@ -274,6 +275,7 @@ class Translator { return [{ source: text, + rawSource: text, term: text, rules: 0, definitions, @@ -320,27 +322,71 @@ class Translator { return deinflections.filter((e) => e.definitions.length > 0); } - getAllDeinflections(text, _options) { + getAllDeinflections(text, options) { + const translationOptions = options.translation; const textOptionVariantArray = [ - [false, true] // convert katakana to hiragana + Translator.getTextOptionEntryVariants(translationOptions.convertKatakanaToHiragana), + Translator.getTextOptionEntryVariants(translationOptions.convertHalfWidthCharacters), + Translator.getTextOptionEntryVariants(translationOptions.convertNumericCharacters), + Translator.getTextOptionEntryVariants(translationOptions.convertAlphabeticCharacters) ]; const deinflections = []; const used = new Set(); - for (const [hiragana] of Translator.getArrayVariants(textOptionVariantArray)) { + for (const [hiragana, halfWidth, numeric, alphabetic] 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 (hiragana) { text2 = jpKatakanaToHiragana(text2); } for (let i = text2.length; i > 0; --i) { const text2Substring = text2.substring(0, i); if (used.has(text2Substring)) { break; } used.add(text2Substring); - deinflections.push(...this.deinflector.deinflect(text2Substring)); + for (const deinflection of this.deinflector.deinflect(text2Substring)) { + deinflection.rawSource = Translator.getDeinflectionRawSource(text, i, sourceMapping); + deinflections.push(deinflection); + } } } return deinflections; } + static getTextOptionEntryVariants(value) { + switch (value) { + case 'true': return [true]; + case 'variant': return [false, true]; + default: return [false]; + } + } + + static getDeinflectionRawSource(source, length, sourceMapping) { + if (sourceMapping === null) { + return source.substring(0, length); + } + + 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) { const dictionaries = dictEnabledSet(options); const titles = Object.keys(dictionaries); diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 23b2bd36..26349094 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -17,6 +17,65 @@ */ +const jpHalfWidthCharacterMapping = new Map([ + ['ヲ', 'ヲヺ-'], + ['ァ', 'ァ--'], + ['ィ', 'ィ--'], + ['ゥ', 'ゥ--'], + ['ェ', 'ェ--'], + ['ォ', 'ォ--'], + ['ャ', 'ャ--'], + ['ュ', 'ュ--'], + ['ョ', 'ョ--'], + ['ッ', 'ッ--'], + ['ー', 'ー--'], + ['ア', 'ア--'], + ['イ', 'イ--'], + ['ウ', 'ウヴ-'], + ['エ', 'エ--'], + ['オ', 'オ--'], + ['カ', 'カガ-'], + ['キ', 'キギ-'], + ['ク', 'クグ-'], + ['ケ', 'ケゲ-'], + ['コ', 'コゴ-'], + ['サ', 'サザ-'], + ['シ', 'シジ-'], + ['ス', 'スズ-'], + ['セ', 'セゼ-'], + ['ソ', 'ソゾ-'], + ['タ', 'タダ-'], + ['チ', 'チヂ-'], + ['ツ', 'ツヅ-'], + ['テ', 'テデ-'], + ['ト', 'トド-'], + ['ナ', 'ナ--'], + ['ニ', 'ニ--'], + ['ヌ', 'ヌ--'], + ['ネ', 'ネ--'], + ['ノ', 'ノ--'], + ['ハ', 'ハバパ'], + ['ヒ', 'ヒビピ'], + ['フ', 'フブプ'], + ['ヘ', 'ヘベペ'], + ['ホ', 'ホボポ'], + ['マ', 'マ--'], + ['ミ', 'ミ--'], + ['ム', 'ム--'], + ['メ', 'メ--'], + ['モ', 'モ--'], + ['ヤ', 'ヤ--'], + ['ユ', 'ユ--'], + ['ヨ', 'ヨ--'], + ['ラ', 'ラ--'], + ['リ', 'リ--'], + ['ル', 'ル--'], + ['レ', 'レ--'], + ['ロ', 'ロ--'], + ['ワ', 'ワ--'], + ['ン', 'ン--'] +]); + function jpIsKanji(c) { const code = c.charCodeAt(0); return code >= 0x4e00 && code < 0x9fb0 || code >= 0x3400 && code < 0x4dc0; @@ -175,3 +234,145 @@ 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 = jpHalfWidthCharacterMapping.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) { + let c = text.charCodeAt(i); + if (c >= 0x41 && c <= 0x5a) { // ['A', 'Z'] + c -= 0x41; + } else if (c >= 0x61 && c <= 0x7a) { // ['a', 'z'] + c -= 0x61; + } else if (c >= 0xff21 && c <= 0xff3a) { // ['A', 'Z'] full width + c -= 0xff21; + } else if (c >= 0xff41 && c <= 0xff5a) { // ['a', 'z'] full width + c -= 0xff41; + } else { + if (part.length > 0) { + result += jpToHiragana(part, sourceMapping, result.length); + part = ''; + } + result += text[i]; + continue; + } + part += String.fromCharCode(c + 0x61); // + 'a' + } + + 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; +} -- cgit v1.2.3 From be2e6e0d9361e844c39bb3e48a3777db0ef52f67 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sun, 22 Dec 2019 15:46:23 -0500 Subject: Optimize jpIsKanji and jpIsKana --- ext/mixed/js/japanese.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 26349094..44db4b8c 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -78,11 +78,18 @@ const jpHalfWidthCharacterMapping = new Map([ function jpIsKanji(c) { const code = c.charCodeAt(0); - return code >= 0x4e00 && code < 0x9fb0 || code >= 0x3400 && code < 0x4dc0; + return ( + (code >= 0x4e00 && code < 0x9fb0) || + (code >= 0x3400 && code < 0x4dc0) + ); } function jpIsKana(c) { - return wanakana.isKana(c); + const code = c.charCodeAt(0); + return ( + (code >= 0x3041 && code <= 0x3096) || // hiragana + (code >= 0x30a1 && code <= 0x30fc) // katakana + ); } function jpIsJapaneseText(text) { -- cgit v1.2.3 From 86d96a903696db98c0680d7665c53da5cd80731f Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sun, 22 Dec 2019 18:26:27 -0500 Subject: Update detection of Japanese characters --- ext/bg/js/search.js | 2 +- ext/bg/js/translator.js | 23 ++++++++++++++++++----- ext/mixed/js/japanese.js | 8 ++++++-- 3 files changed, 25 insertions(+), 8 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index 673f066b..ea68915c 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -265,7 +265,7 @@ class DisplaySearch extends Display { text !== this.clipboardPreviousText ) { this.clipboardPreviousText = text; - if (jpIsJapaneseText(text)) { + if (jpIsAnyCharacterJapanese(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/translator.js b/ext/bg/js/translator.js index d9cb0c54..2fb36194 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -214,11 +214,9 @@ class Translator { } async findTermsInternal(text, dictionaries, details, options) { - if (!options.scanning.alphanumeric && text.length > 0) { - const c = text[0]; - if (!jpIsKana(c) && !jpIsKanji(c)) { - return [[], 0]; - } + text = Translator.getSearchableText(text, options); + if (text.length === 0) { + return [[], 0]; } const titles = Object.keys(dictionaries); @@ -587,4 +585,19 @@ class Translator { yield variant; } } + + static getSearchableText(text, options) { + if (!options.scanning.alphanumeric) { + const ii = text.length; + for (let i = 0; i < ii; ++i) { + const c = text[i]; + if (!jpIsCharacterJapanese(c)) { + text = text.substring(0, i); + break; + } + } + } + + return text; + } } diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 44db4b8c..8d69c180 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -92,9 +92,13 @@ function jpIsKana(c) { ); } -function jpIsJapaneseText(text) { +function jpIsCharacterJapanese(c) { + return jpIsKanji(c) || jpIsKana(c); +} + +function jpIsAnyCharacterJapanese(text) { for (const c of text) { - if (jpIsKanji(c) || jpIsKana(c)) { + if (jpIsCharacterJapanese(c)) { return true; } } -- cgit v1.2.3 From b5015264f25af6b81d13dfee869ea34db4317aaa Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sun, 22 Dec 2019 18:27:41 -0500 Subject: Include half width and full width characters as Japanese characters --- ext/mixed/js/japanese.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 8d69c180..25f0608e 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -92,8 +92,22 @@ function jpIsKana(c) { ); } +function jpIsCharFullWidth(c) { + const code = c.charCodeAt(0); + return ( + (code >= 0xff21 && code <= 0xff3a) || // full width upper case roman letters + (code >= 0xff41 && code <= 0xff3a) || // full width upper case roman letters + (code >= 0xff10 && code <= 0xff19) // full width numbers + ); +} + +function jpIsKanaHalfWidth(c) { + const code = c.charCodeAt(0); + return (code >= 0xff66 && code <= 0xff9f); // half width katakana +} + function jpIsCharacterJapanese(c) { - return jpIsKanji(c) || jpIsKana(c); + return jpIsKanji(c) || jpIsKana(c) || jpIsCharFullWidth(c) || jpIsKanaHalfWidth(c); } function jpIsAnyCharacterJapanese(text) { -- cgit v1.2.3 From 3c17388ff85daf477a1cae21103f705bce96bfcd Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Wed, 22 Jan 2020 20:54:06 -0500 Subject: Update constant naming convention --- ext/mixed/js/japanese.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 25f0608e..8dd5651c 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -17,7 +17,7 @@ */ -const jpHalfWidthCharacterMapping = new Map([ +const JP_HALFWIDTH_KATAKANA_MAPPING = new Map([ ['ヲ', 'ヲヺ-'], ['ァ', 'ァ--'], ['ィ', 'ィ--'], @@ -76,6 +76,7 @@ const jpHalfWidthCharacterMapping = new Map([ ['ン', 'ン--'] ]); + function jpIsKanji(c) { const code = c.charCodeAt(0); return ( @@ -267,7 +268,7 @@ function jpConvertHalfWidthKanaToFullWidth(text, sourceMapping) { for (let i = 0; i < ii; ++i) { const c = text[i]; - const mapping = jpHalfWidthCharacterMapping.get(c); + const mapping = JP_HALFWIDTH_KATAKANA_MAPPING.get(c); if (typeof mapping !== 'string') { result += c; continue; -- cgit v1.2.3 From 9b509d50a94110f92ac52db2ff9566d1104e33c6 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Wed, 22 Jan 2020 21:41:32 -0500 Subject: Add character range definitions --- ext/mixed/js/japanese.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 8dd5651c..956d246a 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -76,6 +76,41 @@ 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 +]; + function jpIsKanji(c) { const code = c.charCodeAt(0); -- cgit v1.2.3 From 1fa8a596266340606de3b090f0081f8ed1627065 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Wed, 22 Jan 2020 21:43:38 -0500 Subject: Create new character/string testing functions --- ext/mixed/js/japanese.js | 55 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 956d246a..98ce9fc4 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -112,6 +112,58 @@ const JP_JAPANESE_RANGES = [ ]; +// Helper functions + +function _jpIsCharCodeInRanges(charCode, ranges) { + for (const [min, max] of ranges) { + if (charCode >= min && charCode <= max) { + return true; + } + } + return false; +} + + +// Character code testing functions + +function jpIsCharCodeKanji(charCode) { + return _jpIsCharCodeInRanges(charCode, JP_CJK_RANGES); +} + +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; +} + + +// Old character/string testing functions + function jpIsKanji(c) { const code = c.charCodeAt(0); return ( @@ -155,6 +207,9 @@ function jpIsAnyCharacterJapanese(text) { return false; } + +// Conversion functions + function jpKatakanaToHiragana(text) { let result = ''; for (const c of text) { -- cgit v1.2.3 From 317bf35bc039fb82b558c66adac236ff6a84d762 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Wed, 22 Jan 2020 21:53:47 -0500 Subject: Replace and remove old character/string testing functions --- ext/bg/js/handlebars.js | 2 +- ext/bg/js/search.js | 2 +- ext/bg/js/translator.js | 3 +-- ext/mixed/js/japanese.js | 51 +++--------------------------------------------- 4 files changed, 6 insertions(+), 52 deletions(-) (limited to 'ext/mixed/js') 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 += `${c}`; } else { result += c; diff --git a/ext/bg/js/search.js b/ext/bg/js/search.js index ea68915c..f5c641a8 100644 --- a/ext/bg/js/search.js +++ b/ext/bg/js/search.js @@ -265,7 +265,7 @@ class DisplaySearch extends Display { text !== this.clipboardPreviousText ) { this.clipboardPreviousText = text; - if (jpIsAnyCharacterJapanese(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/translator.js b/ext/bg/js/translator.js index 2fb36194..cda1099f 100644 --- a/ext/bg/js/translator.js +++ b/ext/bg/js/translator.js @@ -590,8 +590,7 @@ class Translator { if (!options.scanning.alphanumeric) { const ii = text.length; for (let i = 0; i < ii; ++i) { - const c = text[i]; - if (!jpIsCharacterJapanese(c)) { + if (!jpIsCharCodeJapanese(text.charCodeAt(i))) { text = text.substring(0, i); break; } diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 98ce9fc4..93366db0 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -162,52 +162,6 @@ function jpIsStringPartiallyJapanese(str) { } -// Old character/string testing functions - -function jpIsKanji(c) { - const code = c.charCodeAt(0); - return ( - (code >= 0x4e00 && code < 0x9fb0) || - (code >= 0x3400 && code < 0x4dc0) - ); -} - -function jpIsKana(c) { - const code = c.charCodeAt(0); - return ( - (code >= 0x3041 && code <= 0x3096) || // hiragana - (code >= 0x30a1 && code <= 0x30fc) // katakana - ); -} - -function jpIsCharFullWidth(c) { - const code = c.charCodeAt(0); - return ( - (code >= 0xff21 && code <= 0xff3a) || // full width upper case roman letters - (code >= 0xff41 && code <= 0xff3a) || // full width upper case roman letters - (code >= 0xff10 && code <= 0xff19) // full width numbers - ); -} - -function jpIsKanaHalfWidth(c) { - const code = c.charCodeAt(0); - return (code >= 0xff66 && code <= 0xff9f); // half width katakana -} - -function jpIsCharacterJapanese(c) { - return jpIsKanji(c) || jpIsKana(c) || jpIsCharFullWidth(c) || jpIsKanaHalfWidth(c); -} - -function jpIsAnyCharacterJapanese(text) { - for (const c of text) { - if (jpIsCharacterJapanese(c)) { - return true; - } - } - return false; -} - - // Conversion functions function jpKatakanaToHiragana(text) { @@ -250,7 +204,7 @@ function jpConvertReading(expressionFragment, readingFragment, readingMode) { if (readingFragment) { return jpToRomaji(readingFragment); } else { - if (jpIsKana(expressionFragment)) { + if (jpIsStringEntirelyKana(expressionFragment)) { return jpToRomaji(expressionFragment); } } @@ -307,7 +261,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 { -- cgit v1.2.3 From 46e3d72641bee767f5d54e8778597549df85bdb3 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Fri, 24 Jan 2020 17:53:14 -0500 Subject: Move where 'a' character offset is applied --- ext/mixed/js/japanese.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index 93366db0..d299dfe9 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -375,15 +375,16 @@ function jpConvertAlphabeticToKana(text, sourceMapping) { } 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 -= 0x41; + c += (0x61 - 0x41); } else if (c >= 0x61 && c <= 0x7a) { // ['a', 'z'] - c -= 0x61; - } else if (c >= 0xff21 && c <= 0xff3a) { // ['A', 'Z'] full width - c -= 0xff21; - } else if (c >= 0xff41 && c <= 0xff5a) { // ['a', 'z'] full width - c -= 0xff41; + // 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 (part.length > 0) { result += jpToHiragana(part, sourceMapping, result.length); @@ -392,7 +393,7 @@ function jpConvertAlphabeticToKana(text, sourceMapping) { result += text[i]; continue; } - part += String.fromCharCode(c + 0x61); // + 'a' + part += String.fromCharCode(c); } if (part.length > 0) { -- cgit v1.2.3 From be645c2c9856b3723ba1192132d2947d4f13eb9a Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Fri, 24 Jan 2020 17:58:05 -0500 Subject: Add support for dashes --- ext/mixed/js/japanese.js | 2 ++ 1 file changed, 2 insertions(+) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/japanese.js b/ext/mixed/js/japanese.js index d299dfe9..0cbaa723 100644 --- a/ext/mixed/js/japanese.js +++ b/ext/mixed/js/japanese.js @@ -385,6 +385,8 @@ function jpConvertAlphabeticToKana(text, sourceMapping) { 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); -- cgit v1.2.3 From 54a48a7a9ba33fa07b3acaa775f3d1c384172dbd Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 25 Jan 2020 11:17:39 -0500 Subject: Ensure textSource is cleaned up if it isn't used --- ext/mixed/js/text-scanner.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'ext/mixed/js') diff --git a/ext/mixed/js/text-scanner.js b/ext/mixed/js/text-scanner.js index e037109d..88f1e27a 100644 --- a/ext/mixed/js/text-scanner.js +++ b/ext/mixed/js/text-scanner.js @@ -299,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) { -- cgit v1.2.3