text-beautifier-core
v1.0.0
Published
零依赖文本美化核心引擎
Readme
# Text Beautifier Core
一个轻量级、零依赖的文本美化核心引擎,支持多种装饰效果和结构性元素美化。
## 特性
- **零依赖**:纯 TypeScript 实现,不依赖任何第三方库
- **丰富装饰**:下划线、删除线、渐变、发光、高亮、前缀/后缀等
- **结构性元素美化**:上标、下标、分割线、列表项、引用块、代码块
- **设计模式**:策略模式、工厂模式、组合模式、构建器模式、访问者模式
- **智能美化**:自动识别 HTML 元素并应用规则
- **完整类型**:提供完整的 TypeScript 类型定义
- **高测试覆盖率**:>90% 测试覆盖率
## 安装
```bash
npm install text-beautifier-core
# 或
yarn add text-beautifier-core快速开始
import { TextBeautifier } from 'text-beautifier-core';
// 创建实例(默认注册所有内置策略)
const beautifier = new TextBeautifier();
// 1. 基础文本装饰
const underlined = beautifier.createStrategy('underline', { color: 'red', style: 'wavy' })
.apply('Hello World');
console.log(underlined);
// 2. 组合多个装饰
const composite = beautifier.createComposite();
composite.addStrategy('gradient', { colors: ['red', 'blue'] });
composite.addStrategy('glow', { color: 'gold', radius: 3 });
const result = composite.apply('Beautiful Text');
console.log(result);
// 3. 使用构建器链式调用
const builderResult = beautifier.createBuilder()
.underline({ color: 'blue' })
.glow({ color: 'pink', radius: 2 })
.superscript({ color: 'green', icon: { symbol: '✨', position: 'prefix' } })
.build('2<sup>3</sup> = 8');
console.log(builderResult);
// 4. 美化 HTML 文档
const html = `
<p>水的化学式是 H<sub>2</sub>O</p>
<p>2<sup>3</sup> = 8</p>
<hr>
<ul>
<li>第一项</li>
<li>第二项</li>
</ul>
`;
const beautified = beautifier.beautifyHtml(html, {
superscript: { color: '#ff0000', icon: { symbol: '⚡', position: 'prefix' } },
subscript: { color: '#0000ff', fontSize: '0.8em' },
horizontalRule: {
height: 2,
color: 'linear-gradient(to right, gold, orange)',
animation: { type: 'glow', duration: 3 }
},
listItem: (depth) => ({
bullet: {
type: depth === 0 ? 'icon' : 'symbol',
value: depth === 0 ? '🔥' : '•',
color: depth === 0 ? 'orange' : 'gray'
}
})
});
console.log(beautified);主要功能
基础装饰线
- 下划线 (underline)
- 删除线 (line-through)
- 上划线 (overline) - 待实现
文字颜色效果
- 纯色高亮 (highlight)
- 渐变文字 (gradient)
- 描边文字 (stroke) - 待实现
- 文字发光 (glow)
文字间距
- 字符间距 (letter-spacing) - 待实现
- 单词间距 (word-spacing) - 待实现
符号装饰
- 前缀 (prefix)
- 后缀 (suffix)
- 图标装饰 (icon) - 可通过前缀/后缀实现
结构性元素美化
- 上标美化 (superscriptStyle)
- 下标美化 (subscriptStyle)
- 分割线美化 (horizontalRuleStyle)
- 列表项美化 (listItemStyle)
- 引用块美化 (blockquoteStyle)
- 代码块美化 (codeBlockStyle)
API 参考
TextBeautifier
主类,提供所有功能的入口。
构造函数
new TextBeautifier(options?: {
strategies?: DecorationStrategy[]; // 自定义策略列表
autoDetect?: boolean; // 是否自动检测(预留)
})方法
| 方法 | 描述 |
|------|------|
| registerStrategy(strategy) | 注册单个策略 |
| registerStrategies(strategies) | 批量注册策略 |
| createStrategy(type, config) | 获取策略实例 |
| createComposite() | 创建组合装饰器 |
| createBuilder() | 创建构建器 |
| beautify(input, configs?) | 智能美化(自动选择策略) |
| beautifyHtml(html, rules) | 美化 HTML 文档 |
| getAvailableTypes() | 获取所有已注册策略类型 |
| getStrategiesByCategory(category) | 按类别获取策略 |
| getStrategyMetadata(type) | 获取策略元数据 |
| hasStrategy(type) | 检查策略是否存在 |
| validateConfig(type, config) | 验证配置 |
| validateComposite(strategies) | 验证组合配置 |
| generateCSS(type, config) | 生成 CSS 字符串 |
| generatePreview(type, config) | 生成预览 HTML |
| detectElementType(html) | 检测 HTML 元素类型 |
策略接口
所有策略都实现 DecorationStrategy 接口,包含以下核心方法:
apply(input, config):应用装饰getCSS(config):获取 CSS 对象validateConfig(config):验证配置getMetadata():获取元数据supports(input):检查是否支持输入
配置类型
每个策略都有对应的配置类型,例如 UnderlineConfig、GradientConfig、SuperscriptStyleConfig 等。详细字段请参考类型定义。
示例
更多示例请查看 examples 目录。
错误处理
所有错误均继承自 BeautifierError,包含错误码和详细信息。常见错误码:
STRATEGY_NOT_FOUNDINVALID_CONFIGUNSUPPORTED_ELEMENTFACTORY_ERRORCOMPOSITE_ERRORBUILDER_ERRORPARSER_ERROR
示例:
import { StrategyNotFoundError } from 'text-beautifier-core';
try {
beautifier.createStrategy('unknown', {});
} catch (e) {
if (e instanceof StrategyNotFoundError) {
console.error(e.code, e.message, e.details);
}
}开发
git clone https://github.com/yourname/text-beautifier-core.git
cd text-beautifier-core
npm install
npm test
npm run build