1
0
mirror of https://github.com/ialley-workshop-open/uni-halo.git synced 2026-11-13 22:11:42 +08:00
Files
uni-halo/src/utils/text.ts
T
小莫唐尼 abae523a30 refactor: 整理项目代码风格与修复细节问题
本次提交包含多项优化:
1. 修复htmlToPlainText入参类型校验逻辑
2. 移除冗余的overflow-hidden类名,调整分类组件样式
3. 新增自定义导航占位hook统一处理导航栏间距
4. 优化投票筛选选项文字大小,修复文章摘要获取逻辑
5. 重构画廊页面分类吸顶逻辑,调整分类项样式与滚动行为
6. 统一about与contact页面的模糊样式类名,调整页面内文字大小与间距
7. 重构useDataLoading工具函数的导入与代码格式
8. 优化设置页面的UI样式与按钮文字大小
9. 统一投票卡片组件的代码缩进与文字样式
10. 重构联系页面的代码格式,统一变量声明风格
2026-09-13 03:58:05 +08:00

52 lines
1.7 KiB
TypeScript

/**
* 文本工具:HTML 剥离为纯文本 + 摘要截断
* 跨端实现(小程序无 DOM),仅用正则处理,不依赖 DOMParser
*/
/** HTML 实体解码(覆盖常见实体即可) */
const HTML_ENTITY_MAP: Record<string, string> = {
'&nbsp;': ' ',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': '\'',
'&amp;': '&',
}
/** 行首 markdown 标记(# 标题 / * - 列表 / 数字序号 / 引用 > / 代码块 ``` 等) */
const MD_PREFIX_REG = /^\s{0,3}(#{1,6}[ \t]|>|[+*-][ \t]|\d+[.、)][ \t]|```|~~~|!?\[)/gm
/**
* 将 HTML/Markdown 源文本剥离为压缩空白后的纯文本
* @param source 原文(可为空)
*/
export function htmlToPlainText(source?: string): string {
if (typeof source !== 'string' || !source)
return ''
let text = source
// 剥离脚本/样式块
text = text.replace(/<(script|style)[\s\S]*?<\/\1>/gi, ' ')
// 块级/换行标签替换为空格,其余标签整体剥离
text = text
.replace(/<\/(p|div|br|li|h[1-6]|blockquote|pre|tr|section|article)>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
// markdown 行首符号清理
text = text.replace(MD_PREFIX_REG, '')
// 实体解码
text = text.replace(/&[a-z]+;|&#\d+;/gi, match => HTML_ENTITY_MAP[match.toLowerCase()] ?? ' ')
// 压缩空白(含换行)
return text.replace(/\s+/g, ' ').trim()
}
/** 截断文本,超长追加省略号 */
export function truncateText(text: string, max: number, ellipsis = '…'): string {
if (!text || text.length <= max)
return text
return `${text.slice(0, max).trimEnd()}${ellipsis}`
}
/** 从 HTML/Markdown 源提取纯文本摘要(去标签 + 截断) */
export function extractPlainExcerpt(source?: string, max = 120): string {
return truncateText(htmlToPlainText(source), max)
}