2026-02-11 14:18:22 +08:00

126 lines
3.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @file 词典接口基类
* @description 定义词典抽象接口,所有词典实现需继承此类
*/
/**
* 词典查询结果结构
* @typedef {Object} DictionaryResult
* @property {string} word - 查询的单词
* @property {string} [phonetic] - 音标
* @property {Array<Meaning>} meanings - 释义列表
* @property {Array<Example>} [examples] - 例句列表
* @property {string} [url] - 词典页面链接
*/
/**
* 释义项结构
* @typedef {Object} Meaning
* @property {string} partOfSpeech - 词性(如 n., v., adj.
* @property {Array<string>} definitions - 中文释义列表
*/
/**
* 例句结构
* @typedef {Object} Example
* @property {string} sentence - 英文例句
* @property {string} [translation] - 中文翻译
*/
/**
* 词典基类
* 所有词典实现必须继承此类并实现 search 方法
*/
export class DictionaryBase {
/**
* @param {Object} config - 词典配置
* @param {string} config.name - 词典名称
* @param {string} [config.icon] - 词典图标路径
* @param {Array<string>} [config.languages] - 支持的语言代码列表
* @param {Object} [config.options] - 其他配置选项
*/
constructor(config = {}) {
this.name = config.name || 'Unknown';
this.icon = config.icon || '';
this.languages = config.languages || ['en', 'zh'];
this.options = config.options || {};
}
/**
* 查询单词
* @param {string} word - 要查询的单词
* @returns {Promise<DictionaryResult>} 查询结果
* @throws {Error} 子类必须实现此方法
*/
async search(word) {
throw new Error('search() method must be implemented by subclass');
}
/**
* 检查是否支持指定语言
* @param {string} lang - 语言代码(如 'en', 'zh'
* @returns {boolean} 是否支持
*/
supports(lang) {
return this.languages.includes(lang);
}
/**
* 获取词典信息
* @returns {Object} 词典信息
*/
getInfo() {
return {
name: this.name,
icon: this.icon,
languages: this.languages
};
}
}
/**
* 创建标准查询结果对象
* @param {Object} data - 结果数据
* @param {string} data.word - 单词
* @param {string} [data.phonetic] - 音标
* @param {Array<Meaning>} [data.meanings] - 释义列表
* @param {Array<Example>} [data.examples] - 例句列表
* @param {string} [data.url] - 词典页面链接
* @returns {DictionaryResult} 标准化的查询结果
*/
export function createResult(data) {
return {
word: data.word || '',
phonetic: data.phonetic || '',
meanings: data.meanings || [],
examples: data.examples || [],
url: data.url || ''
};
}
/**
* 创建释义项
* @param {string} partOfSpeech - 词性
* @param {Array<string>} definitions - 释义列表
* @returns {Meaning} 释义对象
*/
export function createMeaning(partOfSpeech, definitions) {
return {
partOfSpeech: partOfSpeech || '',
definitions: Array.isArray(definitions) ? definitions : [definitions]
};
}
/**
* 创建例句
* @param {string} sentence - 英文例句
* @param {string} [translation] - 中文翻译
* @returns {Example} 例句对象
*/
export function createExample(sentence, translation = '') {
return {
sentence: sentence || '',
translation: translation || ''
};
}