不使用 Shortcode 渲染 Mermaid 图

Shortcode 不文明。

绘制 Mermaid 图是一个刚需。但是我希望我的 Markdown 文件能正常在编辑器(如 vscode)内预览,又能生成正确的网页。

现在的问题是 Hugo 对 Mermaid 的支持都是用 Shortcode 实现的,这会导致预览失效。

Hugo 使用的 Goldmark 不支持给 Codeblock 添加自定义 class,而 highlight.js 也不能识别到 mermaid,因此需要从 language-fallback 里找到 Mermaid。

幸好 Mermaid 的语法开头都有固定的关键字,极大地方便了这个工作。

<link href="mermaid.css" type="text/css" rel="stylesheet"/>
<script src="mermaid.min.js"></script>
<script src="highlight.min.js"></script>
<script> 
  hljs.initHighlightingOnLoad(); 

  const mermaidKeywords = [
    "graph TD",
    "graph TB",
    "graph BT",
    "graph RL",
    "graph LR",
    "sequenceDiagram",
    "gantt",
    "classDiagram",
    "gitGraph",
    "erDiagram",
    "journey"
  ];
  var elements = $(".language-fallback").each((i, element) => {
    var graphDefinition = element.innerText;
    
    if(mermaidKeywords.some((keyword) => graphDefinition.startsWith(keyword))) {
      var parent = element.parentElement.parentElement;
      if(parent.className == "highlight") {
        parent.className = "mermaid";
        parent.innerHTML = graphDefinition;
        parent.align = "center";
      }
    }
  });
</script>

用例

测试(有的来自 mermaid.js):

Flow Chart

Markdown
Hugo
highlight.js
mermaid.js

Sequence Diagram

AliceBobJohnHello John, how are you?Fight against hypochondrialoop[Healthcheck]Rational thoughts prevail!Great!How about you?Jolly good!AliceBobJohn

Gantt Diagram

2014-01-072014-01-092014-01-112014-01-132014-01-152014-01-172014-01-192014-01-212014-01-23Completed task Active task Future task Future task2 A sectionAdding GANTT diagram to mermaid

Class Diagram

Class01int chimpint gorillasize()AveryLongClassClass03Class04Class05Class06Class07Object[] elementDataequals()Class08Class09C2C3CoolWhere am i?Cool label

Git Graph - experimental

master, cd21743

cc51c7f

7edc1d4

55c4129

newbranch, e4cd836

1d215fa

Entity Relationship Diagram - experimental

CUSTOMERORDERLINE-ITEMDELIVERY-ADDRESSplacescontainsuses

User Journey Diagram

CatMe
Go to work
Go to work
Me
Make tea
Make tea
Me
Go upstairs
Go upstairs
MeCat
Do work
Do work
Go home
Go home
Me
Go downstairs
Go downstairs
Me
Sit down
Sit down
My working day