/**
* 后台富文本清洗(协议、公告等静态内容)
*
* 背景:html 表里的正文是 Word / 旧编辑器导出的,存在两类问题会破坏移动端排版:
* 1. 大量 `
` 空段落,叠加段间距后出现大片空白;
* 2. 几乎每个 span 都带内联 `font-family:宋体;font-size:14px;color:#000`,
* 内联样式优先级最高,会盖掉端上给的 tagStyle,导致字号偏小、暗色模式不可读。
*
* 处理方式:删掉空段落,剥掉会影响排版与主题的内联属性,保留加粗、下划线等语义样式。
*/
// 会破坏排版 / 主题的内联属性,统一剥掉,交给端上的 tagStyle 决定
const DROP_STYLE_PROPS = [
'font-family',
'font-size',
'color',
'background',
'background-color',
'line-height',
'margin',
'margin-top',
'margin-bottom',
'margin-left',
'margin-right',
'padding',
'padding-top',
'padding-bottom',
'width',
'height'
]
/** 判断一段 html 是否只有空白内容(空格、 、
、空标签) */
function isBlankFragment(html) {
const text = String(html || '')
.replace(/
/gi, '')
.replace(/<[^>]+>/g, '')
.replace(/ | |\u00a0/gi, '')
.replace(/\s/g, '')
return text.length === 0
}
/** 过滤单个 style 属性里的危险声明 */
function cleanStyleValue(style) {
return String(style || '')
.split(';')
.map((item) => item.trim())
.filter(Boolean)
.filter((item) => {
const prop = item.split(':')[0].trim().toLowerCase()
return prop && !DROP_STYLE_PROPS.includes(prop)
})
.join('; ')
}
/**
* @param {string} html 后台返回的富文本
* @return {string} 清洗后的富文本
*/
export function cleanRichText(html) {
if (!html) return ''
let text = String(html)
// 1. Word 导出常见的无用标签
text = text
.replace(/<\/?o:p[^>]*>/gi, '')
.replace(//g, '')
.replace(/]*>/gi, '')
.replace(/