zh CN 自定义标签名字符 - chiba233/yumeDSL GitHub Wiki
自定义标签名字符
默认标签名规则:a-z A-Z 0-9 _ -,首字符不能是数字或 -。
想用 $$ui:button(...)$$ 或 $$v2.1(...)$$?改一下标签名字符规则就行。
先看效果
默认规则:
$$bold(ok)$$ ✅ 正常
$$ui:button(ok)$$ ❌ 冒号不允许 → 当成普通文本
$$1tag(ok)$$ ❌ 数字开头不允许 → 当成普通文本
加了自定义规则后:
$$ui:button(ok)$$ ✅ 冒号放行
$$1tag(ok)$$ ✅ 数字开头放行
怎么改
核心就两个函数,告诉解析器"哪些字符能用在标签名里":
解析器扫描到 $$xxx( 时:
│
├─ 第一个字符 → isTagStartChar("x") → true? 继续 : 跳过
│
└─ 后续字符 → isTagChar("x") → true? 继续 : 标签名到此为止
interface TagNameConfig {
isTagStartChar: (char: string) => boolean; // 标签名第一个字符能是啥
isTagChar: (char: string) => boolean; // 后续字符能是啥
}
最简单的写法:直接传 partial 对象
只传你要改的,没传的自动用默认值:
const dsl = createParser({
handlers,
tagName: {
isTagChar: (char) => /[A-Za-z0-9_-]/.test(char) || char === ":",
},
});
// isTagStartChar 没传 → 用默认(a-z, A-Z, _)
用 createTagNameConfig 包一下也行
效果完全一样,只是显式地做了合并:
import {createTagNameConfig} from "yume-dsl-rich-text";
tagName: createTagNameConfig({
isTagChar: (char) => /[A-Za-z0-9_-]/.test(char) || char === ":",
})
实战示例
允许冒号——命名空间标签 ui:button
const dsl = createParser({
handlers: {
"ui:button": {inline: (value, ctx) => ({type: "ui:button", value})},
},
tagName: {
isTagChar: (char) => /[A-Za-z0-9_-]/.test(char) || char === ":",
},
});
dsl.parse("Click $$ui:button(Submit)$$");
// → [text("Click "), ui:button([text("Submit")])]
允许数字开头 1tag
parseRichText("$$1tag(hello)$$", {
handlers: {"1tag": {inline: (v, ctx) => ({type: "1tag", value: v})}},
tagName: {isTagStartChar: (char) => /[A-Za-z0-9_]/.test(char)},
});
允许点号——版本式标签 v2.1
const dsl = createParser({
handlers: {
"v2.1": {inline: (v, ctx) => ({type: "version-note", version: "2.1", value: v})},
},
tagName: createTagNameConfig({
isTagStartChar: (char) => /[A-Za-z0-9_]/.test(char),
isTagChar: (char) => /[A-Za-z0-9_.\-]/.test(char),
}),
});
dsl.parse("See $$v2.1(release notes)$$");
默认值参考
| 函数 | 默认接受 | 角色 |
|---|---|---|
isTagStartChar |
a-z A-Z _ |
标签名第一个字符 |
isTagChar |
a-z A-Z 0-9 _ - |
后续字符 |
注意事项
tagName在所有解析器入口都能用:createParser、parseRichText、stripRichText、parseStructural- 标签名验证只管解析器接受什么字符。没有注册 handler 的标签名只是降级为纯文本,不会报错
createTagNameConfig是纯函数,不改全局状态