Pop-up dictionary browser extension for language learning. Successor to Yomichan. (PERSONAL FORK)
at lambda-fork/main 1168 lines 48 kB view raw
1/* 2 * Copyright (C) 2023-2025 Yomitan Authors 3 * Copyright (C) 2019-2022 Yomichan Authors 4 * 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <https://www.gnu.org/licenses/>. 17 */ 18 19import {ExtensionError} from '../core/extension-error.js'; 20import {safePerformance} from '../core/safe-performance.js'; 21import {getDisambiguations, getGroupedPronunciations, getTermFrequency, groupKanjiFrequencies, groupTermFrequencies, groupTermTags, isNonNounVerbOrAdjective} from '../dictionary/dictionary-data-util.js'; 22import {HtmlTemplateCollection} from '../dom/html-template-collection.js'; 23import {distributeFurigana, getKanaMorae, getPitchCategory, isCodePointKanji} from '../language/ja/japanese.js'; 24import {getLanguageFromText} from '../language/text-utilities.js'; 25import {PronunciationGenerator} from './pronunciation-generator.js'; 26import {StructuredContentGenerator} from './structured-content-generator.js'; 27 28export class DisplayGenerator { 29 /** 30 * @param {import('./display-content-manager.js').DisplayContentManager} contentManager 31 * @param {?import('../input/hotkey-help-controller.js').HotkeyHelpController} hotkeyHelpController 32 */ 33 constructor(contentManager, hotkeyHelpController) { 34 /** @type {import('./display-content-manager.js').DisplayContentManager} */ 35 this._contentManager = contentManager; 36 /** @type {?import('../input/hotkey-help-controller.js').HotkeyHelpController} */ 37 this._hotkeyHelpController = hotkeyHelpController; 38 /** @type {HtmlTemplateCollection} */ 39 this._templates = new HtmlTemplateCollection(); 40 /** @type {StructuredContentGenerator} */ 41 this._structuredContentGenerator = new StructuredContentGenerator(this._contentManager, document, window); 42 /** @type {PronunciationGenerator} */ 43 this._pronunciationGenerator = new PronunciationGenerator(document); 44 /** @type {string} */ 45 this._language = 'ja'; 46 } 47 48 /** @type {import('./display-content-manager.js').DisplayContentManager} */ 49 get contentManager() { return this._contentManager; } 50 51 set contentManager(contentManager) { 52 this._contentManager = contentManager; 53 } 54 55 /** */ 56 async prepare() { 57 await this._templates.loadFromFiles(['/templates-display.html']); 58 this.updateHotkeys(); 59 } 60 61 /** 62 * @param {string} language 63 */ 64 updateLanguage(language) { 65 this._language = language; 66 } 67 68 /** */ 69 updateHotkeys() { 70 const hotkeyHelpController = this._hotkeyHelpController; 71 if (hotkeyHelpController === null) { return; } 72 for (const template of this._templates.getAllTemplates()) { 73 hotkeyHelpController.setupNode(template.content); 74 } 75 } 76 77 /** 78 * @param {import('dictionary').TermDictionaryEntry} dictionaryEntry 79 * @param {import('dictionary-importer').Summary[]} dictionaryInfo 80 * @returns {HTMLElement} 81 */ 82 createTermEntry(dictionaryEntry, dictionaryInfo) { 83 const node = this._instantiate('term-entry'); 84 85 const headwordsContainer = this._querySelector(node, '.headword-list'); 86 const inflectionRuleChainsContainer = this._querySelector(node, '.inflection-rule-chains'); 87 const groupedPronunciationsContainer = this._querySelector(node, '.pronunciation-group-list'); 88 const frequencyGroupListContainer = this._querySelector(node, '.frequency-group-list'); 89 const definitionsContainer = this._querySelector(node, '.definition-list'); 90 const headwordTagsContainer = this._querySelector(node, '.headword-list-tag-list'); 91 92 const {headwords, type, inflectionRuleChainCandidates, definitions, frequencies, pronunciations} = dictionaryEntry; 93 const groupedPronunciations = getGroupedPronunciations(dictionaryEntry); 94 const pronunciationCount = groupedPronunciations.reduce((i, v) => i + v.pronunciations.length, 0); 95 const groupedFrequencies = groupTermFrequencies(dictionaryEntry, dictionaryInfo); 96 const termTags = groupTermTags(dictionaryEntry); 97 98 /** @type {Set<string>} */ 99 const uniqueTerms = new Set(); 100 /** @type {Set<string>} */ 101 const uniqueReadings = new Set(); 102 /** @type {Set<import('dictionary').TermSourceMatchType>} */ 103 const primaryMatchTypes = new Set(); 104 for (const {term, reading, sources} of headwords) { 105 uniqueTerms.add(term); 106 uniqueReadings.add(reading); 107 for (const {matchType, isPrimary} of sources) { 108 if (!isPrimary) { continue; } 109 primaryMatchTypes.add(matchType); 110 } 111 } 112 113 node.dataset.format = type; 114 node.dataset.headwordCount = `${headwords.length}`; 115 node.dataset.definitionCount = `${definitions.length}`; 116 node.dataset.pronunciationDictionaryCount = `${groupedPronunciations.length}`; 117 node.dataset.pronunciationCount = `${pronunciationCount}`; 118 node.dataset.uniqueTermCount = `${uniqueTerms.size}`; 119 node.dataset.uniqueReadingCount = `${uniqueReadings.size}`; 120 node.dataset.frequencyCount = `${frequencies.length}`; 121 node.dataset.groupedFrequencyCount = `${groupedFrequencies.length}`; 122 node.dataset.primaryMatchTypes = [...primaryMatchTypes].join(' '); 123 124 safePerformance.mark('displayGenerator:createTermEntry:createTermHeadword:start'); 125 for (let i = 0, ii = headwords.length; i < ii; ++i) { 126 const node2 = this._createTermHeadword(headwords[i], i, pronunciations); 127 node2.dataset.index = `${i}`; 128 headwordsContainer.appendChild(node2); 129 } 130 headwordsContainer.dataset.count = `${headwords.length}`; 131 safePerformance.mark('displayGenerator:createTermEntry:createTermHeadword:end'); 132 safePerformance.measure('displayGenerator:createTermEntry:createTermHeadword', 'displayGenerator:createTermEntry:createTermHeadword:start', 'displayGenerator:createTermEntry:createTermHeadword:end'); 133 134 safePerformance.mark('displayGenerator:createTermEntry:promises:start'); 135 this._appendMultiple(inflectionRuleChainsContainer, this._createInflectionRuleChain.bind(this), inflectionRuleChainCandidates); 136 this._appendMultiple(frequencyGroupListContainer, this._createFrequencyGroup.bind(this), groupedFrequencies, false); 137 this._appendMultiple(groupedPronunciationsContainer, this._createGroupedPronunciation.bind(this), groupedPronunciations); 138 this._appendMultiple(headwordTagsContainer, this._createTermTag.bind(this), termTags, headwords.length); 139 safePerformance.mark('displayGenerator:createTermEntry:promises:end'); 140 safePerformance.measure('displayGenerator:createTermEntry:promises', 'displayGenerator:createTermEntry:promises:start', 'displayGenerator:createTermEntry:promises:end'); 141 142 for (const term of uniqueTerms) { 143 headwordTagsContainer.appendChild(this._createSearchTag(term)); 144 } 145 for (const reading of uniqueReadings) { 146 if (uniqueTerms.has(reading)) { continue; } 147 headwordTagsContainer.appendChild(this._createSearchTag(reading)); 148 } 149 150 // Add definitions 151 const dictionaryTag = this._createDictionaryTag(''); 152 for (let i = 0, ii = definitions.length; i < ii; ++i) { 153 const definition = definitions[i]; 154 const {dictionary, dictionaryAlias} = definition; 155 156 if (dictionaryTag.dictionaries.includes(dictionary)) { 157 dictionaryTag.redundant = true; 158 } else { 159 dictionaryTag.redundant = false; 160 dictionaryTag.dictionaries.push(dictionary); 161 dictionaryTag.name = dictionaryAlias; 162 dictionaryTag.content = [dictionary]; 163 164 const currentDictionaryInfo = dictionaryInfo.find(({title}) => title === dictionary); 165 if (currentDictionaryInfo) { 166 const dictionaryContentArray = []; 167 dictionaryContentArray.push(currentDictionaryInfo.title); 168 if (currentDictionaryInfo.author) { 169 dictionaryContentArray.push('Author: ' + currentDictionaryInfo.author); 170 } 171 if (currentDictionaryInfo.description) { 172 dictionaryContentArray.push('Description: ' + currentDictionaryInfo.description); 173 } 174 if (currentDictionaryInfo.url) { 175 dictionaryContentArray.push('URL: ' + currentDictionaryInfo.url); 176 } 177 178 const totalTerms = currentDictionaryInfo?.counts?.terms?.total; 179 if (!!totalTerms && totalTerms > 0) { 180 dictionaryContentArray.push('Term Count: ' + totalTerms.toString()); 181 } 182 183 dictionaryTag.content = dictionaryContentArray; 184 } 185 } 186 187 const node2 = this._createTermDefinition(definition, dictionaryTag, headwords, uniqueTerms, uniqueReadings); 188 node2.dataset.index = `${i}`; 189 definitionsContainer.appendChild(node2); 190 } 191 definitionsContainer.dataset.count = `${definitions.length}`; 192 193 return node; 194 } 195 196 /** 197 * @param {import('dictionary').KanjiDictionaryEntry} dictionaryEntry 198 * @param {import('dictionary-importer').Summary[]} dictionaryInfo 199 * @returns {HTMLElement} 200 */ 201 createKanjiEntry(dictionaryEntry, dictionaryInfo) { 202 const node = this._instantiate('kanji-entry'); 203 node.dataset.dictionary = dictionaryEntry.dictionary; 204 205 const glyphContainer = this._querySelector(node, '.kanji-glyph'); 206 const frequencyGroupListContainer = this._querySelector(node, '.frequency-group-list'); 207 const tagContainer = this._querySelector(node, '.kanji-tag-list'); 208 const definitionsContainer = this._querySelector(node, '.kanji-gloss-list'); 209 const chineseReadingsContainer = this._querySelector(node, '.kanji-readings-chinese'); 210 const japaneseReadingsContainer = this._querySelector(node, '.kanji-readings-japanese'); 211 const statisticsContainer = this._querySelector(node, '.kanji-statistics'); 212 const classificationsContainer = this._querySelector(node, '.kanji-classifications'); 213 const codepointsContainer = this._querySelector(node, '.kanji-codepoints'); 214 const dictionaryIndicesContainer = this._querySelector(node, '.kanji-dictionary-indices'); 215 216 this._setTextContent(glyphContainer, dictionaryEntry.character, this._language); 217 if (this._language === 'ja') { glyphContainer.style.fontFamily = 'kanji-stroke-orders, sans-serif'; } 218 const groupedFrequencies = groupKanjiFrequencies(dictionaryEntry.frequencies, dictionaryInfo); 219 220 const dictionaryTag = this._createDictionaryTag(''); 221 dictionaryTag.name = dictionaryEntry.dictionaryAlias; 222 dictionaryTag.content = [dictionaryEntry.dictionary]; 223 const currentDictionaryInfo = dictionaryInfo.find(({title}) => title === dictionaryEntry.dictionary); 224 if (currentDictionaryInfo) { 225 const dictionaryContentArray = []; 226 dictionaryContentArray.push(currentDictionaryInfo.title); 227 if (currentDictionaryInfo.author) { 228 dictionaryContentArray.push('Author: ' + currentDictionaryInfo.author); 229 } 230 if (currentDictionaryInfo.description) { 231 dictionaryContentArray.push('Description: ' + currentDictionaryInfo.description); 232 } 233 if (currentDictionaryInfo.url) { 234 dictionaryContentArray.push('URL: ' + currentDictionaryInfo.url); 235 } 236 237 const totalKanji = currentDictionaryInfo?.counts?.kanji?.total; 238 if (!!totalKanji && totalKanji > 0) { 239 dictionaryContentArray.push('Kanji Count: ' + totalKanji.toString()); 240 } 241 242 dictionaryTag.content = dictionaryContentArray; 243 } 244 245 this._appendMultiple(frequencyGroupListContainer, this._createFrequencyGroup.bind(this), groupedFrequencies, true); 246 this._appendMultiple(tagContainer, this._createTag.bind(this), [...dictionaryEntry.tags, dictionaryTag]); 247 this._appendMultiple(definitionsContainer, this._createKanjiDefinition.bind(this), dictionaryEntry.definitions); 248 this._appendMultiple(chineseReadingsContainer, this._createKanjiReading.bind(this), dictionaryEntry.onyomi); 249 this._appendMultiple(japaneseReadingsContainer, this._createKanjiReading.bind(this), dictionaryEntry.kunyomi); 250 251 statisticsContainer.appendChild(this._createKanjiInfoTable(dictionaryEntry.stats.misc)); 252 classificationsContainer.appendChild(this._createKanjiInfoTable(dictionaryEntry.stats.class)); 253 codepointsContainer.appendChild(this._createKanjiInfoTable(dictionaryEntry.stats.code)); 254 dictionaryIndicesContainer.appendChild(this._createKanjiInfoTable(dictionaryEntry.stats.index)); 255 256 return node; 257 } 258 259 /** 260 * @returns {HTMLElement} 261 */ 262 createEmptyFooterNotification() { 263 return this._instantiate('footer-notification'); 264 } 265 266 /** 267 * @param {HTMLElement} tagNode 268 * @param {?import('dictionary').DictionaryEntry} dictionaryEntry 269 * @returns {DocumentFragment} 270 */ 271 createTagFooterNotificationDetails(tagNode, dictionaryEntry) { 272 const node = this._templates.instantiateFragment('footer-notification-tag-details'); 273 274 let details = tagNode.dataset.details; 275 if (typeof details !== 'string') { 276 const label = tagNode.querySelector('.tag-label-content'); 277 details = label !== null && label.textContent !== null ? label.textContent : ''; 278 } 279 const tagDetails = this._querySelector(node, '.tag-details'); 280 this._setTextContent(tagDetails, details); 281 282 if (dictionaryEntry !== null && dictionaryEntry.type === 'term') { 283 const {headwords} = dictionaryEntry; 284 const disambiguationHeadwords = []; 285 const {headwords: headwordIndices} = tagNode.dataset; 286 if (typeof headwordIndices === 'string' && headwordIndices.length > 0) { 287 for (const headwordIndexString of headwordIndices.split(' ')) { 288 const headwordIndex = Number.parseInt(headwordIndexString, 10); 289 if (!Number.isNaN(headwordIndex) && headwordIndex >= 0 && headwordIndex < headwords.length) { 290 disambiguationHeadwords.push(headwords[headwordIndex]); 291 } 292 } 293 } 294 295 if (disambiguationHeadwords.length > 0 && disambiguationHeadwords.length < headwords.length) { 296 const disambiguationContainer = this._querySelector(node, '.tag-details-disambiguation-list'); 297 const copyAttributes = ['totalHeadwordCount', 'matchedHeadwordCount', 'unmatchedHeadwordCount']; 298 for (const attribute of copyAttributes) { 299 const value = tagNode.dataset[attribute]; 300 if (typeof value === 'undefined') { continue; } 301 disambiguationContainer.dataset[attribute] = value; 302 } 303 for (const {term, reading} of disambiguationHeadwords) { 304 const disambiguationItem = document.createElement('span'); 305 disambiguationItem.className = 'tag-details-disambiguation'; 306 this._appendFurigana(disambiguationItem, term, reading, (container, text) => { 307 container.appendChild(document.createTextNode(text)); 308 }); 309 disambiguationContainer.appendChild(disambiguationItem); 310 } 311 } 312 } 313 314 return node; 315 } 316 317 /** 318 * @param {(DocumentFragment|Node|Error)[]} errors 319 * @returns {HTMLElement} 320 */ 321 createAnkiNoteErrorsNotificationContent(errors) { 322 const content = this._instantiate('footer-notification-anki-errors-content'); 323 324 const header = this._querySelector(content, '.anki-note-error-header'); 325 this._setTextContent(header, (errors.length === 1 ? 'An error occurred:' : `${errors.length} errors occurred:`), 'en'); 326 327 const list = this._querySelector(content, '.anki-note-error-list'); 328 for (const error of errors) { 329 const div = document.createElement('li'); 330 div.className = 'anki-note-error-message'; 331 if (error instanceof DocumentFragment || error instanceof Node) { 332 div.appendChild(error); 333 } else { 334 let message = error.message; 335 let link = null; 336 if (error instanceof ExtensionError && error.data !== null && typeof error.data === 'object') { 337 const {referenceUrl} = /** @type {import('core').UnknownObject} */ (error.data); 338 if (typeof referenceUrl === 'string') { 339 message = message.trimEnd(); 340 if (!/[.!?]^/.test(message)) { message += '.'; } 341 message += ' '; 342 link = document.createElement('a'); 343 link.href = referenceUrl; 344 link.target = '_blank'; 345 link.rel = 'noreferrer noopener'; 346 link.textContent = 'More info'; 347 } 348 } 349 this._setTextContent(div, message); 350 if (link !== null) { div.appendChild(link); } 351 } 352 list.appendChild(div); 353 } 354 355 return content; 356 } 357 358 /** 359 * @returns {HTMLElement} 360 */ 361 createProfileListItem() { 362 return this._instantiate('profile-list-item'); 363 } 364 365 /** 366 * @param {string} name 367 * @returns {HTMLElement} 368 */ 369 instantiateTemplate(name) { 370 return this._instantiate(name); 371 } 372 373 /** 374 * @param {string} name 375 * @returns {DocumentFragment} 376 */ 377 instantiateTemplateFragment(name) { 378 return this._templates.instantiateFragment(name); 379 } 380 381 // Private 382 383 /** 384 * @param {import('dictionary').TermHeadword} headword 385 * @param {number} headwordIndex 386 * @param {import('dictionary').TermPronunciation[]} pronunciations 387 * @returns {HTMLElement} 388 */ 389 _createTermHeadword(headword, headwordIndex, pronunciations) { 390 const {term, reading, tags, sources} = headword; 391 392 let isPrimaryAny = false; 393 const matchTypes = new Set(); 394 const matchSources = new Set(); 395 for (const {matchType, matchSource, isPrimary} of sources) { 396 if (isPrimary) { 397 isPrimaryAny = true; 398 } 399 matchTypes.add(matchType); 400 matchSources.add(matchSource); 401 } 402 403 const node = this._instantiate('headword'); 404 405 const termContainer = this._querySelector(node, '.headword-term'); 406 407 node.dataset.isPrimary = `${isPrimaryAny}`; 408 node.dataset.readingIsSame = `${reading === term}`; 409 node.dataset.frequency = getTermFrequency(tags); 410 node.dataset.matchTypes = [...matchTypes].join(' '); 411 node.dataset.matchSources = [...matchSources].join(' '); 412 413 const {wordClasses} = headword; 414 const pronunciationCategories = this._getPronunciationCategories(reading, pronunciations, wordClasses, headwordIndex); 415 if (pronunciationCategories !== null) { 416 node.dataset.pronunciationCategories = pronunciationCategories; 417 } 418 if (wordClasses.length > 0) { 419 node.dataset.wordClasses = wordClasses.join(' '); 420 } 421 422 const headwordReading = this._querySelector(node, '.headword-reading'); 423 this._setTextContent(headwordReading, reading); 424 425 this._appendFurigana(termContainer, term, reading, this._appendKanjiLinks.bind(this)); 426 427 return node; 428 } 429 430 /** 431 * @param {import('dictionary').InflectionRuleChainCandidate} inflectionRuleChain 432 * @returns {?HTMLElement} 433 */ 434 _createInflectionRuleChain(inflectionRuleChain) { 435 const {source, inflectionRules} = inflectionRuleChain; 436 if (!Array.isArray(inflectionRules) || inflectionRules.length === 0) { return null; } 437 const fragment = this._instantiate('inflection-rule-chain'); 438 439 const sourceIcon = this._getInflectionSourceIcon(source); 440 441 fragment.appendChild(sourceIcon); 442 443 this._appendMultiple(fragment, this._createTermInflection.bind(this), inflectionRules); 444 return fragment; 445 } 446 447 /** 448 * @param {import('dictionary').InflectionSource} source 449 * @returns {HTMLElement} 450 */ 451 _getInflectionSourceIcon(source) { 452 const icon = document.createElement('span'); 453 icon.classList.add('inflection-source-icon'); 454 icon.dataset.inflectionSource = source; 455 switch (source) { 456 case 'dictionary': 457 icon.title = 'Dictionary Deinflection'; 458 return icon; 459 case 'algorithm': 460 icon.title = 'Algorithm Deinflection'; 461 return icon; 462 case 'both': 463 icon.title = 'Dictionary and Algorithm Deinflection'; 464 return icon; 465 } 466 } 467 468 /** 469 * @param {import('dictionary').InflectionRule} inflection 470 * @returns {DocumentFragment} 471 */ 472 _createTermInflection(inflection) { 473 const {name, description} = inflection; 474 const fragment = this._templates.instantiateFragment('inflection'); 475 const node = this._querySelector(fragment, '.inflection'); 476 this._setTextContent(node, name); 477 if (description) { node.title = description; } 478 node.dataset.reason = name; 479 return fragment; 480 } 481 482 /** 483 * @param {import('dictionary').TermDefinition} definition 484 * @param {import('dictionary').Tag} dictionaryTag 485 * @param {import('dictionary').TermHeadword[]} headwords 486 * @param {Set<string>} uniqueTerms 487 * @param {Set<string>} uniqueReadings 488 * @returns {HTMLElement} 489 */ 490 _createTermDefinition(definition, dictionaryTag, headwords, uniqueTerms, uniqueReadings) { 491 const {dictionary, tags, headwordIndices, entries} = definition; 492 const disambiguations = getDisambiguations(headwords, headwordIndices, uniqueTerms, uniqueReadings); 493 494 const node = this._instantiate('definition-item'); 495 496 const tagListContainer = this._querySelector(node, '.definition-tag-list'); 497 const onlyListContainer = this._querySelector(node, '.definition-disambiguation-list'); 498 const entriesContainer = this._querySelector(node, '.gloss-list'); 499 500 node.dataset.dictionary = dictionary; 501 502 this._appendMultiple(tagListContainer, this._createTag.bind(this), [...tags, dictionaryTag]); 503 this._appendMultiple(onlyListContainer, this._createTermDisambiguation.bind(this), disambiguations); 504 this._appendMultiple(entriesContainer, this._createTermDefinitionEntry.bind(this), entries, dictionary); 505 return node; 506 } 507 508 /** 509 * @param {import('dictionary-data').TermGlossaryContent} entry 510 * @param {string} dictionary 511 * @returns {?HTMLElement} 512 */ 513 _createTermDefinitionEntry(entry, dictionary) { 514 switch (typeof entry) { 515 case 'string': 516 return this._createTermDefinitionEntryText(entry); 517 case 'object': { 518 switch (entry.type) { 519 case 'image': 520 return this._createTermDefinitionEntryImage(entry, dictionary); 521 case 'structured-content': 522 return this._createTermDefinitionEntryStructuredContent(entry.content, dictionary); 523 case 'text': 524 break; 525 } 526 break; 527 } 528 } 529 530 return null; 531 } 532 533 /** 534 * @param {string} text 535 * @returns {HTMLElement} 536 */ 537 _createTermDefinitionEntryText(text) { 538 const node = this._instantiate('gloss-item'); 539 const container = this._querySelector(node, '.gloss-content'); 540 this._setMultilineTextContent(container, text); 541 return node; 542 } 543 544 /** 545 * @param {import('dictionary-data').TermGlossaryImage} data 546 * @param {string} dictionary 547 * @returns {HTMLElement} 548 */ 549 _createTermDefinitionEntryImage(data, dictionary) { 550 const {description} = data; 551 552 const node = this._instantiate('gloss-item'); 553 554 const contentContainer = this._querySelector(node, '.gloss-content'); 555 const image = this._structuredContentGenerator.createDefinitionImage(data, dictionary); 556 contentContainer.appendChild(image); 557 558 if (typeof description === 'string') { 559 const fragment = this._templates.instantiateFragment('gloss-item-image-description'); 560 const container = this._querySelector(fragment, '.gloss-image-description'); 561 this._setMultilineTextContent(container, description); 562 contentContainer.appendChild(fragment); 563 } 564 565 return node; 566 } 567 568 /** 569 * @param {import('structured-content').Content} content 570 * @param {string} dictionary 571 * @returns {HTMLElement} 572 */ 573 _createTermDefinitionEntryStructuredContent(content, dictionary) { 574 const node = this._instantiate('gloss-item'); 575 const contentContainer = this._querySelector(node, '.gloss-content'); 576 this._structuredContentGenerator.appendStructuredContent(contentContainer, content, dictionary); 577 return node; 578 } 579 580 /** 581 * @param {string} disambiguation 582 * @returns {HTMLElement} 583 */ 584 _createTermDisambiguation(disambiguation) { 585 const node = this._instantiate('definition-disambiguation'); 586 node.dataset.term = disambiguation; 587 this._setTextContent(node, disambiguation, this._language); 588 return node; 589 } 590 591 /** 592 * @param {string} character 593 * @returns {HTMLAnchorElement} 594 */ 595 _createKanjiLink(character) { 596 const node = document.createElement('a'); 597 node.className = 'headword-kanji-link'; 598 this._setTextContent(node, character, this._language); 599 return node; 600 } 601 602 /** 603 * @param {string} text 604 * @returns {HTMLElement} 605 */ 606 _createKanjiDefinition(text) { 607 const node = this._instantiate('kanji-gloss-item'); 608 const container = this._querySelector(node, '.kanji-gloss-content'); 609 this._setMultilineTextContent(container, text); 610 return node; 611 } 612 613 /** 614 * @param {string} reading 615 * @returns {HTMLElement} 616 */ 617 _createKanjiReading(reading) { 618 const node = this._instantiate('kanji-reading'); 619 this._setTextContent(node, reading, this._language); 620 return node; 621 } 622 623 /** 624 * @param {import('dictionary').KanjiStat[]} details 625 * @returns {HTMLElement} 626 */ 627 _createKanjiInfoTable(details) { 628 const node = this._instantiate('kanji-info-table'); 629 const container = this._querySelector(node, '.kanji-info-table-body'); 630 631 const count = this._appendMultiple(container, this._createKanjiInfoTableItem.bind(this), details); 632 if (count === 0) { 633 const n = this._createKanjiInfoTableItemEmpty(); 634 container.appendChild(n); 635 } 636 637 return node; 638 } 639 640 /** 641 * @param {import('dictionary').KanjiStat} details 642 * @returns {HTMLElement} 643 */ 644 _createKanjiInfoTableItem(details) { 645 const {content, name, value} = details; 646 const node = this._instantiate('kanji-info-table-item'); 647 const nameNode = this._querySelector(node, '.kanji-info-table-item-header'); 648 const valueNode = this._querySelector(node, '.kanji-info-table-item-value'); 649 this._setTextContent(nameNode, content.length > 0 ? content : name); 650 this._setTextContent(valueNode, typeof value === 'string' ? value : `${value}`); 651 return node; 652 } 653 654 /** 655 * @returns {HTMLElement} 656 */ 657 _createKanjiInfoTableItemEmpty() { 658 return this._instantiate('kanji-info-table-empty'); 659 } 660 661 /** 662 * @param {import('dictionary').Tag} tag 663 * @returns {HTMLElement} 664 */ 665 _createTag(tag) { 666 const {content, name, category, redundant} = tag; 667 const node = this._instantiate('tag'); 668 669 const inner = this._querySelector(node, '.tag-label-content'); 670 671 const contentString = content.join('\n'); 672 673 node.title = contentString; 674 this._setTextContent(inner, name); 675 node.dataset.details = contentString.length > 0 ? contentString : name; 676 node.dataset.category = category; 677 if (redundant) { node.dataset.redundant = 'true'; } 678 679 return node; 680 } 681 682 /** 683 * @param {import('dictionary-data-util').TagGroup} tagInfo 684 * @param {number} totalHeadwordCount 685 * @returns {HTMLElement} 686 */ 687 _createTermTag(tagInfo, totalHeadwordCount) { 688 const {tag, headwordIndices} = tagInfo; 689 const node = this._createTag(tag); 690 node.dataset.headwords = headwordIndices.join(' '); 691 node.dataset.totalHeadwordCount = `${totalHeadwordCount}`; 692 node.dataset.matchedHeadwordCount = `${headwordIndices.length}`; 693 node.dataset.unmatchedHeadwordCount = `${Math.max(0, totalHeadwordCount - headwordIndices.length)}`; 694 return node; 695 } 696 697 /** 698 * @param {string} name 699 * @param {string} category 700 * @returns {import('dictionary').Tag} 701 */ 702 _createTagData(name, category) { 703 return { 704 name, 705 category, 706 order: 0, 707 score: 0, 708 content: [], 709 dictionaries: [], 710 redundant: false, 711 }; 712 } 713 714 /** 715 * @param {string} text 716 * @returns {HTMLElement} 717 */ 718 _createSearchTag(text) { 719 return this._createTag(this._createTagData(text, 'search')); 720 } 721 722 /** 723 * @param {import('dictionary-data-util').DictionaryGroupedPronunciations} details 724 * @returns {HTMLElement} 725 */ 726 _createGroupedPronunciation(details) { 727 const {dictionary, dictionaryAlias, pronunciations} = details; 728 729 const node = this._instantiate('pronunciation-group'); 730 node.dataset.dictionary = dictionary; 731 node.dataset.pronunciationsMulti = 'true'; 732 node.dataset.pronunciationsCount = `${pronunciations.length}`; 733 734 const n1 = this._querySelector(node, '.pronunciation-group-tag-list'); 735 const tag = this._createTag(this._createTagData(dictionaryAlias, 'pronunciation-dictionary')); 736 tag.dataset.details = dictionary; 737 n1.appendChild(tag); 738 739 let hasTags = false; 740 for (const {pronunciation: {tags}} of pronunciations) { 741 if (tags.length > 0) { 742 hasTags = true; 743 break; 744 } 745 } 746 747 const n = this._querySelector(node, '.pronunciation-list'); 748 n.dataset.hasTags = `${hasTags}`; 749 this._appendMultiple(n, this._createPronunciation.bind(this), pronunciations); 750 751 return node; 752 } 753 754 /** 755 * @param {import('dictionary-data-util').GroupedPronunciation} details 756 * @returns {HTMLElement} 757 */ 758 _createPronunciation(details) { 759 const {pronunciation} = details; 760 switch (pronunciation.type) { 761 case 'pitch-accent': 762 return this._createPronunciationPitchAccent(pronunciation, details); 763 case 'phonetic-transcription': 764 return this._createPronunciationPhoneticTranscription(pronunciation, details); 765 } 766 } 767 768 769 /** 770 * @param {import('dictionary').PhoneticTranscription} pronunciation 771 * @param {import('dictionary-data-util').GroupedPronunciation} details 772 * @returns {HTMLElement} 773 */ 774 _createPronunciationPhoneticTranscription(pronunciation, details) { 775 const {ipa, tags} = pronunciation; 776 const {exclusiveTerms, exclusiveReadings} = details; 777 778 const node = this._instantiate('pronunciation'); 779 780 node.dataset.pronunciationType = pronunciation.type; 781 node.dataset.tagCount = `${tags.length}`; 782 783 let n = this._querySelector(node, '.pronunciation-tag-list'); 784 this._appendMultiple(n, this._createTag.bind(this), tags); 785 786 n = this._querySelector(node, '.pronunciation-disambiguation-list'); 787 this._createPronunciationDisambiguations(n, exclusiveTerms, exclusiveReadings); 788 789 n = this._querySelector(node, '.pronunciation-text-container'); 790 791 this._setTextContent(n, ipa); 792 793 return node; 794 } 795 796 /** 797 * @param {import('dictionary').PitchAccent} pitchAccent 798 * @param {import('dictionary-data-util').GroupedPronunciation} details 799 * @returns {HTMLElement} 800 */ 801 _createPronunciationPitchAccent(pitchAccent, details) { 802 const {positions, nasalPositions, devoicePositions, tags} = pitchAccent; 803 const {reading, exclusiveTerms, exclusiveReadings} = details; 804 const morae = getKanaMorae(reading); 805 806 const node = this._instantiate('pronunciation'); 807 808 node.dataset.pitchAccentDownstepPosition = `${positions}`; 809 node.dataset.pronunciationType = pitchAccent.type; 810 if (nasalPositions.length > 0) { node.dataset.nasalMoraPosition = nasalPositions.join(' '); } 811 if (devoicePositions.length > 0) { node.dataset.devoiceMoraPosition = devoicePositions.join(' '); } 812 node.dataset.tagCount = `${tags.length}`; 813 814 let n = this._querySelector(node, '.pronunciation-tag-list'); 815 this._appendMultiple(n, this._createTag.bind(this), tags); 816 817 n = this._querySelector(node, '.pronunciation-disambiguation-list'); 818 this._createPronunciationDisambiguations(n, exclusiveTerms, exclusiveReadings); 819 820 n = this._querySelector(node, '.pronunciation-downstep-notation-container'); 821 n.appendChild(this._pronunciationGenerator.createPronunciationDownstepPosition(positions)); 822 823 n = this._querySelector(node, '.pronunciation-text-container'); 824 825 n.lang = this._language; 826 n.appendChild(this._pronunciationGenerator.createPronunciationText(morae, positions, nasalPositions, devoicePositions)); 827 828 n = this._querySelector(node, '.pronunciation-graph-container'); 829 n.appendChild(this._pronunciationGenerator.createPronunciationGraph(morae, positions)); 830 831 return node; 832 } 833 834 /** 835 * @param {HTMLElement} container 836 * @param {string[]} exclusiveTerms 837 * @param {string[]} exclusiveReadings 838 */ 839 _createPronunciationDisambiguations(container, exclusiveTerms, exclusiveReadings) { 840 const templateName = 'pronunciation-disambiguation'; 841 for (const term of exclusiveTerms) { 842 const node = this._instantiate(templateName); 843 node.dataset.type = 'term'; 844 this._setTextContent(node, term, this._language); 845 container.appendChild(node); 846 } 847 848 for (const exclusiveReading of exclusiveReadings) { 849 const node = this._instantiate(templateName); 850 node.dataset.type = 'reading'; 851 this._setTextContent(node, exclusiveReading, this._language); 852 container.appendChild(node); 853 } 854 855 container.dataset.count = `${exclusiveTerms.length + exclusiveReadings.length}`; 856 container.dataset.termCount = `${exclusiveTerms.length}`; 857 container.dataset.readingCount = `${exclusiveReadings.length}`; 858 } 859 860 /** 861 * @param {import('dictionary-data-util').DictionaryFrequency<import('dictionary-data-util').TermFrequency>|import('dictionary-data-util').DictionaryFrequency<import('dictionary-data-util').KanjiFrequency>} details 862 * @param {boolean} kanji 863 * @returns {HTMLElement} 864 */ 865 _createFrequencyGroup(details, kanji) { 866 const {dictionary, dictionaryAlias, frequencies, freqCount} = details; 867 868 const node = this._instantiate('frequency-group-item'); 869 const body = this._querySelector(node, '.tag-body-content'); 870 871 const tagLabel = this._querySelector(node, '.tag-label-content'); 872 const tag = this._querySelector(node, '.tag'); 873 874 this._setTextContent(tagLabel, dictionaryAlias); 875 876 const ii = frequencies.length; 877 for (let i = 0; i < ii; ++i) { 878 const item = frequencies[i]; 879 const itemNode = ( 880 kanji ? 881 this._createKanjiFrequency(/** @type {import('dictionary-data-util').KanjiFrequency} */ (item), dictionary, dictionaryAlias, freqCount?.toString()) : 882 this._createTermFrequency(/** @type {import('dictionary-data-util').TermFrequency} */ (item), dictionary, dictionaryAlias, freqCount?.toString()) 883 ); 884 itemNode.dataset.index = `${i}`; 885 body.appendChild(itemNode); 886 } 887 888 body.dataset.count = `${ii}`; 889 node.dataset.count = `${ii}`; 890 node.dataset.details = dictionary; 891 tag.dataset.details = dictionary + '\nDictionary size: ' + freqCount?.toString() + (kanji ? ' kanji' : ' terms'); 892 return node; 893 } 894 895 /** 896 * @param {import('dictionary-data-util').TermFrequency} details 897 * @param {string} dictionary 898 * @param {string} dictionaryAlias 899 * @param {string} freqCount 900 * @returns {HTMLElement} 901 */ 902 _createTermFrequency(details, dictionary, dictionaryAlias, freqCount) { 903 const {term, reading, values} = details; 904 const node = this._instantiate('term-frequency-item'); 905 const tagLabel = this._querySelector(node, '.tag-label-content'); 906 const tag = this._querySelector(node, '.tag'); 907 const disambiguationTerm = this._querySelector(node, '.frequency-disambiguation-term'); 908 const disambiguationReading = this._querySelector(node, '.frequency-disambiguation-reading'); 909 const frequencyValueList = this._querySelector(node, '.frequency-value-list'); 910 911 this._setTextContent(tagLabel, dictionaryAlias); 912 this._setTextContent(disambiguationTerm, term, this._language); 913 this._setTextContent(disambiguationReading, (reading !== null ? reading : ''), this._language); 914 this._populateFrequencyValueList(frequencyValueList, values); 915 916 node.dataset.term = term; 917 if (typeof reading === 'string') { 918 node.dataset.reading = reading; 919 } 920 node.dataset.hasReading = `${reading !== null}`; 921 node.dataset.readingIsSame = `${reading === term}`; 922 node.dataset.dictionary = dictionary; 923 node.dataset.details = dictionary; 924 tag.dataset.details = dictionary + '\nDictionary size: ' + freqCount + ' terms'; 925 return node; 926 } 927 928 /** 929 * @param {import('dictionary-data-util').KanjiFrequency} details 930 * @param {string} dictionary 931 * @param {string} dictionaryAlias 932 * @param {string} freqCount 933 * @returns {HTMLElement} 934 */ 935 _createKanjiFrequency(details, dictionary, dictionaryAlias, freqCount) { 936 const {character, values} = details; 937 const node = this._instantiate('kanji-frequency-item'); 938 const tagLabel = this._querySelector(node, '.tag-label-content'); 939 const tag = this._querySelector(node, '.tag'); 940 const frequencyValueList = this._querySelector(node, '.frequency-value-list'); 941 942 this._setTextContent(tagLabel, dictionaryAlias); 943 this._populateFrequencyValueList(frequencyValueList, values); 944 945 node.dataset.character = character; 946 node.dataset.dictionary = dictionary; 947 node.dataset.details = dictionary; 948 tag.dataset.details = dictionary + '\nDictionary size: ' + freqCount + ' kanji'; 949 950 return node; 951 } 952 953 /** 954 * @param {HTMLElement} node 955 * @param {import('dictionary-data-util').FrequencyData[]} values 956 */ 957 _populateFrequencyValueList(node, values) { 958 let fullFrequency = ''; 959 for (let i = 0, ii = values.length; i < ii; ++i) { 960 const {frequency, displayValue} = values[i]; 961 const frequencyString = `${frequency}`; 962 const text = displayValue !== null ? displayValue : `${frequency}`; 963 964 if (i > 0) { 965 const node2 = document.createElement('span'); 966 node2.className = 'frequency-value'; 967 node2.dataset.frequency = `${frequency}`; 968 node2.textContent = ', '; 969 node.appendChild(node2); 970 fullFrequency += ', '; 971 } 972 973 const node2 = document.createElement('span'); 974 node2.className = 'frequency-value'; 975 node2.dataset.frequency = frequencyString; 976 if (displayValue !== null) { 977 node2.dataset.displayValue = `${displayValue}`; 978 if (displayValue !== frequencyString) { 979 node2.title = frequencyString; 980 } 981 } 982 this._setTextContent(node2, text, this._language); 983 node.appendChild(node2); 984 985 fullFrequency += text; 986 } 987 988 node.dataset.frequency = fullFrequency; 989 } 990 991 /** 992 * @param {HTMLElement} container 993 * @param {string} text 994 */ 995 _appendKanjiLinks(container, text) { 996 let part = ''; 997 for (const c of text) { 998 if (isCodePointKanji(/** @type {number} */(c.codePointAt(0)))) { 999 if (part.length > 0) { 1000 container.appendChild(document.createTextNode(part)); 1001 part = ''; 1002 } 1003 1004 const link = this._createKanjiLink(c); 1005 container.appendChild(link); 1006 } else { 1007 part += c; 1008 } 1009 } 1010 if (part.length > 0) { 1011 container.appendChild(document.createTextNode(part)); 1012 } 1013 } 1014 1015 /** 1016 * @template [TItem=unknown] 1017 * @template [TExtraArg=void] 1018 * @param {HTMLElement} container 1019 * @param {(item: TItem, arg: TExtraArg) => ?Node} createItem 1020 * @param {TItem[]} detailsArray 1021 * @param {TExtraArg} [arg] 1022 * @returns {number} 1023 */ 1024 _appendMultiple(container, createItem, detailsArray, arg) { 1025 let count = 0; 1026 const {ELEMENT_NODE} = Node; 1027 if (Array.isArray(detailsArray)) { 1028 for (const details of detailsArray) { 1029 const item = createItem(details, /** @type {TExtraArg} */(arg)); 1030 if (item === null) { continue; } 1031 container.appendChild(item); 1032 if (item.nodeType === ELEMENT_NODE) { 1033 /** @type {HTMLElement} */ (item).dataset.index = `${count}`; 1034 } 1035 ++count; 1036 } 1037 } 1038 1039 container.dataset.count = `${count}`; 1040 1041 return count; 1042 } 1043 1044 /** 1045 * @param {HTMLElement} container 1046 * @param {string} term 1047 * @param {string} reading 1048 * @param {(element: HTMLElement, text: string) => void} addText 1049 */ 1050 _appendFurigana(container, term, reading, addText) { 1051 container.lang = this._language; 1052 const segments = distributeFurigana(term, reading); 1053 for (const {text, reading: furigana} of segments) { 1054 if (furigana) { 1055 const ruby = document.createElement('ruby'); 1056 const rt = document.createElement('rt'); 1057 addText(ruby, text); 1058 ruby.appendChild(rt); 1059 rt.appendChild(document.createTextNode(furigana)); 1060 container.appendChild(ruby); 1061 } else { 1062 addText(container, text); 1063 } 1064 } 1065 } 1066 1067 /** 1068 * @param {string} dictionary 1069 * @returns {import('dictionary').Tag} 1070 */ 1071 _createDictionaryTag(dictionary) { 1072 return this._createTagData(dictionary, 'dictionary'); 1073 } 1074 1075 /** 1076 * @param {HTMLElement} node 1077 * @param {string} value 1078 * @param {string} [language] 1079 */ 1080 _setTextContent(node, value, language) { 1081 this._setElementLanguage(node, language, value); 1082 node.textContent = value; 1083 } 1084 1085 /** 1086 * @param {HTMLElement} node 1087 * @param {string} value 1088 * @param {string} [language] 1089 */ 1090 _setMultilineTextContent(node, value, language) { 1091 // This can't just call _setTextContent because the lack of <br> elements will 1092 // cause the text to not copy correctly. 1093 this._setElementLanguage(node, language, value); 1094 1095 let start = 0; 1096 while (true) { 1097 const end = value.indexOf('\n', start); 1098 if (end < 0) { break; } 1099 node.appendChild(document.createTextNode(value.substring(start, end))); 1100 node.appendChild(document.createElement('br')); 1101 start = end + 1; 1102 } 1103 1104 if (start < value.length) { 1105 node.appendChild(document.createTextNode(start === 0 ? value : value.substring(start))); 1106 } 1107 } 1108 1109 /** 1110 * @param {HTMLElement} element 1111 * @param {string|undefined} language 1112 * @param {string} content 1113 */ 1114 _setElementLanguage(element, language, content) { 1115 if (typeof language === 'string') { 1116 element.lang = language; 1117 } else { 1118 const language2 = getLanguageFromText(content, this._language); 1119 if (language2 !== null) { 1120 element.lang = language2; 1121 } 1122 } 1123 } 1124 1125 /** 1126 * @param {string} reading 1127 * @param {import('dictionary').TermPronunciation[]} termPronunciations 1128 * @param {string[]} wordClasses 1129 * @param {number} headwordIndex 1130 * @returns {?string} 1131 */ 1132 _getPronunciationCategories(reading, termPronunciations, wordClasses, headwordIndex) { 1133 if (termPronunciations.length === 0) { return null; } 1134 const isVerbOrAdjective = isNonNounVerbOrAdjective(wordClasses); 1135 /** @type {Set<import('japanese-util').PitchCategory>} */ 1136 const categories = new Set(); 1137 for (const termPronunciation of termPronunciations) { 1138 if (termPronunciation.headwordIndex !== headwordIndex) { continue; } 1139 for (const pronunciation of termPronunciation.pronunciations) { 1140 if (pronunciation.type !== 'pitch-accent') { continue; } 1141 const category = getPitchCategory(reading, pronunciation.positions, isVerbOrAdjective); 1142 if (category !== null) { 1143 categories.add(category); 1144 } 1145 } 1146 } 1147 return categories.size > 0 ? [...categories].join(' ') : null; 1148 } 1149 1150 /** 1151 * @template {HTMLElement} T 1152 * @param {string} name 1153 * @returns {T} 1154 */ 1155 _instantiate(name) { 1156 return /** @type {T} */ (this._templates.instantiate(name)); 1157 } 1158 1159 /** 1160 * @template {HTMLElement} T 1161 * @param {Element|DocumentFragment} element 1162 * @param {string} selector 1163 * @returns {T} 1164 */ 1165 _querySelector(element, selector) { 1166 return /** @type {T} */ (element.querySelector(selector)); 1167 } 1168}