### JavaScript: Text-to-Speech Pronunciation Helper Source: https://context7.com/zmg95171/card/llms.txt Implements a `PronunciationHelper` class using the Web Speech API to provide text-to-speech functionality for pronouncing words and examples. It allows customization of voice, rate, pitch, and volume, and supports selecting English voices with specific accents. The class handles asynchronous loading of voices. ```javascript // Voice synthesis for word pronunciation class PronunciationHelper { constructor() { this.synth = window.speechSynthesis; this.voices = []; this.loadVoices(); } loadVoices() { this.voices = this.synth.getVoices(); // Chrome loads voices asynchronously if (this.voices.length === 0) { this.synth.addEventListener('voiceschanged', () => { this.voices = this.synth.getVoices(); }); } } // Pronounce word with specific voice pronounce(text, options = {}) { const utterance = new SpeechSynthesisUtterance(text); // Select English voice const enVoice = this.voices.find(voice => voice.lang.startsWith('en-') && (options.accent ? voice.lang.includes(options.accent) : true) ); if (enVoice) { utterance.voice = enVoice; } utterance.rate = options.rate || 0.9; // Slightly slower for learning utterance.pitch = options.pitch || 1.0; utterance.volume = options.volume || 1.0; this.synth.speak(utterance); } // Pronounce word with example pronounceWithExample(word, example) { this.pronounce(word); setTimeout(() => { this.pronounce(example, { rate: 0.85 }); }, 1500); } stop() { this.synth.cancel(); } } // Usage const pronunciation = new PronunciationHelper(); // Pronounce single word pronunciation.pronounce('eloquent'); // Pronounce with American accent pronunciation.pronounce('schedule', { accent: 'US' }); // Pronounce word and example pronunciation.pronounceWithExample( 'eloquent', 'She gave an eloquent speech that moved the audience.' ); // Stop current speech pronunciation.stop(); ``` -------------------------------- ### Import Vocabulary from Simple Text Format (JavaScript) Source: https://context7.com/zmg95171/card/llms.txt Parses and imports vocabulary from a simple text format where each line is a word followed by a definition, separated by a hyphen or em dash. It splits the text by newlines, extracts word-definition pairs, assigns a unique ID, and stores them in localStorage. Input is a string of text content. ```javascript // Import from text format: word - definition function importSimpleFormat(textContent) { const lines = textContent.split('\n').filter(line => line.trim()); const words = []; let id = Date.now(); lines.forEach(line => { const match = line.match(/^(.+?)\s*[-–—]\s*(.+)$/); if (match) { words.push({ id: id++, word: match[1].trim(), phonetic: '', definition: match[2].trim(), example: '', example_trans: '', derivatives: [], tags: [], categories: ['自定义'], level: 1, learned: false }); } }); let existingWords = JSON.parse(localStorage.getItem('wordCards') || '{"words":[]}'); existingWords.words = existingWords.words.concat(words); localStorage.setItem('wordCards', JSON.stringify(existingWords)); return { imported: words.length, total: existingWords.words.length }; } // Example usage const textData = ` eloquent - adj. 雄辩的;有口才的 profound - adj. 深刻的;意义深远的 meticulous - adj. 一丝不苟的;精心的 `; const result = importSimpleFormat(textData); console.log(`Imported ${result.imported} words, total: ${result.total}`); ``` -------------------------------- ### Import Vocabulary from URL (JavaScript) Source: https://context7.com/zmg95171/card/llms.txt Fetches and imports vocabulary data from remote URLs, such as GitHub repositories. It handles JSON responses and merges them with existing vocabulary stored in localStorage. It requires the 'fetch' API, which is available in modern browsers and Node.js environments. ```javascript async function importFromURL(url) { try { // Example: https://github.com/zmg95171/md-note/blob/main/Daily.json const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); let existingWords = JSON.parse(localStorage.getItem('wordCards') || '{"words":[]}'); if (data.words && Array.isArray(data.words)) { existingWords.words = existingWords.words.concat(data.words); } else if (Array.isArray(data)) { existingWords.words = existingWords.words.concat(data); } localStorage.setItem('wordCards', JSON.stringify(existingWords)); return { success: true, count: data.words?.length || data.length, message: 'Import successful' }; } catch (error) { return { success: false, error: error.message }; } } // Usage importFromURL('https://raw.githubusercontent.com/username/repo/main/vocabulary.json') .then(result => console.log(result)); ``` -------------------------------- ### Manage Word Learning Progress (JavaScript) Source: https://context7.com/zmg95171/card/llms.txt A JavaScript class for managing the learning status of words. It provides methods to mark words as learned or difficult, retrieve learning statistics (total, learned, difficult, unlearned words), and categorize words. It uses localStorage for persistent storage of word card data. ```javascript // Learning status management class WordProgressManager { constructor() { this.storage = localStorage; this.storageKey = 'wordCards'; } // Mark word as learned markAsLearned(wordId) { const data = this.getData(); const word = data.words.find(w => w.id === wordId); if (word) { word.learned = true; word.lastReviewed = new Date().toISOString(); this.saveData(data); return true; } return false; } // Mark word as difficult markAsDifficult(wordId) { const data = this.getData(); const word = data.words.find(w => w.id === wordId); if (word) { word.difficult = true; word.reviewCount = (word.reviewCount || 0) + 1; this.saveData(data); return true; } return false; } // Get learning statistics getStatistics() { const data = this.getData(); return { total: data.words.length, learned: data.words.filter(w => w.learned).length, difficult: data.words.filter(w => w.difficult).length, unlearned: data.words.filter(w => !w.learned).length, categories: this.getCategoryStats(data.words) }; } getCategoryStats(words) { const stats = {}; words.forEach(word => { word.categories?.forEach(cat => { stats[cat] = (stats[cat] || 0) + 1; }); }); return stats; } getData() { return JSON.parse(this.storage.getItem(this.storageKey) || '{"words":[]}'); } saveData(data) { this.storage.setItem(this.storageKey, JSON.stringify(data)); } } // Usage example const manager = new WordProgressManager(); manager.markAsLearned(1); manager.markAsDifficult(5); const stats = manager.getStatistics(); console.log(`Total: ${stats.total}, Learned: ${stats.learned}, Difficult: ${stats.difficult}`); ``` -------------------------------- ### JavaScript: Tag-Based Search and Filtering Source: https://context7.com/zmg95171/card/llms.txt Provides functions to search and filter word cards based on tags, keywords, categories, and difficulty level. It utilizes localStorage for data persistence and supports both exact and partial matching for tags. The functions are designed to handle potential missing tag data gracefully. ```javascript // Advanced tag-based filtering function searchByTags(tags, matchAll = false) { const data = JSON.parse(localStorage.getItem('wordCards') || '{"words":[]}'); if (matchAll) { // Require all tags to match return data.words.filter(word => tags.every(tag => word.tags?.includes(tag)) ); } else { // Match any tag return data.words.filter(word => tags.some(tag => word.tags?.includes(tag)) ); } } // Search by word or definition function searchWords(query) { const data = JSON.parse(localStorage.getItem('wordCards') || '{"words":[]}'); const lowerQuery = query.toLowerCase(); return data.words.filter(word => word.word.toLowerCase().includes(lowerQuery) || word.definition.toLowerCase().includes(lowerQuery) || word.example?.toLowerCase().includes(lowerQuery) ); } // Combined search with filters function advancedSearch(options) { let data = JSON.parse(localStorage.getItem('wordCards') || '{"words":[]}'); let results = data.words; if (options.query) { const q = options.query.toLowerCase(); results = results.filter(w => w.word.toLowerCase().includes(q) || w.definition.toLowerCase().includes(q) ); } if (options.tags && options.tags.length > 0) { results = results.filter(w => options.tags.some(tag => w.tags?.includes(tag)) ); } if (options.categories && options.categories.length > 0) { results = results.filter(w => options.categories.some(cat => w.categories?.includes(cat)) ); } if (options.level) { results = results.filter(w => w.level === options.level); } return results; } // Usage examples const hotelWords = searchByTags(['酒店', '入住'], false); const foodAllergy = searchByTags(['过敏', '食物'], true); const searchResults = searchWords('check'); const advanced = advancedSearch({ query: 'cart', categories: ['购物'], level: 2 }); ``` -------------------------------- ### Category Management System (JavaScript) Source: https://context7.com/zmg95171/card/llms.txt Manages word categories, allowing for dynamic creation, filtering, and renaming. It interacts with local storage to persist category data. Key methods include retrieving all categories, adding categories to words, filtering words by category, and renaming categories across all associated words. It relies on the browser's localStorage API. ```javascript // Category management system class CategoryManager { constructor() { this.storageKey = 'wordCards'; } // Get all unique categories getAllCategories() { const data = this.getData(); const categoriesSet = new Set(); data.words.forEach(word => { word.categories?.forEach(cat => categoriesSet.add(cat)); }); return Array.from(categoriesSet).sort(); } // Add category to word addCategoryToWord(wordId, category) { const data = this.getData(); const word = data.words.find(w => w.id === wordId); if (word) { word.categories = word.categories || []; if (!word.categories.includes(category)) { word.categories.push(category); this.saveData(data); return true; } } return false; } // Filter words by category filterByCategory(category) { const data = this.getData(); return data.words.filter(w => w.categories?.includes(category)); } // Rename category across all words renameCategory(oldName, newName) { const data = this.getData(); let count = 0; data.words.forEach(word => { if (word.categories?.includes(oldName)) { const index = word.categories.indexOf(oldName); word.categories[index] = newName; count++; } }); this.saveData(data); return count; } getData() { return JSON.parse(localStorage.getItem(this.storageKey) || '{"words":[]}'); } saveData(data) { localStorage.setItem(this.storageKey, JSON.stringify(data)); } } // Usage const catManager = new CategoryManager(); const allCategories = catManager.getAllCategories(); console.log('Available categories:', allCategories); catManager.addCategoryToWord(1, '商务英语'); const businessWords = catManager.filterByCategory('商务英语'); console.log(`Business words: ${businessWords.length}`); const renamed = catManager.renameCategory('旅游', 'Travel'); console.log(`Renamed ${renamed} words`); ``` -------------------------------- ### Random Review Word Selection (JavaScript) Source: https://context7.com/zmg95171/card/llms.txt Selects a random set of words for review based on specified criteria such as learned status, difficulty, category, and level. It retrieves data from local storage, filters words accordingly, shuffles them, and returns the requested count. Dependencies include the browser's localStorage API. ```javascript // Random review selection with filtering function getRandomReviewWords(count = 10, options = {}) { const data = JSON.parse(localStorage.getItem('wordCards') || '{"words":[]}'); let words = data.words; // Filter by learned status if (options.learnedOnly) { words = words.filter(w => w.learned); } // Filter by difficulty if (options.difficultOnly) { words = words.filter(w => w.difficult); } // Filter by category if (options.category) { words = words.filter(w => w.categories?.includes(options.category)); } // Filter by level if (options.level) { words = words.filter(w => w.level === options.level); } // Shuffle and return const shuffled = words.sort(() => Math.random() - 0.5); return shuffled.slice(0, Math.min(count, shuffled.length)); } // Usage examples const reviewWords = getRandomReviewWords(10, { learnedOnly: true }); const difficultWords = getRandomReviewWords(5, { difficultOnly: true }); const travelWords = getRandomReviewWords(15, { category: '旅游' }); const level2Words = getRandomReviewWords(20, { level: 2 }); console.log(`Review set: ${reviewWords.length} words`); console.log(`Difficult words: ${difficultWords.length} words`); console.log(`Travel vocabulary: ${travelWords.length} words`); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.