diff --git a/.github/workflows/link-checker.yml b/.github/workflows/link-checker.yml
index 15259b518..b2c17f9fc 100644
--- a/.github/workflows/link-checker.yml
+++ b/.github/workflows/link-checker.yml
@@ -14,6 +14,7 @@ on:
pull_request:
branches:
- master
+ workflow_dispatch:
schedule:
# * is a special character in YAML so you have to quote this string
- cron: '30 8 * * *'
@@ -37,7 +38,14 @@ jobs:
- name: Link Checker
uses: lycheeverse/lychee-action@v1.6.1
with:
- args: --verbose --no-progress --cache --max-cache-age 1d packages/mermaid/src/docs/**/*.md README.md README.zh-CN.md
+ args: >-
+ --verbose
+ --no-progress
+ --cache
+ --max-cache-age 1d
+ packages/mermaid/src/docs/**/*.md
+ README.md
+ README.zh-CN.md
fail: true
jobSummary: true
env:
diff --git a/.lycheeignore b/.lycheeignore
index 4c781f6a0..5f7b9679e 100644
--- a/.lycheeignore
+++ b/.lycheeignore
@@ -4,16 +4,8 @@
# Network error: Forbidden
https://codepen.io
-# Network error: The certificate was not trusted
-https://mkdocs.org/
-https://osawards.com/javascript/#nominees
-https://osawards.com/javascript/2019
-
# Timeout error, maybe Twitter has anti-bot defenses against GitHub's CI servers?
https://twitter.com/mermaidjs_
# Don't check files that are generated during the build via `pnpm docs:code`
packages/mermaid/src/docs/config/setup/*
-
-# Network error: 502, since few days
-https://bundlephobia.com/
diff --git a/.npmrc b/.npmrc
index 289684302..4c2f52b3b 100644
--- a/.npmrc
+++ b/.npmrc
@@ -1,3 +1,2 @@
auto-install-peers=true
strict-peer-dependencies=false
-use-inline-specifiers-lockfile-format=true
diff --git a/.vite/server.ts b/.vite/server.ts
index 82b75232d..5a86b3d5b 100644
--- a/.vite/server.ts
+++ b/.vite/server.ts
@@ -10,7 +10,7 @@ async function createServer() {
configFile: './vite.config.ts',
mode: 'production',
server: { middlewareMode: true },
- appType: 'custom', // don't include Vite's default HTML handling middlewares
+ appType: 'custom', // don't include Vite's default HTML handling middleware
});
app.use(cors());
diff --git a/README.md b/README.md
index d42e2f7e1..31c6d62c6 100644
--- a/README.md
+++ b/README.md
@@ -226,6 +226,44 @@ pie
### Git graph [experimental - live editor ]
+### Bar chart (using gantt chart) [docs - live editor ]
+
+```
+gantt
+ title Git Issues - days since last update
+ dateFormat X
+ axisFormat %s
+
+ section Issue19062
+ 71 : 0, 71
+ section Issue19401
+ 36 : 0, 36
+ section Issue193
+ 34 : 0, 34
+ section Issue7441
+ 9 : 0, 9
+ section Issue1300
+ 5 : 0, 5
+```
+
+```mermaid
+gantt
+ title Git Issues - days since last update
+ dateFormat X
+ axisFormat %s
+
+ section Issue19062
+ 71 : 0, 71
+ section Issue19401
+ 36 : 0, 36
+ section Issue193
+ 34 : 0, 34
+ section Issue7441
+ 9 : 0, 9
+ section Issue1300
+ 5 : 0, 5
+```
+
### User Journey diagram [docs - live editor ]
```
diff --git a/cypress/integration/rendering/erDiagram.spec.js b/cypress/integration/rendering/erDiagram.spec.js
index df1fac0cd..faa511626 100644
--- a/cypress/integration/rendering/erDiagram.spec.js
+++ b/cypress/integration/rendering/erDiagram.spec.js
@@ -10,7 +10,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render an ER diagram with a recursive relationship', () => {
@@ -23,7 +22,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render an ER diagram with multiple relationships between the same two entities', () => {
@@ -35,7 +33,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render a cyclical ER diagram', () => {
@@ -48,7 +45,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render a not-so-simple ER diagram', () => {
@@ -66,7 +62,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render multiple ER diagrams', () => {
@@ -85,7 +80,6 @@ describe('Entity Relationship Diagram', () => {
],
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render an ER diagram with blank or empty labels', () => {
@@ -98,7 +92,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render an ER diagrams when useMaxWidth is true (default)', () => {
@@ -151,7 +144,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ er: { useMaxWidth: false } }
);
- cy.get('svg');
});
it('should render entities with and without attributes', () => {
@@ -164,7 +156,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render entities with generic and array attributes', () => {
@@ -179,7 +170,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render entities with length in attributes type', () => {
@@ -193,7 +183,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render entities and attributes with big and small entity names', () => {
@@ -209,7 +198,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render entities with keys', () => {
@@ -228,7 +216,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render entities with comments', () => {
@@ -247,7 +234,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render entities with keys and comments', () => {
@@ -267,7 +253,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('should render entities with aliases', () => {
@@ -285,7 +270,6 @@ describe('Entity Relationship Diagram', () => {
`,
{ logLevel: 1 }
);
- cy.get('svg');
});
it('1433: should render a simple ER diagram with a title', () => {
diff --git a/cypress/integration/rendering/errorDiagram.spec.js b/cypress/integration/rendering/errorDiagram.spec.js
new file mode 100644
index 000000000..e837565d3
--- /dev/null
+++ b/cypress/integration/rendering/errorDiagram.spec.js
@@ -0,0 +1,45 @@
+import { imgSnapshotTest } from '../../helpers/util';
+
+describe('Error Diagrams', () => {
+ beforeEach(() => {
+ cy.on('uncaught:exception', (err) => {
+ expect(err.message).to.include('Parse error');
+ // return false to prevent the error from
+ // failing this test
+ return false;
+ });
+ });
+
+ it('should render a simple ER diagram', () => {
+ imgSnapshotTest(
+ `
+ error
+ `,
+ { logLevel: 1 }
+ );
+ });
+
+ it('should render error diagram for actual errors', () => {
+ imgSnapshotTest(
+ `
+ flowchart TD
+ A[Christmas] --|Get money| B(Go shopping)
+ `,
+ { logLevel: 1 }
+ );
+ });
+
+ it('should render error for wrong ER diagram', () => {
+ imgSnapshotTest(
+ `
+ erDiagram
+ ATLAS-ORGANIZATION ||--|{ ATLAS-PROJECTS : "has many"
+ ATLAS-PROJECTS ||--|{ MONGODB-CLUSTERS : "has many"
+ ATLAS-PROJECTS ||--|{ ATLAS-TEAMS : "has many"
+ MONGODB-CLUSTERS ||..|{
+ ATLAS-TEAMS ||..|{
+ `,
+ { logLevel: 1 }
+ );
+ });
+});
diff --git a/cypress/integration/rendering/flowchart-elk.spec.js b/cypress/integration/rendering/flowchart-elk.spec.js
index 414037651..68d8b3ce5 100644
--- a/cypress/integration/rendering/flowchart-elk.spec.js
+++ b/cypress/integration/rendering/flowchart-elk.spec.js
@@ -684,4 +684,149 @@ A --> B
{ titleTopMargin: 0 }
);
});
+ describe('Markdown strings flowchart-elk (#4220)', () => {
+ describe('html labels', () => {
+ it('With styling and classes', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart-elk LR
+ A:::someclass --> B["\`The **cat** in the hat\`"]:::someclass
+ id1(Start)-->id2(Stop)
+ style id1 fill:#f9f,stroke:#333,stroke-width:4px
+ style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
+ classDef someclass fill:#f96
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('With formatting in a node', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart-elk LR
+ a{"\`The **cat** in the hat\`"} -- 1o --> b
+ a -- 2o --> c
+ a -- 3o --> d
+ g --2i--> a
+ d --1i--> a
+ h --3i -->a
+ b --> d(The dog in the hog)
+ c --> d
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('New line in node and formatted edge label', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart-elk LR
+b("\`The dog in **the** hog.(1)
+NL\`") --"\`1o **bold**\`"--> c
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Wrapping long text with a new line', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart-elk LR
+b(\`The dog in **the** hog.(1).. a a a a *very long text* about it
+Word!
+
+Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`) --> c
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Sub graphs and markdown strings', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart-elk LR
+subgraph "One"
+ a("\`The **cat**
+ in the hat\`") -- "1o" --> b{{"\`The **dog** in the hog\`"}}
+end
+subgraph "\`**Two**\`"
+ c("\`The **cat**
+ in the hat\`") -- "\`1o **ipa**\`" --> d("The dog in the hog")
+end
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ });
+
+ describe('svg text labels', () => {
+ it('With styling and classes', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart-elk LR
+ A:::someclass --> B["\`The **cat** in the hat\`"]:::someclass
+ id1(Start)-->id2(Stop)
+ style id1 fill:#f9f,stroke:#333,stroke-width:4px
+ style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
+ classDef someclass fill:#f96
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('With formatting in a node', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart-elk LR
+ a{"\`The **cat** in the hat\`"} -- 1o --> b
+ a -- 2o --> c
+ a -- 3o --> d
+ g --2i--> a
+ d --1i--> a
+ h --3i -->a
+ b --> d(The dog in the hog)
+ c --> d
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('New line in node and formatted edge label', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart-elk LR
+b("\`The dog in **the** hog.(1)
+NL\`") --"\`1o **bold**\`"--> c
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Wrapping long text with a new line', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart-elk LR
+b("\`The dog in **the** hog.(1).. a a a a *very long text* about it
+Word!
+
+Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`") --> c
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Sub graphs and markdown strings', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart-elk LR
+subgraph "One"
+ a("\`The **cat**
+ in the hat\`") -- "1o" --> b{{"\`The **dog** in the hog\`"}}
+end
+subgraph "\`**Two**\`"
+ c("\`The **cat**
+ in the hat\`") -- "\`1o **ipa**\`" --> d("The dog in the hog")
+end
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ });
+ });
});
diff --git a/cypress/integration/rendering/flowchart-v2.spec.js b/cypress/integration/rendering/flowchart-v2.spec.js
index abdb22265..4513cc87d 100644
--- a/cypress/integration/rendering/flowchart-v2.spec.js
+++ b/cypress/integration/rendering/flowchart-v2.spec.js
@@ -685,4 +685,149 @@ A ~~~ B
{ titleTopMargin: 0 }
);
});
+ describe('Markdown strings flowchart (#4220)', () => {
+ describe('html labels', () => {
+ it('With styling and classes', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart LR
+ A:::someclass --> B["\`The **cat** in the hat\`"]:::someclass
+ id1(Start)-->id2(Stop)
+ style id1 fill:#f9f,stroke:#333,stroke-width:4px
+ style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
+ classDef someclass fill:#f96
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('With formatting in a node', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart LR
+ a{"\`The **cat** in the hat\`"} -- 1o --> b
+ a -- 2o --> c
+ a -- 3o --> d
+ g --2i--> a
+ d --1i--> a
+ h --3i -->a
+ b --> d(The dog in the hog)
+ c --> d
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('New line in node and formatted edge label', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart LR
+b("\`The dog in **the** hog.(1)
+NL\`") --"\`1o **bold**\`"--> c
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Wrapping long text with a new line', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart LR
+b("\`The dog in **the** hog.(1).. a a a a *very long text* about it
+Word!
+
+Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`") --> c
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Sub graphs and markdown strings', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": true}} }%%
+flowchart LR
+subgraph "One"
+ a("\`The **cat**
+ in the hat\`") -- "1o" --> b{{"\`The **dog** in the hog\`"}}
+end
+subgraph "\`**Two**\`"
+ c("\`The **cat**
+ in the hat\`") -- "\`1o **ipa**\`" --> d("The dog in the hog")
+end
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ });
+
+ describe('svg text labels', () => {
+ it('With styling and classes', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart LR
+ A:::someclass --> B["\`The **cat** in the hat\`"]:::someclass
+ id1(Start)-->id2(Stop)
+ style id1 fill:#f9f,stroke:#333,stroke-width:4px
+ style id2 fill:#bbf,stroke:#f66,stroke-width:2px,color:#fff,stroke-dasharray: 5 5
+ classDef someclass fill:#f96
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('With formatting in a node', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart LR
+ a{"\`The **cat** in the hat\`"} -- 1o --> b
+ a -- 2o --> c
+ a -- 3o --> d
+ g --2i--> a
+ d --1i--> a
+ h --3i -->a
+ b --> d(The dog in the hog)
+ c --> d
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('New line in node and formatted edge label', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart LR
+b("\`The dog in **the** hog.(1)
+NL\`") --"\`1o **bold**\`"--> c
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Wrapping long text with a new line', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart LR
+b("\`The dog in **the** hog.(1).. a a a a *very long text* about it
+Word!
+
+Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. \`") --> c
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ it('Sub graphs and markdown strings', () => {
+ imgSnapshotTest(
+ `%%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart LR
+subgraph "One"
+ a("\`The **cat**
+ in the hat\`") -- "1o" --> b{{"\`The **dog** in the hog\`"}}
+end
+subgraph "\`**Two**\`"
+ c("\`The **cat**
+ in the hat\`") -- "\`1o **ipa**\`" --> d("The dog in the hog")
+end
+
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ });
+ });
});
diff --git a/cypress/integration/rendering/gantt.spec.js b/cypress/integration/rendering/gantt.spec.js
index c0156eee3..cb65f73b0 100644
--- a/cypress/integration/rendering/gantt.spec.js
+++ b/cypress/integration/rendering/gantt.spec.js
@@ -133,6 +133,24 @@ describe('Gantt diagram', () => {
);
});
+ it('should default to showing today marker', () => {
+ // This test only works if the environment thinks today is 1010-10-10
+ imgSnapshotTest(
+ `
+ gantt
+ title Show today marker (vertical line should be visible)
+ dateFormat YYYY-MM-DD
+ axisFormat %d
+ %% Should default to being on
+ %% todayMarker on
+ section Section1
+ Yesterday: 1010-10-09, 1d
+ Today: 1010-10-10, 1d
+ `,
+ {}
+ );
+ });
+
it('should hide today marker', () => {
imgSnapshotTest(
`
@@ -142,7 +160,8 @@ describe('Gantt diagram', () => {
axisFormat %d
todayMarker off
section Section1
- Today: 1, -1h
+ Yesterday: 1010-10-09, 1d
+ Today: 1010-10-10, 1d
`,
{}
);
@@ -157,7 +176,8 @@ describe('Gantt diagram', () => {
axisFormat %d
todayMarker stroke-width:5px,stroke:#00f,opacity:0.5
section Section1
- Today: 1, -1h
+ Yesterday: 1010-10-09, 1d
+ Today: 1010-10-10, 1d
`,
{}
);
@@ -435,4 +455,39 @@ describe('Gantt diagram', () => {
{ gantt: { topAxis: true } }
);
});
+
+ it('should render when compact is true', () => {
+ imgSnapshotTest(
+ `
+ ---
+ displayMode: compact
+ ---
+ gantt
+ title GANTT compact
+ dateFormat HH:mm:ss
+ axisFormat %Hh%M
+
+ section DB Clean
+ Clean: 12:00:00, 10m
+ Clean: 12:30:00, 12m
+ Clean: 13:00:00, 8m
+ Clean: 13:30:00, 9m
+ Clean: 14:00:00, 13m
+ Clean: 14:30:00, 10m
+ Clean: 15:00:00, 11m
+
+ section Sessions
+ A: 12:00:00, 63m
+ B: 12:30:00, 12m
+ C: 13:05:00, 12m
+ D: 13:06:00, 33m
+ E: 13:15:00, 55m
+ F: 13:20:00, 12m
+ G: 13:32:00, 18m
+ H: 13:50:00, 20m
+ I: 14:10:00, 10m
+ `,
+ {}
+ );
+ });
});
diff --git a/cypress/integration/rendering/mindmap.spec.ts b/cypress/integration/rendering/mindmap.spec.ts
index 4663f6225..94b3f9ca0 100644
--- a/cypress/integration/rendering/mindmap.spec.ts
+++ b/cypress/integration/rendering/mindmap.spec.ts
@@ -223,5 +223,18 @@ mindmap
shouldHaveRoot
);
});
+ describe('Markdown strings mindmaps (#4220)', () => {
+ it('Formatted label with linebreak and a wrapping label and emojis', () => {
+ imgSnapshotTest(
+ `mindmap
+ id1[\`**Start** with
+ a second line ๐\`]
+ id2[\`The dog in **the** hog... a *very long text* about it
+Word!\`]
+`,
+ { titleTopMargin: 0 }
+ );
+ });
+ });
/* The end */
});
diff --git a/cypress/platform/knsv2.html b/cypress/platform/knsv2.html
index fccd65004..08a4c0e68 100644
--- a/cypress/platform/knsv2.html
+++ b/cypress/platform/knsv2.html
@@ -51,27 +51,48 @@
font-family: monospace;
font-size: 72px;
}
+ /* tspan {
+ font-size: 6px !important;
+ } */
-%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%%
-graph BT
-a{The cat in the hat} -- 1o --> b
-a -- 2o --> c
-a -- 3o --> d
-g --2i--> a
-d --1i--> a
-h --3i -->a
-b --> d(The dog in the hog)
-c --> d
-
+ %%{init: {"flowchart": {"htmlLabels": false}} }%%
+flowchart-elk LR
+b(`The dog in **the** hog(2)... a a a a *very long text* about it
+Word!
+Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. Another line with many, many words. `)
+
-flowchart-elk TB
- a --> b
- a --> c
- b --> d
- c --> d
+flowchart-elk LR
+b("The dog in the hog... a very long text about it Word!")
+
+
+flowchart-elk LR
+b("The dog in the hog... a very long text about it Word!")
+
+ >
+
+mindmap
+ id1[`**Start2**
+ second line ๐ with long text that is wrapping to the next line`]
+ id2[`Child **with bold** text`]
+ id3[`Children of which some
+ is using *italic type of* text`]
+ id4[Child]
+ id5[`Child
+ Row
+ and another
+ `]
+
+
+mindmap
+ id1["`**Start** with
+ a second line ๐`"]
+ id2["`The dog in **the** hog... a *very long text* about it
+Word!`"]
%%{init: {"flowchart": {"defaultRenderer": "elk"}} }%%
@@ -272,12 +293,14 @@ mindmap
mermaid.initialize({
theme: 'forest',
startOnLoad: true,
- logLevel: 5,
+ logLevel: 0,
flowchart: {
// defaultRenderer: 'elk',
useMaxWidth: false,
- htmlLabels: true,
+ htmlLabels: false,
+ // htmlLabels: true,
},
+ // htmlLabels: true,
gantt: {
useMaxWidth: false,
},
diff --git a/cypress/platform/viewer.js b/cypress/platform/viewer.js
index 2e1093519..99533192d 100644
--- a/cypress/platform/viewer.js
+++ b/cypress/platform/viewer.js
@@ -47,7 +47,6 @@ const contentLoaded = async function () {
await mermaid2.registerExternalDiagrams([externalExample]);
mermaid2.initialize(graphObj.mermaid);
await mermaid2.run();
- markRendered();
}
};
@@ -123,7 +122,6 @@ const contentLoadedApi = async function () {
bindFunctions(div);
}
}
- markRendered();
};
if (typeof document !== 'undefined') {
@@ -135,10 +133,10 @@ if (typeof document !== 'undefined') {
function () {
if (this.location.href.match('xss.html')) {
this.console.log('Using api');
- void contentLoadedApi();
+ void contentLoadedApi().finally(markRendered);
} else {
this.console.log('Not using api');
- void contentLoaded();
+ void contentLoaded().finally(markRendered);
}
},
false
diff --git a/demos/error.html b/demos/error.html
new file mode 100644
index 000000000..2d6d1b01f
--- /dev/null
+++ b/demos/error.html
@@ -0,0 +1,38 @@
+
+
+
+
+
+ Error | Mermaid Quick Test Page
+
+
+
+
+
+ erDiagram
+ ATLAS-ORGANIZATION ||--|{ ATLAS-PROJECTS : "has many"
+ ATLAS-PROJECTS ||--|{ MONGODB-CLUSTERS : "has many"
+ ATLAS-PROJECTS ||--|{ ATLAS-TEAMS : "has many"
+
+
+ erDiagram
+ ATLAS-ORGANIZATION ||--|{ ATLAS-PROJECTS : "has many"
+ ATLAS-PROJECTS ||--|{ MONGODB-CLUSTERS : "has many"
+ ATLAS-PROJECTS ||--|{ ATLAS-TEAMS : "has many"
+ MONGODB-CLUSTERS ||..|{
+ ATLAS-TEAMS ||..|{
+
+
+
+ flowchart TD
+ A[Christmas] -->|Get money| B(Go shopping)
+
+
+ flowchart TD
+ A[Christmas] --|Get money| B(Go shopping)
+
+
+
+
diff --git a/demos/gantt.html b/demos/gantt.html
index 613dc8694..88f52ef5c 100644
--- a/demos/gantt.html
+++ b/demos/gantt.html
@@ -78,7 +78,7 @@
axisFormat %d/%m
todayMarker off
section Section1
- Today: 1, -01:00, 5min
+ Today: 1, 08-08-09-01:00, 5min
@@ -89,7 +89,7 @@
axisFormat %d/%m
todayMarker stroke-width:5px,stroke:#00f,opacity:0.5
section Section1
- Today: 1, -01:00, 5min
+ Today: 1, 08-08-09-01:00, 5min
@@ -166,6 +166,37 @@
+
+ ---
+ displayMode: compact
+ ---
+ gantt
+ title GANTT compact
+ dateFormat HH:mm:ss
+ axisFormat %Hh%M
+
+ section DB Clean
+ Clean: 12:00:00, 10m
+ Clean: 12:30:00, 12m
+ Clean: 13:00:00, 8m
+ Clean: 13:30:00, 9m
+ Clean: 14:00:00, 13m
+ Clean: 14:30:00, 10m
+ Clean: 15:00:00, 11m
+
+ section Sessions
+ A: 12:00:00, 63m
+ B: 12:30:00, 12m
+ C: 13:05:00, 12m
+ D: 13:06:00, 33m
+ E: 13:15:00, 55m
+ F: 13:20:00, 12m
+ G: 13:32:00, 18m
+ H: 13:50:00, 20m
+ I: 14:10:00, 10m
+
+
+
```
+To determine the type of diagram present in a given text, you can utilize the `mermaid.detectType` function, as demonstrated in the example below.
+
+```html
+
+```
+
### Binding events
Sometimes the generated graph also has defined interactions like tooltip and click events. When using the API one must
diff --git a/docs/ecosystem/integrations.md b/docs/ecosystem/integrations.md
index a9b7b974d..3a9b7cd74 100644
--- a/docs/ecosystem/integrations.md
+++ b/docs/ecosystem/integrations.md
@@ -89,7 +89,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [FosWiki](https://foswiki.org)
- [Mermaid Plugin](https://foswiki.org/Extensions/MermaidPlugin)
- [DokuWiki](https://dokuwiki.org)
- - [Flowcharts](https://www.dokuwiki.org/plugin:flowcharts?s[]=mermaid)
+ - [Mermaid Plugin](https://www.dokuwiki.org/plugin:mermaid)
- [ComboStrap](https://combostrap.com/mermaid)
- [TiddlyWiki](https://tiddlywiki.com/)
- [mermaid-tw5: full js library](https://github.com/efurlanm/mermaid-tw5)
@@ -150,7 +150,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [remark-mermaid](https://github.com/temando/remark-mermaid)
- [jSDoc](https://jsdoc.app/)
- [jsdoc-mermaid](https://github.com/Jellyvision/jsdoc-mermaid)
-- [MkDocs](https://mkdocs.org)
+- [MkDocs](https://www.mkdocs.org)
- [mkdocs-mermaid2-plugin](https://github.com/fralau/mkdocs-mermaid2-plugin)
- [mkdocs-material](https://github.com/squidfunk/mkdocs-material), check the [docs](https://squidfunk.github.io/mkdocs-material/reference/diagrams/)
- [Type Doc](https://typedoc.org/)
diff --git a/docs/syntax/flowchart.md b/docs/syntax/flowchart.md
index 547847f54..c79f12b23 100644
--- a/docs/syntax/flowchart.md
+++ b/docs/syntax/flowchart.md
@@ -183,20 +183,6 @@ flowchart LR
### A hexagon node
-Code:
-
-```mermaid-example
-flowchart LR
- id1{{This is the text in the box}}
-```
-
-```mermaid
-flowchart LR
- id1{{This is the text in the box}}
-```
-
-Render:
-
```mermaid-example
flowchart LR
id1{{This is the text in the box}}
diff --git a/docs/syntax/gantt.md b/docs/syntax/gantt.md
index 6a7af3331..091cdeabe 100644
--- a/docs/syntax/gantt.md
+++ b/docs/syntax/gantt.md
@@ -257,9 +257,41 @@ The pattern is:
More info in:
+## Output in compact mode
+
+The compact mode allows you to display multiple tasks in the same row. Compact mode can be enabled for a gantt chart by setting the display mode of the graph via preceeding YAML settings.
+
+```mermaid-example
+---
+displayMode: compact
+---
+gantt
+ title A Gantt Diagram
+ dateFormat YYYY-MM-DD
+
+ section Section
+ A task :a1, 2014-01-01, 30d
+ Another task :a2, 2014-01-20, 25d
+ Another one :a3, 2014-02-10, 20d
+```
+
+```mermaid
+---
+displayMode: compact
+---
+gantt
+ title A Gantt Diagram
+ dateFormat YYYY-MM-DD
+
+ section Section
+ A task :a1, 2014-01-01, 30d
+ Another task :a2, 2014-01-20, 25d
+ Another one :a3, 2014-02-10, 20d
+```
+
## Comments
-Comments can be entered within a gantt chart, which will be ignored by the parser. Comments need to be on their own line and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax
+Comments can be entered within a gantt chart, which will be ignored by the parser. Comments need to be on their own line and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax.
```mermaid-example
gantt
@@ -432,3 +464,41 @@ Beginner's tipโa full example using interactive links in an html context:
```
+
+## Examples
+
+### Bar chart (using gantt chart)
+
+```mermaid-example
+gantt
+ title Git Issues - days since last update
+ dateFormat X
+ axisFormat %s
+ section Issue19062
+ 71 : 0, 71
+ section Issue19401
+ 36 : 0, 36
+ section Issue193
+ 34 : 0, 34
+ section Issue7441
+ 9 : 0, 9
+ section Issue1300
+ 5 : 0, 5
+```
+
+```mermaid
+gantt
+ title Git Issues - days since last update
+ dateFormat X
+ axisFormat %s
+ section Issue19062
+ 71 : 0, 71
+ section Issue19401
+ 36 : 0, 36
+ section Issue193
+ 34 : 0, 34
+ section Issue7441
+ 9 : 0, 9
+ section Issue1300
+ 5 : 0, 5
+```
diff --git a/docs/syntax/mindmap.md b/docs/syntax/mindmap.md
index ad8aab77f..babe47756 100644
--- a/docs/syntax/mindmap.md
+++ b/docs/syntax/mindmap.md
@@ -224,7 +224,7 @@ mindmap
C
```
-_These classes needs top be supplied by the site administrator._
+_These classes need to be supplied by the site administrator._
## Unclear indentation
diff --git a/docs/syntax/timeline.md b/docs/syntax/timeline.md
index 58b12313d..f3db4bb59 100644
--- a/docs/syntax/timeline.md
+++ b/docs/syntax/timeline.md
@@ -8,7 +8,7 @@
> Timeline: This is an experimental diagram for now. The syntax and properties can change in future releases. The syntax is stable except for the icon integration which is the experimental part.
-"A timeline is a type of diagram used to illustrate a chronology of events, dates, or periods of time. It is usually presented graphically to indicate the passing of time, and it is usually organized chronologically. A basic timeline presents a list of events in chronological order, usually using dates as markers. A timeline can also be used to show the relationship between events, such as the relationship between the events of a person's life. A timeline can also be used to show the relationship between events, such as the relationship between the events of a person's life." Wikipedia
+"A timeline is a type of diagram used to illustrate a chronology of events, dates, or periods of time. It is usually presented graphically to indicate the passing of time, and it is usually organized chronologically. A basic timeline presents a list of events in chronological order, usually using dates as markers. A timeline can also be used to show the relationship between events, such as the relationship between the events of a person's life." Wikipedia
### An example of a timeline.
@@ -213,7 +213,7 @@ However, if there is no section defined, then we have two possibilities:
```
-Note that this is no, section defined, and each time period and its corresponding events will have its own color scheme.
+Note that there are no sections defined, and each time period and its corresponding events will have its own color scheme.
2. Disable the multiColor option using the `disableMultiColor` option. This will make all time periods and events follow the same color scheme.
@@ -257,7 +257,7 @@ let us look at same example, where we have disabled the multiColor option.
### Customizing Color scheme
-You can customize the color scheme using the `cScale0` to `cScale11` theme variables. Mermaid allows you to set unique colors for up-to 12, where `cScale0` variable will drive the value of the first section or time-period, `cScale1` will drive the value of the second section and so on.
+You can customize the color scheme using the `cScale0` to `cScale11` theme variables. Mermaid allows you to set unique colors for up-to 12 sections, where `cScale0` variable will drive the value of the first section or time-period, `cScale1` will drive the value of the second section and so on.
In case you have more than 12 sections, the color scheme will start to repeat.
NOTE: Default values for these theme variables are picked from the selected theme. If you want to override the default values, you can use the `initialize` call to add your custom theme variable values.
diff --git a/package.json b/package.json
index 89de95949..ca642e890 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"version": "10.0.2",
"description": "Markdownish syntax for generating flowcharts, sequence diagrams, class diagrams, gantt charts and git graphs.",
"type": "module",
- "packageManager": "pnpm@7.29.0",
+ "packageManager": "pnpm@7.30.1",
"keywords": [
"diagram",
"markdown",
@@ -112,6 +112,6 @@
"vitest": "^0.29.0"
},
"volta": {
- "node": "18.14.2"
+ "node": "18.15.0"
}
}
diff --git a/packages/mermaid/package.json b/packages/mermaid/package.json
index 190d9e783..fc789e292 100644
--- a/packages/mermaid/package.json
+++ b/packages/mermaid/package.json
@@ -55,11 +55,12 @@
},
"dependencies": {
"@braintree/sanitize-url": "^6.0.0",
+ "@khanacademy/simple-markdown": "^0.8.6",
"cytoscape": "^3.23.0",
"cytoscape-cose-bilkent": "^4.1.0",
"cytoscape-fcose": "^2.1.0",
"d3": "^7.4.0",
- "dagre-d3-es": "7.0.9",
+ "dagre-d3-es": "7.0.10",
"dayjs": "^1.11.7",
"dompurify": "2.4.5",
"elkjs": "^0.8.2",
@@ -76,7 +77,7 @@
"@types/d3": "^7.4.0",
"@types/dompurify": "^2.4.0",
"@types/jsdom": "^21.0.0",
- "@types/lodash-es": "^4.17.6",
+ "@types/lodash-es": "^4.17.7",
"@types/micromatch": "^4.0.2",
"@types/prettier": "^2.7.1",
"@types/stylis": "^4.0.2",
diff --git a/packages/mermaid/src/Diagram.ts b/packages/mermaid/src/Diagram.ts
index 3010ce130..adb596734 100644
--- a/packages/mermaid/src/Diagram.ts
+++ b/packages/mermaid/src/Diagram.ts
@@ -5,6 +5,7 @@ import { detectType, getDiagramLoader } from './diagram-api/detectType';
import { extractFrontMatter } from './diagram-api/frontmatter';
import { UnknownDiagramError } from './errors';
import { DetailedError } from './utils';
+import { cleanupComments } from './diagram-api/comments';
export type ParseErrorFunction = (err: string | DetailedError | unknown, hash?: any) => void;
@@ -43,7 +44,10 @@ export class Diagram {
// Similarly, we can't do this in getDiagramFromText() because some code
// calls diagram.db.clear(), which would reset anything set by
// extractFrontMatter().
- this.parser.parse = (text: string) => originalParse(extractFrontMatter(text, this.db));
+
+ this.parser.parse = (text: string) =>
+ originalParse(cleanupComments(extractFrontMatter(text, this.db)));
+
this.parser.parser.yy = this.db;
if (diagram.init) {
diagram.init(cnf);
diff --git a/packages/mermaid/src/commonDb.ts b/packages/mermaid/src/commonDb.ts
index 42ffde004..a9ad0f54b 100644
--- a/packages/mermaid/src/commonDb.ts
+++ b/packages/mermaid/src/commonDb.ts
@@ -3,6 +3,7 @@ import { getConfig } from './config';
let title = '';
let diagramTitle = '';
let description = '';
+
const sanitizeText = (txt: string): string => _sanitizeText(txt, getConfig());
export const clear = function (): void {
@@ -36,10 +37,10 @@ export const getDiagramTitle = function (): string {
};
export default {
- setAccTitle,
getAccTitle,
+ setAccTitle,
+ getDiagramTitle,
setDiagramTitle,
- getDiagramTitle: getDiagramTitle,
getAccDescription,
setAccDescription,
clear,
diff --git a/packages/mermaid/src/config.type.ts b/packages/mermaid/src/config.type.ts
index 157304149..545fdbbfb 100644
--- a/packages/mermaid/src/config.type.ts
+++ b/packages/mermaid/src/config.type.ts
@@ -335,6 +335,7 @@ export interface GanttDiagramConfig extends BaseDiagramConfig {
axisFormat?: string;
tickInterval?: string;
topAxis?: boolean;
+ displayMode?: string;
}
export interface SequenceDiagramConfig extends BaseDiagramConfig {
@@ -385,6 +386,7 @@ export interface FlowchartDiagramConfig extends BaseDiagramConfig {
curve?: string;
padding?: number;
defaultRenderer?: string;
+ wrappingWidth?: number;
}
export interface FontConfig {
diff --git a/packages/mermaid/src/dagre-wrapper/clusters.js b/packages/mermaid/src/dagre-wrapper/clusters.js
index 57c3ff513..453fcb8f5 100644
--- a/packages/mermaid/src/dagre-wrapper/clusters.js
+++ b/packages/mermaid/src/dagre-wrapper/clusters.js
@@ -1,12 +1,13 @@
import intersectRect from './intersect/intersect-rect';
import { log } from '../logger';
import createLabel from './createLabel';
+import { createText } from '../rendering-util/createText';
import { select } from 'd3';
import { getConfig } from '../config';
import { evaluate } from '../diagrams/common/common';
const rect = (parent, node) => {
- log.trace('Creating subgraph rect for ', node.id, node);
+ log.info('Creating subgraph rect for ', node.id, node);
// Add outer g element
const shapeSvg = parent
@@ -17,12 +18,18 @@ const rect = (parent, node) => {
// add the rect
const rect = shapeSvg.insert('rect', ':first-child');
+ const useHtmlLabels = evaluate(getConfig().flowchart.htmlLabels);
+
// Create the label and insert it after the rect
const label = shapeSvg.insert('g').attr('class', 'cluster-label');
- const text = label
- .node()
- .appendChild(createLabel(node.labelText, node.labelStyle, undefined, true));
+ // const text = label
+ // .node()
+ // .appendChild(createLabel(node.labelText, node.labelStyle, undefined, true));
+ const text =
+ node.labelType === 'markdown'
+ ? createText(label, node.labelText, { style: node.labelStyle, useHtmlLabels })
+ : label.node().appendChild(createLabel(node.labelText, node.labelStyle, undefined, true));
// Get the size of the label
let bbox = text.getBBox();
@@ -61,7 +68,7 @@ const rect = (parent, node) => {
'transform',
// This puts the labal on top of the box instead of inside it
// 'translate(' + (node.x - bbox.width / 2) + ', ' + (node.y - node.height / 2 - bbox.height) + ')'
- 'translate(' + (node.x - bbox.width / 2) + ', ' + (node.y - node.height / 2) + ')'
+ 'translate(' + node.x + ', ' + (node.y - node.height / 2) + ')'
);
const rectBox = rect.node().getBBox();
diff --git a/packages/mermaid/src/dagre-wrapper/createLabel.js b/packages/mermaid/src/dagre-wrapper/createLabel.js
index af5032096..ff7834c4f 100644
--- a/packages/mermaid/src/dagre-wrapper/createLabel.js
+++ b/packages/mermaid/src/dagre-wrapper/createLabel.js
@@ -41,7 +41,13 @@ function addHtmlLabel(node) {
div.attr('xmlns', 'http://www.w3.org/1999/xhtml');
return fo.node();
}
-
+/**
+ * @param _vertexText
+ * @param style
+ * @param isTitle
+ * @param isNode
+ * @deprecated svg-util/createText instead
+ */
const createLabel = (_vertexText, style, isTitle, isNode) => {
let vertexText = _vertexText || '';
if (typeof vertexText === 'object') {
diff --git a/packages/mermaid/src/dagre-wrapper/edges.js b/packages/mermaid/src/dagre-wrapper/edges.js
index f8c113694..d4b7d37b8 100644
--- a/packages/mermaid/src/dagre-wrapper/edges.js
+++ b/packages/mermaid/src/dagre-wrapper/edges.js
@@ -1,5 +1,6 @@
import { log } from '../logger';
import createLabel from './createLabel';
+import { createText } from '../rendering-util/createText';
import { line, curveBasis, select } from 'd3';
import { getConfig } from '../config';
import utils from '../utils';
@@ -14,8 +15,17 @@ export const clear = () => {
};
export const insertEdgeLabel = (elem, edge) => {
+ const useHtmlLabels = evaluate(getConfig().flowchart.htmlLabels);
// Create the actual text element
- const labelElement = createLabel(edge.label, edge.labelStyle);
+ const labelElement =
+ edge.labelType === 'markdown'
+ ? createText(elem, edge.label, {
+ style: edge.labelStyle,
+ useHtmlLabels,
+ addSvgBackground: true,
+ })
+ : createLabel(edge.label, edge.labelStyle);
+ log.info('abc82', edge, edge.labelType);
// Create outer g, edgeLabel, this will be positioned after graph layout
const edgeLabel = elem.insert('g').attr('class', 'edgeLabel');
@@ -26,7 +36,7 @@ export const insertEdgeLabel = (elem, edge) => {
// Center the label
let bbox = labelElement.getBBox();
- if (evaluate(getConfig().flowchart.htmlLabels)) {
+ if (useHtmlLabels) {
const div = labelElement.children[0];
const dv = select(labelElement);
bbox = div.getBoundingClientRect();
diff --git a/packages/mermaid/src/dagre-wrapper/nodes.js b/packages/mermaid/src/dagre-wrapper/nodes.js
index 49b96b685..3e71f500a 100644
--- a/packages/mermaid/src/dagre-wrapper/nodes.js
+++ b/packages/mermaid/src/dagre-wrapper/nodes.js
@@ -313,19 +313,18 @@ const cylinder = (parent, node) => {
const rect = (parent, node) => {
const { shapeSvg, bbox, halfPadding } = labelHelper(parent, node, 'node ' + node.classes, true);
- log.trace('Classes = ', node.classes);
// add the rect
const rect = shapeSvg.insert('rect', ':first-child');
- const totalWidth = bbox.width + node.padding;
- const totalHeight = bbox.height + node.padding;
+ const totalWidth = bbox.width + node.padding * 2;
+ const totalHeight = bbox.height + node.padding * 2;
rect
.attr('class', 'basic label-container')
.attr('style', node.style)
.attr('rx', node.rx)
.attr('ry', node.ry)
- .attr('x', -bbox.width / 2 - halfPadding)
- .attr('y', -bbox.height / 2 - halfPadding)
+ .attr('x', -bbox.width / 2 - node.padding)
+ .attr('y', -bbox.height / 2 - node.padding)
.attr('width', totalWidth)
.attr('height', totalHeight);
@@ -352,7 +351,7 @@ const rect = (parent, node) => {
const labelRect = (parent, node) => {
const { shapeSvg } = labelHelper(parent, node, 'label', true);
- log.trace('Classes = ', node.classes);
+ log.info('Classes = ', node.classes);
// add the rect
const rect = shapeSvg.insert('rect', ':first-child');
diff --git a/packages/mermaid/src/dagre-wrapper/shapes/util.js b/packages/mermaid/src/dagre-wrapper/shapes/util.js
index 6de0da638..b5de2bd6b 100644
--- a/packages/mermaid/src/dagre-wrapper/shapes/util.js
+++ b/packages/mermaid/src/dagre-wrapper/shapes/util.js
@@ -1,4 +1,5 @@
import createLabel from '../createLabel';
+import { createText } from '../../rendering-util/createText';
import { getConfig } from '../../config';
import { decodeEntities } from '../../mermaidAPI';
import { select } from 'd3';
@@ -27,9 +28,17 @@ export const labelHelper = (parent, node, _classes, isNode) => {
labelText = typeof node.labelText === 'string' ? node.labelText : node.labelText[0];
}
- const text = label
- .node()
- .appendChild(
+ const textNode = label.node();
+ let text;
+ if (node.labelType === 'markdown') {
+ // text = textNode;
+ text = createText(label, sanitizeText(decodeEntities(labelText), getConfig()), {
+ useHtmlLabels: getConfig().flowchart.htmlLabels,
+ width: node.width || getConfig().flowchart.wrappingWidth,
+ classes: 'markdown-node-label',
+ });
+ } else {
+ text = textNode.appendChild(
createLabel(
sanitizeText(decodeEntities(labelText), getConfig()),
node.labelStyle,
@@ -37,6 +46,7 @@ export const labelHelper = (parent, node, _classes, isNode) => {
isNode
)
);
+ }
// Get the size of the label
let bbox = text.getBBox();
@@ -52,8 +62,12 @@ export const labelHelper = (parent, node, _classes, isNode) => {
const halfPadding = node.padding / 2;
// Center the label
- label.attr('transform', 'translate(' + -bbox.width / 2 + ', ' + -bbox.height / 2 + ')');
-
+ if (getConfig().flowchart.htmlLabels) {
+ label.attr('transform', 'translate(' + -bbox.width / 2 + ', ' + -bbox.height / 2 + ')');
+ } else {
+ label.attr('transform', 'translate(' + 0 + ', ' + -bbox.height / 2 + ')');
+ }
+ label.insert('rect', ':first-child');
return { shapeSvg, bbox, halfPadding, label };
};
diff --git a/packages/mermaid/src/defaultConfig.ts b/packages/mermaid/src/defaultConfig.ts
index 666efc364..2ca995251 100644
--- a/packages/mermaid/src/defaultConfig.ts
+++ b/packages/mermaid/src/defaultConfig.ts
@@ -258,6 +258,18 @@ const config: Partial = {
* Default value: 'dagre-wrapper'
*/
defaultRenderer: 'dagre-wrapper',
+ /**
+ * | Parameter | Description | Type | Required | Values |
+ * | --------------- | ----------- | ------- | -------- | ----------------------- |
+ * | wrappingWidth | See notes | number | 4 | width of nodes where text is wrapped |
+ *
+ * **Notes:**
+ *
+ * When using markdown strings the text ius wrapped automatically, this
+ * value sets the max width of a text before it continues on a new line.
+ * Default value: 'dagre-wrapper'
+ */
+ wrappingWidth: 200,
},
/** The object containing configurations specific for sequence diagrams */
@@ -659,6 +671,17 @@ const config: Partial = {
*/
numberSectionStyles: 4,
+ /**
+ * | Parameter | Description | Type | Required | Values |
+ * | ----------- | ------------------------- | ------ | -------- | --------- |
+ * | displayMode | Controls the display mode | string | 4 | 'compact' |
+ *
+ * **Notes**:
+ *
+ * - **compact**: Enables displaying multiple tasks on the same row.
+ */
+ displayMode: '',
+
/**
* | Parameter | Description | Type | Required | Values |
* | ---------- | ---------------------------- | ---- | -------- | ---------------- |
@@ -684,7 +707,6 @@ const config: Partial = {
* Default value: undefined
*/
tickInterval: undefined,
-
/**
* | Parameter | Description | Type | Required | Values |
* | ----------- | ----------- | ------- | -------- | ----------- |
diff --git a/packages/mermaid/src/diagram-api/comments.spec.ts b/packages/mermaid/src/diagram-api/comments.spec.ts
new file mode 100644
index 000000000..a2c896079
--- /dev/null
+++ b/packages/mermaid/src/diagram-api/comments.spec.ts
@@ -0,0 +1,94 @@
+// tests to check that comments are removed
+
+import { cleanupComments } from './comments';
+import { describe, it, expect } from 'vitest';
+
+describe('comments', () => {
+ it('should remove comments', () => {
+ const text = `
+
+%% This is a comment
+%% This is another comment
+graph TD
+ A-->B
+%% This is a comment
+`;
+ expect(cleanupComments(text)).toMatchInlineSnapshot(`
+ "graph TD
+ A-->B
+ "
+ `);
+ });
+
+ it('should keep init statements when removing comments', () => {
+ const text = `
+%% This is a comment
+
+%% This is another comment
+%%{init: {'theme': 'forest'}}%%
+%%{ init: {'theme': 'space before init'}}%%
+%%{init: {'theme': 'space after ending'}}%%
+graph TD
+ A-->B
+
+ B-->C
+%% This is a comment
+`;
+ expect(cleanupComments(text)).toMatchInlineSnapshot(`
+ "%%{init: {'theme': 'forest'}}%%
+ %%{ init: {'theme': 'space before init'}}%%
+ %%{init: {'theme': 'space after ending'}}%%
+ graph TD
+ A-->B
+
+ B-->C
+ "
+ `);
+ });
+
+ it('should remove indented comments', () => {
+ const text = `
+%% This is a comment
+graph TD
+ A-->B
+ %% This is a comment
+ C-->D
+`;
+ expect(cleanupComments(text)).toMatchInlineSnapshot(`
+ "graph TD
+ A-->B
+ C-->D
+ "
+ `);
+ });
+
+ it('should remove empty newlines from start', () => {
+ const text = `
+
+
+
+
+%% This is a comment
+graph TD
+ A-->B
+`;
+ expect(cleanupComments(text)).toMatchInlineSnapshot(`
+ "graph TD
+ A-->B
+ "
+ `);
+ });
+
+ it('should remove comments at end of text with no newline', () => {
+ const text = `
+graph TD
+ A-->B
+%% This is a comment`;
+
+ expect(cleanupComments(text)).toMatchInlineSnapshot(`
+ "graph TD
+ A-->B
+ "
+ `);
+ });
+});
diff --git a/packages/mermaid/src/diagram-api/comments.ts b/packages/mermaid/src/diagram-api/comments.ts
new file mode 100644
index 000000000..be39b0a0f
--- /dev/null
+++ b/packages/mermaid/src/diagram-api/comments.ts
@@ -0,0 +1,8 @@
+/**
+ * Remove all lines starting with `%%` from the text that don't contain a `%%{`
+ * @param text - The text to remove comments from
+ * @returns cleaned text
+ */
+export const cleanupComments = (text: string): string => {
+ return text.trimStart().replace(/^\s*%%(?!{)[^\n]+\n?/gm, '');
+};
diff --git a/packages/mermaid/src/diagram-api/diagram-orchestration.ts b/packages/mermaid/src/diagram-api/diagram-orchestration.ts
index 73bfcf084..a88a34f19 100644
--- a/packages/mermaid/src/diagram-api/diagram-orchestration.ts
+++ b/packages/mermaid/src/diagram-api/diagram-orchestration.ts
@@ -13,7 +13,7 @@ import classDiagramV2 from '../diagrams/class/classDetector-V2';
import state from '../diagrams/state/stateDetector';
import stateV2 from '../diagrams/state/stateDetector-V2';
import journey from '../diagrams/user-journey/journeyDetector';
-import error from '../diagrams/error/errorDetector';
+import errorDiagram from '../diagrams/error/errorDiagram';
import flowchartElk from '../diagrams/flowchart/elk/detector';
import timeline from '../diagrams/timeline/detector';
import mindmap from '../diagrams/mindmap/detector';
@@ -28,6 +28,9 @@ export const addDiagrams = () => {
// This is added here to avoid race-conditions.
// We could optimize the loading logic somehow.
hasLoadedDiagrams = true;
+ registerDiagram('error', errorDiagram, (text) => {
+ return text.toLowerCase().trim() === 'error';
+ });
registerDiagram(
'---',
// --- diagram type may appear if YAML front-matter is not parsed correctly
@@ -57,7 +60,6 @@ export const addDiagrams = () => {
);
// Ordering of detectors is important. The first one to return true will be used.
registerLazyLoadedDiagrams(
- error,
c4,
classDiagramV2,
classDiagram,
diff --git a/packages/mermaid/src/diagram-api/frontmatter.ts b/packages/mermaid/src/diagram-api/frontmatter.ts
index d6811388c..a9c4995e6 100644
--- a/packages/mermaid/src/diagram-api/frontmatter.ts
+++ b/packages/mermaid/src/diagram-api/frontmatter.ts
@@ -11,6 +11,8 @@ export const frontMatterRegex = /^-{3}\s*[\n\r](.*?)[\n\r]-{3}\s*[\n\r]+/s;
type FrontMatterMetadata = {
title?: string;
+ // Allows custom display modes. Currently used for compact mode in gantt charts.
+ displayMode?: string;
};
/**
@@ -33,6 +35,10 @@ export function extractFrontMatter(text: string, db: DiagramDb): string {
db.setDiagramTitle?.(parsed.title);
}
+ if (parsed?.displayMode) {
+ db.setDisplayMode?.(parsed.displayMode);
+ }
+
return text.slice(matches[0].length);
} else {
return text;
diff --git a/packages/mermaid/src/diagram-api/types.ts b/packages/mermaid/src/diagram-api/types.ts
index 081136563..8c5d14eb8 100644
--- a/packages/mermaid/src/diagram-api/types.ts
+++ b/packages/mermaid/src/diagram-api/types.ts
@@ -16,6 +16,7 @@ export interface InjectUtils {
export interface DiagramDb {
clear?: () => void;
setDiagramTitle?: (title: string) => void;
+ setDisplayMode?: (title: string) => void;
getAccTitle?: () => string;
getAccDescription?: () => string;
bindFunctions?: (element: Element) => void;
diff --git a/packages/mermaid/src/diagrams/er/parser/erDiagram.jison b/packages/mermaid/src/diagrams/er/parser/erDiagram.jison
index d9f03c387..8ffa87c63 100644
--- a/packages/mermaid/src/diagrams/er/parser/erDiagram.jison
+++ b/packages/mermaid/src/diagrams/er/parser/erDiagram.jison
@@ -19,8 +19,6 @@ accDescr\s*"{"\s* { this.begin("acc_descr_multili
":" { this.popState(); this.begin('arg_directive'); return ':'; }
\}\%\% { this.popState(); this.popState(); return 'close_directive'; }
((?:(?!\}\%\%).|\n)*) return 'arg_directive';
-\%%(?!\{)[^\n]* /* skip comments */
-[^\}]\%\%[^\n]* /* skip comments */
[\n]+ return 'NEWLINE';
\s+ /* skip whitespace */
[\s]+ return 'SPACE';
@@ -35,8 +33,6 @@ accDescr\s*"{"\s* { this.begin("acc_descr_multili
[A-Za-z_][A-Za-z0-9\-_\[\]\(\)]* return 'ATTRIBUTE_WORD'
\"[^"]*\" return 'COMMENT';
[\n]+ /* nothing */
-\%%(?!\{)[^\n]* /* skip comments in attribute block */
-[^\}]\%\%[^\n]* /* skip comments in attribute block */
"}" { this.popState(); return 'BLOCK_STOP'; }
. return yytext[0];
diff --git a/packages/mermaid/src/diagrams/error/errorDetector.ts b/packages/mermaid/src/diagrams/error/errorDetector.ts
deleted file mode 100644
index 2bdcd7028..000000000
--- a/packages/mermaid/src/diagrams/error/errorDetector.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { DiagramDetector, ExternalDiagramDefinition } from '../../diagram-api/types';
-
-const id = 'error';
-
-const detector: DiagramDetector = (text) => {
- return text.toLowerCase().trim() === 'error';
-};
-
-const loader = async () => {
- const { diagram } = await import('./errorDiagram');
- return { id, diagram };
-};
-
-const plugin: ExternalDiagramDefinition = {
- id,
- detector,
- loader,
-};
-
-export default plugin;
diff --git a/packages/mermaid/src/diagrams/error/errorDiagram.ts b/packages/mermaid/src/diagrams/error/errorDiagram.ts
index d081e1028..7b9f18c3b 100644
--- a/packages/mermaid/src/diagrams/error/errorDiagram.ts
+++ b/packages/mermaid/src/diagrams/error/errorDiagram.ts
@@ -19,3 +19,5 @@ export const diagram: DiagramDefinition = {
// no op
},
};
+
+export default diagram;
diff --git a/packages/mermaid/src/diagrams/error/errorRenderer.ts b/packages/mermaid/src/diagrams/error/errorRenderer.ts
index 60877cb8d..046bcfdcf 100644
--- a/packages/mermaid/src/diagrams/error/errorRenderer.ts
+++ b/packages/mermaid/src/diagrams/error/errorRenderer.ts
@@ -4,15 +4,13 @@ import { select } from 'd3';
import { log } from '../../logger';
import { getErrorMessage } from '../../utils';
-let conf = {};
-
/**
* Merges the value of `conf` with the passed `cnf`
*
* @param cnf - Config to merge
*/
-export const setConf = function (cnf: any) {
- conf = { ...conf, ...cnf };
+export const setConf = function () {
+ // no-op
};
/**
@@ -78,7 +76,7 @@ export const draw = (_text: string, id: string, mermaidVersion: string) => {
.attr('y', 250)
.attr('font-size', '150px')
.style('text-anchor', 'middle')
- .text('Syntax error in graph');
+ .text('Syntax error in text');
g.append('text') // text label for the x axis
.attr('class', 'error-text')
.attr('x', 1250)
diff --git a/packages/mermaid/src/diagrams/flowchart/elk/flowRenderer-elk.js b/packages/mermaid/src/diagrams/flowchart/elk/flowRenderer-elk.js
index 426d22dbb..5849177b9 100644
--- a/packages/mermaid/src/diagrams/flowchart/elk/flowRenderer-elk.js
+++ b/packages/mermaid/src/diagrams/flowchart/elk/flowRenderer-elk.js
@@ -3,6 +3,7 @@ import { insertNode } from '../../../dagre-wrapper/nodes.js';
import insertMarkers from '../../../dagre-wrapper/markers.js';
import { insertEdgeLabel } from '../../../dagre-wrapper/edges.js';
import { findCommonAncestor } from './render-utils';
+import { labelHelper } from '../../../dagre-wrapper/shapes/util';
import { addHtmlLabel } from 'dagre-d3-es/src/dagre-js/label/add-html-label.js';
import { getConfig } from '../../../config';
import { log } from '../../../logger';
@@ -12,7 +13,7 @@ import { interpolateToCurve, getStylesFromArray } from '../../../utils';
import ELK from 'elkjs/lib/elk.bundled.js';
const elk = new ELK();
-const portPos = {};
+let portPos = {};
const conf = {};
export const setConf = function (cnf) {
@@ -52,7 +53,7 @@ export const addVertices = function (vert, svgId, root, doc, diagObj, parentLook
if (vertex.classes.length > 0) {
classStr = vertex.classes.join(' ');
}
-
+ classStr = classStr + ' flowchart-label';
const styles = getStylesFromArray(vertex.styles);
// Use vertex id as text in the box if no text is provided by the graph definition
@@ -61,40 +62,6 @@ export const addVertices = function (vert, svgId, root, doc, diagObj, parentLook
// We create a SVG label, either by delegating to addHtmlLabel or manually
let vertexNode;
const labelData = { width: 0, height: 0 };
- if (evaluate(getConfig().flowchart.htmlLabels)) {
- // TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
- const node = {
- label: vertexText.replace(
- /fa[blrs]?:fa-[\w-]+/g,
- (s) => ` `
- ),
- };
- vertexNode = addHtmlLabel(svg, node).node();
- const bbox = vertexNode.getBBox();
- labelData.width = bbox.width;
- labelData.height = bbox.height;
- labelData.labelNode = vertexNode;
- vertexNode.parentNode.removeChild(vertexNode);
- } else {
- const svgLabel = doc.createElementNS('http://www.w3.org/2000/svg', 'text');
- svgLabel.setAttribute('style', styles.labelStyle.replace('color:', 'fill:'));
-
- const rows = vertexText.split(common.lineBreakRegex);
-
- for (const row of rows) {
- const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
- tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
- tspan.setAttribute('dy', '1em');
- tspan.setAttribute('x', '1');
- tspan.textContent = row;
- svgLabel.appendChild(tspan);
- }
- vertexNode = svgLabel;
- const bbox = vertexNode.getBBox();
- labelData.width = bbox.width;
- labelData.height = bbox.height;
- labelData.labelNode = vertexNode;
- }
const ports = [
{
@@ -186,11 +153,13 @@ export const addVertices = function (vert, svgId, root, doc, diagObj, parentLook
default:
_shape = 'rect';
}
+
// Add the node
const node = {
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
+ labelType: vertex.labelType,
rx: radious,
ry: radious,
class: classStr,
@@ -209,10 +178,33 @@ export const addVertices = function (vert, svgId, root, doc, diagObj, parentLook
};
let boundingBox;
let nodeEl;
+
+ // Add the element to the DOM
if (node.type !== 'group') {
nodeEl = insertNode(nodes, node, vertex.dir);
boundingBox = nodeEl.node().getBBox();
+ } else {
+ const svgLabel = doc.createElementNS('http://www.w3.org/2000/svg', 'text');
+ // svgLabel.setAttribute('style', styles.labelStyle.replace('color:', 'fill:'));
+ // const rows = vertexText.split(common.lineBreakRegex);
+ // for (const row of rows) {
+ // const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
+ // tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
+ // tspan.setAttribute('dy', '1em');
+ // tspan.setAttribute('x', '1');
+ // tspan.textContent = row;
+ // svgLabel.appendChild(tspan);
+ // }
+ // vertexNode = svgLabel;
+ // const bbox = vertexNode.getBBox();
+ const { shapeSvg, bbox } = labelHelper(nodes, node, undefined, true);
+ labelData.width = bbox.width;
+ labelData.wrappingWidth = getConfig().flowchart.wrappingWidth;
+ labelData.height = bbox.height;
+ labelData.labelNode = shapeSvg.node();
+ node.labelData = labelData;
}
+ // const { shapeSvg, bbox } = labelHelper(svg, node, undefined, true);
const data = {
id: vertex.id,
@@ -520,7 +512,7 @@ export const addEdges = function (edges, diagObj, graph, svg) {
edgeData.labelpos = 'c';
}
- edgeData.labelType = 'text';
+ edgeData.labelType = edge.labelType;
edgeData.label = edge.text.replace(common.lineBreakRegex, '\n');
if (edge.style === undefined) {
@@ -775,6 +767,7 @@ export const draw = async function (text, id, _version, diagObj) {
// Add temporary render element
diagObj.db.clear();
nodeDb = {};
+ portPos = {};
diagObj.db.setGen('gen-2');
// Parse the graph definition
diagObj.parser.parse(text);
@@ -845,9 +838,17 @@ export const draw = async function (text, id, _version, diagObj) {
log.info('Subgraphs - ', subGraphs);
for (let i = subGraphs.length - 1; i >= 0; i--) {
subG = subGraphs[i];
- diagObj.db.addVertex(subG.id, subG.title, 'group', undefined, subG.classes, subG.dir);
+ diagObj.db.addVertex(
+ subG.id,
+ { text: subG.title, type: subG.labelType },
+ 'group',
+ undefined,
+ subG.classes,
+ subG.dir
+ );
}
+ // debugger;
// Add an element in the svg to be used to hold the subgraphs container
// elements
const subGraphsEl = svg.insert('g').attr('class', 'subgraphs');
@@ -860,7 +861,7 @@ export const draw = async function (text, id, _version, diagObj) {
// in order to get the size of the node. You can't get the size of a node
// that is not in the dom so we need to add it to the dom, get the size
// we will position the nodes when we get the layout from elkjs
- graph = addVertices(vert, id, root, doc, diagObj, parentLookupDb, graph);
+ graph = addVertices(vert, id, root, doc, diagObj, parentLookupDb, graph, svg);
// Time for the edges, we start with adding an element in the node to hold the edges
const edgesEl = svg.insert('g').attr('class', 'edges edgePath');
@@ -887,6 +888,8 @@ export const draw = async function (text, id, _version, diagObj) {
},
width: node.labelData.width,
height: node.labelData.height,
+ // width: 100,
+ // height: 100,
},
];
delete node.x;
@@ -895,6 +898,7 @@ export const draw = async function (text, id, _version, diagObj) {
delete node.height;
}
});
+
insertChildren(graph.children, parentLookupDb);
log.info('after layout', JSON.stringify(graph, null, 2));
const g = await elk.layout(graph);
diff --git a/packages/mermaid/src/diagrams/flowchart/elk/styles.ts b/packages/mermaid/src/diagrams/flowchart/elk/styles.ts
index e8e7065a0..60659df45 100644
--- a/packages/mermaid/src/diagrams/flowchart/elk/styles.ts
+++ b/packages/mermaid/src/diagrams/flowchart/elk/styles.ts
@@ -81,7 +81,7 @@ const getStyles = (options: FlowChartStyleOptions) =>
.edgeLabel {
background-color: ${options.edgeLabelBackground};
rect {
- opacity: 0.5;
+ opacity: 0.85;
background-color: ${options.edgeLabelBackground};
fill: ${options.edgeLabelBackground};
}
@@ -132,6 +132,11 @@ const getStyles = (options: FlowChartStyleOptions) =>
// fill:#ccc;
// // stroke:black;
// }
+
+ .flowchart-label text {
+ text-anchor: middle;
+ }
+
${genSections(options)}
`;
diff --git a/packages/mermaid/src/diagrams/flowchart/flowDb.js b/packages/mermaid/src/diagrams/flowchart/flowDb.js
index 31196ba96..85dc5337e 100644
--- a/packages/mermaid/src/diagrams/flowchart/flowDb.js
+++ b/packages/mermaid/src/diagrams/flowchart/flowDb.js
@@ -59,13 +59,14 @@ export const lookUpDomId = function (id) {
*
* @param _id
* @param text
+ * @param textObj
* @param type
* @param style
* @param classes
* @param dir
* @param props
*/
-export const addVertex = function (_id, text, type, style, classes, dir, props = {}) {
+export const addVertex = function (_id, textObj, type, style, classes, dir, props = {}) {
let txt;
let id = _id;
if (id === undefined) {
@@ -80,16 +81,17 @@ export const addVertex = function (_id, text, type, style, classes, dir, props =
if (vertices[id] === undefined) {
vertices[id] = {
id: id,
+ labelType: 'text',
domId: MERMAID_DOM_ID_PREFIX + id + '-' + vertexCounter,
styles: [],
classes: [],
};
}
vertexCounter++;
- if (text !== undefined) {
+ if (textObj !== undefined) {
config = configApi.getConfig();
- txt = sanitizeText(text.trim());
-
+ txt = sanitizeText(textObj.text.trim());
+ vertices[id].labelType = textObj.type;
// strip quotes if string starts and ends with a quote
if (txt[0] === '"' && txt[txt.length - 1] === '"') {
txt = txt.substring(1, txt.length - 1);
@@ -131,24 +133,27 @@ export const addVertex = function (_id, text, type, style, classes, dir, props =
* @param _end
* @param type
* @param linkText
+ * @param linkTextObj
*/
-export const addSingleLink = function (_start, _end, type, linkText) {
+export const addSingleLink = function (_start, _end, type) {
let start = _start;
let end = _end;
// if (start[0].match(/\d/)) start = MERMAID_DOM_ID_PREFIX + start;
// if (end[0].match(/\d/)) end = MERMAID_DOM_ID_PREFIX + end;
// log.info('Got edge...', start, end);
- const edge = { start: start, end: end, type: undefined, text: '' };
- linkText = type.text;
+ const edge = { start: start, end: end, type: undefined, text: '', labelType: 'text' };
+ log.info('abc78 Got edge...', edge);
+ const linkTextObj = type.text;
- if (linkText !== undefined) {
- edge.text = sanitizeText(linkText.trim());
+ if (linkTextObj !== undefined) {
+ edge.text = sanitizeText(linkTextObj.text.trim());
// strip quotes if string starts and ends with a quote
if (edge.text[0] === '"' && edge.text[edge.text.length - 1] === '"') {
edge.text = edge.text.substring(1, edge.text.length - 1);
}
+ edge.labelType = linkTextObj.type;
}
if (type !== undefined) {
@@ -158,11 +163,12 @@ export const addSingleLink = function (_start, _end, type, linkText) {
}
edges.push(edge);
};
-export const addLink = function (_start, _end, type, linktext) {
+export const addLink = function (_start, _end, type) {
+ log.info('addLink (abc78)', _start, _end, type);
let i, j;
for (i = 0; i < _start.length; i++) {
for (j = 0; j < _end.length; j++) {
- addSingleLink(_start[i], _end[j], type, linktext);
+ addSingleLink(_start[i], _end[j], type);
}
}
};
@@ -457,10 +463,9 @@ export const defaultStyle = function () {
* @param _title
*/
export const addSubGraph = function (_id, list, _title) {
- // console.log('addSubGraph', _id, list, _title);
- let id = _id.trim();
- let title = _title;
- if (_id === _title && _title.match(/\s/)) {
+ let id = _id.text.trim();
+ let title = _title.text;
+ if (_id === _title && _title.text.match(/\s/)) {
id = undefined;
}
/** @param a */
@@ -502,7 +507,14 @@ export const addSubGraph = function (_id, list, _title) {
title = title || '';
title = sanitizeText(title);
subCount = subCount + 1;
- const subGraph = { id: id, nodes: nodeList, title: title.trim(), classes: [], dir };
+ const subGraph = {
+ id: id,
+ nodes: nodeList,
+ title: title.trim(),
+ classes: [],
+ dir,
+ labelType: _title.type,
+ };
log.info('Adding', subGraph.id, subGraph.nodes, subGraph.dir);
diff --git a/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js b/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js
index 2d3e21a44..a87f23e04 100644
--- a/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js
+++ b/packages/mermaid/src/diagrams/flowchart/flowRenderer-v2.js
@@ -47,7 +47,7 @@ export const addVertices = function (vert, g, svgId, root, doc, diagObj) {
if (vertex.classes.length > 0) {
classStr = vertex.classes.join(' ');
}
-
+ classStr = classStr + ' flowchart-label';
const styles = getStylesFromArray(vertex.styles);
// Use vertex id as text in the box if no text is provided by the graph definition
@@ -55,31 +55,36 @@ export const addVertices = function (vert, g, svgId, root, doc, diagObj) {
// We create a SVG label, either by delegating to addHtmlLabel or manually
let vertexNode;
- if (evaluate(getConfig().flowchart.htmlLabels)) {
- // TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
- const node = {
- label: vertexText.replace(
- /fa[blrs]?:fa-[\w-]+/g,
- (s) => ` `
- ),
- };
- vertexNode = addHtmlLabel(svg, node).node();
- vertexNode.parentNode.removeChild(vertexNode);
+ log.info('vertex', vertex, vertex.labelType);
+ if (vertex.labelType === 'markdown') {
+ log.info('vertex', vertex, vertex.labelType);
} else {
- const svgLabel = doc.createElementNS('http://www.w3.org/2000/svg', 'text');
- svgLabel.setAttribute('style', styles.labelStyle.replace('color:', 'fill:'));
+ if (evaluate(getConfig().flowchart.htmlLabels)) {
+ // TODO: addHtmlLabel accepts a labelStyle. Do we possibly have that?
+ const node = {
+ label: vertexText.replace(
+ /fa[blrs]?:fa-[\w-]+/g,
+ (s) => ` `
+ ),
+ };
+ vertexNode = addHtmlLabel(svg, node).node();
+ vertexNode.parentNode.removeChild(vertexNode);
+ } else {
+ const svgLabel = doc.createElementNS('http://www.w3.org/2000/svg', 'text');
+ svgLabel.setAttribute('style', styles.labelStyle.replace('color:', 'fill:'));
- const rows = vertexText.split(common.lineBreakRegex);
+ const rows = vertexText.split(common.lineBreakRegex);
- for (const row of rows) {
- const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
- tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
- tspan.setAttribute('dy', '1em');
- tspan.setAttribute('x', '1');
- tspan.textContent = row;
- svgLabel.appendChild(tspan);
+ for (const row of rows) {
+ const tspan = doc.createElementNS('http://www.w3.org/2000/svg', 'tspan');
+ tspan.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
+ tspan.setAttribute('dy', '1em');
+ tspan.setAttribute('x', '1');
+ tspan.textContent = row;
+ svgLabel.appendChild(tspan);
+ }
+ vertexNode = svgLabel;
}
- vertexNode = svgLabel;
}
let radious = 0;
@@ -146,6 +151,7 @@ export const addVertices = function (vert, g, svgId, root, doc, diagObj) {
labelStyle: styles.labelStyle,
shape: _shape,
labelText: vertexText,
+ labelType: vertex.labelType,
rx: radious,
ry: radious,
class: classStr,
@@ -165,6 +171,7 @@ export const addVertices = function (vert, g, svgId, root, doc, diagObj) {
log.info('setNode', {
labelStyle: styles.labelStyle,
+ labelType: vertex.labelType,
shape: _shape,
labelText: vertexText,
rx: radious,
@@ -312,7 +319,7 @@ export const addEdges = function (edges, g, diagObj) {
edgeData.labelpos = 'c';
}
- edgeData.labelType = 'text';
+ edgeData.labelType = edge.labelType;
edgeData.label = edge.text.replace(common.lineBreakRegex, '\n');
if (edge.style === undefined) {
@@ -405,7 +412,14 @@ export const draw = function (text, id, _version, diagObj) {
for (let i = subGraphs.length - 1; i >= 0; i--) {
subG = subGraphs[i];
log.info('Subgraph - ', subG);
- diagObj.db.addVertex(subG.id, subG.title, 'group', undefined, subG.classes, subG.dir);
+ diagObj.db.addVertex(
+ subG.id,
+ { text: subG.title, type: subG.labelType },
+ 'group',
+ undefined,
+ subG.classes,
+ subG.dir
+ );
}
// Fetch the vertices/nodes and edges/links from the parsed graph definition
diff --git a/packages/mermaid/src/diagrams/flowchart/parser/flow-comments.spec.js b/packages/mermaid/src/diagrams/flowchart/parser/flow-comments.spec.js
index 7aeed304c..cb1e4a923 100644
--- a/packages/mermaid/src/diagrams/flowchart/parser/flow-comments.spec.js
+++ b/packages/mermaid/src/diagrams/flowchart/parser/flow-comments.spec.js
@@ -1,6 +1,7 @@
import flowDb from '../flowDb';
import flow from './flow';
import { setConfig } from '../../../config';
+import { cleanupComments } from '../../../diagram-api/comments';
setConfig({
securityLevel: 'strict',
@@ -13,7 +14,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle comments', function () {
- const res = flow.parser.parse('graph TD;\n%% Comment\n A-->B;');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n%% Comment\n A-->B;'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -28,7 +29,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle comments at the start', function () {
- const res = flow.parser.parse('%% Comment\ngraph TD;\n A-->B;');
+ const res = flow.parser.parse(cleanupComments('%% Comment\ngraph TD;\n A-->B;'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -43,7 +44,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle comments at the end', function () {
- const res = flow.parser.parse('graph TD;\n A-->B\n %% Comment at the end\n');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n A-->B\n %% Comment at the end\n'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -58,7 +59,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle comments at the end no trailing newline', function () {
- const res = flow.parser.parse('graph TD;\n A-->B\n%% Comment');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n A-->B\n%% Comment'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -73,7 +74,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle comments at the end many trailing newlines', function () {
- const res = flow.parser.parse('graph TD;\n A-->B\n%% Comment\n\n\n');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n A-->B\n%% Comment\n\n\n'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -88,7 +89,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle no trailing newlines', function () {
- const res = flow.parser.parse('graph TD;\n A-->B');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n A-->B'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -103,7 +104,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle many trailing newlines', function () {
- const res = flow.parser.parse('graph TD;\n A-->B\n\n');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n A-->B\n\n'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -118,7 +119,7 @@ describe('[Comments] when parsing', () => {
});
it('should handle a comment with blank rows in-between', function () {
- const res = flow.parser.parse('graph TD;\n\n\n %% Comment\n A-->B;');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n\n\n %% Comment\n A-->B;'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
@@ -134,7 +135,9 @@ describe('[Comments] when parsing', () => {
it('should handle a comment with mermaid flowchart code in them', function () {
const res = flow.parser.parse(
- 'graph TD;\n\n\n %% Test od>Odd shape]-->|Two line edge comment|ro;\n A-->B;'
+ cleanupComments(
+ 'graph TD;\n\n\n %% Test od>Odd shape]-->|Two line edge comment|ro;\n A-->B;'
+ )
);
const vert = flow.parser.yy.getVertices();
diff --git a/packages/mermaid/src/diagrams/flowchart/parser/flow-md-string.spec.js b/packages/mermaid/src/diagrams/flowchart/parser/flow-md-string.spec.js
new file mode 100644
index 000000000..005d257e0
--- /dev/null
+++ b/packages/mermaid/src/diagrams/flowchart/parser/flow-md-string.spec.js
@@ -0,0 +1,64 @@
+import flowDb from '../flowDb';
+import flow from './flow';
+import { setConfig } from '../../../config';
+
+setConfig({
+ securityLevel: 'strict',
+});
+
+describe('parsing a flow chart with markdown strings', function () {
+ beforeEach(function () {
+ flow.parser.yy = flowDb;
+ flow.parser.yy.clear();
+ });
+
+ it('mardown formatting in nodes and labels', function () {
+ const res = flow.parser.parse(`flowchart
+A["\`The cat in **the** hat\`"]-- "\`The *bat* in the chat\`" -->B["The dog in the hog"] -- "The rat in the mat" -->C;`);
+
+ const vert = flow.parser.yy.getVertices();
+ const edges = flow.parser.yy.getEdges();
+
+ expect(vert['A'].id).toBe('A');
+ expect(vert['A'].text).toBe('The cat in **the** hat');
+ expect(vert['A'].labelType).toBe('markdown');
+ expect(vert['B'].id).toBe('B');
+ expect(vert['B'].text).toBe('The dog in the hog');
+ expect(vert['B'].labelType).toBe('text');
+ expect(edges.length).toBe(2);
+ expect(edges[0].start).toBe('A');
+ expect(edges[0].end).toBe('B');
+ expect(edges[0].type).toBe('arrow_point');
+ expect(edges[0].text).toBe('The *bat* in the chat');
+ expect(edges[0].labelType).toBe('markdown');
+ expect(edges[1].start).toBe('B');
+ expect(edges[1].end).toBe('C');
+ expect(edges[1].type).toBe('arrow_point');
+ expect(edges[1].text).toBe('The rat in the mat');
+ expect(edges[1].labelType).toBe('text');
+ });
+ it('mardown formatting in subgraphs', function () {
+ const res = flow.parser.parse(`flowchart LR
+subgraph "One"
+ a("\`The **cat**
+ in the hat\`") -- "1o" --> b{{"\`The **dog** in the hog\`"}}
+end
+subgraph "\`**Two**\`"
+ c("\`The **cat**
+ in the hat\`") -- "\`1o **ipa**\`" --> d("The dog in the hog")
+end`);
+
+ const subgraphs = flow.parser.yy.getSubGraphs();
+ expect(subgraphs.length).toBe(2);
+ const subgraph = subgraphs[0];
+
+ expect(subgraph.nodes.length).toBe(2);
+ expect(subgraph.title).toBe('One');
+ expect(subgraph.labelType).toBe('text');
+
+ const subgraph2 = subgraphs[1];
+ expect(subgraph2.nodes.length).toBe(2);
+ expect(subgraph2.title).toBe('**Two**');
+ expect(subgraph2.labelType).toBe('markdown');
+ });
+});
diff --git a/packages/mermaid/src/diagrams/flowchart/parser/flow.jison b/packages/mermaid/src/diagrams/flowchart/parser/flow.jison
index e2dad5881..51427118f 100644
--- a/packages/mermaid/src/diagrams/flowchart/parser/flow.jison
+++ b/packages/mermaid/src/diagrams/flowchart/parser/flow.jison
@@ -7,6 +7,7 @@
/* lexical grammar */
%lex
%x string
+%x md_string
%x acc_title
%x acc_descr
%x acc_descr_multiline
@@ -27,8 +28,6 @@
":" { this.popState(); this.begin('arg_directive'); return ':'; }
\}\%\% { this.popState(); this.popState(); return 'close_directive'; }
((?:(?!\}\%\%).|\n)*) return 'arg_directive';
-\%\%(?!\{)[^\n]* /* skip comments */
-[^\}]\%\%[^\n]* /* skip comments */
accTitle\s*":"\s* { this.begin("acc_title");return 'acc_title'; }
(?!\n|;|#)*[^\n]* { this.popState(); return "acc_title_value"; }
accDescr\s*":"\s* { this.begin("acc_descr");return 'acc_descr'; }
@@ -37,6 +36,9 @@ accDescr\s*"{"\s* { this.begin("acc_descr_multili
[\}] { this.popState(); }
[^\}]* return "acc_descr_multiline_value";
// .*[^\n]* { return "acc_descr_line"}
+["][`] { this.begin("md_string");}
+[^`"]+ { return "MD_STR";}
+[`]["] { this.popState();}
["] this.begin("string");
["] this.popState();
[^"]* return "STR";
@@ -434,11 +436,13 @@ arrowText:
;
text: textToken
- {$$=$1;}
+ { $$={text:$1, type: 'text'};}
| text textToken
- {$$=$1+''+$2;}
+ { $$={text:$1.text+''+$2, type: $1.type};}
| STR
- {$$=$1;}
+ { $$={text: $1, type: 'text'};}
+ | MD_STR
+ { $$={text: $1, type: 'markdown'};}
;
diff --git a/packages/mermaid/src/diagrams/flowchart/parser/flow.spec.js b/packages/mermaid/src/diagrams/flowchart/parser/flow.spec.js
index 6b440da79..692e72f37 100644
--- a/packages/mermaid/src/diagrams/flowchart/parser/flow.spec.js
+++ b/packages/mermaid/src/diagrams/flowchart/parser/flow.spec.js
@@ -1,6 +1,7 @@
import flowDb from '../flowDb';
import flow from './flow';
import { setConfig } from '../../../config';
+import { cleanupComments } from '../../../diagram-api/comments';
setConfig({
securityLevel: 'strict',
@@ -13,7 +14,7 @@ describe('parsing a flow chart', function () {
});
it('should handle a trailing whitespaces after statements', function () {
- const res = flow.parser.parse('graph TD;\n\n\n %% Comment\n A-->B; \n B-->C;');
+ const res = flow.parser.parse(cleanupComments('graph TD;\n\n\n %% Comment\n A-->B; \n B-->C;'));
const vert = flow.parser.yy.getVertices();
const edges = flow.parser.yy.getEdges();
diff --git a/packages/mermaid/src/diagrams/flowchart/styles.ts b/packages/mermaid/src/diagrams/flowchart/styles.ts
index a89d33d3d..86ffcb7ed 100644
--- a/packages/mermaid/src/diagrams/flowchart/styles.ts
+++ b/packages/mermaid/src/diagrams/flowchart/styles.ts
@@ -41,6 +41,15 @@ const getStyles = (options: FlowChartStyleOptions) =>
stroke: ${options.nodeBorder};
stroke-width: 1px;
}
+ .flowchart-label text {
+ text-anchor: middle;
+ }
+ // .flowchart-label .text-outer-tspan {
+ // text-anchor: middle;
+ // }
+ // .flowchart-label .text-inner-tspan {
+ // text-anchor: start;
+ // }
.node .label {
text-align: center;
diff --git a/packages/mermaid/src/diagrams/gantt/ganttDb.js b/packages/mermaid/src/diagrams/gantt/ganttDb.js
index 475ee4de4..fa872027d 100644
--- a/packages/mermaid/src/diagrams/gantt/ganttDb.js
+++ b/packages/mermaid/src/diagrams/gantt/ganttDb.js
@@ -32,6 +32,7 @@ let links = {};
let sections = [];
let tasks = [];
let currentSection = '';
+let displayMode = '';
const tags = ['active', 'done', 'crit', 'milestone'];
let funs = [];
let inclusiveEndDates = false;
@@ -55,6 +56,7 @@ export const clear = function () {
rawTasks = [];
dateFormat = '';
axisFormat = '';
+ displayMode = '';
tickInterval = undefined;
todayMarker = '';
includes = [];
@@ -110,6 +112,14 @@ export const topAxisEnabled = function () {
return topAxis;
};
+export const setDisplayMode = function (txt) {
+ displayMode = txt;
+};
+
+export const getDisplayMode = function () {
+ return displayMode;
+};
+
export const getDateFormat = function () {
return dateFormat;
};
@@ -143,11 +153,11 @@ export const getSections = function () {
};
export const getTasks = function () {
- let allItemsPricessed = compileTasks();
+ let allItemsProcessed = compileTasks();
const maxDepth = 10;
let iterationCount = 0;
- while (!allItemsPricessed && iterationCount < maxDepth) {
- allItemsPricessed = compileTasks();
+ while (!allItemsProcessed && iterationCount < maxDepth) {
+ allItemsProcessed = compileTasks();
iterationCount++;
}
@@ -719,6 +729,8 @@ export default {
getAccTitle,
setDiagramTitle,
getDiagramTitle,
+ setDisplayMode,
+ getDisplayMode,
setAccDescription,
getAccDescription,
addSection,
diff --git a/packages/mermaid/src/diagrams/gantt/ganttDb.spec.ts b/packages/mermaid/src/diagrams/gantt/ganttDb.spec.ts
index d65f2fdfd..812cfd9b8 100644
--- a/packages/mermaid/src/diagrams/gantt/ganttDb.spec.ts
+++ b/packages/mermaid/src/diagrams/gantt/ganttDb.spec.ts
@@ -34,6 +34,7 @@ describe('when using the ganttDb', function () {
beforeEach(function () {
ganttDb.setDateFormat('YYYY-MM-DD');
ganttDb.enableInclusiveEndDates();
+ ganttDb.setDisplayMode('compact');
ganttDb.setTodayMarker('off');
ganttDb.setExcludes('weekends 2019-02-06,friday');
ganttDb.addSection('weekends skip test');
@@ -53,6 +54,7 @@ describe('when using the ganttDb', function () {
${'getExcludes'} | ${[]}
${'getSections'} | ${[]}
${'endDatesAreInclusive'} | ${false}
+ ${'getDisplayMode'} | ${''}
`)('should clear $fn', ({ fn, expected }) => {
expect(ganttDb[fn]()).toEqual(expected);
});
diff --git a/packages/mermaid/src/diagrams/gantt/ganttRenderer.js b/packages/mermaid/src/diagrams/gantt/ganttRenderer.js
index 7a012beb5..78bf2fcea 100644
--- a/packages/mermaid/src/diagrams/gantt/ganttRenderer.js
+++ b/packages/mermaid/src/diagrams/gantt/ganttRenderer.js
@@ -24,12 +24,43 @@ export const setConf = function () {
log.debug('Something is calling, setConf, remove the call');
};
+/**
+ * For this issue:
+ * https://github.com/mermaid-js/mermaid/issues/1618
+ *
+ * Finds the number of intersections between tasks that happen at any point in time.
+ * Used to figure out how many rows are needed to display the tasks when the display
+ * mode is set to 'compact'.
+ *
+ * @param tasks
+ * @param orderOffset
+ */
+const getMaxIntersections = (tasks, orderOffset) => {
+ let timeline = [...tasks].map(() => -Infinity);
+ let sorted = [...tasks].sort((a, b) => a.startTime - b.startTime || a.order - b.order);
+ let maxIntersections = 0;
+ for (const element of sorted) {
+ for (let j = 0; j < timeline.length; j++) {
+ if (element.startTime >= timeline[j]) {
+ timeline[j] = element.endTime;
+ element.order = j + orderOffset;
+ if (j > maxIntersections) {
+ maxIntersections = j;
+ }
+ break;
+ }
+ }
+ }
+
+ return maxIntersections;
+};
+
let w;
export const draw = function (text, id, version, diagObj) {
const conf = getConfig().gantt;
+
// diagObj.db.clear();
// parser.parse(text);
-
const securityLevel = getConfig().securityLevel;
// Handle root and Document for when rendering in sandbox mode
let sandboxElement;
@@ -56,7 +87,40 @@ export const draw = function (text, id, version, diagObj) {
const taskArray = diagObj.db.getTasks();
// Set height based on number of tasks
- const h = taskArray.length * (conf.barHeight + conf.barGap) + 2 * conf.topPadding;
+
+ let categories = [];
+
+ for (const element of taskArray) {
+ categories.push(element.type);
+ }
+
+ categories = checkUnique(categories);
+ const categoryHeights = {};
+
+ let h = 2 * conf.topPadding;
+ if (diagObj.db.getDisplayMode() === 'compact' || conf.displayMode === 'compact') {
+ const categoryElements = {};
+ for (const element of taskArray) {
+ if (categoryElements[element.section] === undefined) {
+ categoryElements[element.section] = [element];
+ } else {
+ categoryElements[element.section].push(element);
+ }
+ }
+
+ let intersections = 0;
+ for (const category of Object.keys(categoryElements)) {
+ const categoryHeight = getMaxIntersections(categoryElements[category], intersections) + 1;
+ intersections += categoryHeight;
+ h += categoryHeight * (conf.barHeight + conf.barGap);
+ categoryHeights[category] = categoryHeight;
+ }
+ } else {
+ h += taskArray.length * (conf.barHeight + conf.barGap);
+ for (const category of categories) {
+ categoryHeights[category] = taskArray.filter((task) => task.type === category).length;
+ }
+ }
// Set viewBox
elem.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
@@ -74,16 +138,6 @@ export const draw = function (text, id, version, diagObj) {
])
.rangeRound([0, w - conf.leftPadding - conf.rightPadding]);
- let categories = [];
-
- for (const element of taskArray) {
- categories.push(element.type);
- }
-
- const catsUnfiltered = categories; // for vert labels
-
- categories = checkUnique(categories);
-
/**
* @param a
* @param b
@@ -157,11 +211,15 @@ export const draw = function (text, id, version, diagObj) {
* @param w
*/
function drawRects(theArray, theGap, theTopPad, theSidePad, theBarHeight, theColorScale, w) {
+ // Get unique task orders. Required to draw the background rects when display mode is compact.
+ const uniqueTaskOrderIds = [...new Set(theArray.map((item) => item.order))];
+ const uniqueTasks = uniqueTaskOrderIds.map((id) => theArray.find((item) => item.order === id));
+
// Draw background rects covering the entire width of the graph, these form the section rows.
svg
.append('g')
.selectAll('rect')
- .data(theArray)
+ .data(uniqueTasks)
.enter()
.append('rect')
.attr('x', 0)
@@ -582,12 +640,9 @@ export const draw = function (text, id, version, diagObj) {
* @param theTopPad
*/
function vertLabels(theGap, theTopPad) {
- const numOccurances = [];
let prevGap = 0;
- for (const [i, category] of categories.entries()) {
- numOccurances[i] = [category, getCount(category, catsUnfiltered)];
- }
+ const numOccurances = Object.keys(categoryHeights).map((d) => [d, categoryHeights[d]]);
svg
.append('g') // without doing this, impossible to put grid lines behind text
@@ -625,7 +680,6 @@ export const draw = function (text, id, version, diagObj) {
}
})
.attr('font-size', conf.sectionFontSize)
- .attr('font-size', conf.sectionFontSize)
.attr('class', function (d) {
for (const [i, category] of categories.entries()) {
if (d[0] === category) {
@@ -682,31 +736,6 @@ export const draw = function (text, id, version, diagObj) {
}
return result;
}
-
- /**
- * From this stack exchange question:
- * http://stackoverflow.com/questions/14227981/count-how-many-strings-in-an-array-have-duplicates-in-the-same-array
- *
- * @param arr
- */
- function getCounts(arr) {
- let i = arr.length; // const to loop over
- const obj = {}; // obj to store results
- while (i) {
- obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
- }
- return obj;
- }
-
- /**
- * Get specific from everything
- *
- * @param word
- * @param arr
- */
- function getCount(word, arr) {
- return getCounts(arr)[word] || 0;
- }
};
export default {
diff --git a/packages/mermaid/src/diagrams/gantt/parser/gantt.jison b/packages/mermaid/src/diagrams/gantt/parser/gantt.jison
index 2223aa378..0eb45ec41 100644
--- a/packages/mermaid/src/diagrams/gantt/parser/gantt.jison
+++ b/packages/mermaid/src/diagrams/gantt/parser/gantt.jison
@@ -131,9 +131,10 @@ statement
| includes {yy.setIncludes($1.substr(9));$$=$1.substr(9);}
| todayMarker {yy.setTodayMarker($1.substr(12));$$=$1.substr(12);}
| title {yy.setDiagramTitle($1.substr(6));$$=$1.substr(6);}
- | acc_title acc_title_value { $$=$2.trim();yy.setAccTitle($$); }
- | acc_descr acc_descr_value { $$=$2.trim();yy.setAccDescription($$); }
- | acc_descr_multiline_value { $$=$1.trim();yy.setAccDescription($$); } | section {yy.addSection($1.substr(8));$$=$1.substr(8);}
+ | acc_title acc_title_value { $$=$2.trim();yy.setAccTitle($$); }
+ | acc_descr acc_descr_value { $$=$2.trim();yy.setAccDescription($$); }
+ | acc_descr_multiline_value { $$=$1.trim();yy.setAccDescription($$); }
+ | section { yy.addSection($1.substr(8));$$=$1.substr(8); }
| clickStatement
| taskTxt taskData {yy.addTask($1,$2);$$='task';}
| directive
diff --git a/packages/mermaid/src/diagrams/mindmap/mindmapRenderer.js b/packages/mermaid/src/diagrams/mindmap/mindmapRenderer.js
index c5b5fede1..a2a4def59 100644
--- a/packages/mermaid/src/diagrams/mindmap/mindmapRenderer.js
+++ b/packages/mermaid/src/diagrams/mindmap/mindmapRenderer.js
@@ -167,12 +167,15 @@ function positionNodes(cy) {
export const draw = async (text, id, version, diagObj) => {
const conf = getConfig();
+ // console.log('Config: ', conf);
+ conf.htmlLabels = false;
+
// This is done only for throwing the error if the text is not valid.
diagObj.db.clear();
// Parse the graph definition
diagObj.parser.parse(text);
- log.debug('Renering info diagram\n' + text);
+ log.debug('Renering mindmap diagram\n' + text, diagObj);
const securityLevel = getConfig().securityLevel;
// Handle root and Document for when rendering in sandbox mode
diff --git a/packages/mermaid/src/diagrams/mindmap/parser/mindmap.jison b/packages/mermaid/src/diagrams/mindmap/parser/mindmap.jison
index d2f6bbf1a..84a6191cf 100644
--- a/packages/mermaid/src/diagrams/mindmap/parser/mindmap.jison
+++ b/packages/mermaid/src/diagrams/mindmap/parser/mindmap.jison
@@ -12,6 +12,7 @@
%}
%x NODE
%x NSTR
+%x NSTR2
%x ICON
%x CLASS
@@ -41,6 +42,9 @@
// !(-\() return 'NODE_ID';
[^\(\[\n\-\)\{\}]+ return 'NODE_ID';
<> return 'EOF';
+["][`] { this.begin("NSTR2");}
+[^`"]+ { return "NODE_DESCR";}
+[`]["] { this.popState();}
["] { yy.getLogger().trace('Starting NSTR');this.begin("NSTR");}
[^"]+ { yy.getLogger().trace('description:', yytext); return "NODE_DESCR";}
["] {this.popState();}
diff --git a/packages/mermaid/src/diagrams/mindmap/styles.js b/packages/mermaid/src/diagrams/mindmap/styles.js
index 986a04514..863522fdf 100644
--- a/packages/mermaid/src/diagrams/mindmap/styles.js
+++ b/packages/mermaid/src/diagrams/mindmap/styles.js
@@ -70,5 +70,12 @@ const getStyles = (options) =>
.edge {
fill: none;
}
+ .mindmap-node-label {
+ dy: 1em;
+ alignment-baseline: middle;
+ text-anchor: middle;
+ dominant-baseline: middle;
+ text-align: center;
+ }
`;
export default getStyles;
diff --git a/packages/mermaid/src/diagrams/mindmap/svgDraw.js b/packages/mermaid/src/diagrams/mindmap/svgDraw.js
index 2b1aa021e..8b58c11a3 100644
--- a/packages/mermaid/src/diagrams/mindmap/svgDraw.js
+++ b/packages/mermaid/src/diagrams/mindmap/svgDraw.js
@@ -1,5 +1,6 @@
import { select } from 'd3';
import * as db from './mindmapDb';
+import { createText } from '../../rendering-util/createText';
const MAX_SECTIONS = 12;
/**
@@ -11,7 +12,7 @@ function wrap(text, width) {
var text = select(this),
words = text
.text()
- .split(/(\s+| )/)
+ .split(/(\s+| )/)
.reverse(),
word,
line = [],
@@ -28,10 +29,10 @@ function wrap(text, width) {
word = words[words.length - 1 - j];
line.push(word);
tspan.text(line.join(' ').trim());
- if (tspan.node().getComputedTextLength() > width || word === ' ') {
+ if (tspan.node().getComputedTextLength() > width || word === ' ') {
line.pop();
tspan.text(line.join(' ').trim());
- if (word === ' ') {
+ if (word === ' ') {
line = [''];
} else {
line = [word];
@@ -203,6 +204,7 @@ const roundedRectBkg = function (elem, node) {
* @returns {number} The height nodes dom element
*/
export const drawNode = function (elem, node, fullSection, conf) {
+ const htmlLabels = conf.htmlLabels;
const section = fullSection % (MAX_SECTIONS - 1);
const nodeElem = elem.append('g');
node.section = section;
@@ -215,15 +217,21 @@ export const drawNode = function (elem, node, fullSection, conf) {
// Create the wrapped text element
const textElem = nodeElem.append('g');
- const txt = textElem
- .append('text')
- .text(node.descr)
- .attr('dy', '1em')
- .attr('alignment-baseline', 'middle')
- .attr('dominant-baseline', 'middle')
- .attr('text-anchor', 'middle')
- .call(wrap, node.width);
- const bbox = txt.node().getBBox();
+ const newEl = createText(textElem, node.descr, {
+ useHtmlLabels: htmlLabels,
+ width: node.width,
+ classes: 'mindmap-node-label',
+ });
+
+ if (!htmlLabels) {
+ textElem
+ .attr('dy', '1em')
+ .attr('alignment-baseline', 'middle')
+ .attr('dominant-baseline', 'middle')
+ .attr('text-anchor', 'middle');
+ }
+ // .call(wrap, node.width);
+ const bbox = textElem.node().getBBox();
const fontSize = conf.fontSize.replace ? conf.fontSize.replace('px', '') : conf.fontSize;
node.height = bbox.height + fontSize * 1.1 * 0.5 + node.padding;
node.width = bbox.width + 2 * node.padding;
@@ -267,7 +275,16 @@ export const drawNode = function (elem, node, fullSection, conf) {
);
}
} else {
- textElem.attr('transform', 'translate(' + node.width / 2 + ', ' + node.padding / 2 + ')');
+ if (!htmlLabels) {
+ const dx = node.width / 2;
+ const dy = node.padding / 2;
+ textElem.attr('transform', 'translate(' + dx + ', ' + dy + ')');
+ // textElem.attr('transform', 'translate(' + node.width / 2 + ', ' + node.padding / 2 + ')');
+ } else {
+ const dx = (node.width - bbox.width) / 2;
+ const dy = (node.height - bbox.height) / 2;
+ textElem.attr('transform', 'translate(' + dx + ', ' + dy + ')');
+ }
}
switch (node.type) {
diff --git a/packages/mermaid/src/docs/config/Tutorials.md b/packages/mermaid/src/docs/config/Tutorials.md
index e07635641..875f15245 100644
--- a/packages/mermaid/src/docs/config/Tutorials.md
+++ b/packages/mermaid/src/docs/config/Tutorials.md
@@ -1,6 +1,6 @@
# Tutorials
-This is list of publicly available Tutorials for using Mermaid.JS . This is intended as a basic introduction for the use of the Live Editor for generating diagrams, and deploying Mermaid.JS through HTML.
+This is a list of publicly available Tutorials for using Mermaid.JS and is intended as a basic introduction for the use of the Live Editor for generating diagrams, and deploying Mermaid.JS through HTML.
**Note that these tutorials might display an older interface, but the usage of the live-editor will largely be the same.**
diff --git a/packages/mermaid/src/docs/config/usage.md b/packages/mermaid/src/docs/config/usage.md
index c74023952..211a06af7 100644
--- a/packages/mermaid/src/docs/config/usage.md
+++ b/packages/mermaid/src/docs/config/usage.md
@@ -244,6 +244,23 @@ The example below show an outline of how this could be used. The example just lo
```
+To determine the type of diagram present in a given text, you can utilize the `mermaid.detectType` function, as demonstrated in the example below.
+
+```html
+
+```
+
### Binding events
Sometimes the generated graph also has defined interactions like tooltip and click events. When using the API one must
diff --git a/packages/mermaid/src/docs/ecosystem/integrations.md b/packages/mermaid/src/docs/ecosystem/integrations.md
index 6550d5ef7..ac8f2659b 100644
--- a/packages/mermaid/src/docs/ecosystem/integrations.md
+++ b/packages/mermaid/src/docs/ecosystem/integrations.md
@@ -83,7 +83,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [FosWiki](https://foswiki.org)
- [Mermaid Plugin](https://foswiki.org/Extensions/MermaidPlugin)
- [DokuWiki](https://dokuwiki.org)
- - [Flowcharts](https://www.dokuwiki.org/plugin:flowcharts?s[]=mermaid)
+ - [Mermaid Plugin](https://www.dokuwiki.org/plugin:mermaid)
- [ComboStrap](https://combostrap.com/mermaid)
- [TiddlyWiki](https://tiddlywiki.com/)
- [mermaid-tw5: full js library](https://github.com/efurlanm/mermaid-tw5)
@@ -144,7 +144,7 @@ They also serve as proof of concept, for the variety of things that can be built
- [remark-mermaid](https://github.com/temando/remark-mermaid)
- [jSDoc](https://jsdoc.app/)
- [jsdoc-mermaid](https://github.com/Jellyvision/jsdoc-mermaid)
-- [MkDocs](https://mkdocs.org)
+- [MkDocs](https://www.mkdocs.org)
- [mkdocs-mermaid2-plugin](https://github.com/fralau/mkdocs-mermaid2-plugin)
- [mkdocs-material](https://github.com/squidfunk/mkdocs-material), check the [docs](https://squidfunk.github.io/mkdocs-material/reference/diagrams/)
- [Type Doc](https://typedoc.org/)
diff --git a/packages/mermaid/src/docs/syntax/flowchart.md b/packages/mermaid/src/docs/syntax/flowchart.md
index 6997ca088..8e73f597b 100644
--- a/packages/mermaid/src/docs/syntax/flowchart.md
+++ b/packages/mermaid/src/docs/syntax/flowchart.md
@@ -122,16 +122,7 @@ flowchart LR
### A hexagon node
-Code:
-
-```mmd
-flowchart LR
- id1{{This is the text in the box}}
-```
-
-Render:
-
-```mermaid
+```mermaid-example
flowchart LR
id1{{This is the text in the box}}
```
diff --git a/packages/mermaid/src/docs/syntax/gantt.md b/packages/mermaid/src/docs/syntax/gantt.md
index 7c446d91f..422358d3e 100644
--- a/packages/mermaid/src/docs/syntax/gantt.md
+++ b/packages/mermaid/src/docs/syntax/gantt.md
@@ -189,9 +189,27 @@ The pattern is:
More info in: [https://github.com/d3/d3-time#interval_every](https://github.com/d3/d3-time#interval_every)
+## Output in compact mode
+
+The compact mode allows you to display multiple tasks in the same row. Compact mode can be enabled for a gantt chart by setting the display mode of the graph via preceeding YAML settings.
+
+```mmd
+---
+displayMode: compact
+---
+gantt
+ title A Gantt Diagram
+ dateFormat YYYY-MM-DD
+
+ section Section
+ A task :a1, 2014-01-01, 30d
+ Another task :a2, 2014-01-20, 25d
+ Another one :a3, 2014-02-10, 20d
+```
+
## Comments
-Comments can be entered within a gantt chart, which will be ignored by the parser. Comments need to be on their own line and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax
+Comments can be entered within a gantt chart, which will be ignored by the parser. Comments need to be on their own line and must be prefaced with `%%` (double percent signs). Any text after the start of the comment to the next newline will be treated as a comment, including any diagram syntax.
```mmd
gantt
@@ -356,3 +374,24 @@ Beginner's tipโa full example using interactive links in an html context: