生态产品多个设计器现已发布正式版

查看生态总览
跳转到内容

富文本模型 ​

@xihan-ui/core/rich-text 是结构化的富文本:段落、标题、列表、分隔线与带样式的文字,整份是 JSON,不含 HTML。外来的 HTML 按白名单换成模型,模型再写回 HTML 或纯文字;按模型生成 DOM 在 @xihan-ui/core/rich-text-dom。打印设计器的富文本元素存的就是这份模型。

ts
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-domrenderRichText 与它的选项类型需要一个 Document

模型 ​

文档
RichTextDocument { blocks }
块 RichBlock
paragraph { runs }heading { level, runs }list { ordered, start?, items }divider
段落与标题可带 align;list 的 items 每一项是 { blocks },又回到这一层,最多嵌套三层
paragraph 与 heading 的 runs
行内 RichInline
text { text, marks? }field { field, format?, marks? }break
field 只记字段路径与格式说明,显示什么值由使用方给出
text 与 field 的 marks
样式 RichMarks
bolditalicunderlinelineThroughsuperscriptsubscriptcolorbackgroundfontSizefontFamilylink
文档由块组成,段落与标题里是行内内容,文字与字段带样式;列表项里又是一组块,最多嵌套三层
ts
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 为空表示一个空行
段落、标题alignleft、center、right、justify,可省略
标题level1、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_DEPTH3
RICH_TEXT_FONT_FAMILY_MAX200,字体名的最大长度

行内样式 ​

文字与字段可以带 marks,键都可省略:

键取值写出 HTML / 渲染 DOM 时
bold布尔strong
italic布尔em
underline布尔u
lineThrough布尔s
superscript布尔,不能与 subscript 同时为 truesup
subscript布尔sub(两个都打开时只写 sup)
color#RGB、#RGBA、#RRGGBB、#RRGGBBAAspan 的 color
background同上span 的 background-color
fontSize1 至 500 的数,单位 ptspan 的 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)
按白名单换成模型,丢掉的记进 dropped
checkRichTextDocument(json)
从库里、接口里读到的 JSON 先查形状
RichTextDocument
只存 JSON:块、行内、样式;存进模板、数据库与接口的只有它
serializeRichTextHtml
转义后的 HTML 串
./rich-text
richTextPlainText
纯文字,列表带序号
./rich-text
renderRichText
DocumentFragment,不碰 innerHTML
./rich-text-dom
外来 HTML 经白名单解析、库里读出的 JSON 经检查,都汇成同一份模型;再按出口写成 HTML、纯文字或 DOM
函数输入输出出错时
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、bbold
em、i、cite、dfn、varitalic
u、insunderline
s、strike、dellineThrough
sup、subsuperscript、subscript,内层的覆盖外层的
markbackground:取 data-color,认不出或没有时是 #FFFF00
code、kbd、samp、tt外层没给字体时 fontFamily: "monospace"
alink:href 过了 toSafeLinkHref 才留(处理后的地址,首尾空白已去掉);没过的只留文字,记一条 link,名字是协议名
fontcolor 换成模型颜色(认不出记一条 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 属性 ​

属性换成认不出时
colorcolor记一条 style
background-color、backgroundbackground(只认整个值是一个颜色)同上
font-weightbold、bolder 或不小于 600 的数打开粗体;normal、lighter 与 1 至 599 的数关掉同上
font-styleitalic、oblique… 打开斜体,normal 关掉同上
text-decoration、text-decoration-line含 underline、line-through 的打开对应样式,含 none 的先全部关掉不记录
vertical-alignsuper、sub 打开上下标,baseline 关掉记一条 style
font-size只认 px 与 pt,换成 pt 后须在 1 至 500 之间同上
font-family可用的字体名原样记下同上
text-align只在块元素上生效,见上文块上认不出时记一条 style
其他属性不认记一条 style,名字是属性名

颜色认十六进制、rgb() / rgba()(逗号、空格与斜杠分隔都行,通道可写百分比)与上文的基本色名;值末尾的 !important 会去掉再判定。

空白与字符引用 ​

  • 空格、制表与换行按 HTML 的规则合并成一个空格,段落首尾与换行两侧的空格去掉;pre 里保留空格,换行变成行内换行。
  • 字符引用解码:十进制与十六进制的数字引用全部认,码位不合法的换成替换字符 �;具名引用只认常用的一组,且必须带分号(&amp;、&lt;、&gt;、&quot;、&apos;、&nbsp;、&ensp;、&emsp;、&thinsp;、&copy;、&reg;、&trade;、&hellip;、&mdash;、&ndash;、&lsquo;、&rsquo;、&ldquo;、&rdquo;、&middot;、&bull;、&times;、&divide;、&yen;、&euro;、&deg;、&plusmn;、&sect;、&para;、&laquo;、&raquo;),其余原样保留。&nbsp; 解成不换行空格,不参与空白合并。
  • 注释、doctype 与处理指令跳过。

一段从网页粘贴来的 HTML:

ts
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 里,同类同名合成一条并计数,按第一次出现的先后排:

ts
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、表单控件
stylestyle 里不认识或取值不合法的属性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列表嵌套超过三层第四层的列表块
ts
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。
ts
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 回调给出行内字段的文字,缺省写成 {路径}。
ts
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。
ts
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>&lt;b&gt;不是标签&lt;/b&gt;【a.b】</p>

在组件里显示一段只读的富文本:

vue
<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>
tsx
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} />;
}
html
<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 是普通对象;路径是否存在、格式说明是否合法由宿主校验。

下面这段校验在检查之后再查字体与字段,可以前后端共用:

ts
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 约定为受限表达式的格式说明:

    ts
    import 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。

延伸阅读 ​

Released under The MIT License