Skip to content

Commit

Permalink
feat: 增加mermaid配置功能,可指定mermaid生成的是svg还是图片
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsonliu committed May 22, 2023
1 parent e8542fa commit 2bcded7
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
3 changes: 3 additions & 0 deletions src/Cherry.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ const defaultConfig = {
customRenderer: {
// 自定义语法渲染器
},
mermaid: {
svg2img: false, // 是否将mermaid生成的画图变成img格式
},
/**
* indentedCodeBlock是缩进代码块是否启用的开关
*
Expand Down
9 changes: 6 additions & 3 deletions src/addons/cherry-code-block-mermaid-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,10 @@ export default class MermaidCodeEngine {
// fix end
svgHtml = svgDoc.documentElement.outerHTML;
// 屏蔽转img标签功能,如需要转换为img解除屏蔽即可
// const dataUrl = `data:image/svg+xml,${encodeURIComponent(svgDoc.documentElement.outerHTML)}`;
// svgHtml = `<img class="svg-img" src="${dataUrl}" alt="${graphId}" />`;
if (this.svg2img) {
const dataUrl = `data:image/svg+xml,${encodeURIComponent(svgDoc.documentElement.outerHTML)}`;
svgHtml = `<img class="svg-img" src="${dataUrl}" alt="${graphId}" />`;
}
} else {
svgHtml = injectSvgFallback(svgCode);
}
Expand All @@ -123,7 +125,7 @@ export default class MermaidCodeEngine {
return svgHtml;
}

render(src, sign, $engine) {
render(src, sign, $engine, config = {}) {
let $sign = sign;
if (!$sign) {
$sign = Math.round(Math.random() * 100000000);
Expand All @@ -134,6 +136,7 @@ export default class MermaidCodeEngine {
// 需要通过添加时间戳使得多次渲染相同内容的图像ID唯一
// 图像渲染节流在CodeBlock Hook内部控制
const graphId = `mermaid-${$sign}-${new Date().getTime()}`;
this.svg2img = config?.svg2img ?? false;
try {
this.mermaidAPIRefs.render(
graphId,
Expand Down
3 changes: 2 additions & 1 deletion src/core/hooks/CodeBlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export default class CodeBlock extends ParagraphBase {
this.wrap = config.wrap; // 超出是否换行
this.lineNumber = config.lineNumber; // 是否显示行号
this.copyCode = config.copyCode; // 是否显示“复制”按钮
this.mermaid = config.mermaid; // mermaid的配置,目前仅支持格式设置,svg2img=true 展示成图片,false 展示成svg
this.indentedCodeBlock = typeof config.indentedCodeBlock === 'undefined' ? true : config.indentedCodeBlock; // 是否支持缩进代码块
this.INLINE_CODE_REGEX = /(`+)(.+?(?:\n.+?)*?)\1/g;
if (config && config.customRenderer) {
Expand Down Expand Up @@ -69,7 +70,7 @@ export default class CodeBlock extends ParagraphBase {
if (!engine || typeof engine.render !== 'function') {
return false;
}
const html = engine.render(codeSrc, props.sign, this.$engine);
const html = engine.render(codeSrc, props.sign, this.$engine, this.mermaid);
if (!html) {
return false;
}
Expand Down

0 comments on commit 2bcded7

Please sign in to comment.