富文本模型
@xihan-ui/core/rich-text 是结构化的富文本:段落、标题、列表、分隔线与带样式的文字,整份是 JSON,不含 HTML。外来的 HTML 按白名单换成模型,模型再写回 HTML 或纯文字;按模型生成 DOM 在 @xihan-ui/core/rich-text-dom。打印设计器的富文本元素存的就是这份模型。
import { checkRichTextDocument, parseRichTextHtml, serializeRichTextHtml } from "@xihan-ui/core/rich-text";
import { renderRichText } from "@xihan-ui/core/rich-text-dom";
const { document: model, dropped } = parseRichTextHtml("<p>你好,<strong>世界</strong></p><script>x()</script>");
// model: { blocks: [{ type: "paragraph", runs: [{ type: "text", text: "你好," }, { type: "text", text: "世界", marks: { bold: true } }] }] }
// dropped: [{ kind: "content", name: "script", count: 1 }]
checkRichTextDocument(model); // []
container.replaceChildren(renderRichText(document, model));
serializeRichTextHtml(model); // "<p>你好,<strong>世界</strong></p>"概念
解决什么问题
模板里常有一段「带格式的说明文字」:加粗的金额、红色的提示、编号的条款,中间还嵌着「客户名」「合同号」这样的字段。这段文字要存进模板、数据库与接口,又要在浏览器、打印页与纯文字导出里各显示一遍。
最省事的做法是存 HTML,再用 innerHTML 显示,但它带来三个问题:
- 安全:HTML 能带脚本、事件属性与
javascript:链接,直接塞进innerHTML就是跨站脚本的入口。 - 不可控:从办公软件、网页粘贴来的 HTML 什么标签与样式都有,打印排版、导出纯文字时无从下手。
- 不可检查:一段 HTML 合不合规,只能交给浏览器解析后才知道;服务端保存前无法逐项核对。
富文本模型把这段内容收成一份封闭的 JSON:只有固定几种块、几种行内内容与一组样式键,每个字段都有明确的取值范围。HTML 只在进出两头出现,中间流转、保存与检查的都是 JSON。
存 HTML 还是存模型
| 方案 | 代价 | 适合 |
|---|---|---|
| 存 HTML 串 | 显示前必须再过一遍净化;标签、样式无法穷举,打印与导出要自己再解析一次;服务端难以校验 | 内容只在浏览器里原样显示,且来源可信 |
| 存富文本模型 | 只有段落、标题、列表、分隔线与行内样式,表格、图片、代码块这类结构放不进来;外来 HTML 导入时会丢东西(丢了什么会报出来) | 模板、设计器、表单里的说明文字:要检查、要打印、要导出纯文字、要嵌字段 |
何时用:内容要在多个出口(页面、打印、纯文字)显示;需要嵌入数据字段;需要在服务端保存前校验。
何时别用:需要表格、图片、代码块的长文档;Markdown 内容(用流式 Markdown);协同编辑的长篇文章编辑器。
设计约束
- 模型里不存 HTML:存进模板、数据库或接口的只有这份 JSON。HTML 只在进出两头出现,进来时按白名单解析,出去时逐个转义。
- 渲染不碰 innerHTML:
renderRichText只用createElement、文字节点、setAttribute与style.setProperty,文字永远是文字节点;样式只写判定合法的值,链接只写toSafeLinkHref放行的地址。 - 不依赖 DOM:模型、解析、检查与写出在
./rich-text,浏览器与 Node.js 里都能用;只有渲染在./rich-text-dom。 - 不认识的报出来:
checkRichTextDocument遇到不认识的块、行内类型、样式键与多余的键都报成问题,不抛异常,也不静默丢掉;解析时丢掉的东西都记在dropped里。
引入
两个入口都在 @xihan-ui/core 里,安装任意一个适配器即自动获得;只用模型、不用组件时,单独安装 @xihan-ui/core。
| 入口 | 内容 | 运行环境 |
|---|---|---|
@xihan-ui/core/rich-text | 类型与常量、parseRichTextHtml、checkRichTextDocument、serializeRichTextHtml、richTextPlainText、样式值的判定与换算 | 浏览器与 Node.js |
@xihan-ui/core/rich-text-dom | renderRichText 与它的选项类型 | 需要一个 Document |
模型
interface RichTextDocument { blocks: RichBlock[] }
type RichBlock
= | { type: "paragraph"; runs: RichInline[]; align?: RichTextAlign } // RichParagraph,runs 为空是一个空行
| { type: "heading"; level: 1 | 2 | 3; runs: RichInline[]; align?: RichTextAlign } // RichHeading
| { type: "list"; ordered: boolean; start?: number; items: RichListItem[] } // RichList
| { type: "divider" }; // RichDivider
interface RichListItem { blocks: RichBlock[] }
type RichInline
= | { type: "text"; text: string; marks?: RichMarks } // RichTextRun
| { type: "field"; field: string; format?: JsonObject; marks?: RichMarks } // RichFieldRun
| { type: "break" }; // RichBreak
type RichTextAlign = "left" | "center" | "right" | "justify";类型里的字段全部是 readonly,数组是 readonly 数组。各字段的取值范围:
| 位置 | 字段 | 取值 |
|---|---|---|
| 段落、标题 | runs | 行内内容数组,必填;段落的 runs 为空表示一个空行 |
| 段落、标题 | align | left、center、right、justify,可省略 |
| 标题 | level | 1、2、3 |
| 列表 | ordered | 布尔,必填 |
| 列表 | start | 有序列表的起始序号,0 至 999999 的整数,省略时从 1 开始 |
| 列表 | items | 列表项数组,每项是 { blocks };列表最多嵌套三层 |
| 文字 | text | 字符串,必填 |
| 字段 | field | 字段路径,去掉首尾空白后不能为空 |
| 字段 | format | 格式说明,必须是能 JSON 序列化的普通对象,形状由使用方约定 |
- 行内字段只记字段路径与格式说明,显示什么值由使用方决定:打印设计器按数据取值并按
format格式化;写纯文字与渲染 DOM 时由field回调给出文字,缺省写成{路径}。 - 段落间距、行高、缺省字体与字号不在模型里,由使用方的基准样式决定。
模型的几张取值表也作为常量导出,属性面板与自己的校验可以直接用:
| 常量 | 值 |
|---|---|
RICH_BLOCK_TYPES | ["paragraph", "heading", "list", "divider"] |
RICH_INLINE_TYPES | ["text", "field", "break"] |
RICH_MARK_KEYS | ["bold", "italic", "underline", "lineThrough", "color", "background", "fontSize", "fontFamily", "superscript", "subscript", "link"] |
RICH_TEXT_ALIGNS | ["left", "center", "right", "justify"] |
RICH_TEXT_FONT_SIZE_RANGE | { min: 1, max: 500 },单位 pt |
RICH_TEXT_MAX_LIST_DEPTH | 3 |
RICH_TEXT_FONT_FAMILY_MAX | 200,字体名的最大长度 |
行内样式
文字与字段可以带 marks,键都可省略:
| 键 | 取值 | 写出 HTML / 渲染 DOM 时 |
|---|---|---|
bold | 布尔 | strong |
italic | 布尔 | em |
underline | 布尔 | u |
lineThrough | 布尔 | s |
superscript | 布尔,不能与 subscript 同时为 true | sup |
subscript | 布尔 | sub(两个都打开时只写 sup) |
color | #RGB、#RGBA、#RRGGBB、#RRGGBBAA | span 的 color |
background | 同上 | span 的 background-color |
fontSize | 1 至 500 的数,单位 pt | span 的 font-size,如 10.5pt |
fontFamily | 不超过 200 个字符的字体栈:逗号分隔的每一项都不空,只含字母、数字、空格与 -、_、.、+,可以整项包在一对引号里 | span 的 font-family |
link | 过了 toSafeLinkHref 的地址:http、https、mailto、tel 与不带协议的相对地址 | 带 href 的 a |
一段文字落到标签时,从外到内依次是链接、上下标、粗体、斜体、下划线、删除线,最内层是带 style 的 span;没有任何样式时只有文字。不合法的值在写出与渲染时跳过。
样式值的判定与换算函数也一并导出,解析器与检查用的就是它们:
| 函数 | 作用 | 例 |
|---|---|---|
isRichColor(value) | 是否为模型认的颜色 | "#fff"、"#FFFFFF80" 是;"red"、"rgb(0,0,0)" 不是 |
isRichFontSize(value) | 是否为 1 至 500 之间的有限数 | 12 是;0.5、501 不是 |
isRichFontFamily(value) | 是否为可用的字体名 | "宋体"、'SimSun, "Song", monospace' 是;" "、"Arial;"、"Font (Bold)"、"Arial," 不是 |
isRichAlign(value) | 是否为对齐取值 | "justify" 是;"start" 不是 |
parseCssColor(text) | CSS 颜色换成模型颜色:十六进制原样返回,基本色名与 rgb() / rgba() 换成大写十六进制,透明度小于 1 时带两位透明度;认不出返回 undefined | "red" → "#FF0000","rgba(255 0 0 / 50%)" → "#FF000080","hsl(0 100% 50%)" → undefined |
parseCssFontSize(text) | CSS 字号换成 pt:只认 px(乘 0.75)与 pt,保留两位小数,超出 1 至 500 返回 undefined | "16px" → 12,"1.5em" → undefined,"1000px" → undefined |
parseCssColor 认的色名:black、silver、gray、grey、white、maroon、red、purple、fuchsia、green、lime、olive、yellow、navy、blue、teal、aqua、orange。
进出模型
| 函数 | 输入 | 输出 | 出错时 |
|---|---|---|---|
parseRichTextHtml(html) | 任意 HTML 串 | { document, dropped } | 不抛异常;不认识的丢掉并记进 dropped |
checkRichTextDocument(value) | 任意值 | 问题数组,合规时为空 | 不抛异常 |
serializeRichTextHtml(document) | 模型 | HTML 串 | 不认识的块与行内类型跳过 |
richTextPlainText(document, options?) | 模型 | 纯文字 | 同上 |
renderRichText(doc, document, options?) | Document 与模型 | DocumentFragment | 同上 |
写出与渲染不再检查模型,只跳过不认识的类型、不写不合法的样式值。从外部读到的 JSON 先过 checkRichTextDocument,再交给它们。
解析 HTML
parseRichTextHtml(html) 不依赖 DOM:先切分,按浏览器的宽松规则搭出元素树(标签不分大小写;块元素收尾还开着的 p;新的 li 收尾同一列表里的上一项;h1–h6 互相收尾),再逐个元素换成块与行内内容。
块
| HTML | 换成 |
|---|---|
p | 段落;<p></p> 与只有 br 的 p 是一个空行,段末的单个 br 不多算一行 |
div、section、article、main、header、footer、aside、nav、address、center、figcaption、summary、legend、dt、dd、thead、tbody、tfoot、tr、td、th、caption、colgroup、hgroup、search、html、body | 容器:自己不留结构,里面的行内内容成为段落;空的容器什么也不留 |
blockquote、pre、figure、details、form、fieldset、dl、table | 同上,另在 dropped 记一条 element |
h1、h2、h3 | 对应级别的标题 |
h4、h5、h6 | 三级标题,并记一条 element |
ul、menu | 无序列表 |
ol | 有序列表;start 属性是 0 至 999999 的整数且不是 1 时记进 start |
li | 列表项,里面的 p 成为该项的段落;列表里不在 li 中的文字也成为一项;列表外的 li 当容器并记一条 element |
| 超过三层的列表 | 这一层的项展平到上一层,记一条 element(名字是列表标签) |
hr | 分隔线 |
br | 行内换行 |
对齐取自块元素的 style 里的 text-align 或 HTML 的 align 属性(start 当 left,end 当 right),center 元素居中。容器里的段落与标题继承容器的对齐,列表项不继承。
行内
| HTML | 换成 |
|---|---|
strong、b | bold |
em、i、cite、dfn、var | italic |
u、ins | underline |
s、strike、del | lineThrough |
sup、sub | superscript、subscript,内层的覆盖外层的 |
mark | background:取 data-color,认不出或没有时是 #FFFF00 |
code、kbd、samp、tt | 外层没给字体时 fontFamily: "monospace" |
a | link:href 过了 toSafeLinkHref 才留(处理后的地址,首尾空白已去掉);没过的只留文字,记一条 link,名字是协议名 |
font | color 换成模型颜色(认不出记一条 style);face 是可用的字体名时记进 fontFamily,不是时记一条 style,名字是 font-family |
span data-field="路径" | 行内字段;data-format 是普通对象的 JSON 时记进 format,否则省略;路径为空白时当普通 span |
span、abbr、time、label、data、bdi、bdo、nobr | 去掉标签、保留文字,不记录 |
| 其他不认识的标签 | 去掉标签、保留文字,记一条 element |
script、style、iframe、object、embed、img、picture、svg、math、video、audio、canvas、template、noscript、dialog、表单控件等 | 连同内容去掉,记一条 content |
head、title、meta、link、base | 连同内容去掉,不记录 |
style 属性
| 属性 | 换成 | 认不出时 |
|---|---|---|
color | color | 记一条 style |
background-color、background | background(只认整个值是一个颜色) | 同上 |
font-weight | bold、bolder 或不小于 600 的数打开粗体;normal、lighter 与 1 至 599 的数关掉 | 同上 |
font-style | italic、oblique… 打开斜体,normal 关掉 | 同上 |
text-decoration、text-decoration-line | 含 underline、line-through 的打开对应样式,含 none 的先全部关掉 | 不记录 |
vertical-align | super、sub 打开上下标,baseline 关掉 | 记一条 style |
font-size | 只认 px 与 pt,换成 pt 后须在 1 至 500 之间 | 同上 |
font-family | 可用的字体名原样记下 | 同上 |
text-align | 只在块元素上生效,见上文 | 块上认不出时记一条 style |
| 其他属性 | 不认 | 记一条 style,名字是属性名 |
颜色认十六进制、rgb() / rgba()(逗号、空格与斜杠分隔都行,通道可写百分比)与上文的基本色名;值末尾的 !important 会去掉再判定。
空白与字符引用
- 空格、制表与换行按 HTML 的规则合并成一个空格,段落首尾与换行两侧的空格去掉;
pre里保留空格,换行变成行内换行。 - 字符引用解码:十进制与十六进制的数字引用全部认,码位不合法的换成替换字符
�;具名引用只认常用的一组,且必须带分号(&、<、>、"、'、 、 、 、 、©、®、™、…、—、–、‘、’、“、”、·、•、×、÷、¥、€、°、±、§、¶、«、»),其余原样保留。 解成不换行空格,不参与空白合并。 - 注释、doctype 与处理指令跳过。
一段从网页粘贴来的 HTML:
const { document: model, dropped } = parseRichTextHtml(`
<h1 style="text-align:center">季度报告</h1>
<p>客户:<span data-field="customer.name" data-format='{"kind":"text"}'>客户名</span>,金额 <b><font color="red">¥1,000</font></b></p>
<ul><li>第一项<ul><li>子项 <a href="javascript:alert(1)">危险</a> <a href="https://example.com">安全</a></li></ul></li></ul>
<p style="position:absolute;font-size:2em">相对字号</p>
<table><tr><td>表格里的字</td></tr></table>
<img src="a.png"><h5>五级标题</h5>`);
richTextPlainText(model);
// 季度报告
// 客户:{customer.name},金额 ¥1,000
// • 第一项
// • 子项 危险 安全
// 相对字号
// 表格里的字
// 五级标题
dropped;
// [
// { kind: "link", name: "javascript", count: 1 },
// { kind: "style", name: "position", count: 1 },
// { kind: "style", name: "font-size", count: 1 },
// { kind: "element", name: "table", count: 1 },
// { kind: "content", name: "img", count: 1 },
// { kind: "element", name: "h5", count: 1 },
// ]丢弃清单
丢掉的东西逐项记在 dropped 里,同类同名合成一条并计数,按第一次出现的先后排:
interface RichTextDrop {
kind: "element" | "content" | "style" | "link";
name: string; // 标签名、style 属性名,或链接的协议名
count: number;
}
interface ParseRichTextHtmlResult {
document: RichTextDocument;
dropped: RichTextDrop[];
}| kind | 含义 | 例 |
|---|---|---|
element | 标签去掉或降级,文字保留 | table、blockquote、pre、h5、超过三层的 ul |
content | 连同内容去掉 | script、style、iframe、img、video、表单控件 |
style | style 里不认识或取值不合法的属性 | position、相对单位的 font-size |
link | 没过判定的链接地址,文字保留 | javascript |
导入外来 HTML(粘贴、旧系统的模板)时,这份清单可以直接作为导入报告:content 与 element 里的表格、图片需要人工补,style 与 link 通常可以忽略。
检查
checkRichTextDocument(value) 检查任意值是不是合规的文档,返回全部问题 { code, path }[];合规时返回空数组,从不抛异常。path 是从文档根算起的键与下标数组,指到出问题的字段;需要一行文字时用 @xihan-ui/core/json 的 formatJsonPath(path),如 blocks[0].runs[0].marks.link。
| 问题码 | 含义 | path 指向 |
|---|---|---|
invalid-document | 不是普通对象,或 blocks 不是数组 | 根,或 blocks |
unknown-block | 不认识的块类型 | 块的 type |
unknown-inline | 不认识的行内类型 | 行内内容的 type |
unknown-mark | 不认识的样式键 | 该键 |
unknown-key | 认识的对象上多出来的键 | 该键 |
missing | 缺少必填的字段(含缺少 type) | 该字段 |
invalid-value | 类型或取值不对:标题级别、对齐、列表起始序号、颜色、字号、字体名、布尔样式、空的字段路径、format 不是可序列化的普通对象、块或行内内容不是对象 | 该字段 |
unsafe-link | 链接地址没过 toSafeLinkHref,或与处理后的地址不一致(如首尾带空格) | marks.link |
conflicting-marks | 上标与下标同时打开 | marks |
list-too-deep | 列表嵌套超过三层 | 第四层的列表块 |
checkRichTextDocument({
blocks: [
{ type: "paragraph", runs: [{ type: "text", text: "x", marks: { bold: "yes", link: "javascript:x", superscript: true, subscript: true, shadow: 1 } }], extra: 1 },
{ type: "heading", level: 4, runs: [] },
{ type: "quote" },
{ type: "paragraph", runs: [{ type: "field", field: " " }, { type: "text" }] },
],
});
// [
// { code: "unknown-key", path: ["blocks", 0, "extra"] },
// { code: "invalid-value", path: ["blocks", 0, "runs", 0, "marks", "bold"] },
// { code: "unsafe-link", path: ["blocks", 0, "runs", 0, "marks", "link"] },
// { code: "unknown-mark", path: ["blocks", 0, "runs", 0, "marks", "shadow"] },
// { code: "conflicting-marks", path: ["blocks", 0, "runs", 0, "marks"] },
// { code: "invalid-value", path: ["blocks", 1, "level"] },
// { code: "unknown-block", path: ["blocks", 2, "type"] },
// { code: "invalid-value", path: ["blocks", 3, "runs", 0, "field"] },
// { code: "missing", path: ["blocks", 3, "runs", 1, "text"] },
// ]解析器产出的模型本身能通过检查。保存前、从数据库或接口读到模型 JSON 时都应先检查;问题的类型是 RichTextIssue,问题码的联合类型是 RichTextIssueCode。
写成 HTML
serializeRichTextHtml(document) 把模型写成 HTML 串,用于复制到剪贴板、导出或交给只认 HTML 的系统:
- 文字与属性值都转义
&、<、>、"、';只用解析器认得的标签:p、h1–h3、ul、ol、li、hr、br、a、sup、sub、strong、em、u、s、span。 - 对齐写成块上的
style="text-align: …";有序列表的start不是 1 时写start属性,无序列表不写。 - 块上的取值先判定再写,与渲染一致:对齐不是
left、center、right、justify时不写,start不是整数时不写,标题级别不是 1 至 3 的整块跳过。没先检查的模型也写不出作者没给的元素、属性或样式声明。 - 行内字段写成
<span data-field="路径" data-format="…">路径</span>,data-format是格式说明的 JSON。
serializeRichTextHtml({
blocks: [
{ type: "paragraph", runs: [{ type: "text", text: "单号:" }, { type: "field", field: "order.no" }] },
{ type: "list", ordered: true, start: 9, items: [{ blocks: [{ type: "paragraph", runs: [{ type: "text", text: "甲" }, { type: "break" }, { type: "text", text: "甲续" }] }] }] },
{ type: "divider" },
],
});
// "<p>单号:<span data-field=\"order.no\">order.no</span></p><ol start=\"9\"><li><p>甲<br>甲续</p></li></ol><hr>"写出的 HTML 再经 parseRichTextHtml 读回,得到的是显示上等价的模型,但不保证逐键相同:
| 写出前 | 读回后 |
|---|---|
| 文字里的连续空白、首尾空格、换行符 | 按 HTML 规则合并成一个空格或去掉 |
段末的 break | 去掉 |
| 相邻、样式相同的两段文字 | 合成一段 |
值为 false 的样式键 | 去掉 |
有序列表 start: 1、无序列表带的 start | 去掉 |
blocks 为空的列表项 | 补一个空段落 |
marks 里键的先后 | 可能变化 |
需要原样保存时存 JSON,HTML 只作为出口。比较两份模型是否相同,用 @xihan-ui/core/json 的 jsonEquals,它不看键的先后。
写成纯文字
richTextPlainText(document, { field? }) 写成纯文字,用于搜索索引、短信、日志或表格单元格:
- 块之间换一行;空段落是一个空行;行内换行是换行符。
- 无序列表项前加
•,有序列表项前加序号.,序号从start起;嵌套一层缩进两格,项内的后续行也缩进。 - 分隔线写成
———。 field回调给出行内字段的文字,缺省写成{路径}。
import type { RichTextDocument } from "@xihan-ui/core/rich-text";
import { richTextPlainText } from "@xihan-ui/core/rich-text";
const model = {
blocks: [
{ type: "paragraph", runs: [{ type: "text", text: "单号:" }, { type: "field", field: "order.no" }] },
{
type: "list",
ordered: true,
start: 9,
items: [
{ blocks: [
{ type: "paragraph", runs: [{ type: "text", text: "甲" }, { type: "break" }, { type: "text", text: "甲续" }] },
{ type: "list", ordered: false, items: [{ blocks: [{ type: "paragraph", runs: [{ type: "text", text: "甲一" }] }] }] },
] },
{ blocks: [{ type: "paragraph", runs: [{ type: "text", text: "乙" }] }] },
],
},
{ type: "divider" },
],
} satisfies RichTextDocument;
richTextPlainText(model, { field: run => (run.field === "order.no" ? "SO-001" : "") });
// 单号:SO-001
// 9. 甲
// 甲续
// • 甲一
// 10. 乙
// ———渲染成 DOM
renderRichText(doc, document, { field? }) 在 doc 里按模型生成节点,返回 DocumentFragment,交给 replaceChildren 或 append 即可:
- 段落
p、标题h1–h3、列表ul/ol与li、分隔线hr、换行br;对齐写在块的style上,有序列表的start不是 1 时写start属性。 - 样式按上文「行内样式」的顺序包标签,颜色、底色、字号与字体用
style.setProperty写在最内层的span上,浏览器不接受的值自然落空。 - 没有内容的段落与标题放一个
br占住一行;不认识的块与行内类型、级别不对的标题跳过。 field回调给出行内字段的文字,缺省写成{路径};回调返回的串作为文字节点插入,不会被当作 HTML。
renderRichText(document, {
blocks: [
{ type: "heading", level: 1, runs: [{ type: "text", text: "标题" }], align: "center" },
{ type: "paragraph", runs: [] },
{ type: "paragraph", runs: [{ type: "text", text: "<b>不是标签</b>" }, { type: "field", field: "a.b" }] },
],
}, { field: run => `【${run.field}】` });
// <h1 style="text-align: center;">标题</h1><p><br></p><p><b>不是标签</b>【a.b】</p>在组件里显示一段只读的富文本:
<script setup lang="ts">
import type { RichTextDocument } from "@xihan-ui/core/rich-text";
import { renderRichText } from "@xihan-ui/core/rich-text-dom";
import { ref, watchEffect } from "vue";
const props = defineProps<{ model: RichTextDocument; data: Record<string, string> }>();
const host = ref<HTMLElement>();
watchEffect(() => {
host.value?.replaceChildren(renderRichText(document, props.model, { field: run => props.data[run.field] ?? "" }));
});
</script>
<template>
<div ref="host" />
</template>import type { RichTextDocument } from "@xihan-ui/core/rich-text";
import type { ReactNode } from "react";
import { renderRichText } from "@xihan-ui/core/rich-text-dom";
import { useLayoutEffect, useRef } from "react";
interface RichTextViewProps {
model: RichTextDocument;
data: Record<string, string>;
}
export default function RichTextView({ model, data }: RichTextViewProps): ReactNode {
const host = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
host.current?.replaceChildren(renderRichText(document, model, { field: run => data[run.field] ?? "" }));
}, [model, data]);
return <div ref={host} />;
}<div id="notice"></div>
<script type="module">
import { checkRichTextDocument } from "@xihan-ui/core/rich-text";
import { renderRichText } from "@xihan-ui/core/rich-text-dom";
const model = await (await fetch("/api/notice")).json();
if (checkRichTextDocument(model).length === 0)
document.getElementById("notice").replaceChildren(renderRichText(document, model));
</script>服务端渲染时没有 Document:在服务端用 serializeRichTextHtml 输出 HTML 串,或者只在客户端挂载后调用 renderRichText。
大型项目建议
- 服务端是权威。
./rich-text不依赖 DOM,Node.js 后端保存前直接跑checkRichTextDocument,不信任前端送来的 JSON。接口层再限制请求体大小:模型本身没有长度与块数上限。 - 字体名限定在自己的字体清单里。
isRichFontFamily只查字体栈的字符与形状,不判断字体是否存在。打印与导出要在别的机器上还原字体,宿主应把fontFamily限定在自己的字体清单里,保存时校验。 - 字段路径对着数据模型校验。 检查只保证
field非空、format是普通对象;路径是否存在、格式说明是否合法由宿主校验。
下面这段校验在检查之后再查字体与字段,可以前后端共用:
import type { RichBlock, RichInline, RichTextDocument } from "@xihan-ui/core/rich-text";
import { formatJsonPath } from "@xihan-ui/core/json";
import { checkRichTextDocument } from "@xihan-ui/core/rich-text";
const FONTS = new Set(["宋体", "黑体", "monospace"]);
function eachRun(blocks: readonly RichBlock[], visit: (run: RichInline) => void): void {
for (const block of blocks) {
if (block.type === "list") {
for (const item of block.items)
eachRun(item.blocks, visit);
}
else if (block.type === "paragraph" || block.type === "heading") {
block.runs.forEach(visit);
}
}
}
export function validateRichText(value: unknown, fields: ReadonlySet<string>): string[] {
const problems = checkRichTextDocument(value).map(issue => `${issue.code} ${formatJsonPath(issue.path)}`);
if (problems.length > 0)
return problems;
eachRun((value as RichTextDocument).blocks, (run) => {
if (run.type === "break")
return;
if (run.marks?.fontFamily !== undefined && !FONTS.has(run.marks.fontFamily))
problems.push(`字体不在清单里:${run.marks.fontFamily}`);
if (run.type === "field" && !fields.has(run.field))
problems.push(`未知字段:${run.field}`);
});
return problems;
}
// 对 <p>客户:<span data-field="customer.name">…</span></p><p><font face="Comic Sans">花体</font><span data-field="order.memo">…</span></p>
// 解析出的模型,fields 只有 customer.name 时:
// ["字体不在清单里:Comic Sans", "未知字段:order.memo"]写成 HTML 时的字体名
serializeRichTextHtml 把字体名原样写进 style 属性:字体名里的引号会被转义,但分号不会,"Arial; position: fixed" 写出来就多了一条 position 声明(检查也不会报)。renderRichText 走 style.setProperty,不受影响。要把写出的 HTML 交给别的系统显示时,先按上面的白名单校验字体名。
- 导入时把丢弃清单给人看。 粘贴或批量导入旧内容时,把
dropped汇总成报告,表格、图片这类content/element条目交人工处理。 - 存 JSON,不存 HTML。 HTML 读回只保证显示等价(见写成 HTML),反复转换会把空白与键序磨平;比较、去重用
jsonEquals。 - 只读显示用
renderRichText。 它不经过 HTML 解析,比innerHTML快也更安全;长列表逐行显示时只渲染可见的行。
更多大型项目的组织方式见大型项目。
扩展与二次开发
模型是封闭的:不能加块类型、行内类型或样式键,加了会被检查报成 unknown-*。扩展的方式是在模型之外做:
字段的取值与格式化:
field回调拿到整个字段对象,按路径取数据、按format格式化都由你决定。下面把format约定为受限表达式的格式说明:tsimport type { JsonObject } from "@xihan-ui/core/json"; import type { RichTextDocument } from "@xihan-ui/core/rich-text"; import type { FormatSpec } from "@xihan-ui/expression"; import { getJsonAt } from "@xihan-ui/core/json"; import { renderRichText } from "@xihan-ui/core/rich-text-dom"; import { checkFormatSpec, formatValue } from "@xihan-ui/expression"; export function renderWithData(model: RichTextDocument, data: JsonObject): DocumentFragment { return renderRichText(document, model, { field: (run) => { const value = getJsonAt(data, run.field.split(".")); if (value === undefined || value === null) return ""; if (run.format !== undefined && checkFormatSpec(run.format).length === 0) return formatValue(value, run.format as unknown as FormatSpec); return String(value); }, }); } // 「客户:{customer.name},合计 {order.total}」,order.total 的 format 是 { kind: "number", decimals: 2, grouping: true }, // 数据 { customer: { name: "张三" }, order: { total: 1234567.891 } } 显示为「客户:张三,合计 1,234,567.89」自己的出口:模型是普通 JSON,按
type递归即可写出别的格式(Markdown、Canvas 排版、PDF)。上面的eachRun就是最小的遍历骨架;打印设计器的富文本排版也是这样按块与行内内容自己换行分页的。编辑器:库里没有富文本编辑组件。自己做时,编辑态可以用
contenteditable:载入时renderRichText进去,保存时把元素的innerHTML交给parseRichTextHtml换回模型,dropped告诉你哪些操作超出了模型能表达的范围。
常见问题
粘贴进来的表格、图片为什么没了?
模型没有表格与图片。表格的文字按段落保留并记一条 element;图片连同内容去掉并记一条 content。需要这些结构的内容不适合用富文本模型。
h4 为什么变成了三级标题?
标题只有三级,h4–h6 降成三级标题,并在 dropped 记一条 element。
字号为什么丢了?
字号只认绝对单位 px 与 pt,换成 pt 后须在 1 至 500 之间;em、rem、% 与关键字(large)都认不出,记一条 style。
颜色写成 hsl() 为什么丢了?
颜色只认十六进制、rgb() / rgba() 与基本色名;hsl()、transparent、currentColor 等认不出,记一条 style。
手写的链接为什么检查报 unsafe-link?
除了协议不在放行范围内,地址与 toSafeLinkHref 处理后的结果不一致也会报,例如首尾带空格的地址。保存前先用处理后的地址替换。解析器产出的链接已经是处理后的地址。
有序列表能从 0 开始吗?
可以。start 取 0 至 999999 的整数;HTML 里 <ol start="0"> 解析为 start: 0。
延伸阅读
- 跨站脚本:为什么不能把外来 HTML 直接交给
innerHTML。 - innerHTML 与 DocumentFragment:MDN 上的安全说明与片段的用法。
- 受限表达式、流式 Markdown、SVG 导出。
