### Get Sino-Vietnamese Reading (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Retrieves the Sino-Vietnamese (Han Viet) reading for Chinese characters. This function performs a character-by-character phonetic transcription and preserves any non-Chinese characters in the input string. It requires the input string and the loaded dictionaries. ```javascript import { getHanViet } from './m_dictionary.js'; // Basic Sino-Vietnamese reading const hanViet = getHanViet('中国人', dictionaries); console.log(hanViet); // Output: 'trung quoc nhan' // Mixed content (Chinese + other characters preserved) const mixed = getHanViet('我是ABC123', dictionaries); console.log(mixed); // Output: 'nga thi ABC123' // Long phrase const phrase = getHanViet('天下无敌', dictionaries); console.log(phrase); // Output: 'thien ha vo dich' // Used in quick edit panel to show HV reading document.getElementById('hanviet-input').value = getHanViet(selectedWord, dictionaries) || ''; ``` -------------------------------- ### Get Sino-Vietnamese (Han Viet) Reading (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Retrieves the Sino-Vietnamese (Han Viet) phonetic reading for Chinese characters within a given string. It processes characters individually, preserving any non-Chinese characters in their original form. This function is useful for displaying phonetic transcriptions. ```javascript import { getHanViet } from './m_dictionary.js'; // Basic Sino-Vietnamese reading const hanViet = getHanViet('中国人', dictionaries); console.log(hanViet); // Output: 'trung quoc nhan' // Mixed content (Chinese + other characters preserved) const mixed = getHanViet('我是ABC123', dictionaries); console.log(mixed); // Output: 'nga thi ABC123' // Long phrase const phrase = getHanViet('天下无敌', dictionaries); console.log(phrase); // Output: 'thien ha vo dich' // Used in quick edit panel to show HV reading document.getElementById('hanviet-input').value = getHanViet(selectedWord, dictionaries) || ''; ``` -------------------------------- ### Initialize Name List System in JavaScript Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Shows how to initialize the name list system, which includes loading data from localStorage, setting up UI event handlers for various operations (sorting, saving, deleting, import/export), and building essential data structures. This function should be called after the DOM is ready. ```javascript import { initializeNameList } from './m_nameList.js'; // Call during application initialization after DOM is ready initializeNameList(state); // This sets up: // - Load name dictionary from localStorage // - Sort dropdown handlers (newest, oldest, A-Z Vietnamese, A-Z Chinese) // - Save button: parse textarea and save to localStorage // - Delete button: clear entire name list // - Export button: download as NamesUser.txt // - Import button: load from .txt file and merge // - Auto-rebuild masterKeySet and Trie when names change // - Auto-retranslate when name list is modified ``` -------------------------------- ### Initialize Modal UI (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Initializes interactive modal dialogs and UI event handlers for text selection, quick edit panels, and name editing. This function sets up various user interactions within the application's interface. ```javascript import { initializeModal } from './m_modal.js'; // Initialize after DOM is ready and dictionaries are loaded initializeModal(state); // This sets up the following interactions: // - Single click/selection on output panel: Opens quick edit panel // - Double-click on word: Opens full edit modal (via quick edit) // - Expand selection left/right buttons // - Quick add buttons (temporary, permanent) // - Lock/pin panel functionality (persists across sessions) // - Delete from name list button // - Case transformation buttons (capitalize, uppercase, etc.) // - Google Translate search button // - Clipboard copy for Chinese text // The quick edit panel shows: // - hv: Han Viet (lowercase) // - HV: Han Viet (uppercase) // - zw: Original Chinese text // - Vp: Vietphrase meaning // - tc: Custom input field ``` -------------------------------- ### Application State Object Initialization (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Defines the application's state object, which holds runtime data structures like dictionaries, master key sets, and the Trie. It is initialized on startup and updated as dictionaries are loaded and processed. ```javascript // Initialize state on application startup const state = { dictionaries: null, // Map masterKeySet: new Set(), // Set of all known Chinese words dictionaryTrie: null, // Trie for fast lookups lastTranslatedText: '' // For re-translation after edits }; // After loading dictionaries const db = await initializeDictionaries(); if (db) { state.dictionaries = db; rebuildMasterData(state); // Builds masterKeySet and dictionaryTrie } // State is modified by: // - initializeDictionaries() - sets dictionaries // - rebuildMasterData() - sets masterKeySet, dictionaryTrie // - performTranslation() - sets lastTranslatedText ``` -------------------------------- ### Initialize Dictionaries from IndexedDB Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Initializes and loads dictionaries from the IndexedDB cache. This function returns a Map of dictionaries with their priorities and lookup tables. It should be called on application startup to restore previously imported dictionaries. If no cached data exists, it returns null. ```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 number = lower priority // Check if a specific word exists if (vietphraseDict.dict.has('你好')) { console.log('Translation:', vietphraseDict.dict.get('你好')); // 'xin chào' } } else { console.log('No cached dictionaries, please import dictionary files'); } ``` -------------------------------- ### Load Dictionaries from Files (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Processes multiple user-uploaded dictionary files (.txt) from a file input. It matches file names to predefined dictionary types (e.g., Vietphrase.txt, Names.txt) and merges them with existing dictionaries. Requires a FileList object and a log handler for feedback. ```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 = state.dictionaries || new Map(); const logHandler = { append: (msg, type) => { console.log(`[${type}] ${msg}`); return {}; }, update: (item, msg, type) => console.log(`[${type}] ${msg}`) }; // Recognized file names (case-insensitive): // - Vietphrase.txt, VP.txt - Main translation dictionary // - Names.txt, Name.txt - Proper nouns/character names // - Names2.txt, Name2.txt - Secondary names dictionary // - HanViet.txt, PhienAm.txt - Sino-Vietnamese readings // - LuatNhan.txt - Pattern replacement rules // - Blacklist.txt, IgnoreList.txt - Words to ignore // - Pronouns.txt, DaiTuNhanXung.txt - Pronouns // - Chapter.txt, Number.txt - Chapter/number translations const dictionaries = await loadDictionariesFromFile(files, currentDicts, logHandler); console.log('Loaded dictionaries:', [...dictionaries.keys()]); // Output: Loaded dictionaries: ['Vietphrase', 'Names', 'PhienAm', ...] }); ``` -------------------------------- ### Manage Name Dictionaries and Temporary Names in JavaScript Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Demonstrates how to use `nameDictionary` and `temporaryNameDictionary` to manage user-defined translations. `nameDictionary` persists to localStorage, while `temporaryNameDictionary` is session-specific. Includes adding, checking, and deleting entries, along with saving to storage and updating the UI. ```javascript import { nameDictionary, temporaryNameDictionary, saveNameDictionaryToStorage, renderNameList } from './m_nameList.js'; // Add a permanent name (persists across browser sessions) nameDictionary.set('李云龙', 'Ly Van Long'); nameDictionary.set('赵刚', 'Trieu Cuong'); saveNameDictionaryToStorage(); // Save to localStorage renderNameList(); // Update UI textarea // Add a temporary name (session only, for quick corrections) temporaryNameDictionary.set('张三', 'Truong Tam'); // Will be used in translation but cleared after performTranslation() // Check if word exists in name list if (nameDictionary.has('李云龙')) { console.log('Found:', nameDictionary.get('李云龙')); // 'Ly Van Long' } // Delete from name list nameDictionary.delete('赵刚'); saveNameDictionaryToStorage(); renderNameList(); ``` -------------------------------- ### Load Dictionaries from Server and Store in IndexedDB Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Fetches dictionary files from the server's `/data/` directory, processes them using a Web Worker, and stores the parsed data in IndexedDB. This function automatically looks for standard dictionary file names and accepts a log handler for progress updates. ```javascript import { loadDictionariesFromServer } from './m_dictionary.js'; // Log handler for progress updates displayed in modal const logHandler = { append: (message, type) => { // types: 'loading', 'success', 'error', 'info', 'complete' const li = document.createElement('li'); li.textContent = `[${type}] ${message}`; logList.appendChild(li); return li; // Return log item reference for updates }, update: (logItem, message, type) => { logItem.textContent = `[${type}] ${message}`; } }; try { // Automatically fetches from /data/ directory: // - Vietphrase.txt, VP.txt // - Names.txt, Name.txt, Names2.txt // - HanViet.txt, PhienAm.txt // - LuatNhan.txt // - Blacklist.txt, Pronouns.txt, etc. 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); } ``` -------------------------------- ### Render Name List to UI in JavaScript Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Demonstrates how to render the name dictionary to a UI textarea, supporting various sorting options. The output format in the textarea is `ChineseKey=VietnameseTranslation`. Available sorts include default (newest first), oldest first, Vietnamese A-Z/Z-A, and Chinese A-Z/Z-A. ```javascript import { renderNameList } from './m_nameList.js'; // Render with default sort (newest first - insertion order) renderNameList(); // Render with specific sort renderNameList('oldest'); // Oldest first renderNameList('vn-az'); // Vietnamese name A-Z renderNameList('vn-za'); // Vietnamese name Z-A renderNameList('cn-az'); // Chinese key A-Z renderNameList('cn-za'); // Chinese key Z-A // Output format in textarea: // 李云龙=Ly Van Long // 赵刚=Trieu Cuong // 张三=Truong Tam ``` -------------------------------- ### Manage Name Dictionaries (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Manages user-defined translations using persistent (localStorage) and temporary dictionaries. Includes adding, checking, and deleting entries, with persistence and UI updates. ```javascript import { nameDictionary, temporaryNameDictionary, saveNameDictionaryToStorage, renderNameList } from './m_nameList.js'; // Add a permanent name (persists across browser sessions) nameDictionary.set('李云龙', 'Ly Van Long'); nameDictionary.set('赵刚', 'Trieu Cuong'); saveNameDictionaryToStorage(); // Save to localStorage renderNameList(); // Update UI textarea // Add a temporary name (session only, for quick corrections) temporaryNameDictionary.set('张三', 'Truong Tam'); // Will be used in translation but cleared after performTranslation() // Check if word exists in name list if (nameDictionary.has('李云龙')) { console.log('Found:', nameDictionary.get('李云龙')); // 'Ly Van Long' } // Delete from name list nameDictionary.delete('赵刚'); saveNameDictionaryToStorage(); renderNameList(); ``` -------------------------------- ### Load Single Dictionary File (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Loads a single dictionary file and explicitly assigns it a dictionary type. This is useful for updating a specific dictionary without reprocessing all files. It takes a File object, the desired dictionary type string, and the current dictionaries map. ```javascript import { loadSingleDictionaryFromFile } from './m_dictionary.js'; // For single dictionary import buttons const singleFileInput = document.getElementById('single-file-importer'); async function importSingleDictionary(file, dictionaryType) { // dictionaryType: 'Vietphrase', 'Names', 'PhienAm', 'LuatNhan', etc. const logHandler = { append: (msg, type) => { console.log(`[${type}] ${msg}`); return {}; }, update: (item, msg, type) => console.log(`[${type}] ${msg}`) }; const currentDicts = state.dictionaries || new Map(); const newDicts = await loadSingleDictionaryFromFile( file, dictionaryType, // e.g., 'Names' currentDicts, logHandler ); if (newDicts) { console.log(`Successfully imported ${dictionaryType}`); return newDicts; } } ``` -------------------------------- ### getAllMeanings Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Retrieves all available meanings from different dictionary sources for a given word. This is useful for displaying all translation options in edit panels. ```APIDOC ## getAllMeanings ### Description Retrieves all available meanings from different dictionary sources for a word. Useful for displaying all translation options in edit panels. ### Method `getAllMeanings(word: string, dictionaries: Map, nameDictionary: any) => object` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { getAllMeanings } from './m_dictionary.js'; const word = '李白'; const meanings = getAllMeanings(word, dictionaries, nameDictionary); console.log(meanings); /* Output: { name: 'Ly Bach', // From user's Name List (highest priority) names: ['Ly Bach'], // From Names.txt names2: [], // From Names2.txt vietphrase: ['ly bach'], // From Vietphrase.txt chapter: [], // From Chapter number dictionary number: [], // From Number dictionary hanviet: 'ly bach' // Sino-Vietnamese reading } */ // Use in UI to populate dropdown with all options const allOptions = new Set(); if (meanings.name) allOptions.add(meanings.name); meanings.names.forEach(m => allOptions.add(m)); meanings.vietphrase.forEach(m => allOptions.add(m)); // Display allOptions in dropdown ``` ### Response #### Success Response (200) - **meanings** (object) - An object containing various meanings from different sources. ``` -------------------------------- ### Render Name List to UI (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Renders the name dictionary to a UI textarea, supporting various sorting options. The output format is 'ChineseKey=VietnameseValue' per line. ```javascript import { renderNameList } from './m_nameList.js'; // Render with default sort (newest first - insertion order) renderNameList(); // Render with specific sort renderNameList('oldest'); // Oldest first renderNameList('vn-az'); // Vietnamese name A-Z renderNameList('vn-za'); // Vietnamese name Z-A renderNameList('cn-az'); // Chinese key A-Z renderNameList('cn-za'); // Chinese key Z-A // Output format in textarea: // 李云龙=Ly Van Long // 赵刚=Trieu Cuong // 张三=Truong Tam ``` -------------------------------- ### Synthesize Compound Translation Combinations (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Generates all possible translation combinations for compound words by combining the meanings of their individual segments. This function is used in the quick edit panel to suggest translations. It takes the text and the state object as input and returns an array of suggested translations, limited to a certain number of combinations. It also handles long inputs with a specific output format. ```javascript import { synthesizeCompoundTranslation } from './m_translation.js'; const text = '大家好'; const suggestions = synthesizeCompoundTranslation(text, state); console.log(suggestions); // Output: ['moi nguoi tot', 'dai gia tot', 'moi nguoi hay', ...] // Returns up to 100 unique combinations // Handle long inputs (limited to 7 segments) const longText = '这是一个很长很长的句子'; const longSuggestions = synthesizeCompoundTranslation(longText, state); console.log(longSuggestions); // Output: ['这是一个很长很长的句子 - Qua dai de goi y'] // Use in quick edit panel const editSuggestions = synthesizeCompoundTranslation(selectedText, state); editSuggestions.forEach(suggestion => { // Add to dropdown options }); ``` -------------------------------- ### Synthesize Compound Translation Combinations (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/README.md Generates all possible translation combinations for compound words by combining meanings of individual segments. This is used in the quick edit panel to suggest translations. The function returns an array of suggested translations, limited to 100 unique combinations. ```javascript import { synthesizeCompoundTranslation } from './m_translation.js'; const text = '大家好'; const suggestions = synthesizeCompoundTranslation(text, state); console.log(suggestions); // Output: ['moi nguoi tot', 'dai gia tot', 'moi nguoi hay', ...] // Returns up to 100 unique combinations // Handle long inputs (limited to 7 segments) const longText = '这是一个很长很长的句子'; const longSuggestions = synthesizeCompoundTranslation(longText, state); console.log(longSuggestions); // Output: ['这是一个很长很长的句子 - Qua dai de goi y'] // Use in quick edit panel const editSuggestions = synthesizeCompoundTranslation(selectedText, state); editSuggestions.forEach(suggestion => { // Add to dropdown options }); ``` -------------------------------- ### Retrieve All Meanings for a Word (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/README.md Retrieves all available meanings for a given word from different dictionary sources. This is useful for displaying all translation options in edit panels. The function returns an object containing various types of meanings. ```javascript import { getAllMeanings } from './m_dictionary.js'; const word = '李白'; const meanings = getAllMeanings(word, dictionaries, nameDictionary); console.log(meanings); /* Output: { name: 'Ly Bach', // From user's Name List (highest priority) names: ['Ly Bach'], // From Names.txt names2: [], // From Names2.txt vietphrase: ['ly bach'], // From Vietphrase.txt chapter: [], // From Chapter number dictionary number: [], // From Number dictionary hanviet: 'ly bach' // Sino-Vietnamese reading } */ // Use in UI to populate dropdown with all options const allOptions = new Set(); if (meanings.name) allOptions.add(meanings.name); meanings.names.forEach(m => allOptions.add(m)); meanings.vietphrase.forEach(m => allOptions.add(m)); // Display allOptions in dropdown ``` -------------------------------- ### Synthesize Compound Translation Combinations (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Generates all possible translation combinations for compound words by combining the meanings of their individual segments. This function is used in the quick edit panel to suggest translations. It returns up to 100 unique combinations and has limitations for very long inputs. ```javascript import { synthesizeCompoundTranslation } from './m_translation.js'; const text = '大家好'; const suggestions = synthesizeCompoundTranslation(text, state); console.log(suggestions); // Output: ['moi nguoi tot', 'dai gia tot', 'moi nguoi hay', ...] // Returns up to 100 unique combinations // Handle long inputs (limited to 7 segments) const longText = '这是一个很长很长的句子'; const longSuggestions = synthesizeCompoundTranslation(longText, state); console.log(longSuggestions); // Output: ['这是一个很长很长的句子 - Qua dai de goi y'] // Use in quick edit panel const editSuggestions = synthesizeCompoundTranslation(selectedText, state); editSuggestions.forEach(suggestion => { // Add to dropdown options }); ``` -------------------------------- ### Translate Word with Prioritized Lookups (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Translates a given word or phrase by searching through multiple dictionaries in a specific order: user-defined names, session-only names, and then loaded dictionaries. It returns the best match and an array of all possible meanings found, along with a boolean indicating if the word was found. ```javascript import { translateWord } from './m_dictionary.js'; import { nameDictionary, temporaryNameDictionary } from './m_nameList.js'; // Basic translation lookup const word = '你好'; const result = translateWord( word, dictionaries, // Loaded dictionaries Map nameDictionary, // User's custom name list (Map) temporaryNameDictionary, // Session-only translations (Map) false // getAllMeanings flag (unused) ); console.log(result); // Output: { best: 'xin chào', all: ['xin chào', 'chào'], found: true } // For words with multiple meanings separated by / or ; const multiMeaning = translateWord('我', dictionaries, nameDictionary, temporaryNameDictionary); console.log(multiMeaning); // Output: { best: 'tôi', all: ['tôi', 'ta', 'mình'], found: true } // For unknown words (not in any dictionary) const unknown = translateWord('未知词汇', dictionaries, nameDictionary, temporaryNameDictionary); console.log(unknown); // Output: { best: '未知词汇', all: [], found: false } ``` -------------------------------- ### Rebuild Master Data Structures (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Rebuilds the masterKeySet and Trie data structures, essential for efficient translation lookups. This function is typically called automatically when the name list changes but can be invoked manually after programmatic dictionary modifications. ```javascript import { rebuildMasterData } from './m_nameList.js'; // After modifying dictionaries or name list programmatically nameDictionary.set('新词', 'tu moi'); rebuildMasterData(state); // The function rebuilds: // 1. masterKeySet - Set of all Chinese words from all sources // 2. dictionaryTrie - 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) // Lower priority number = higher precedence in translation ``` -------------------------------- ### Retrieve All Meanings for a Word (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Retrieves all available meanings for a given word from different dictionary sources. This is useful for displaying all translation options in edit panels. The function takes the word and dictionary data as input and returns an object containing various types of meanings, including user-defined names, standard dictionary entries, and Sino-Vietnamese readings. ```javascript import { getAllMeanings } from './m_dictionary.js'; const word = '李白'; const meanings = getAllMeanings(word, dictionaries, nameDictionary); console.log(meanings); /* Output: { name: 'Ly Bach', // From user's Name List (highest priority) names: ['Ly Bach'], // From Names.txt names2: [], // From Names2.txt vietphrase: ['ly bach'], // From Vietphrase.txt chapter: [], // From Chapter number dictionary number: [], // From Number dictionary hanviet: 'ly bach' // Sino-Vietnamese reading } */ // Use in UI to populate dropdown with all options const allOptions = new Set(); if (meanings.name) allOptions.add(meanings.name); meanings.names.forEach(m => allOptions.add(m)); meanings.vietphrase.forEach(m => allOptions.add(m)); // Display allOptions in dropdown ``` -------------------------------- ### synthesizeCompoundTranslation Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Generates all possible translation combinations for compound words by combining the meanings of their individual segments. This is used in the quick edit panel to suggest translations. ```APIDOC ## synthesizeCompoundTranslation ### Description Generates all possible translation combinations for compound words by combining meanings of individual segments. Used in the quick edit panel to suggest translations. ### Method `synthesizeCompoundTranslation(text: string, state: object) => string[]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { synthesizeCompoundTranslation } from './m_translation.js'; const text = '大家好'; const suggestions = synthesizeCompoundTranslation(text, state); console.log(suggestions); // Output: ['moi nguoi tot', 'dai gia tot', 'moi nguoi hay', ...] // Returns up to 100 unique combinations // Handle long inputs (limited to 7 segments) const longText = '这是一个很长很长的句子'; const longSuggestions = synthesizeCompoundTranslation(longText, state); console.log(longSuggestions); // Output: ['这是一个很长很长的句子 - Qua dai de goi y'] // Use in quick edit panel const editSuggestions = synthesizeCompoundTranslation(selectedText, state); editSuggestions.forEach(suggestion => { // Add to dropdown options }); ``` ### Response #### Success Response (200) - **suggestions** (string[]) - An array of possible translation combinations for the compound word. ``` -------------------------------- ### Perform Main Translation (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md The main translation function that processes input text through multiple stages: name substitution, LuatNhan pattern rules, word segmentation, translation with smart spacing, and automatic capitalization. It requires a state object containing dictionaries and other necessary data. It can perform standard translations or 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 fast lookups lastTranslatedText: '' // Stores last input for re-translation }; // Standard translation from input textarea // Reads from DOMElements.inputText.value // Writes HTML output to DOMElements.outputPanel performTranslation(state); // Force translate specific text (useful for re-translation after name edits) performTranslation(state, { forceText: '这是一段中文文本', preserveTempDict: true // Keep temporary translations between calls }); // The output HTML structure with interactive spans: //

// day // la // Truong Tam // //

// Vietphrase mode (show all meanings) DOMElements.modeToggle.checked = true; performTranslation(state); // Output: (toi/ta/minh) (la) (nguoi/nhan) ... ``` -------------------------------- ### Perform Full Text Translation (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/README.md The main translation function that processes input text through multiple layers including name substitution, pattern rules, word segmentation, smart spacing, and automatic capitalization. It requires a state object containing dictionaries and other necessary data. ```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 fast lookups lastTranslatedText: '' // Stores last input for re-translation }; // Standard translation from input textarea // Reads from DOMElements.inputText.value // Writes HTML output to DOMElements.outputPanel performTranslation(state); // Force translate specific text (useful for re-translation after name edits) performTranslation(state, { forceText: '这是一段中文文本', preserveTempDict: true // Keep temporary translations between calls }); // The output HTML structure with interactive spans: //

// day // la // Truong Tam // //

// Vietphrase mode (show all meanings) DOMElements.modeToggle.checked = true; performTranslation(state); // Output: (toi/ta/minh) (la) (nguoi/nhan) ... ``` -------------------------------- ### Perform Translation with Multiple Layers (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt The main translation function that processes input text through several stages: name substitution, LuatNhan pattern rules, word segmentation, translation with smart spacing, and automatic capitalization. It requires a state object containing dictionaries, master key set, and a trie structure. It can perform standard translations or force translation of specific text, with options to preserve temporary dictionaries. ```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 fast lookups lastTranslatedText: '' // Stores last input for re-translation }; // Standard translation from input textarea // Reads from DOMElements.inputText.value // Writes HTML output to DOMElements.outputPanel performTranslation(state); // Force translate specific text (useful for re-translation after name edits) performTranslation(state, { forceText: '这是一段中文文本', preserveTempDict: true // Keep temporary translations between calls }); // The output HTML structure with interactive spans: //

// day // la // Truong Tam // //

// Vietphrase mode (show all meanings) DOMElements.modeToggle.checked = true; performTranslation(state); // Output: (toi/ta/minh) (la) (nguoi/nhan) ... ``` -------------------------------- ### clearAllDictionaries Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Clears all stored dictionaries from IndexedDB. This function is useful for resetting the application or freeing up storage space. ```APIDOC ## clearAllDictionaries ### Description Clears all stored dictionaries from IndexedDB. Useful for resetting the application or freeing storage space. ### Method `clearAllDictionaries() => Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { clearAllDictionaries } from './m_dictionary.js'; // Clear all dictionaries after user confirmation if (await customConfirm('Delete all dictionaries? This cannot be undone.')) { await clearAllDictionaries(); console.log('All dictionaries cleared'); location.reload(); // Reload to reset application state } ``` ### Response #### Success Response (200) - **None** - This function does not return a value upon successful completion. ``` -------------------------------- ### performTranslation Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt The main translation function that processes input text through multiple layers, including name substitution, pattern rules, word segmentation, smart spacing, and automatic capitalization. ```APIDOC ## performTranslation ### Description Main translation function that processes input text through multiple layers: name substitution with placeholders, LuatNhan pattern rules, word segmentation, translation with smart spacing, and automatic capitalization. ### Method `performTranslation(state: object, options?: { forceText?: string, preserveTempDict?: boolean }) => void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```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 fast lookups lastTranslatedText: '' // Stores last input for re-translation }; // Standard translation from input textarea // Reads from DOMElements.inputText.value // Writes HTML output to DOMElements.outputPanel performTranslation(state); // Force translate specific text (useful for re-translation after name edits) performTranslation(state, { forceText: '这是一段中文文本', preserveTempDict: true // Keep temporary translations between calls }); // The output HTML structure with interactive spans: //

// day // la // Truong Tam // //

// Vietphrase mode (show all meanings) DOMElements.modeToggle.checked = true; performTranslation(state); // Output: (toi/ta/minh) (la) (nguoi/nhan) ... ``` ### Response #### Success Response (200) - **None** - This function modifies the DOM or internal state and does not return a value. ``` -------------------------------- ### segmentText Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Segments Chinese text into words using the longest-match algorithm against a provided set of known dictionary words. ```APIDOC ## segmentText ### Description Segments Chinese text into words using longest-match algorithm with the master key set containing all known dictionary words. ### Method `segmentText(text: string, masterKeySet: Set) => string[]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { segmentText } from './m_dictionary.js'; // masterKeySet is a Set containing all known words from all dictionaries const text = '我今天很高兴见到你'; const segments = segmentText(text, state.masterKeySet); console.log(segments); // Output: ['我', '今天', '很', '高兴', '见到', '你'] // Segments are matched against dictionary entries for optimal word boundaries // With mixed content const mixedText = '我有100元'; const mixedSegments = segmentText(mixedText, state.masterKeySet); console.log(mixedSegments); // Output: ['我', '有', '100元'] or ['我', '有', '100', '元'] depending on dictionary ``` ### Response #### Success Response (200) - **segments** (string[]) - An array of segmented words. ``` -------------------------------- ### Standardize Dictionary Line (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Normalizes dictionary entry lines for parsing, preserving Vietnamese translations and handling comments or lines without an '=' sign. It ensures that only the Chinese part of a dictionary entry is processed while the Vietnamese part remains untouched. ```javascript import { standardizeDictionaryLine } from './m_preprocessor.js'; // Standard dictionary line format: Chinese=Vietnamese const line = '你好!=xin chao'; const standardized = standardizeDictionaryLine(line); console.log(standardized); // Output: '你好!=xin chao' (only Chinese part is normalized) // Preserve Vietnamese side completely const withSpecial = '什么?=cai gi?'; console.log(standardizeDictionaryLine(withSpecial)); // Output: '什么?=cai gi?' (Vietnamese "?" preserved as-is) // Blacklist entries (no '=' sign) - entire line normalized const blacklistLine = '广告词!'; console.log(standardizeDictionaryLine(blacklistLine)); // Output: '广告词!' // Comment lines preserved const comment = '# This is a comment'; console.log(standardizeDictionaryLine(comment)); // Output: '# This is a comment' ``` -------------------------------- ### Trie Data Structure for Lookups (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt An internal Trie data structure used for efficient longest-match word lookup during translation. It allows for quick retrieval of dictionary entries based on text segments. The Trie stores words as keys and their associated translation metadata as values. ```javascript // Trie is used internally but understanding its structure helps with debugging // The Trie stores words with associated metadata class Trie { insert(key, value, overwrite = false) { // Inserts Chinese word as key with translation metadata as value // value = { translation: string, type: string, ruleKey: string } } findLongestMatch(text, startIndex) { // Returns longest matching word starting at startIndex // Returns: { key: '中国', value: { translation: '...' } } or null } } // Used during translation to find longest dictionary matches const match = state.dictionaryTrie.findLongestMatch('我是中国人', 2); console.log(match); // Output: { key: '中国人', value: { translation: 'nguoi Trung Quoc', type: 'Names' } } ``` -------------------------------- ### Segment Chinese Text using Longest-Match Algorithm (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/README.md Segments Chinese text into words using the longest-match algorithm. It requires a master key set containing all known dictionary words. The function returns an array of segmented words. ```javascript import { segmentText } from './m_dictionary.js'; // masterKeySet is a Set containing all known words from all dictionaries const text = '我今天很高兴见到你'; const segments = segmentText(text, state.masterKeySet); console.log(segments); // Output: ['我', '今天', '很', '高兴', '见到', '你'] // Segments are matched against dictionary entries for optimal word boundaries // With mixed content const mixedText = '我有100元'; const mixedSegments = segmentText(mixedText, state.masterKeySet); console.log(mixedSegments); // Output: ['我', '有', '100元'] or ['我', '有', '100', '元'] depending on dictionary ``` -------------------------------- ### Segment Chinese Text using Longest-Match Algorithm (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Segments Chinese text into words using the longest-match algorithm. It relies on a master key set containing all known dictionary words. The function takes the text and the master key set as input and returns an array of segmented words. It can handle both pure Chinese text and mixed content with numbers. ```javascript import { segmentText } from './m_dictionary.js'; // masterKeySet is a Set containing all known words from all dictionaries const text = '我今天很高兴见到你'; const segments = segmentText(text, state.masterKeySet); console.log(segments); // Output: ['我', '今天', '很', '高兴', '见到', '你'] // Segments are matched against dictionary entries for optimal word boundaries // With mixed content const mixedText = '我有100元'; const mixedSegments = segmentText(mixedText, state.masterKeySet); console.log(mixedSegments); // Output: ['我', '有', '100元'] or ['我', '有', '100', '元'] depending on dictionary ``` -------------------------------- ### Standardize Text for Normalization (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Normalizes Chinese text by removing extra spaces around punctuation and converting various full-width and Chinese punctuation marks to their ASCII equivalents. Certain characters, like Chinese quotes, are preserved. ```javascript import { standardizeText } from './m_preprocessor.js'; // Normalize punctuation const input = '你好!我叫张三。'; const standardized = standardizeText(input); console.log(standardized); // Output: '你好!我叫张三.' // Converts: !→! 。→. ,→, :→: ;→; ?→? // Remove extra spaces around punctuation const messy = '你 好 ! 我 叫 张三 。'; console.log(standardizeText(messy)); // Output: '你好!我叫张三.' // Full-width to half-width conversion const fullWidth = '(你好)【重要】'; console.log(standardizeText(fullWidth)); // Output: '(你好)[重要]' // Preserved characters (Chinese quotes for dialogue) const dialogue = '他说:「你好」'; console.log(standardizeText(dialogue)); // Output: '他说:「你好」' (「」 preserved, : converted) ``` -------------------------------- ### Standardize Dictionary Line (JavaScript) Source: https://context7.com/johnlikescarrot/vietphrase/llms.txt Normalizes Chinese text in dictionary entries while preserving the Vietnamese translation part. It handles various line formats including comments and blacklist entries. This function is crucial for parsing dictionary files accurately. ```javascript import { standardizeDictionaryLine } from './m_preprocessor.js'; // Standard dictionary line format: Chinese=Vietnamese const line = '你好!=xin chao'; const standardized = standardizeDictionaryLine(line); console.log(standardized); // Output: '你好!=xin chao' (only Chinese part is normalized) // Preserve Vietnamese side completely const withSpecial = '什么?=cai gi?'; console.log(standardizeDictionaryLine(withSpecial)); // Output: '什么?=cai gi?' (Vietnamese "?" preserved as-is) // Blacklist entries (no '=' sign) - entire line normalized const blacklistLine = '广告词!'; console.log(standardizeDictionaryLine(blacklistLine)); // Output: '广告词!' // Comment lines preserved const comment = '# This is a comment'; console.log(standardizeDictionaryLine(comment)); // Output: '# This is a comment' ``` -------------------------------- ### Trie Class for Longest Match Lookup (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Implements an internal Trie data structure for efficient longest-match word lookup during translation. It allows for inserting words with associated metadata and finding the longest matching word within a given text segment. ```javascript // Trie is used internally but understanding its structure helps with debugging // The Trie stores words with associated metadata class Trie { insert(key, value, overwrite = false) { // Inserts Chinese word as key with translation metadata as value // value = { translation: string, type: string, ruleKey: string } } findLongestMatch(text, startIndex) { // Returns longest matching word starting at startIndex // Returns: { key: '中国', value: { translation: '...' } } or null } } // Used during translation to find longest dictionary matches const match = state.dictionaryTrie.findLongestMatch('我是中国人', 2); console.log(match); // Output: { key: '中国人', value: { translation: 'nguoi Trung Quoc', type: 'Names' } } ``` -------------------------------- ### Clear All Dictionaries from IndexedDB (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/README.md Clears all stored dictionaries from IndexedDB. This function is useful for resetting the application or freeing up storage space. It requires user confirmation before proceeding. ```javascript import { clearAllDictionaries } from './m_dictionary.js'; // Clear all dictionaries after user confirmation if (await customConfirm('Delete all dictionaries? This cannot be undone.')) { await clearAllDictionaries(); console.log('All dictionaries cleared'); location.reload(); // Reload to reset application state } ``` -------------------------------- ### Clear All Dictionaries from IndexedDB (JavaScript) Source: https://github.com/johnlikescarrot/vietphrase/blob/main/AGENTS.md Clears all stored dictionaries from IndexedDB. This function is useful for resetting the application or freeing up storage space. It requires user confirmation before proceeding and typically reloads the application after clearing. ```javascript import { clearAllDictionaries } from './m_dictionary.js'; // Clear all dictionaries after user confirmation if (await customConfirm('Delete all dictionaries? This cannot be undone.')) { await clearAllDictionaries(); console.log('All dictionaries cleared'); location.reload(); // Reload to reset application state } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.