ttrpg-tools/src/markdown/index.ts

149 lines
5.6 KiB
TypeScript
Raw Normal View History

2026-03-21 18:30:40 +08:00
import { Marked, type MarkedExtension } from 'marked';
2026-02-27 17:54:09 +08:00
import {createDirectives, presetDirectiveConfigs} from 'marked-directive';
2026-02-28 11:42:42 +08:00
import yaml from 'js-yaml';
2026-02-28 13:58:51 +08:00
import markedAlert from "marked-alert";
2026-03-02 11:03:51 +08:00
import markedMermaid from "./mermaid";
2026-03-21 18:30:40 +08:00
import markedTable from "./table";
2026-03-02 13:39:36 +08:00
import {gfmHeadingId} from "marked-gfm-heading-id";
2026-03-23 22:18:11 +08:00
import markedColumns from "./columns";
2026-02-26 00:17:23 +08:00
2026-03-13 11:14:01 +08:00
let globalIconPrefix: string | undefined = undefined;
function overrideIconPrefix(path?: string){
globalIconPrefix = path;
return {
[Symbol.dispose](){
globalIconPrefix = undefined;
}
}
}
2026-03-21 17:50:47 +08:00
2026-02-26 00:47:26 +08:00
// 使用 marked-directive 来支持指令语法
2026-02-28 13:58:51 +08:00
const marked = new Marked()
2026-03-02 13:39:36 +08:00
.use(gfmHeadingId())
2026-02-28 13:58:51 +08:00
.use(markedAlert())
2026-03-02 11:03:51 +08:00
.use(markedMermaid())
2026-03-21 18:30:40 +08:00
.use(markedTable())
2026-02-28 13:58:51 +08:00
.use(createDirectives([
2026-02-27 17:54:09 +08:00
...presetDirectiveConfigs,
{
marker: '::::',
level: 'container'
},
{
marker: ':::::',
level: 'container'
},
{
level: 'inline',
marker: ':',
// :[icon] 或 :[icon.ext] 语法
// 支持的扩展名: .svg, .png, .gif, .jpg, .jpeg, .webp
// 如果不指定扩展名,默认为 .png
2026-02-27 17:54:09 +08:00
renderer(token) {
if (!token.meta.name) {
const iconText = token.text || '';
// 已知支持的图片扩展名
const supportedExtensions = ['svg', 'png', 'gif', 'jpg', 'jpeg', 'webp'];
// 检查是否包含扩展名(查找最后一个点)
let iconName = iconText;
let extension = 'png'; // 默认扩展名
const lastDotIndex = iconName.lastIndexOf('.');
if (lastDotIndex > 0) {
const potentialExt = iconName.slice(lastDotIndex + 1).toLowerCase();
if (supportedExtensions.includes(potentialExt)) {
extension = potentialExt;
iconName = iconName.slice(0, lastDotIndex);
}
}
const label = token.attrs?.label as string | undefined;
const inner = label ? `<span class="icon-label-stroke">${label}</span><span class="icon-label">${label}</span>` : "";
const style = globalIconPrefix ? `style="--icon-src: url('${globalIconPrefix}/${iconName}.${extension}')"` : '';
const iconHtml = `<icon ${style} class="icon-${iconName} ${token.attrs?.class || ""}">${inner}</icon>`;
const repeat = parseInt(`${token.attrs?.repeat || ''}`);
const join = token.attrs?.join || '';
const separator = join ? `<${join}></${join}>` : '';
if(isNaN(repeat) || repeat < 1) return iconHtml;
return Array(repeat).fill(iconHtml).join(separator);
2026-02-27 17:54:09 +08:00
}
return false;
}
},
2026-02-28 11:42:42 +08:00
]), {
2026-03-23 22:18:11 +08:00
extensions: [
...markedColumns(),
{
2026-02-28 11:42:42 +08:00
// 自定义代码块渲染器,支持 yaml/tag 格式
name: 'code-block-yaml-tag',
level: 'block',
start(src: string) {
// 检测 ```yaml/tag 开头的代码块
return src.match(/^```yaml\/tag\s*\n/m)?.index;
},
tokenizer(src: string) {
const rule = /^```yaml\/tag\s*\n([\s\S]*?)\n```/;
const match = rule.exec(src);
if (match) {
const yamlContent = match[1]?.trim() || '';
2026-03-26 11:46:33 +08:00
let props: Record<string, unknown> = {};
try {
props = (yaml.load(yamlContent) as Record<string, unknown>) || {};
} catch (e) {
console.error("YAML Parse Error in code-block-yaml-tag:", e);
props = { error: "Invalid YAML content" };
}
2026-03-21 17:50:47 +08:00
2026-02-28 11:42:42 +08:00
// 提取 tag 名称,默认为 tag-unknown
const tagName = (props.tag as string) || 'tag-unknown';
2026-03-21 17:50:47 +08:00
2026-02-28 11:42:42 +08:00
// 移除 tag 属性,剩下的作为 HTML 属性
const { tag, ...rest } = props;
2026-03-21 17:50:47 +08:00
2026-02-28 11:42:42 +08:00
// 提取 innerText 内容(如果有 body 字段)
let content = '';
if ('body' in rest) {
content = String(rest.body || '');
delete (rest as Record<string, unknown>).body;
}
2026-03-21 17:50:47 +08:00
2026-02-28 11:42:42 +08:00
// 构建属性字符串
const propsStr = Object.entries(rest)
.map(([key, value]) => {
const strValue = String(value);
// 如果值包含空格或特殊字符,添加引号
if (strValue.includes(' ') || strValue.includes('"')) {
return `${key}="${strValue.replace(/"/g, '&quot;')}"`;
}
return `${key}="${strValue}"`;
})
.join(' ');
2026-03-21 17:50:47 +08:00
2026-02-28 11:42:42 +08:00
return {
type: 'code-block-yaml-tag',
raw: match[0],
tagName,
props: propsStr,
content
};
}
},
renderer(token: any) {
// 渲染为自定义 HTML 标签
const propsAttr = token.props ? ` ${token.props}` : '';
return `<${token.tagName}${propsAttr}>${token.content || ''}</${token.tagName}>\n`;
}
}]
});
2026-02-26 00:17:23 +08:00
2026-03-13 11:14:01 +08:00
export function parseMarkdown(content: string, iconPrefix?: string): string {
using prefix = overrideIconPrefix(iconPrefix);
return marked.parse(content.trimStart()) as string;
2026-02-26 00:17:23 +08:00
}
export { marked };