### Get All Meanings for a Word (JavaScript) Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Retrieves all available meanings for a given word from different dictionary sources, including user-defined name lists, Names.txt, Names2.txt, Vietphrase.txt, chapter numbers, number dictionaries, and Sino-Vietnamese readings. ```javascript import { getAllMeanings } from './m_dictionary.js'; const word = '李白'; const meanings = getAllMeanings(word, dictionaries, nameDictionary); console.log(meanings); /* Output: { name: 'Lý Bạch', // From user's Name List (highest priority) names: ['Lý Bạch'], // From Names.txt names2: [], // From Names2.txt vietphrase: ['lý bạch'], // From Vietphrase.txt chapter: [], // From Chapter number dictionary number: [], // From Number dictionary hanviet: 'lý bạch' // Sino-Vietnamese reading } */ ``` -------------------------------- ### Get Sino-Vietnamese Reading (JavaScript) Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Retrieves the Sino-Vietnamese (Hán Việt) reading for Chinese characters, returning a character-by-character phonetic transcription. It can handle mixed content of Chinese and other characters. ```javascript import { getHanViet } from './m_dictionary.js'; const hanViet = getHanViet('中国人', dictionaries); console.log(hanViet); // Output: 'trung quốc nhân' // Mixed content (Chinese + other characters) const mixed = getHanViet('我是ABC', dictionaries); console.log(mixed); // Output: 'ngã thị ABC' ``` -------------------------------- ### Initialize Name List System (JavaScript) Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Initializes the name list system by loading data from localStorage, setting up UI event handlers for sorting and actions (Save, Delete, Export, Import), and building essential master data structures like `masterKeySet` and `Trie`. ```javascript import { initializeNameList, rebuildMasterData } from './m_nameList.js'; // Call during application initialization initializeNameList(state); // Sets up: // - Load name dictionary from localStorage // - Sort dropdown handlers (newest, oldest, A-Z Vietnamese/Chinese) // - Save, Delete, Export, Import button handlers // - Auto-rebuild masterKeySet and Trie when names change ``` -------------------------------- ### Initialize Modal and UI in JavaScript Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Initializes all interactive modal dialogs and UI event handlers for text selection, quick edit panels, and name editing. This function sets up various UI interactions for user convenience. ```javascript import { initializeModal } from './m_modal.js'; // Initialize after DOM is ready and dictionaries are loaded initializeModal(state); // Sets up: // - Double-click on word: Opens full edit modal // - Single click/selection: Opens quick edit panel // - Expand selection left/right buttons // - Temporary vs permanent name add buttons // - Lock/pin panel functionality // - Google Translate integration // - Clipboard copy for Chinese text ``` -------------------------------- ### Initialize Dictionaries from IndexedDB Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Initializes and loads dictionaries from IndexedDB cache. It returns a Map of dictionaries, each with its priority and lookup table. This function is crucial for fast lookups on application startup if data is already cached. ```javascript import { initializeDictionaries } from './m_dictionary.js'; // Load dictionaries from IndexedDB on application startup const dictionaries = await initializeDictionaries(); if (dictionaries) { console.log('Dictionaries loaded successfully'); // dictionaries is a Map}> // Available dictionaries: Vietphrase, Names, Names2, PhienAm, LuatNhan, etc. const vietphraseDict = dictionaries.get('Vietphrase'); console.log(`Vietphrase entries: ${vietphraseDict.dict.size}`); console.log(`Priority: ${vietphraseDict.priority}`); // Higher = lower priority } else { console.log('No cached dictionaries, please import dictionary files'); } ``` -------------------------------- ### Load Dictionaries from User Files Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Processes user-uploaded dictionary files (e.g., .txt format) via an HTML file input. It matches file names to predefined dictionary configurations and updates the existing dictionaries. A log handler is used for feedback during processing. ```javascript import { loadDictionariesFromFile } from './m_dictionary.js'; // HTML: const fileInput = document.getElementById('file-input'); fileInput.addEventListener('change', async (e) => { const files = e.target.files; // FileList with .txt files const currentDicts = new Map(); // Existing dictionaries or empty Map const logHandler = { append: (msg, type) => console.log(`[${type}] ${msg}`), update: (item, msg, type) => console.log(`[${type}] ${msg}`) }; // Recognized file names: // - Vietphrase.txt, VP.txt - Main translation dictionary // - Names.txt, Name.txt - Proper nouns/character names // - HanViet.txt, PhienAm.txt - Sino-Vietnamese readings // - LuatNhan.txt - Pattern replacement rules // - Blacklist.txt - Words to ignore const dictionaries = await loadDictionariesFromFile(files, currentDicts, logHandler); console.log('Loaded dictionaries:', [...dictionaries.keys()]); // Output: Loaded dictionaries: ['Vietphrase', 'Names', 'PhienAm', ...] }); ``` -------------------------------- ### Load Dictionaries from Server Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Fetches dictionary files from the server's `/data/` directory. It uses a Web Worker for processing and stores the parsed data in IndexedDB. This function includes a log handler for progress updates during the loading process. ```javascript import { loadDictionariesFromServer } from './m_dictionary.js'; // Log handler for progress updates const logHandler = { append: (message, type) => { console.log(`[${type}] ${message}`); // types: 'loading', 'success', 'error', 'info', 'complete' return { id: Date.now() }; // Return log item reference }, update: (logItem, message, type) => { console.log(`[${type}] Updated: ${message}`); } }; try { // Automatically fetches: Vietphrase.txt, Names.txt, HanViet.txt, etc. from /data/ const dictionaries = await loadDictionariesFromServer(logHandler); if (dictionaries) { console.log('Server dictionaries loaded:', dictionaries.size, 'dictionaries'); // Output: Server dictionaries loaded: 10 dictionaries } } catch (error) { console.error('Failed to load dictionaries:', error.message); } ``` -------------------------------- ### Name List Module Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Manages user-defined custom translations for names and words, with persistence options. ```APIDOC ## nameDictionary and temporaryNameDictionary ### Description Global Maps storing user's custom translations. `nameDictionary` persists to localStorage, while `temporaryNameDictionary` is session-only. ### Method GET/SET (conceptual) ### Endpoint N/A (Object access and methods) ### Parameters None ### Request Example ```javascript import { nameDictionary, temporaryNameDictionary, saveNameDictionaryToStorage, renderNameList } from './m_nameList.js'; // Add a permanent name nameDictionary.set('李云龙', 'Lý Vân Long'); saveNameDictionaryToStorage(); renderNameList(); // Add a temporary name temporaryNameDictionary.set('张三', 'Trương Tam'); // Check if word is in name list if (nameDictionary.has('李云龙')) { console.log('Found:', nameDictionary.get('李云龙')); } ``` ### Response #### Success Response (200) - Operations modify the respective dictionaries and potentially the UI. #### Response Example ```json { "status": "success" } ``` ## initializeNameList ### Description Initializes the name list system, loads from localStorage, sets up UI event handlers, and builds the master data structures. ### Method GET (conceptual) ### Endpoint N/A (Function call) ### Parameters - **state** (object) - The current state of the translation system. ### Request Example ```javascript import { initializeNameList, rebuildMasterData } from './m_nameList.js'; initializeNameList(state); ``` ### Response #### Success Response (200) - Initializes the name list system and sets up necessary event handlers and data structures. #### Response Example ```json { "status": "initialized" } ``` ``` -------------------------------- ### Manage Name Dictionaries (JavaScript) Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Manages global Maps for user-defined custom translations. `nameDictionary` persists to localStorage, while `temporaryNameDictionary` is session-only. Functions are provided to add, check, save, and render the name lists. ```javascript import { nameDictionary, temporaryNameDictionary, saveNameDictionaryToStorage, renderNameList } from './m_nameList.js'; // Add a permanent name (persists across sessions) nameDictionary.set('李云龙', 'Lý Vân Long'); saveNameDictionaryToStorage(); renderNameList(); // Update UI textarea // Add a temporary name (session only, for quick edits) temporaryNameDictionary.set('张三', 'Trương Tam'); // Check if word is in name list if (nameDictionary.has('李云龙')) { console.log('Found:', nameDictionary.get('李云龙')); // 'Lý Vân Long' } ``` -------------------------------- ### Dictionary API Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Functions for retrieving linguistic information from various dictionaries. ```APIDOC ## getHanViet ### Description Retrieves the Sino-Vietnamese (Hán Việt) reading for Chinese characters. Returns character-by-character phonetic transcription. ### Method GET (conceptual) ### Endpoint N/A (Function call) ### Parameters None ### Request Example ```javascript import { getHanViet } from './m_dictionary.js'; const hanViet = getHanViet('中国人', dictionaries); console.log(hanViet); // Output: 'trung quốc nhân' const mixed = getHanViet('我是ABC', dictionaries); console.log(mixed); // Output: 'ngã thị ABC' ``` ### Response #### Success Response (200) - **hanViet** (string) - The Sino-Vietnamese reading of the input characters. #### Response Example ```json { "hanViet": "trung quốc nhân" } ``` ## segmentText ### Description Segments Chinese text into words using the longest-match algorithm with the master key set. ### Method GET (conceptual) ### Endpoint N/A (Function call) ### Parameters - **text** (string) - The Chinese text to segment. - **masterKeySet** (Set) - A set containing all known words from all dictionaries. ### Request Example ```javascript import { segmentText } from './m_dictionary.js'; const text = '我今天很高兴'; const segments = segmentText(text, state.masterKeySet); console.log(segments); // Output: ['我', '今天', '很', '高兴'] ``` ### Response #### Success Response (200) - **segments** (array of strings) - An array of segmented words. #### Response Example ```json { "segments": ["我", "今天", "很", "高兴"] } ``` ## getAllMeanings ### Description Retrieves all available meanings from different dictionary sources for a given word. ### Method GET (conceptual) ### Endpoint N/A (Function call) ### Parameters - **word** (string) - The word to retrieve meanings for. - **dictionaries** (Map) - A map containing all loaded dictionaries. - **nameDictionary** (Map) - A map containing user-defined name translations. ### Request Example ```javascript import { getAllMeanings } from './m_dictionary.js'; const word = '李白'; const meanings = getAllMeanings(word, dictionaries, nameDictionary); console.log(meanings); /* Output: { name: 'Lý Bạch', names: ['Lý Bạch'], names2: [], vietphrase: ['lý bạch'], chapter: [], number: [], hanviet: 'lý bạch' } */ ``` ### Response #### Success Response (200) - **meanings** (object) - An object containing various meanings and readings for the word. #### Response Example ```json { "meanings": { "name": "Lý Bạch", "names": ["Lý Bạch"], "names2": [], "vietphrase": ["lý bạch"], "chapter": [], "number": [], "hanviet": "lý bạch" } } ``` ``` -------------------------------- ### Rebuild Master Data in JavaScript Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Rebuilds masterKeySet and Trie data structures after dictionary changes to improve search performance. This function is crucial for maintaining search efficiency when dictionaries are updated. ```javascript import { rebuildMasterData } from './m_nameList.js'; // After modifying dictionaries or name list nameDictionary.set('新词', 'từ mới'); rebuildMasterData(state); // The function: // 1. Rebuilds masterKeySet with all dictionary keys // 2. Rebuilds Trie with priority order: // NamesUser(0) > Names2(20) > Names(21) > LuatNhan(30) > // Vietphrase(40) > Chapter(41) > Number(42) > Pronouns(50) > // PhienAm(60) > English(98) > Blacklist(99) ``` -------------------------------- ### Synthesize Compound Translation (JavaScript) Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Generates all possible translation combinations for compound words by combining the meanings of individual segments. It returns up to 100 unique combinations suitable for a quick edit panel. ```javascript import { synthesizeCompoundTranslation } from './m_translation.js'; const text = '大家好'; const suggestions = synthesizeCompoundTranslation(text, state); console.log(suggestions); // Output: ['mọi người tốt', 'đại gia tốt', 'mọi người hay', ...] // Returns up to 100 unique combinations for the quick edit panel ``` -------------------------------- ### Translation Module Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Functions for performing text translation, including name substitution, rule application, segmentation, and formatting. ```APIDOC ## performTranslation ### Description Main translation function that processes input text through multiple layers: name substitution, LuatNhan rules, word segmentation, and translation with proper formatting. ### Method POST (conceptual) ### Endpoint N/A (Function call) ### Parameters - **state** (object) - The current state of the translation system, including dictionaries, master key set, and trie structure. - **options** (object, optional) - Additional options for translation. - **forceText** (string) - Force translation of a specific text. - **preserveTempDict** (boolean) - Keep temporary translations. ### Request Example ```javascript import { performTranslation } from './m_translation.js'; const state = { dictionaries: loadedDictionaries, masterKeySet: allKeys, dictionaryTrie: trie, lastTranslatedText: '' }; // Standard translation performTranslation(state); // Force translate specific text performTranslation(state, { forceText: '这是一段中文文本', preserveTempDict: true }); ``` ### Response #### Success Response (200) - The function modifies the DOM to display the translated HTML output. #### Response Example ```html

đây một đoạn ...

``` ## synthesizeCompoundTranslation ### Description Generates all possible translation combinations for compound words by combining meanings of individual segments. ### Method GET (conceptual) ### Endpoint N/A (Function call) ### Parameters - **text** (string) - The compound word to generate translations for. - **state** (object) - The current state of the translation system. ### Request Example ```javascript import { synthesizeCompoundTranslation } from './m_translation.js'; const text = '大家好'; const suggestions = synthesizeCompoundTranslation(text, state); console.log(suggestions); // Output: ['mọi người tốt', 'đại gia tốt', 'mọi người hay', ...] ``` ### Response #### Success Response (200) - **suggestions** (array of strings) - An array of possible translation combinations. #### Response Example ```json { "suggestions": [ "mọi người tốt", "đại gia tốt", "mọi người hay" ] } ``` ``` -------------------------------- ### Standardize Dictionary Line in JavaScript Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Normalizes dictionary entry lines while preserving the Vietnamese translation part. This function handles both standard dictionary entries and blacklist entries. ```javascript import { standardizeDictionaryLine } from './m_preprocessor.js'; // Standard dictionary line format: Chinese=Vietnamese const line = '你好!=xin chào'; const standardized = standardizeDictionaryLine(line); console.log(standardized); // Output: '你好!=xin chào' (only Chinese part is normalized) // Blacklist entries (no '=' sign) const blacklistLine = '广告词!'; console.log(standardizeDictionaryLine(blacklistLine)); // Output: '广告词!' ``` -------------------------------- ### Standardize Text in JavaScript Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Normalizes Chinese text by converting full-width characters to ASCII and standardizing punctuation. It also removes extra spaces around punctuation for cleaner output. ```javascript import { standardizeText } from './m_preprocessor.js'; const input = '你好!我叫张三。'; const standardized = standardizeText(input); console.log(standardized); // Output: '你好!我叫张三.' // Converts: !→! 。→. ,→, :→: etc. // Also removes extra spaces around punctuation const messy = '你 好 ! 我 叫 张三 。'; console.log(standardizeText(messy)); // Output: '你好!我叫张三.' ``` -------------------------------- ### Segment Chinese Text (JavaScript) Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Segments Chinese text into words using the longest-match algorithm with a master key set. The output segments are matched against dictionary entries to determine optimal word boundaries. ```javascript import { segmentText } from './m_dictionary.js'; // masterKeySet contains all known words from all dictionaries const text = '我今天很高兴'; const segments = segmentText(text, state.masterKeySet); console.log(segments); // Output: ['我', '今天', '很', '高兴'] // Segments matched against dictionary entries for optimal word boundaries ``` -------------------------------- ### Perform Text Translation (JavaScript) Source: https://context7.com/hoangtuantk/vietphrase/llms.txt The main translation function that processes input text through multiple layers: name substitution, LuatNhan rules, word segmentation, and translation with proper formatting. It can be used for standard translation from input or to force translation of specific text. ```javascript import { performTranslation } from './m_translation.js'; // State object required by the translation system const state = { dictionaries: loadedDictionaries, // Map of all dictionaries masterKeySet: allKeys, // Set of all known Chinese words dictionaryTrie: trie, // Trie structure for lookups lastTranslatedText: '' // Stores last input for re-translation }; // Standard translation from input textarea performTranslation(state); // Reads from DOMElements.inputText.value // Writes HTML output to DOMElements.outputPanel // Force translate specific text (useful for re-translation after edits) performTranslation(state, { forceText: '这是一段中文文本', preserveTempDict: true // Keep temporary translations }); // The output HTML structure: //

// đây // // một đoạn // ... //

``` -------------------------------- ### Translate Single Word/Phrase Source: https://context7.com/hoangtuantk/vietphrase/llms.txt Translates a single word or phrase using a prioritized lookup across multiple dictionaries, including user-defined name lists and temporary session translations. It returns the best match and all possible meanings, or indicates if the word was not found. ```javascript import { translateWord } from './m_dictionary.js'; import { nameDictionary, temporaryNameDictionary } from './m_nameList.js'; // Assume dictionaries are loaded const word = '你好'; const result = translateWord( word, dictionaries, nameDictionary, // User's custom name list temporaryNameDictionary, // Session-only translations false // getAllMeanings flag ); console.log(result); // Output: { best: 'xin chào', all: ['xin chào', 'chào'], found: true } // For unfound words: const unknown = translateWord('未知词', dictionaries, nameDictionary, temporaryNameDictionary); console.log(unknown); // Output: { best: '未知词', all: [], found: false } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.