Skip to main content

nargo_document/plugin/
mermaid.rs

1//! Mermaid 图表渲染插件
2//!
3//! 提供对 Markdown 中 Mermaid 图表的支持,包括流程图、时序图、甘特图等
4
5use crate::plugin::{DocumentPlugin, PluginContext, PluginMeta};
6use lazy_static::lazy_static;
7use regex::Regex;
8
9lazy_static! {
10    /// 匹配 Mermaid 代码块的正则表达式
11    static ref MERMAID_BLOCK_RE: Regex = Regex::new(r"```mermaid\s*\n([\s\S]*?)\n```").unwrap();
12}
13
14/// Mermaid 图表渲染插件
15pub struct MermaidPlugin {
16    /// 插件元数据
17    meta: PluginMeta,
18}
19
20impl MermaidPlugin {
21    /// 创建新的 Mermaid 插件实例
22    pub fn new() -> Self {
23        Self { meta: PluginMeta::new("nargo-document-plugin-mermaid".to_string(), "0.1.0".to_string(), "Mermaid 图表渲染插件,支持流程图、时序图、甘特图等".to_string()) }
24    }
25
26    /// 处理 Mermaid 代码块,将 ```mermaid ... ``` 替换为 <div class="mermaid">...</div>
27    ///
28    /// # Arguments
29    ///
30    /// * `content` - 包含 Mermaid 图表的文本内容
31    ///
32    /// # Returns
33    ///
34    /// 替换后的文本内容
35    fn process_mermaid_blocks(&self, content: &str) -> String {
36        MERMAID_BLOCK_RE
37            .replace_all(content, |caps: &regex::Captures| {
38                let diagram = &caps[1];
39                format!("<div class=\"mermaid\">{}</div>", diagram.trim())
40            })
41            .to_string()
42    }
43}
44
45impl Default for MermaidPlugin {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl DocumentPlugin for MermaidPlugin {
52    /// 获取插件元数据
53    fn meta(&self) -> &PluginMeta {
54        &self.meta
55    }
56
57    /// 渲染前钩子,在 Markdown 解析后、HTML 渲染前处理 Mermaid 图表
58    ///
59    /// # Arguments
60    ///
61    /// * `context` - 插件上下文,包含文档内容等信息
62    ///
63    /// # Returns
64    ///
65    /// 处理后的插件上下文
66    fn before_render(&self, context: PluginContext) -> PluginContext {
67        let content = self.process_mermaid_blocks(&context.content);
68
69        PluginContext { content, frontmatter: context.frontmatter, path: context.path }
70    }
71}