Databricksにてmemaid.jsを利用する方法

## 更新情報

2023年5月14日： mermaid.min.js のダウンロード元のリンクがきれていいたため、URLを更新
2023年5月14日： Git graph の記述方法が変更となっていたため、変更

## 概要

Databricksにて、mermaid.jsのダイアグラムを作成が可能であったため検証結果を共有します。Databricksノートブック内に、mermaid.jsのダイアグラムを残すことで、コードと一緒に設計書を残すことができるため便利です。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/bc4c253f-ec1c-57dc-5c7e-493e5efdc428.png)

displayHTML関数、もしくは、%md-sandboxにより表示可能であり、設計書として残す際には%md-sandboxを利用した方がよさそうです。displayHTML関数で残す場合には、ノートブックが実行されるたびに再生成する処理されるためです。


## mermaid.jsとは
mermaid.jsとは、javascriptベースで開発されており、コードからダイアグラムを作成するツールです。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/229353ea-2d0c-d03f-8c22-9a185ab40a60.png)
引用元：[About Mermaid (mermaid-js.github.io)](https://mermaid-js.github.io/mermaid/#/README)

コードからきれいなダイヤグラムを作成できることもあり、設計書として使われることがあるようです。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/72b7662d-3a30-0022-24c2-1b0053a175e9.png)
引用元：[Online FlowChart & Diagrams Editor - Mermaid Live Editor (mermaid-js.github.io)](https://mermaid-js.github.io/mermaid-live-editor/edit#eyJjb2RlIjoiZXJEaWFncmFtXG5cbnVzZXIgfHwtLW97IHBvc3QgOiBvd25zXG5wb3N0IHx8LS1veyB1cGRvb3QgOiBoYXNcbnVzZXIgfXwtLW97IHVwZG9vdCA6IGhhc1xuXG51c2VyIHtcbm51bWJlciBpZFxuc3RyaW5nIHVzZXJuYW1lXG5zdHJpbmcgZW1haWxcbnN0cmluZyBwYXNzd29yZFxufVxuXG5wb3N0IHtcbm51bWJlciBpZFxuc3RyaW5nIHRpdGxlXG5zdHJpbmcgdGV4dFxubnVtYmVyIHBvaW50c1xubnVtYmVyIHZvdGVTdGF0dXNcbn1cblxudXBkb290IHtcbm51bWJlciB1c2VySWRcbm51bWJlciBwb3N0SWRcbm51bWJlciB2YWx1ZVxufSIsIm1lcm1haWQiOiJ7XG4gIFwidGhlbWVcIjogXCJmb3Jlc3RcIlxufSIsInVwZGF0ZUVkaXRvciI6ZmFsc2UsImF1dG9TeW5jIjp0cnVlLCJ1cGRhdGVEaWFncmFtIjpmYWxzZX0)

## 基本的な検証
### displayHTML関数で表示する方法

```databricks
displayHTML("""
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
        <script>mermaid.initialize({startOnLoad:true});</script>
    </head>
    <body>
        <div class="mermaid">
            graph TD;
              A-->B;
              A-->C;
              B-->D;
              C-->D;
        </div>
    </body>
</html>
""")
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/1db1533c-3417-a0a3-cecb-67c644707628.png)

### %md-sandboxで表示する方法
```databricks
%md-sandbox
<html>
    <head>
        <link rel="stylesheet" href="https://unpkg.com/mermaid/dist/mermaid.min.css">
        <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
        <script>mermaid.initialize({startOnLoad:true});</script>
    </head>
    <body>
        <div class="mermaid">
            graph TD;
              A-->B;
              A-->C;
              B-->D;
              C-->D;
        </div>
    </body>
</html>
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/49a54aab-d85d-0c29-7ec1-cb348169adac.png)

## memeidのダイアグラム別検証
下記の関数を作成して検証しました。

```python
def mermeaid_display(code):
    mermeid_html =f"""
                    <html>
                        <head>
                            <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
                            <script>mermaid.initialize({{startOnLoad:true}});</script>
                        </head>
                        <body>
                            <div class="mermaid">
                                {code}
                            </div>
                        </body>
                    </html>
                    """
    displayHTML(mermeid_html)
    
code = """
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
"""
 
mermeaid_display(code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/e1cd8fb6-e2b2-92e5-6e2c-2417d6fa8b5d.png)

### Flowcharts

```python
mermaid_code = """
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
"""
 
mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/c05fa4b1-9514-8a8f-bd80-e2a0ac8e18d1.png)


### Sequence diagrams

```python
mermaid_code = """
sequenceDiagram
    participant Alice
    participant Bob
    Alice->>John: Hello John, how are you?
    loop Healthcheck
        John->>John: Fight against hypochondria
    end
    Note right of John: Rational thoughts <br/>prevail!
    John-->>Alice: Great!
    John->>Bob: How about you?
    Bob-->>John: Jolly good!
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/787ca152-9b5f-c037-b755-ef02b43d1b1d.png)

### Class diagrams

```python
mermaid_code = """
classDiagram
Class01 <|-- AveryLongClass : Cool
Class03 *-- Class04
Class05 o-- Class06
Class07 .. Class08
Class09 --> C2 : Where am i?
Class09 --* C3
Class09 --|> Class07
Class07 : equals()
Class07 : Object[] elementData
Class01 : size()
Class01 : int chimp
Class01 : int gorilla
Class08 <--> C2: Cool label
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/37987dcb-c7f5-9e41-ef75-9134a294c095.png)

### Entity Relationship Diagrams

```python
mermaid_code = """
erDiagram
    CUSTOMER ||--o{ ORDER : places
    CUSTOMER {
        string name
        string custNumber
        string sector
    }
    ORDER ||--|{ LINE-ITEM : contains
    ORDER {
        int orderNumber
        string deliveryAddress
    }
    LINE-ITEM {
        string productCode
        int quantity
        float pricePerUnit
    }
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/e42b0640-0f0e-97a9-2721-83dca146b88e.png)

### User Journey Diagram

```python
mermaid_code = """
journey
    title My working day
    section Go to work
      Make tea: 5: Me
      Go upstairs: 3: Me
      Do work: 1: Me, Cat
    section Go home
      Go downstairs: 5: Me
      Sit down: 5: Me
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/9f35be0c-18e6-3e40-8a9b-3d7036efd873.png)

### Gantt diagrams

```python
mermaid_code = """
gantt
dateFormat  YYYY-MM-DD
title Adding GANTT diagram to mermaid
excludes weekdays 2014-01-10

section A section
Completed task            :done,    des1, 2014-01-06,2014-01-08
Active task               :active,  des2, 2014-01-09, 3d
Future task               :         des3, after des2, 5d
Future task2               :         des4, after des3, 5d
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/8ee71f08-b87a-75e4-3c93-b33956e12059.png)


### Pie chart diagrams

```python
mermaid_code = """
pie
    title Key elements in Product X
    "Calcium" : 42.96
    "Potassium" : 50.05
    "Magnesium" : 10.01
    "Iron" :  5
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/1d52c8c4-c70d-ef95-0564-864e61265d16.png)

### Requirement Diagram

```python
mermaid_code = """
requirementDiagram

requirement test_req {
id: 1
text: the test text.
risk: high
verifymethod: test
}

element test_entity {
type: simulation
}

test_entity - satisfies -> test_req
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/40967364-40af-24a4-82fe-b52a49915daa.png)

### Git graph

```python
mermaid_code = """
---
title: Example Git diagram
---
gitGraph
   commit
   commit
   branch develop
   checkout develop
   commit
   commit
   checkout main
   merge develop
   commit
   commit
"""

mermeaid_display(mermaid_code)
```

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/24031/1c3c05ad-42b9-2394-7ec4-6b4b1dc5fea2.png)