UNPKG

vitepress-mermaid-preview

Version:

Mermaid preview for vitepress

14 lines (11 loc) 1.93 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("fs"),u=require("path");function p(t,e={}){const s=t.renderer.rules.fence;t.renderer.rules.fence=(n,o,r,c,a)=>{const i=n[o];if((i.info.trim()||"text")==="mermaid"){let l=e.showToolbar!==!1;const h=i.content.match(/^---\s*([\s\S]*?)\s*---/);if(h){const d=h[1].match(/showToolbar:\s*(true|false)/i);d&&(l=d[1]==="true")}return` <ClientOnly> <MermaidChart code="${encodeURIComponent(i.content)}" showToolbar="${l?"1":"0"}" /> </ClientOnly> `}return s(n,o,r,c,a)}}const w=/<PreviewMermaidPath\s*(.*?)\s*\/>/g,M=/<PreviewMermaidPath\s*(.*?)><\/PreviewMermaidPath>/g;function P(t){const e=/path=['"](.*?)['"]/.exec(t);return e?e[1]:""}function f(t,e,s){try{const n=/\bshowToolbar\b/i.test(t)||s.showToolbar,o=P(t);let r="",c="";if(e&&e.path?c=u.dirname(e.path):process.cwd&&(c=process.cwd()),o){const a=u.resolve(c,o);try{if(r=m.readFileSync(a,"utf-8"),!r.trim())return`<div class="mermaid-error">文件内容为空: ${o}</div>`}catch(i){return console.error(`无法读取文件: ${a}`,i),`<div class="mermaid-error">无法加载文件: ${o}</div>`}}else if(e&&e.path)try{r=m.readFileSync(e.path,"utf-8")}catch(a){console.error(`无法读取当前MD文件: ${e.path}`,a),r=`# 文件读取失败 无法加载: 当前文档`}else r=`# 文件读取失败 未指定 path,且无法获取当前文档路径`;return` <ClientOnly> <MermaidChart code="${encodeURIComponent(r)}" showToolbar="${n?"1":"0"}" /> </ClientOnly> `}catch(n){return console.error("处理 PreviewMermaidPath 组件时出错:",n),'<div class="mermaid-error">加载 mermaid 图表失败</div>'}}function b(t,e={}){const s=t.render;t.render=function(n,o){let r=s.call(this,n,o);return r=r.replace(w,(c,a)=>f(a,o,e)),r=r.replace(M,(c,a)=>f(a,o,e)),r}}function C(t,e={}){p(t,e),b(t,e)}exports.vitepressMermaidPreview=C;