Compare commits

...

269 Commits

Author SHA1 Message Date
darshanr0107
180dc7bdff Merge branch 'knsv/mindmap-refactoring' of https://github.com/mermaid-js/mermaid into knsv/mindmap-refactoring 2025-08-14 18:21:38 +05:30
darshanr0107
cc9581842d fix: increase the radius and remove border for rounded rect
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-14 18:21:17 +05:30
autofix-ci[bot]
d782e4bb17 [autofix.ci] apply automated fixes 2025-08-14 11:07:17 +00:00
darshanr0107
ba9ad9385b fix: shape for default mindmap node
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-14 16:31:48 +05:30
darshanr0107
91edfa40f7 fix: organize imports and remove render.d.ts file
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-14 13:20:27 +05:30
darshanr0107
c8b00bb929 fix: revert the curve setting for edges
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-14 13:13:48 +05:30
darshanr0107
57eadbf6af docs: update mindmaps docs and move instructions under configuration and deployment
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-13 19:31:10 +05:30
darshanr0107
a906adce26 Merge branch 'develop' into knsv/mindmap-refactoring 2025-08-13 14:07:02 +05:30
darshanr0107
a6d26ef6c3 fix: remove cose-bilkent algorithm from tiny
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-12 18:38:22 +05:30
darshanr0107
2b3f94eb7d docs: update mindmap docs to specify tidy tree layout
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-12 16:35:43 +05:30
Sidharth Vinod
bf3ca9d1ef Merge pull request #6332 from ajuckel/ajuckel/issue-6171-equals-in-sequence-labels
fix: Allow equals sign in sequenceDiagram labels
2025-08-11 14:36:42 +00:00
darshanr0107
dd36046e23 docs: update tidy-tree Readme
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-11 14:22:08 +05:30
darshanr0107
1507435e15 chore: remove unwanted logs
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-11 13:51:10 +05:30
Shubham P
e53c17a012 Merge pull request #6841 from mermaid-js/renovate/peter-evans-create-pull-request-digest
chore(deps): update peter-evans/create-pull-request digest to 1310d7d
2025-08-11 07:24:30 +00:00
renovate[bot]
bb2d6973ba chore(deps): update peter-evans/create-pull-request digest to 1310d7d 2025-08-11 02:12:30 +00:00
Sidharth Vinod
9322771b5c Merge pull request #6839 from aloisklink/refactor/remove-unnecessary-check-in-DOMPurify-hooks
refactor: remove unnecessary `Element` check since DOMPurify 3.2.2
2025-08-08 13:09:49 +00:00
Sidharth Vinod
2fe3063bf5 Merge pull request #6838 from saurabhg772244/saurabh/fix-node-border-style-for-hand-drawn-shapes
Saurabh/fix-node-border-style-for-hand-drawn-shapes
2025-08-08 13:02:38 +00:00
Shubham P
4e55a45b1b Merge branch 'develop' into saurabh/fix-node-border-style-for-hand-drawn-shapes 2025-08-08 16:57:55 +05:30
Knut Sveidqvist
3d319824a6 Merge pull request #6683 from mermaid-js/6576-state-diagram-label-position
6576: State diagram edge label position
2025-08-08 10:26:18 +00:00
Knut Sveidqvist
aa5d443a46 Merge pull request #6693 from mermaid-js/6649-gantt-chart-dateformat
6649: gantt chart date format issue
2025-08-08 10:09:59 +00:00
Knut Sveidqvist
356da0b4d7 Merge branch 'develop' into 6576-state-diagram-label-position 2025-08-08 12:01:34 +02:00
Knut Sveidqvist
22530a8bdf Merge pull request #6653 from mermaid-js/4459-remove-beta-suffix
#4459: Remove beta suffix
2025-08-08 09:55:06 +00:00
Knut Sveidqvist
e6574ef40c Merge pull request #6651 from mermaid-js/6584-piechart-zero-negative-values
6584: prevent pie chart crash on zero or negative values
2025-08-08 09:52:16 +00:00
Knut Sveidqvist
c4eb526162 Merge pull request #6734 from mermaid-js/6730-gantt-excludes-datetime-format
6730: Fix excluded dates ignored in YYYY-MM-DD HH:mm:ss date format in gantt diagram
2025-08-08 09:33:56 +00:00
darshanr0107
68c01b76bf fix: failing unit tests
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-08 14:32:25 +05:30
saurabhg772244
4d62d59632 added changeset 2025-08-08 14:19:03 +05:30
saurabhg772244
5af489d8dd Fix border style for hand drawn shapes 2025-08-08 14:17:09 +05:30
darshanr0107
28717e108d chore: remove duplicate code and throw generic error if nodes are not present
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-08 13:52:22 +05:30
darshanr0107
688d9b383d chore: update changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-08 13:16:46 +05:30
Knut Sveidqvist
074701e316 Merge pull request #6833 from mermaid-js/6611-block-diagram-arrow-direction
6611: Block diagram shows incorrect arrow direction
2025-08-08 07:24:02 +00:00
darshanr0107
e68424d748 fix: updated changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-08 12:45:16 +05:30
Sidharth Vinod
4b31361506 Merge pull request #6733 from mermaid-js/fix-connection-gaps-in-flowchart-shapes
Fix: Connection gaps in flowchart shapes
2025-08-07 14:36:34 +00:00
darshanr0107
204a9a338f fix: fix failing sequence diagram
unit test

on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-07 18:54:45 +05:30
darshanr0107
6a6a39ff33 chore: remove disallowed path and regenerate dependencies
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-07 18:00:10 +05:30
autofix-ci[bot]
b296db9a33 [autofix.ci] apply automated fixes 2025-08-07 11:39:39 +00:00
darshanr0107
01ce84d8ee fix: lint and build issues
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-07 17:04:01 +05:30
darshanr0107
f48e663d4c Merge branch 'develop' into knsv/mindmap-refactoring 2025-08-07 13:58:19 +05:30
darshanr0107
a4aa2bd355 fix: failing test case caused by invalid expected value
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-07 13:52:41 +05:30
darshanr0107
b51b9d50c2 fix: failing e2e for mindmaps
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-07 13:10:28 +05:30
darshanr0107
165ffefad5 chore: remove unnecessary test case
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-07 12:09:49 +05:30
darshanr0107
9258b2933b add changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-06 20:05:35 +05:30
darshanr0107
f5445b266e fix: incorrect arrow direction in block direction
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-06 20:01:28 +05:30
Alois Klink
7a1530d911 refactor: remove unnecessary Element check
[DOMPurify v3.2.2][1] narrowed down the types of these hooks so that
these are known to have the `Element` type, which means checking the
type of these at runtime is unnecessary.

[1]: https://github.com/cure53/DOMPurify/releases/tag/3.2.2

See: fe3cffbb67
See: 4cdfd1ffef
2025-08-06 22:30:09 +08:00
darshanr0107
b61780f735 fix: failing unit tests
Some optional description over here if you need to add more info

on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-06 16:35:54 +05:30
Shubham P
d93d9a521d Merge pull request #6820 from kriss-u/fix/6815_escape_namespace_class_diagram
fix: add classLiteral to the language for class diagram namespace
2025-08-06 08:12:54 +00:00
Krishna Upadhyay
c99bce6bab fix: add classLiteral to the language for class diagram namespace 2025-08-05 12:15:44 -05:00
darshanr0107
074f18dfb8 fix: build issues
Some optional description over here if you need to add more info

on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-05 20:22:17 +05:30
omkarht
b451c66d7c chore: added test case for updated shapes
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-05 19:43:34 +05:30
darshanr0107
d7308b0f43 fix: build issues for cose - bilkent
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-05 19:16:02 +05:30
omkarht
1dd11705d9 fix: updated changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-05 17:40:18 +05:30
darshanr0107
2f1860386a fix: build for tidy-tree layout
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-05 15:35:42 +05:30
darshanr0107
f0bca7da55 Merge branch 'develop' into knsv/mindmap-refactoring 2025-08-04 20:07:15 +05:30
Sidharth Vinod
6fcdf5bfcc Merge pull request #6807 from mermaid-js/refactor/layout-algorithms-to-packages
Extract tidy-tree layout into separate package
2025-08-04 19:44:55 +05:30
darshanr0107
e2ce0450c1 fix:separate out tidy-tree and elk from deafult loaders
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-04 19:40:34 +05:30
omkarht
29de40478f Merge branch 'develop' into fix-connection-gaps-in-flowchart-shapes 2025-08-04 17:06:03 +05:30
darshanr0107
c95c64139d Decouple layout loaders from core package, register tidy-tree and elk loaders separately
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-04 14:25:08 +05:30
Shubham P
4ab98c2ec7 Merge pull request #6813 from mermaid-js/renovate/peter-evans-create-pull-request-digest
chore(deps): update peter-evans/create-pull-request digest to 07cbaeb
2025-08-04 07:36:23 +00:00
renovate[bot]
aeb51e56e2 chore(deps): update peter-evans/create-pull-request digest to 07cbaeb 2025-08-04 03:11:32 +00:00
shubhamparikh2704
a7f12f1baa fix: fixed workflow
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-01 16:28:30 +05:30
darshanr0107
2a8653de2b move tidy-tree-layout to separate package
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-01 14:05:28 +05:30
darshanr0107
a92c3bb251 extract tidy-tree layout into separate package
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-08-01 13:36:35 +05:30
darshanr0107
3677abe9e5 Merge branch 'develop' into knsv/mindmap-refactoring 2025-07-30 19:53:22 +05:30
Shubham P
ddcd8a5e73 Merge pull request #6803 from mermaid-js/6774-update-db-class-architecture-diagram
6774: update architecture diagram to reflect new class-based DB structure
2025-07-30 13:37:32 +00:00
Shubham P
e464d080ef Merge pull request #6804 from mermaid-js/6691-update-packet-diagram-class-based-db
6691: update packet diagram to use new class-based DB approach
2025-07-30 13:36:43 +00:00
Sidharth Vinod
1a9b94ca2d Merge pull request #6688 from zarhasan/patch-1
Update integrations-community.md
2025-07-30 13:32:11 +00:00
darshanr0107
95847ad236 clean up unused files, types, and commented code; remove unnecessary d3 mock test
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-30 18:48:23 +05:30
darshanr0107
e0152fb873 fix: resolve duplicate keys in lockfile and fix test failures
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-30 15:33:03 +05:30
Shubham P
e4b33a1d99 Merge pull request #6796 from HashanCP/bug/6795_fix-flowchart-elk-detector
make flowchart elk detector regex match less greedy
2025-07-30 09:41:37 +00:00
darshanr0107
2298b96d8e Merge branch 'develop' into knsv/mindmap-refactoring 2025-07-30 15:07:32 +05:30
darshanr0107
5db83365b6 Merge branch 'develop' of https://github.com/mermaid-js/mermaid into knsv/mindmap-refactoring 2025-07-30 14:59:39 +05:30
omkarht
e27a9da61d Update .changeset/vast-buses-see.md
Co-authored-by: Sidharth Vinod <github@sidharth.dev>
2025-07-30 13:18:44 +05:30
omkarht
03cf10003f fix: modified changeset to patch
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-30 13:16:49 +05:30
omkarht
8e31fdb611 Merge branch 'develop' into 6774-update-db-class-architecture-diagram 2025-07-29 17:01:12 +05:30
omkarht
5dd748148f fix: refactored code
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-29 16:59:02 +05:30
omkarht
895f9d43ff 6691: update packet diagram to use new class-based DB approach
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-29 16:55:04 +05:30
shubham-mermaid
fb890a2be8 Merge branch 'develop' into bug/6795_fix-flowchart-elk-detector 2025-07-29 16:09:29 +05:30
shubham-mermaid
5986189a52 Merge pull request #6801 from mermaid-js/sidv/fixID
fix: Casing of ID in requirement diagram
2025-07-29 10:16:51 +00:00
omkarht
1988dfc956 Merge branch 'develop' into 6774-update-db-class-architecture-diagram 2025-07-29 15:41:46 +05:30
omkarht
e48b0ba61d chore: added changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-29 15:41:21 +05:30
omkarht
1a4b8662cf 6774: update architecture diagram to reflect new class-based DB structure
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-29 15:21:34 +05:30
shubham-mermaid
6083463c8e Merge pull request #6799 from mermaid-js/renovate/patch-eslint
chore(deps): update eslint (patch)
2025-07-29 09:49:28 +00:00
shubham-mermaid
1a14e331ea Merge pull request #6739 from kriss-u/bug/6681_td_tb_behavior
fix: trim the direction string in flowchart
2025-07-29 09:43:32 +00:00
shubham-mermaid
ebb6680eba Merge pull request #6792 from mermaid-js/prashants/mermaid-diagrams-flowchart-mindmap-mermaidAPI
chore: Mermaid diagrams flowchart mindmap mermaid api
2025-07-29 09:42:41 +00:00
shubham-mermaid
6d1d46f88a Merge branch 'develop' into bug/6795_fix-flowchart-elk-detector 2025-07-29 15:11:56 +05:30
shubham-mermaid
435790f931 Merge pull request #6798 from ZenUml/fix/zenuml-rendering
Fix: zenuml rendering
2025-07-29 09:41:00 +00:00
shubham-mermaid
ffe9c1090e Merge branch 'develop' into sidv/fixID 2025-07-29 15:09:56 +05:30
renovate[bot]
a476e99d4c chore(deps): update eslint 2025-07-29 08:41:36 +00:00
Alois Klink
0cc0b63e52 Merge pull request #6702 from qraqras/bug/6633_remove-unexpected-spaces-in-block-diagram
Fix: Remove unexpected spaces in Block Diagram
2025-07-29 08:29:22 +00:00
Prashant-7718
694844050a removed changeset 2025-07-29 13:34:18 +05:30
autofix-ci[bot]
1be1620000 [autofix.ci] apply automated fixes 2025-07-29 07:45:04 +00:00
shubham-mermaid
c36cd05c45 Create light-flowers-judge.md 2025-07-29 13:10:10 +05:30
darshanr0107
341a81a113 add sample mind maps rendered with all layouts for baseline validation
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-29 12:51:39 +05:30
darshanr0107
8a62b4cace fix: apply intersection logic for edges in tidy-tree layout
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-29 12:21:42 +05:30
Alois Klink
b7a591b8d3 docs(block): add clarifying comment for overflow
This line is a bit confusing to me, so I thought I should clarify it!

See: 939da082b2
2025-07-29 15:45:53 +09:00
Alois Klink
8bb29fc879 docs(block): add changeset for overflow bug
Add a changeset that explains that overflowing blocks no longer
create an empty line in block diagrams or cause bugs in later lines.

Technically, this is a breaking change since it can change the layout of
block diagrams, but this diagram is still in `-beta` and they all will
still render correctly.
2025-07-29 15:40:36 +09:00
Alois Klink
e073c80019 test(e2e): test block column overflowing
Add a test-case for 939da082b (Fix 6633, 2025-06-28), that checks
whether overflowing blocks render correctly.
2025-07-29 15:27:10 +09:00
Sidharth Vinod
01aaef39b4 docs: Add changeset 2025-07-29 11:31:28 +05:30
Sidharth Vinod
3d640fc620 fix: Casing of ID to match https://www.britannica.com/dictionary/ID 2025-07-29 11:30:11 +05:30
MrCoder
724197c910 chore: add missing newline at end of README.md 2025-07-27 21:25:46 +10:00
MrCoder
6180c5f2ff chore: add TypeScript declaration for ZenUml module 2025-07-27 21:12:08 +10:00
MrCoder
a9f7a94ae3 fix: remove TypeScript error suppression for ZenUml instantiation 2025-07-27 21:08:00 +10:00
MrCoder
3ffe9618ae chore: added changeset. 2025-07-27 21:05:49 +10:00
MrCoder
da539c1fa1 chore: Upgrade @zenuml/core to version 3.35.2 2025-07-27 20:55:58 +10:00
Hashan Chandika
5e8aa2dccf add unit tests for coverage #6795 2025-07-27 15:21:46 +05:30
Hashan Chandika
ac04172cf8 add tests for #6795 2025-07-27 14:53:28 +05:30
Hashan Chandika
cf5b4b89a8 make regex match less greedy 2025-07-27 13:51:26 +05:30
MrCoder
1c269e0432 Convert mermaid-zenuml README from symlink to regular file
Changed packages/mermaid-zenuml/README.md from a symbolic link pointing to ../mermaid/src/docs/syntax/zenuml.md to a standalone README file with comprehensive documentation for the @mermaid-js/mermaid-zenuml package.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-25 07:52:32 +10:00
darshanr0107
ccafc20917 add support for cloud and bang shape
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-24 18:07:25 +05:30
Prashant-7718
999b836508 updated changeset 2025-07-24 14:46:34 +05:30
Prashant-7718
326e4e3693 added mermaid files for documentation 2025-07-24 14:16:18 +05:30
autofix-ci[bot]
9c92da487f [autofix.ci] apply automated fixes 2025-07-24 08:39:03 +00:00
Prashant-7718
10752f1357 added mermaid files 2025-07-24 14:03:50 +05:30
autofix-ci[bot]
1a80854242 [autofix.ci] apply automated fixes 2025-07-24 07:30:35 +00:00
Prashant-7718
fc9c600a31 Merge branch 'develop' of https://github.com/mermaid-js/mermaid into prashants/mermaid-diagrams-flowchart-mindmap-mermaidAPI 2025-07-24 12:52:47 +05:30
Prashant-7718
da8ce0b93e chore: removed unwanted files 2025-07-24 12:49:08 +05:30
Prashant-7718
00a79353fc changeset added 2025-07-24 12:40:39 +05:30
shubham-mermaid
1ceeca1ef1 Merge pull request #6782 from mermaid-js/renovate/peter-evans-create-pull-request-digest
chore(deps): update peter-evans/create-pull-request digest to 2e50522
2025-07-24 06:21:23 +00:00
shubham-mermaid
94890390ef Merge pull request #6783 from mermaid-js/renovate/patch-eslint
chore(deps): update eslint (patch)
2025-07-24 06:20:37 +00:00
darshanr0107
d5cb4eaa59 add support for elk layout in mindmap
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-23 20:11:38 +05:30
Prashant-7718
adfeb093cb chore: mermaid diagrams for flowchart, mindmap and mermaidAPI files 2025-07-23 18:55:25 +05:30
darshanr0107
425fb7ee33 fix: handle undefined edge list in insertEdge to prevent runtime error
Fixes a runtime error in cose-bilkent layout caused by insertEdge calling .filter() on an undefined edge list. Now defaults to an empty array to prevent the crash.

on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-23 17:18:48 +05:30
renovate[bot]
366d217928 chore(deps): update eslint 2025-07-23 09:15:14 +00:00
renovate[bot]
b94f1336ab chore(deps): update peter-evans/create-pull-request digest to 2e50522 2025-07-23 09:14:38 +00:00
shubham-mermaid
020c6d66e0 Merge pull request #6744 from SpecularAura/feature/6617_per-link-style
6617: Support Per-Link Curve Styling in Flowcharts
2025-07-23 09:00:42 +00:00
darshanr0107
cd6f8e5a24 tidy-tree as the default layout for mindmaps
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-21 18:41:18 +05:30
Sidharth Vinod
cfc2551bdc Merge pull request #6778 from lcnittl/docs/NA_update-mime-type-iana-status
Update MIME type IANA status
2025-07-21 00:46:51 +05:30
autofix-ci[bot]
000308c8f5 [autofix.ci] apply automated fixes 2025-07-18 21:44:56 +00:00
SpecularAura
6039a8b930 Merge remote-tracking branch 'origin/feature/6617_per-link-style' into feature/6617_per-link-style 2025-07-18 21:38:04 +00:00
SpecularAura
cd282f2245 Added Documentation for the per link styling in syntax/flowchat 2025-07-18 21:19:06 +00:00
autofix-ci[bot]
a27d90fe9c [autofix.ci] apply automated fixes 2025-07-18 13:05:27 +00:00
Christian Knittl-Frank
64bf34b9ab Update MIME type IANA status
The mermaid media type has been recognized by IANA on 2023-09-18
2025-07-18 13:54:16 +01:00
Alois Klink
9faf2f9fb2 Merge pull request #6717 from mermaid-js/6633-Stacking-blocks-renders-unexpected-space
6633: Log warning for blocks exceeding column width
2025-07-18 07:31:17 +00:00
darshanr0107
f683b03645 Merge branch '6633-Stacking-blocks-renders-unexpected-space' of https://github.com/mermaid-js/mermaid into 6633-Stacking-blocks-renders-unexpected-space 2025-07-18 12:50:36 +05:30
darshanr0107
9cef40d164 update changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-18 12:50:26 +05:30
SpecularAura
04612e078a Removed directive syntax from the documentation 2025-07-17 21:12:51 +00:00
SpecularAura
af585bdcc7 Added a functioning visual test for per link curve styling 2025-07-17 21:09:22 +00:00
autofix-ci[bot]
37bfa2aa75 [autofix.ci] apply automated fixes 2025-07-17 14:46:30 +00:00
darshanr0107
54640ce476 resolved PR comments
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-17 20:11:21 +05:30
shubham-mermaid
47b4c56b2b Merge pull request #6772 from hustcc/patch-2
chore: update to add mcp-mermaid
2025-07-17 07:28:14 +00:00
Sidharth Vinod
6b1b0bf151 chore: Add symlink 2025-07-17 12:45:46 +05:30
Sidharth Vinod
7ba332ad4a docs: Move changelog content 2025-07-17 12:45:03 +05:30
autofix-ci[bot]
412d2a09d3 [autofix.ci] apply automated fixes 2025-07-17 01:41:47 +00:00
hustcc
7886fed8b2 chore: update to add mcp-mermaid 2025-07-17 09:36:16 +08:00
Sidharth Vinod
af3d5b6528 docs: Add README for examples 2025-07-16 20:11:38 +05:30
Sidharth Vinod
404286a90d Merge branch 'master' into develop
* master:
  Version Packages
2025-07-16 19:53:10 +05:30
Sidharth Vinod
827a9af790 chore: Add repo to examples package 2025-07-16 19:52:52 +05:30
darshanr0107
a14cd0e2a1 fix: update test case
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-16 18:47:45 +05:30
darshanr0107
0823e08a54 Merge branch 'develop' into 6584-piechart-zero-negative-values 2025-07-16 18:05:06 +05:30
Ashish Jain
95733b6295 Merge pull request #6762 from mermaid-js/changeset-release/master
Version Packages
2025-07-16 14:05:42 +02:00
darshanr0107
5cafe241d0 Merge branch 'develop' into 6649-gantt-chart-dateformat 2025-07-16 17:29:52 +05:30
darshanr0107
c847817a54 Merge branch 'develop' into 6730-gantt-excludes-datetime-format 2025-07-16 17:29:37 +05:30
darshanr0107
8b86d617e7 Merge branch 'develop' into 6633-Stacking-blocks-renders-unexpected-space 2025-07-16 17:29:09 +05:30
darshanr0107
3ab0961bdc fix: PR comment and updated test case
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-16 17:27:08 +05:30
darshanr0107
cc2112c7aa fix: updated test case
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-16 15:25:16 +05:30
omkarht
0892870b5d Merge branch 'develop' into fix-connection-gaps-in-flowchart-shapes 2025-07-16 14:55:22 +05:30
omkarht
500f90a105 Merge branch 'fix-connection-gaps-in-flowchart-shapes' of https://github.com/mermaid-js/mermaid into fix-connection-gaps-in-flowchart-shapes 2025-07-16 14:54:09 +05:30
omkarht
14983158a2 fix: updated hexagon shape
on-behalf-of: @Mermaid-Chart hello@mermaidchart.com
2025-07-16 14:52:53 +05:30
github-actions[bot]
767754f4fb Version Packages 2025-07-16 08:25:22 +00:00
Ashish Jain
cff59c58b4 Merge pull request #6757 from mermaid-js/develop
Pre Release
2025-07-16 10:23:12 +02:00
darshanr0107
3fea9e8759 fix: update changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-16 13:40:40 +05:30
darshanr0107
e5ea2ed0b1 Merge branch 'develop' of https://github.com/mermaid-js/mermaid into 4459-remove-beta-suffix 2025-07-16 13:38:28 +05:30
darshanr0107
34e7f9704b fix: update changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-16 13:20:47 +05:30
darshanr0107
ac976245ad fix: fix review comments
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-16 13:11:44 +05:30
darshanr0107
1176d30668 fix: update changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-16 12:38:35 +05:30
Sidharth Vinod
5b241bbb97 Merge pull request #6758 from mermaid-js/fix/certificate-error-for-noteshub
add noteshub.app to exclusions for certificate errors
2025-07-15 21:43:32 +05:30
shubham-mermaid
7e5e47843b add noteshub.app to exclusions for certificate errors
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-15 21:36:22 +05:30
Sidharth Vinod
6728852b7a Merge branch 'develop' into fix-connection-gaps-in-flowchart-shapes 2025-07-15 20:37:20 +05:30
Sidharth Vinod
15e7c890ed Merge branch 'develop' into 6576-state-diagram-label-position 2025-07-15 20:21:40 +05:30
Sidharth Vinod
9e2cd1a926 Merge pull request #6738 from mermaid-js/treemap-diagram-to-use-the-new-class-based-approach
Updated code to use class based approach for treemap
2025-07-15 14:43:24 +00:00
Sidharth Vinod
abf2227faf Merge pull request #6751 from mermaid-js/6750-convert-mindmap-to-class-based-approach
6750: Change MindmapDB to class based architecture
2025-07-15 14:40:29 +00:00
Sidharth Vinod
7db942b0e1 Merge pull request #6756 from mzner/chore/update-katex-to-latest-version
chore: update katex to latest version due to CVE vulnerability
2025-07-15 14:36:33 +00:00
Matteo
70041c806f chore: update katex to latest version due to CVE vulnerability 2025-07-15 14:59:14 +02:00
shubham-mermaid
77e2703f72 Merge branch 'develop' into treemap-diagram-to-use-the-new-class-based-approach 2025-07-15 17:41:20 +05:30
shubham-mermaid
771801b366 Updated changeset
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-15 17:40:59 +05:30
darshanr0107
a9a0a9b2de Merge branch '6750-convert-mindmap-to-class-based-approach' of https://github.com/mermaid-js/mermaid into 6750-convert-mindmap-to-class-based-approach 2025-07-15 16:51:10 +05:30
darshanr0107
1e5e835c41 updated changeset on-behalf-of: @Mermaid-Chart hello@mermaidchart.com 2025-07-15 16:50:15 +05:30
Sidharth Vinod
1f3f8da0f7 Merge pull request #6749 from mermaid-js/chore/downgrade-chokidar-to-3.6.0
chore: downgrade chokidar to 3.6.0
2025-07-15 16:40:56 +05:30
Sidharth Vinod
b11f40e8ce Merge branch 'develop' into chore/downgrade-chokidar-to-3.6.0
* develop:
  chore: Update jsdom
  Update @argos-ci/cypress to v5.0.2
  Update @argos-ci/cypress to v5.0.1
  chore: Upgrade cypress
  chore: Update @argos-ci/cypress to v5
  chore(test): Finish refactoring of jsdomit tests
  docs(tests): Documentation for `jsdomIt` tests
  test(refactor): Provide SVG selection in `jsdomIt` function
  test(refactor): Use real-ish rendering instead of heavy mocking in unit tests
2025-07-15 16:40:18 +05:30
Sidharth Vinod
1fe045e638 chore: pin chokidar version 2025-07-15 16:36:13 +05:30
Sidharth Vinod
1c750ffc70 Merge pull request #6675 from quilicicf/chore/6627_improve-rendering-tests
Improve unit tests to allow pseudo-render tests
2025-07-15 09:57:48 +00:00
Sidharth Vinod
b0ec93f29c chore: Update jsdom 2025-07-15 13:54:45 +05:30
shubham-mermaid
6b071c135a Merge branch 'develop' into 6750-convert-mindmap-to-class-based-approach 2025-07-15 13:49:35 +05:30
shubham-mermaid
42a3c3487f Remove constructor and clear method call from TreeMapDB class
on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com>
2025-07-15 13:44:26 +05:30
Sidharth Vinod
d7b8ed2c5a Merge remote-tracking branch 'origin/develop' into pr/quilicicf/6675
* origin/develop:
  Update @argos-ci/cypress to v5.0.2
  Update @argos-ci/cypress to v5.0.1
  chore: Upgrade cypress
  chore: Update @argos-ci/cypress to v5
2025-07-15 13:34:11 +05:30
darshanr0107
96c21c7e54 resolve PR comments and update changeset 2025-07-15 12:19:02 +05:30
shubham-mermaid
e95e4d155a Updated changeset on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com> 2025-07-15 12:09:17 +05:30
shubham-mermaid
688170558c Updated changeset on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com> 2025-07-15 12:07:52 +05:30
shubham-mermaid
832f012e10 Merge branch 'treemap-diagram-to-use-the-new-class-based-approach' of https://github.com/mermaid-js/mermaid into treemap-diagram-to-use-the-new-class-based-approach 2025-07-15 12:07:01 +05:30
shubham-mermaid
2e2e8c4152 Added clear function in constructor on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com> 2025-07-15 12:06:22 +05:30
Sidharth Vinod
6ff6e08c4b Merge branch 'develop' into treemap-diagram-to-use-the-new-class-based-approach 2025-07-15 00:00:49 +05:30
darshanr0107
d3e2be35be added changeset 2025-07-14 20:12:31 +05:30
darshanr0107
260a045da0 migrate mindmap to class based approach 2025-07-14 20:00:13 +05:30
omkarht
a28965064d chore: downgrade chokidar to 3.6.0 2025-07-14 19:34:02 +05:30
quilicicf
34e91f8b65 chore(test): Finish refactoring of jsdomit tests 2025-07-14 14:04:53 +02:00
quilicicf
627ee1f34d docs(tests): Documentation for jsdomIt tests 2025-07-14 14:04:53 +02:00
quilicicf
28840ebd84 test(refactor): Provide SVG selection in jsdomIt function 2025-07-14 14:04:53 +02:00
quilicicf
4145879003 test(refactor): Use real-ish rendering instead of heavy mocking in unit tests
* Creates a utility method `jsdomIt` that overrides `it` from `vitest` and fakes a browser environment by :
  * Creating a DOM with `jsdom` (and `canvas`)
  * Adding (for the duration of the test) that DOM's `window` and `document` on `global`
  * Monkey-patching DOM methods that require a rendering engine (`Element.getBBox` & `Element.getComputedLength`)
* Removes all d3 mocking since it can now work normally in `jsdomIt` tests
* Re-writes existing rendering tests to :
  * Use `jsdomIt`
  * Get rid of most of the involved mocking
  * Run `expect` calls on the generated SVG instead

Inspired by d3's own test code mocking : https://github.com/d3/d3-selection/blob/v3.0.0/test/jsdom.js
2025-07-14 14:04:52 +02:00
omkarht
0451e343ef Merge branch 'develop' into fix-connection-gaps-in-flowchart-shapes 2025-07-14 16:53:02 +05:30
omkarht
a2dbc8e4b3 updated hexagon shape 2025-07-14 16:51:34 +05:30
shubham-mermaid
e097b480d5 Merge branch 'develop' into treemap-diagram-to-use-the-new-class-based-approach 2025-07-14 16:12:37 +05:30
autofix-ci[bot]
003d1c7a70 [autofix.ci] apply automated fixes 2025-07-12 20:03:58 +00:00
SpecularAura
daf8d8d3be Added Changeset for Per Link Styling of edges 2025-07-12 19:41:01 +00:00
SpecularAura
d7a55b422b Added tests for Per Link Curve Styling 2025-07-12 19:08:42 +00:00
shubham-mermaid
12e3d31437 Addresses type incompatibility by setting the parser database to undefined, on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com> 2025-07-11 16:54:56 +05:30
shubham-mermaid
ad024b01d6 Updated the function to use class method on-behalf-of: @Mermaid-Chart <hello@mermaidchart.com> 2025-07-11 15:18:41 +05:30
shubham-mermaid
c12aea588c Updated code as per suggestions on-behalf-of: @MermaidChart <hello@mermaidchart.com> 2025-07-11 15:16:49 +05:30
shubham-mermaid
9dfbf1166d Refactors treemap DB to class-based state management on-behalf-of: @MermaidChart shubham-mermaid@mermaidchart.com 2025-07-11 14:04:30 +05:30
Krishna Upadhyay
98bf9b4cb4 test: add tests for directions in flowchart 2025-07-10 22:17:30 -05:00
Krishna Upadhyay
e9ce8cf4da fix: trim the direction string in flowchart 2025-07-10 22:01:50 -05:00
shubham-mermaid
d90634bf2b added changeset 2025-07-10 20:39:52 +05:30
shubham-mermaid
90707e8062 fix(parser): initialize parser.yy as TreemapDB 2025-07-10 20:25:46 +05:30
shubham-mermaid
7e23f984e6 Updated code to use class based approach 2025-07-10 20:21:27 +05:30
SpecularAura
b3a12237c0 Added per link styling
Edited flowDB.ts which already had interpolate for styling links
individually. Added the ability to modify this parameter using the
newer @ syntax using the curve property.
2025-07-10 12:55:09 +00:00
darshanr0107
aea16eaf7e Merge branch 'develop' into 6584-piechart-zero-negative-values 2025-07-10 16:36:41 +05:30
darshanr0107
bb7cd70034 Merge branch 'develop' into 6730-gantt-excludes-datetime-format 2025-07-10 16:35:54 +05:30
darshanr0107
35a92efcdc resolve PR comments 2025-07-10 15:49:53 +05:30
darshanr0107
fce7cabb71 add changeset 2025-07-09 20:24:36 +05:30
darshanr0107
38e6dc497a Merge branch 'develop' into 6730-gantt-excludes-datetime-format 2025-07-09 20:06:07 +05:30
darshanr0107
5f0c53c8a7 fix excluded dates ignored in YYYY-MM-DD HH:mm:ss date format 2025-07-09 20:02:18 +05:30
omkarht
f9da4433ff Merge branch 'develop' into fix-connection-gaps-in-flowchart-shapes 2025-07-09 19:07:25 +05:30
omkarht
fc07f0d8ab added changeset 2025-07-09 19:06:57 +05:30
omkarht
ce7a487dfc Fix: Fixed Connection gaps in flowchart shapes 2025-07-09 18:37:52 +05:30
darshanr0107
8c0d12027d Merge branch 'develop' into 6584-piechart-zero-negative-values 2025-07-09 12:22:59 +05:30
Sidharth Vinod
12c94a177b Merge pull request #6728 from mermaid-js/develop
Pre Release
2025-07-08 01:12:32 +05:30
darshanr0107
71b04f93b0 added changeset 2025-07-04 18:37:32 +05:30
darshanr0107
27185f62e4 throw error when block width is greater than column width 2025-07-04 18:26:39 +05:30
darshanr0107
1414380181 Merge branch 'develop' into 6584-piechart-zero-negative-values 2025-07-01 12:34:50 +05:30
darshanr0107
6686ee9253 Merge branch 'develop' into 4459-remove-beta-suffix 2025-07-01 12:34:33 +05:30
darshanr0107
7f109c7b94 Merge branch 'develop' into 6576-state-diagram-label-position 2025-07-01 11:15:46 +05:30
darshanr0107
b9c3375be3 Merge branch '6576-state-diagram-label-position' of https://github.com/mermaid-js/mermaid into 6576-state-diagram-label-position 2025-06-30 20:20:48 +05:30
darshanr0107
4254bdd473 added test cases for edge label positions 2025-06-30 20:15:32 +05:30
darshanr0107
4012cbf013 Update changeset
Co-authored-by: Sidharth Vinod <github@sidharth.dev>
2025-06-30 18:32:31 +05:30
qraqras
939da082b2 Fix 6633 2025-06-28 08:18:19 +00:00
darshanr0107
814b68b4a9 added changeset 2025-06-27 15:16:20 +05:30
darshanr0107
bfa0eefa32 fix gantt chart date format issue 2025-06-27 15:01:45 +05:30
autofix-ci[bot]
e70be4f155 [autofix.ci] apply automated fixes 2025-06-25 11:00:55 +00:00
Khizar Hasan
6621f6ddb2 Update integrations-community.md
Added 'WP Documentation' in integrations.
2025-06-25 16:25:47 +05:30
darshanr0107
579c22cf5d refactor code 2025-06-24 17:08:42 +05:30
darshanr0107
33e08daf17 added changeset 2025-06-24 15:10:36 +05:30
darshanr0107
24257de8a6 fix state diagram edge label position 2025-06-24 14:50:20 +05:30
darshanr0107
42ac1848dd Merge branch 'develop' into 6584-piechart-zero-negative-values 2025-06-23 19:52:23 +05:30
darshanr0107
3920ad442d resolved PR comments 2025-06-23 15:08:11 +05:30
darshanr0107
53d27b771d Merge branch 'develop' into 4459-remove-beta-suffix 2025-06-17 15:57:40 +05:30
darshanr0107
2c0931da46 added changeset 2025-06-17 15:53:25 +05:30
darshanr0107
8224a81ab6 fix xychart test cases 2025-06-17 13:52:04 +05:30
darshanr0107
98442294ed resolved PR comments 2025-06-17 13:44:12 +05:30
darshanr0107
a3d164fde8 remove beta suffix for block diagram 2025-06-17 12:43:26 +05:30
darshanr0107
9dc987b28b remove beta support for sankey diagram 2025-06-17 12:12:40 +05:30
darshanr0107
72c0d9df26 added test case for preventing zero% values from rendering 2025-06-16 19:38:58 +05:30
darshanr0107
cfbce54638 prevent zero% slices from rendering in pie chart 2025-06-16 19:11:29 +05:30
darshanr0107
6979aa1013 Fix failing test cases and update error messages for negative and zero inputs 2025-06-16 14:53:09 +05:30
darshanr0107
ea60525988 remove beta suffix from xyChart 2025-06-13 19:33:43 +05:30
darshanr0107
9da6fb39ae added changeset 2025-06-12 19:18:36 +05:30
darshanr0107
83b9a17277 fix: prevent pie chart crash on zero or negative values 2025-06-12 18:13:11 +05:30
Knut Sveidqvist
f0445b74d1 #6646 Tidy-tree layout in place for Mindmaps 2025-06-12 13:33:05 +02:00
Knut Sveidqvist
ba52eef257 Tidy-tree getting closer handling of multi point edges 2025-06-12 11:21:35 +02:00
Knut Sveidqvist
c13ce2a5c0 Tidy-tree getting closer, now algorithm works 2025-06-11 20:58:54 +02:00
Knut Sveidqvist
d2463f41b5 Tidy-tree WIP 2025-06-11 18:04:21 +02:00
Knut Sveidqvist
eadb343292 Tidy-tree POC 2025-06-11 16:55:58 +02:00
Knut Sveidqvist
e7208622f7 Merge branch '6088-fix-for-diamond-intersections 2025-06-06 20:14:02 +02:00
Knut Sveidqvist
fbae611406 Refresh 2025-06-06 20:10:19 +02:00
Knut Sveidqvist
34027bc589 Repackaging cose-bilkins 2025-06-06 20:03:34 +02:00
Knut Sveidqvist
f2eef37599 Updated renderinig flow for mindmaps 2025-06-06 11:20:31 +02:00
Anthony Juckel
6cc192680a Added changeset 2025-03-03 15:10:37 -06:00
Anthony Juckel
3dd6107e76 fix: Allow equals sign in sequenceDiagram labels 2025-03-03 15:08:34 -06:00
Knut Sveidqvist
1e3ea13323 Fix for when last point is on the intersection 2024-11-29 09:07:47 +01:00
Knut Sveidqvist
4c8c48cde9 Generic solution for intersection of shapes with elk 2024-11-28 14:31:54 +01:00
Knut Sveidqvist
c8e50276e8 Added changeset 2024-11-27 15:54:05 +01:00
Knut Sveidqvist
1e6419a63f #6088 Updated offset calculations 2024-11-27 15:52:24 +01:00
219 changed files with 15543 additions and 8984 deletions

View File

@@ -33,6 +33,11 @@ export const packageOptions = {
packageName: 'mermaid-layout-elk',
file: 'layouts.ts',
},
'mermaid-layout-tidy-tree': {
name: 'mermaid-layout-tidy-tree',
packageName: 'mermaid-layout-tidy-tree',
file: 'index.ts',
},
examples: {
name: 'mermaid-examples',
packageName: 'examples',

View File

@@ -0,0 +1,5 @@
---
'@mermaid-js/mermaid-zenuml': patch
---
Fixed a critical bug that the ZenUML diagram is not rendered.

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
chore: Remove the "-beta" suffix from the XYChart, Block, Sankey diagrams to reflect their stable status

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Position the edge label in state diagram correctly relative to the edge

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Apply correct dateFormat in Gantt chart to show only day when specified

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: handle exclude dates properly in Gantt charts when using dateFormat: 'YYYY-MM-DD HH:mm:ss'

View File

@@ -1,5 +0,0 @@
---
'mermaid': minor
---
feat: Add `getRegisteredDiagramsMetadata` to `mermaid`, which returns all the registered diagram IDs in mermaid

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: fixed connection gaps in flowchart for roundedRect, stadium and diamond shape

View File

@@ -0,0 +1,7 @@
---
'mermaid': minor
'@mermaid-js/layout-tidy-tree': minor
'@mermaid-js/layout-elk': minor
---
feat: Update mindmap rendering to support multiple layouts, improved edge intersections, and new shapes

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Update casing of ID in requirement diagram

View File

@@ -0,0 +1,5 @@
---
'mermaid': minor
---
feat: Added support for per link curve styling in flowchart diagram using edge ids

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Make flowchart elk detector regex match less greedy

View File

@@ -0,0 +1,8 @@
---
'mermaid': patch
---
fix(block): overflowing blocks no longer affect later lines
This may change the layout of block diagrams that have overflowing lines
(i.e. block diagrams that use up more columns that the `columns` specifier).

View File

@@ -0,0 +1,7 @@
---
'mermaid': patch
---
fix: log warning for blocks exceeding column width
This update adds a validation check that logs a warning message when a block's width exceeds the defined column layout.

View File

@@ -1,5 +0,0 @@
---
'@mermaid-js/examples': minor
---
feat: Add examples for diagrams in the `@mermaid-js/examples` package

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Add escaped class literal name on namespace

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Allow equals sign in sequenceDiagram labels

View File

@@ -0,0 +1,9 @@
---
'mermaid': patch
---
Add validation for negative values in pie charts:
Prevents crashes during parsing by validating values post-parsing.
Provides clearer, user-friendly error messages for invalid negative inputs.

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
chore: migrate to class-based ArchitectureDB implementation

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: node border style for handdrawn shapes

View File

@@ -1,7 +0,0 @@
---
'@mermaid-js/examples': patch
'mermaid': patch
'@mermaid-js/parser': patch
---
chore: Move packet diagram out of beta

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: Update flowchart direction TD's behavior to be the same as TB

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
fix: correctly render non-directional lines for '---' in block diagrams

View File

@@ -1,5 +0,0 @@
---
'mermaid': patch
---
fix: adjust sequence diagram title positioning to prevent overlap with top border in Safari

View File

@@ -0,0 +1,5 @@
---
'mermaid': patch
---
chore: Update packet diagram to use new class-based database structure

View File

@@ -1,7 +0,0 @@
---
'mermaid': patch
---
fix(timeline): fix loading `leftMargin` from config
The `timeline.leftMargin` config value should now correctly control the size of the left margin, instead of being ignored.

3
.github/lychee.toml vendored
View File

@@ -52,6 +52,9 @@ exclude = [
# Swimm returns 404, even though the link is valid
"https://docs.swimm.io",
# Certificate Error
"https://noteshub.app",
# Timeout
"https://huehive.co",
"https://foswiki.org",

View File

@@ -58,7 +58,7 @@ jobs:
echo "EOF" >> $GITHUB_OUTPUT
- name: Commit and create pull request
uses: peter-evans/create-pull-request@889dce9eaba7900ce30494f5e1ac7220b27e5c81
uses: peter-evans/create-pull-request@1310d7dab503600742045e6fd4b84dda64352858
with:
add-paths: |
cypress/timings.json

View File

@@ -35,7 +35,7 @@ jobs:
# 2) No unwanted vitepress paths
if grep -qF 'packages/mermaid/src/vitepress' pnpm-lock.yaml; then
issues+=("• Disallowed path 'packages/mermaid/src/vitepress' present. Run `rm -rf packages/mermaid/src/vitepress && pnpm install` to regenerate.")
issues+=("• Disallowed path 'packages/mermaid/src/vitepress' present. Run \`rm -rf packages/mermaid/src/vitepress && pnpm install\` to regenerate.")
fi
# 3) Lockfile only changes when package.json changes

1
.gitignore vendored
View File

@@ -4,6 +4,7 @@ node_modules/
coverage/
.idea/
.pnpm-store/
.instructions/
dist
v8-compile-cache-0

File diff suppressed because it is too large Load Diff

1
CHANGELOG.md Symbolic link
View File

@@ -0,0 +1 @@
./packages/mermaid/CHANGELOG.md

View File

@@ -1,13 +0,0 @@
import { MockedD3 } from '../packages/mermaid/src/tests/MockedD3.js';
export const select = function () {
return new MockedD3();
};
export const selectAll = function () {
return new MockedD3();
};
export const curveBasis = 'basis';
export const curveLinear = 'linear';
export const curveCardinal = 'cardinal';

View File

@@ -16,7 +16,7 @@ describe('Block diagram', () => {
it('BL2: should handle columns statement in sub-blocks', () => {
imgSnapshotTest(
`block-beta
`block
id1["Hello"]
block
columns 3
@@ -32,7 +32,7 @@ describe('Block diagram', () => {
it('BL3: should align block widths and handle columns statement in sub-blocks', () => {
imgSnapshotTest(
`block-beta
`block
block
columns 1
id1
@@ -48,7 +48,7 @@ describe('Block diagram', () => {
it('BL4: should align block widths and handle columns statements in deeper sub-blocks then 1 level', () => {
imgSnapshotTest(
`block-beta
`block
columns 1
block
columns 1
@@ -68,7 +68,7 @@ describe('Block diagram', () => {
it('BL5: should align block widths and handle columns statements in deeper sub-blocks then 1 level (alt)', () => {
imgSnapshotTest(
`block-beta
`block
columns 1
block
id1
@@ -87,7 +87,7 @@ describe('Block diagram', () => {
it('BL6: should handle block arrows and spece statements', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
space:3
ida idb idc
@@ -106,7 +106,7 @@ describe('Block diagram', () => {
it('BL7: should handle different types of edges', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
A space:5
A --o B
@@ -119,7 +119,7 @@ describe('Block diagram', () => {
it('BL8: should handle sub-blocks without columns statements', () => {
imgSnapshotTest(
`block-beta
`block
columns 2
C A B
block
@@ -133,7 +133,7 @@ describe('Block diagram', () => {
it('BL9: should handle edges from blocks in sub blocks to other blocks', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
B space
block
@@ -147,7 +147,7 @@ describe('Block diagram', () => {
it('BL10: should handle edges from composite blocks', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
B space
block BL
@@ -161,7 +161,7 @@ describe('Block diagram', () => {
it('BL11: should handle edges to composite blocks', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
B space
block BL
@@ -175,7 +175,7 @@ describe('Block diagram', () => {
it('BL12: edges should handle labels', () => {
imgSnapshotTest(
`block-beta
`block
A
space
A -- "apa" --> E
@@ -186,7 +186,7 @@ describe('Block diagram', () => {
it('BL13: should handle block arrows in different directions', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
space blockArrowId1<["down"]>(down) space
blockArrowId2<["right"]>(right) blockArrowId3<["Sync"]>(x, y) blockArrowId4<["left"]>(left)
@@ -199,7 +199,7 @@ describe('Block diagram', () => {
it('BL14: should style statements and class statements', () => {
imgSnapshotTest(
`block-beta
`block
A
B
classDef blue fill:#66f,stroke:#333,stroke-width:2px;
@@ -212,7 +212,7 @@ describe('Block diagram', () => {
it('BL15: width alignment - D and E should share available space', () => {
imgSnapshotTest(
`block-beta
`block
block
D
E
@@ -225,7 +225,7 @@ describe('Block diagram', () => {
it('BL16: width alignment - C should be as wide as the composite block', () => {
imgSnapshotTest(
`block-beta
`block
block
A("This is the text")
B
@@ -238,7 +238,7 @@ describe('Block diagram', () => {
it('BL17: width alignment - blocks should be equal in width', () => {
imgSnapshotTest(
`block-beta
`block
A("This is the text")
B
C
@@ -249,7 +249,7 @@ describe('Block diagram', () => {
it('BL18: block types 1 - square, rounded and circle', () => {
imgSnapshotTest(
`block-beta
`block
A["square"]
B("rounded")
C(("circle"))
@@ -260,7 +260,7 @@ describe('Block diagram', () => {
it('BL19: block types 2 - odd, diamond and hexagon', () => {
imgSnapshotTest(
`block-beta
`block
A>"rect_left_inv_arrow"]
B{"diamond"}
C{{"hexagon"}}
@@ -271,7 +271,7 @@ describe('Block diagram', () => {
it('BL20: block types 3 - stadium', () => {
imgSnapshotTest(
`block-beta
`block
A(["stadium"])
`,
{}
@@ -280,7 +280,7 @@ describe('Block diagram', () => {
it('BL21: block types 4 - lean right, lean left, trapezoid and inv trapezoid', () => {
imgSnapshotTest(
`block-beta
`block
A[/"lean right"/]
B[\"lean left"\]
C[/"trapezoid"\]
@@ -292,7 +292,7 @@ describe('Block diagram', () => {
it('BL22: block types 1 - square, rounded and circle', () => {
imgSnapshotTest(
`block-beta
`block
A["square"]
B("rounded")
C(("circle"))
@@ -303,7 +303,7 @@ describe('Block diagram', () => {
it('BL23: sizing - it should be possible to make a block wider', () => {
imgSnapshotTest(
`block-beta
`block
A("rounded"):2
B:2
C
@@ -314,7 +314,7 @@ describe('Block diagram', () => {
it('BL24: sizing - it should be possible to make a composite block wider', () => {
imgSnapshotTest(
`block-beta
`block
block:2
A
end
@@ -326,7 +326,7 @@ describe('Block diagram', () => {
it('BL25: block in the middle with space on each side', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
space
middle["In the middle"]
@@ -337,7 +337,7 @@ describe('Block diagram', () => {
});
it('BL26: space and an edge', () => {
imgSnapshotTest(
`block-beta
`block
columns 5
A space B
A --x B
@@ -347,7 +347,7 @@ describe('Block diagram', () => {
});
it('BL27: block sizes for regular blocks', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
a["A wide one"] b:2 c:2 d
`,
@@ -356,7 +356,7 @@ describe('Block diagram', () => {
});
it('BL28: composite block with a set width - f should use the available space', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
a:3
block:e:3
@@ -370,7 +370,7 @@ describe('Block diagram', () => {
it('BL29: composite block with a set width - f and g should split the available space', () => {
imgSnapshotTest(
`block-beta
`block
columns 3
a:3
block:e:3
@@ -384,4 +384,28 @@ describe('Block diagram', () => {
{}
);
});
it('BL30: block should overflow if too wide for columns', () => {
imgSnapshotTest(
`block-beta
columns 2
fit:2
overflow:3
short:1
also_overflow:2
`,
{}
);
});
it('BL31: edge without arrow syntax should render with no arrowheads', () => {
imgSnapshotTest(
`block-beta
a
b
a --- b
`,
{}
);
});
});

View File

@@ -495,4 +495,34 @@ describe('Class diagram', () => {
cy.get('a').should('have.attr', 'target', '_blank').should('have.attr', 'rel', 'noopener');
});
});
describe('Include char sequence "graph" in text (#6795)', () => {
it('has a label with char sequence "graph"', () => {
imgSnapshotTest(
`
classDiagram
class Person {
+String name
-Int id
#double age
+Text demographicProfile
}
`,
{ flowchart: { defaultRenderer: 'elk' } }
);
});
});
it('should handle backticks for namespace and class names', () => {
imgSnapshotTest(
`
classDiagram
namespace \`A::B\` {
class \`IPC::Sender\`
}
RenderProcessHost --|> \`IPC::Sender\`
`,
{}
);
});
});

View File

@@ -354,4 +354,19 @@ ORDER ||--|{ LINE-ITEM : contains
{ logLevel: 1 }
);
});
describe('Include char sequence "graph" in text (#6795)', () => {
it('has a label with char sequence "graph"', () => {
imgSnapshotTest(
`
erDiagram
p[Photograph] {
varchar(12) jobId
date dateCreated
}
`,
{ flowchart: { defaultRenderer: 'elk' } }
);
});
});
});

View File

@@ -1113,4 +1113,55 @@ end
);
});
});
describe('Flowchart Node Shape Rendering', () => {
it('should render a stadium-shaped node', () => {
imgSnapshotTest(
`flowchart TB
A(["Start"]) --> n1["Untitled Node"]
A --> n2["Untitled Node"]
`,
{}
);
});
it('should render a diamond-shaped node using shape config', () => {
imgSnapshotTest(
`flowchart BT
n2["Untitled Node"] --> n1["Diamond"]
n1@{ shape: diam}
`,
{}
);
});
it('should render a rounded rectangle and a normal rectangle', () => {
imgSnapshotTest(
`flowchart BT
n2["Untitled Node"] --> n1["Rounded Rectangle"]
n3["Untitled Node"] --> n1
n1@{ shape: rounded}
n3@{ shape: rect}
`,
{}
);
});
});
it('6617: Per Link Curve Styling using edge Ids', () => {
imgSnapshotTest(
`flowchart TD
A e1@-->B e5@--> E
E e7@--> D
B e3@-->D
A e2@-->C e4@-->D
C e6@--> F
F e8@--> D
e1@{ curve: natural }
e2@{ curve: stepAfter }
e3@{ curve: monotoneY }
e4@{ curve: bumpY }
e5@{ curve: linear }
e6@{ curve: catmullRom }
e7@{ curve: cardinal }
`
);
});
});

View File

@@ -565,6 +565,18 @@ describe('Gantt diagram', () => {
);
});
it('should render only the day when using dateFormat D', () => {
imgSnapshotTest(
`
gantt
title Test
dateFormat D
A :a, 1, 1d
`,
{}
);
});
// TODO: fix it
//
// This test is skipped deliberately
@@ -647,6 +659,49 @@ describe('Gantt diagram', () => {
);
});
it('should render a gantt diagram excluding a specific date in YYYY-MM-DD HH:mm:ss format', () => {
imgSnapshotTest(
`
gantt
dateFormat YYYY-MM-DD HH:mm:ss
excludes 2025-07-07
section Section
A task :a1, 2025-07-04 20:30:30, 2025-07-08 10:30:30
Another task:after a1, 20h
`,
{}
);
});
it('should render a gantt diagram excluding saturday and sunday in YYYY-MM-DD HH:mm:ss format', () => {
imgSnapshotTest(
`
gantt
dateFormat YYYY-MM-DD HH:mm:ss
excludes weekends
weekend saturday
section Section
A task :a1, 2025-07-04 20:30:30, 2025-07-08 10:30:30
Another task:after a1, 20h
`,
{}
);
});
it('should render a gantt diagram excluding friday and saturday in YYYY-MM-DD HH:mm:ss format', () => {
imgSnapshotTest(
`
gantt
dateFormat YYYY-MM-DD HH:mm:ss
excludes weekends
weekend friday
section Section
A task :a1, 2025-07-04 20:30:30, 2025-07-08 10:30:30
Another task:after a1, 20h
`,
{}
);
});
it("should render when there's a semicolon in the title", () => {
imgSnapshotTest(
`

View File

@@ -159,12 +159,10 @@ root
});
it('square shape', () => {
imgSnapshotTest(
`
mindmap
`mindmap
root[
The root
]
`,
]`,
{},
undefined,
shouldHaveRoot
@@ -172,12 +170,10 @@ mindmap
});
it('rounded rect shape', () => {
imgSnapshotTest(
`
mindmap
`mindmap
root((
The root
))
`,
))`,
{},
undefined,
shouldHaveRoot
@@ -185,12 +181,10 @@ mindmap
});
it('circle shape', () => {
imgSnapshotTest(
`
mindmap
`mindmap
root(
The root
)
`,
)`,
{},
undefined,
shouldHaveRoot
@@ -198,10 +192,8 @@ mindmap
});
it('default shape', () => {
imgSnapshotTest(
`
mindmap
The root
`,
`mindmap
The root`,
{},
undefined,
shouldHaveRoot
@@ -209,12 +201,10 @@ mindmap
});
it('adding children', () => {
imgSnapshotTest(
`
mindmap
`mindmap
The root
child1
child2
`,
child2`,
{},
undefined,
shouldHaveRoot
@@ -222,13 +212,11 @@ mindmap
});
it('adding grand children', () => {
imgSnapshotTest(
`
mindmap
`mindmap
The root
child1
child2
child3
`,
child3`,
{},
undefined,
shouldHaveRoot
@@ -246,5 +234,22 @@ Word!\`]
);
});
});
describe('Include char sequence "graph" in text (#6795)', () => {
it('has a label with char sequence "graph"', () => {
imgSnapshotTest(
`
mindmap
root
Photograph
Waterfall
Landscape
Geography
Mountains
Rocks
`,
{ flowchart: { defaultRenderer: 'elk' } }
);
});
});
/* The end */
});

View File

@@ -82,4 +82,13 @@ describe('pie chart', () => {
`
);
});
it('should render pie slices only for non-zero values but shows all legends', () => {
imgSnapshotTest(
` pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 1
`
);
});
});

View File

@@ -15,7 +15,7 @@ describe('Sankey Diagram', () => {
describe('when given a linkColor', function () {
this.beforeAll(() => {
cy.wrap(
`sankey-beta
`sankey
a,b,10
`
).as('graph');
@@ -62,7 +62,7 @@ describe('Sankey Diagram', () => {
this.beforeAll(() => {
cy.wrap(
`
sankey-beta
sankey
a,b,8
b,c,8

View File

@@ -602,6 +602,231 @@ State1 --> [*]
--
55
}
`,
{}
);
});
it('should render edge labels correctly', () => {
imgSnapshotTest(
`---
title: On The Way To Something Something DarkSide
config:
look: default
theme: default
---
stateDiagram-v2
state State1_____________
{
c0
}
state State2_____________
{
c1
}
state State3_____________
{
c7
}
state State4_____________
{
c2
}
state State5_____________
{
c3
}
state State6_____________
{
c4
}
state State7_____________
{
c5
}
state State8_____________
{
c6
}
[*] --> State1_____________
State1_____________ --> State2_____________ : Transition1_____
State2_____________ --> State4_____________ : Transition2_____
State2_____________ --> State3_____________ : Transition3_____
State3_____________ --> State2_____________
State4_____________ --> State2_____________ : Transition5_____
State4_____________ --> State5_____________ : Transition6_____
State5_____________ --> State6_____________ : Transition7_____
State6_____________ --> State4_____________ : Transition8_____
State2_____________ --> State7_____________ : Transition4_____
State4_____________ --> State7_____________ : Transition4_____
State5_____________ --> State7_____________ : Transition4_____
State6_____________ --> State7_____________ : Transition4_____
State7_____________ --> State1_____________ : Transition9_____
State5_____________ --> State8_____________ : Transition10____
State8_____________ --> State5_____________ : Transition11____
`,
{}
);
});
it('should render edge labels correctly with multiple transitions', () => {
imgSnapshotTest(
`---
title: Multiple Transitions
config:
look: default
theme: default
---
stateDiagram-v2
state State1_____________
{
c0
}
state State2_____________
{
c1
}
state State3_____________
{
c7
}
state State4_____________
{
c2
}
state State5_____________
{
c3
}
state State6_____________
{
c4
}
state State7_____________
{
c5
}
state State8_____________
{
c6
}
state State9_____________
{
c9
}
[*] --> State1_____________
State1_____________ --> State2_____________ : Transition1_____
State2_____________ --> State4_____________ : Transition2_____
State2_____________ --> State3_____________ : Transition3_____
State3_____________ --> State2_____________
State4_____________ --> State2_____________ : Transition5_____
State4_____________ --> State5_____________ : Transition6_____
State5_____________ --> State6_____________ : Transition7_____
State6_____________ --> State4_____________ : Transition8_____
State2_____________ --> State7_____________ : Transition4_____
State4_____________ --> State7_____________ : Transition4_____
State5_____________ --> State7_____________ : Transition4_____
State6_____________ --> State7_____________ : Transition4_____
State7_____________ --> State1_____________ : Transition9_____
State5_____________ --> State8_____________ : Transition10____
State8_____________ --> State5_____________ : Transition11____
State9_____________ --> State8_____________ : Transition12____
`,
{}
);
});
it('should render edge labels correctly with multiple states', () => {
imgSnapshotTest(
`---
title: Multiple States
config:
look: default
theme: default
---
stateDiagram-v2
state State1_____________
{
c0
}
state State2_____________
{
c1
}
state State3_____________
{
c7
}
state State4_____________
{
c2
}
state State5_____________
{
c3
}
state State6_____________
{
c4
}
state State7_____________
{
c5
}
state State8_____________
{
c6
}
state State9_____________
{
c9
}
state State10_____________
{
c10
}
[*] --> State1_____________
State1_____________ --> State2_____________ : Transition1_____
State2_____________ --> State3_____________ : Transition2_____
State3_____________ --> State4_____________ : Transition3_____
State4_____________ --> State5_____________ : Transition4_____
State5_____________ --> State6_____________ : Transition5_____
State6_____________ --> State7_____________ : Transition6_____
State7_____________ --> State8_____________ : Transition7_____
State8_____________ --> State9_____________ : Transition8_____
State9_____________ --> State10_____________ : Transition9_____
`,
{}
);

View File

@@ -1,7 +1,7 @@
import { imgSnapshotTest, renderGraph } from '../../helpers/util.ts';
describe('XY Chart', () => {
it('should render the simplest possible chart', () => {
it('should render the simplest possible xy-beta chart', () => {
imgSnapshotTest(
`
xychart-beta
@@ -10,10 +10,19 @@ describe('XY Chart', () => {
{}
);
});
it('should render the simplest possible xy chart', () => {
imgSnapshotTest(
`
xychart
line [10, 30, 20]
`,
{}
);
});
it('Should render a complete chart', () => {
imgSnapshotTest(
`
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -26,7 +35,7 @@ describe('XY Chart', () => {
it('Should render a chart without title', () => {
imgSnapshotTest(
`
xychart-beta
xychart
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
bar [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]
@@ -38,7 +47,7 @@ describe('XY Chart', () => {
it('y-axis title not required', () => {
imgSnapshotTest(
`
xychart-beta
xychart
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis 4000 --> 11000
bar [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]
@@ -50,7 +59,7 @@ describe('XY Chart', () => {
it('Should render a chart without y-axis with different range', () => {
imgSnapshotTest(
`
xychart-beta
xychart
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
bar [5000, 6000, 7500, 8200, 9500, 10500, 14000, 3200, 9200, 9900, 3400, 6000]
line [2000, 7000, 6500, 9200, 9500, 7500, 11000, 10200, 3200, 8500, 7000, 8800]
@@ -61,7 +70,7 @@ describe('XY Chart', () => {
it('x axis title not required', () => {
imgSnapshotTest(
`
xychart-beta
xychart
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
bar [5000, 6000, 7500, 8200, 9500, 10500, 14000, 3200, 9200, 9900, 3400, 6000]
line [2000, 7000, 6500, 9200, 9500, 7500, 11000, 10200, 3200, 8500, 7000, 8800]
@@ -72,7 +81,7 @@ describe('XY Chart', () => {
it('Multiple plots can be rendered', () => {
imgSnapshotTest(
`
xychart-beta
xychart
line [23, 46, 77, 34]
line [45, 32, 33, 12]
bar [87, 54, 99, 85]
@@ -86,7 +95,7 @@ describe('XY Chart', () => {
it('Decimals and negative numbers are supported', () => {
imgSnapshotTest(
`
xychart-beta
xychart
y-axis -2.4 --> 3.5
line [+1.3, .6, 2.4, -.34]
`,
@@ -104,7 +113,7 @@ describe('XY Chart', () => {
height: 20
plotReservedSpacePercent: 100
---
xychart-beta
xychart
line [5000, 9000, 7500, 6200, 9500, 5500, 11000, 8200, 9200, 9500, 7000, 8800]
`,
{}
@@ -130,7 +139,7 @@ describe('XY Chart', () => {
showTick: false
showAxisLine: false
---
xychart-beta
xychart
bar [5000, 9000, 7500, 6200, 9500, 5500, 11000, 8200, 9200, 9500, 7000, 8800]
`,
{}
@@ -140,7 +149,7 @@ describe('XY Chart', () => {
imgSnapshotTest(
`
%%{init: {"xyChart": {"width": 1000, "height": 600, "titlePadding": 5, "titleFontSize": 10, "xAxis": {"labelFontSize": "20", "labelPadding": 10, "titleFontSize": 30, "titlePadding": 20, "tickLength": 10, "tickWidth": 5}, "yAxis": {"labelFontSize": "20", "labelPadding": 10, "titleFontSize": 30, "titlePadding": 20, "tickLength": 10, "tickWidth": 5}, "plotBorderWidth": 5, "chartOrientation": "horizontal", "plotReservedSpacePercent": 60 }}}%%
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -181,7 +190,7 @@ describe('XY Chart', () => {
plotReservedSpacePercent: 60
showDataLabel: true
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -202,7 +211,7 @@ describe('XY Chart', () => {
yAxis:
showTitle: false
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -223,7 +232,7 @@ describe('XY Chart', () => {
yAxis:
showLabel: false
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -244,7 +253,7 @@ describe('XY Chart', () => {
yAxis:
showTick: false
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -265,7 +274,7 @@ describe('XY Chart', () => {
yAxis:
showAxisLine: false
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -294,7 +303,7 @@ describe('XY Chart', () => {
xAxisLineColor: "#87ceeb"
plotColorPalette: "#008000, #faba63"
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -307,7 +316,7 @@ describe('XY Chart', () => {
it('should use the correct distances between data points', () => {
imgSnapshotTest(
`
xychart-beta
xychart
x-axis 0 --> 2
line [0, 1, 0, 1]
bar [1, 0, 1, 0]
@@ -325,7 +334,7 @@ describe('XY Chart', () => {
xyChart:
showDataLabel: true
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -344,7 +353,7 @@ describe('XY Chart', () => {
showDataLabel: true
chartOrientation: horizontal
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -357,7 +366,7 @@ describe('XY Chart', () => {
it('should render vertical bar chart without labels by default', () => {
imgSnapshotTest(
`
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -375,7 +384,7 @@ describe('XY Chart', () => {
xyChart:
chartOrientation: horizontal
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -393,7 +402,7 @@ describe('XY Chart', () => {
xyChart:
showDataLabel: true
---
xychart-beta
xychart
title "Multiple Bar Plots"
x-axis Categories [A, B, C]
y-axis "Values" 0 --> 100
@@ -412,7 +421,7 @@ describe('XY Chart', () => {
showDataLabel: true
chartOrientation: horizontal
---
xychart-beta
xychart
title "Multiple Bar Plots"
x-axis Categories [A, B, C]
y-axis "Values" 0 --> 100
@@ -430,7 +439,7 @@ describe('XY Chart', () => {
xyChart:
showDataLabel: true
---
xychart-beta
xychart
title "Single Bar Chart"
x-axis Categories [A]
y-axis "Value" 0 --> 100
@@ -449,7 +458,7 @@ describe('XY Chart', () => {
showDataLabel: true
chartOrientation: horizontal
---
xychart-beta
xychart
title "Single Bar Chart"
x-axis Categories [A]
y-axis "Value" 0 --> 100
@@ -467,7 +476,7 @@ describe('XY Chart', () => {
xyChart:
showDataLabel: true
---
xychart-beta
xychart
title "Decimal and Negative Values"
x-axis Categories [A, B, C]
y-axis -10 --> 10
@@ -486,7 +495,7 @@ describe('XY Chart', () => {
showDataLabel: true
chartOrientation: horizontal
---
xychart-beta
xychart
title "Decimal and Negative Values"
x-axis Categories [A, B, C]
y-axis -10 --> 10
@@ -504,7 +513,7 @@ describe('XY Chart', () => {
xyChart:
showDataLabel: true
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan,b,c]
y-axis "Revenue (in $)" 4000 --> 12000
@@ -561,7 +570,7 @@ describe('XY Chart', () => {
showDataLabel: true
chartOrientation: horizontal
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan,b,c]
y-axis "Revenue (in $)" 4000 --> 12000
@@ -615,7 +624,7 @@ describe('XY Chart', () => {
xyChart:
showDataLabel: true
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
y-axis "Revenue (in $)" 4000 --> 12000
@@ -672,7 +681,7 @@ describe('XY Chart', () => {
showDataLabel: true
chartOrientation: horizontal
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s]
y-axis "Revenue (in $)" 4000 --> 12000
@@ -726,7 +735,7 @@ describe('XY Chart', () => {
xyChart:
showDataLabel: true
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan]
y-axis "Revenue (in $)" 3000 --> 12000
@@ -783,7 +792,7 @@ describe('XY Chart', () => {
showDataLabel: true
chartOrientation: horizontal
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan]
y-axis "Revenue (in $)" 3000 --> 12000

View File

@@ -0,0 +1,35 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Mermaid Quick Test Page</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=" />
<style>
div.mermaid {
font-family: 'Courier New', Courier, monospace !important;
}
</style>
</head>
<body>
<h1>Pie chart demos</h1>
<pre class="mermaid">
pie title Default text position: Animal adoption
accTitle: simple pie char demo
accDescr: pie chart with 3 sections: dogs, cats, rats. Most are dogs.
"dogs" : -60.67
"rats" : 40.12
</pre>
<hr />
<script type="module">
import mermaid from '/mermaid.esm.mjs';
mermaid.initialize({
theme: 'forest',
logLevel: 3,
securityLevel: 'loose',
});
</script>
</body>
</html>

View File

@@ -130,6 +130,76 @@
</head>
<body>
<pre id="diagram4" class="mermaid2">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness<br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
Pen and paper
Mermaid
</pre>
<pre id="diagram4" class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap is a long thing))
A
B
C
D
</pre
>
<pre id="diagram4" class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
A
B
</pre
>
<pre id="diagram4" class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
A
a
apa[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa2[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
b
c
d
B
apa3[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
D
apa5[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa4[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
</pre>
<pre id="diagram4" class="mermaid">
treemap
"Section 1"
@@ -175,8 +245,145 @@ treemap
"Item B2": 25
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
a
apa[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa2[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
b
apa3[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa4[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: tidy-tree
---
flowchart TB
A --> n0["1"]
A --> n1["2"]
A --> n2["3"]
A --> n3["4"] --> Q & R & S & T
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: elk
---
flowchart TB
A --> n0["1"]
A --> n1["2"]
A --> n2["3"]
A --> n3["4"] --> Q & R & S & T
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: dagre
---
mindmap
root((mindmap is a long thing))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness&lt;br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
Pen and paper
Mermaid
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: cose-bilkent
---
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness&lt;br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
Pen and paper
Mermaid
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: elk
---
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness&lt;br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
Pen and paper
Mermaid
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: cose-bilkent
---
flowchart LR
AB["apa@apa@"] --> B(("`apa@apa`"))
root{mindmap} --- Origins --- Europe
Origins --> Asia
root --- Background --- Rich
Background --- Poor
subgraph apa
Background
Poor
end
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: elk
---
flowchart LR
root{mindmap} --- Origins --- Europe
Origins --> Asia
root --- Background --- Rich
Background --- Poor
</pre>
<pre id="diagram4" class="mermaid2">
flowchart
@@ -258,6 +465,44 @@ config:
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: elk
---
flowchart LR
a
subgraph s0["APA"]
subgraph s8["APA"]
subgraph s1["APA"]
D{"X"}
E[Q]
end
subgraph s3["BAPA"]
F[Q]
I
end
D --> I
D --> I
D --> I
I{"X"}
end
end
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: elk
---
flowchart LR
a
D{"Use the editor"}
D -- Mermaid js --> I{"fa:fa-code Text"}
D-->I
D-->I
</pre>
<pre id="diagram4" class="mermaid2">
---
config:
layout: elk
---

View File

@@ -0,0 +1,379 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Mermaid Quick Test Page</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=" />
<style>
div.mermaid {
font-family: 'Courier New', Courier, monospace !important;
}
</style>
</head>
<body>
<pre class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
A
B
</pre>
<pre class="mermaid">
---
config:
layout: dagre
---
mindmap
root((mindmap))
A
B
</pre>
<pre class="mermaid">
---
config:
layout: elk
---
mindmap
root((mindmap))
A
B
</pre>
<pre class="mermaid">
---
config:
layout: cose-bilkent
---
mindmap
root((mindmap))
A
B
</pre>
<pre class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap is a long thing))
A
B
C
D
</pre>
<pre class="mermaid">
---
config:
layout: dagre
---
mindmap
root((mindmap is a long thing))
A
B
C
D
</pre>
<pre class="mermaid">
---
config:
layout: elk
---
mindmap
root((mindmap is a long thing))
A
B
C
D
</pre>
<pre class="mermaid">
---
config:
layout: cose-bilkent
---
mindmap
root((mindmap is a long thing))
A
B
C
D
</pre>
<pre class="mermaid">
mindmap
root((mindmap is a long thing))
A
B
C
D
</pre>
<pre class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness&lt;br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
id)I am a cloud(
id))I am a bang((
Tools
</pre>
<pre class="mermaid">
---
config:
layout: dagre
---
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness&lt;br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
id)I am a cloud(
id))I am a bang((
Tools
</pre>
<pre class="mermaid">
---
config:
layout: elk
---
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness&lt;br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
id)I am a cloud(
id))I am a bang((
Tools
</pre>
<pre class="mermaid">
---
config:
layout: cose-bilkent
---
mindmap
root((mindmap))
Origins
Long history
::icon(fa fa-book)
Popularisation
British popular psychology author Tony Buzan
Research
On effectiveness&lt;br/>and features
On Automatic creation
Uses
Creative techniques
Strategic planning
Argument mapping
Tools
id)I am a cloud(
id))I am a bang((
Tools
</pre>
<pre class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
A
a
apa[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa2[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
b
c
d
B
apa3[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
D
apa5[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa4[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
</pre>
<pre class="mermaid">
---
config:
layout: dagre
---
mindmap
root((mindmap))
A
a
apa[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa2[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
b
c
d
B
apa3[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
D
apa5[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa4[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
</pre>
<pre class="mermaid">
---
config:
layout: elk
---
mindmap
root((mindmap))
A
a
apa[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa2[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
b
c
d
B
apa3[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
D
apa5[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa4[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
</pre>
<pre class="mermaid">
---
config:
layout: cose-bilkent
---
mindmap
root((mindmap))
A
a
apa[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa2[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
b
c
d
B
apa3[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
D
apa5[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
apa4[I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on. I am a long long multline string passing several levels of text. Lorum ipsum and so on]
</pre>
<pre class="mermaid">
---
config:
layout: tidy-tree
---
mindmap
((This is a mindmap))
child1
grandchild 1
grandchild 2
child2
grandchild 3
grandchild 4
child3
grandchild 5
grandchild 6
</pre>
<pre class="mermaid">
---
config:
layout: dagre
---
mindmap
((This is a mindmap))
child1
grandchild 1
grandchild 2
child2
grandchild 3
grandchild 4
child3
grandchild 5
grandchild 6
</pre>
<pre class="mermaid">
---
config:
layout: elk
---
mindmap
((This is a mindmap))
child1
grandchild 1
grandchild 2
child2
grandchild 3
grandchild 4
child3
grandchild 5
grandchild 6
</pre>
<pre class="mermaid">
---
config:
layout: cose-bilkent
---
mindmap
((This is a mindmap))
child1
grandchild 1
grandchild 2
child2
grandchild 3
grandchild 4
child3
grandchild 5
grandchild 6
</pre>
<hr />
<script type="module">
import mermaid from '/mermaid.esm.mjs';
mermaid.initialize({
theme: 'default',
logLevel: 3,
securityLevel: 'loose',
});
</script>
</body>
</html>

View File

@@ -10,7 +10,7 @@
<body>
<h1>Block diagram demos</h1>
<pre id="diagram" class="mermaid">
block-beta
block
columns 1
db(("DB"))
blockArrowId6<["&nbsp;&nbsp;&nbsp;"]>(down)
@@ -26,7 +26,7 @@ columns 1
style B fill:#f9F,stroke:#333,stroke-width:4px
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
A1["square"]
B1("rounded")
C1(("circle"))
@@ -36,7 +36,7 @@ block-beta
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
A1(["stadium"])
A2[["subroutine"]]
B1[("cylinder")]
@@ -48,7 +48,7 @@ block-beta
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
block:e:4
columns 2
f
@@ -57,7 +57,7 @@ block-beta
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
block:e:4
columns 2
f
@@ -67,7 +67,7 @@ block-beta
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
columns 3
a:3
block:e:3
@@ -80,7 +80,7 @@ block-beta
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
columns 4
a b c d
block:e:4
@@ -97,19 +97,19 @@ flowchart LR
X-- "a label" -->z
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
columns 5
A space B
A --x B
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
columns 3
a["A wide one"] b:2 c:2 d
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
columns 3
a b c
e:3
@@ -117,7 +117,7 @@ columns 3
</pre>
<pre id="diagram" class="mermaid">
block-beta
block
A1:3
A2:1

View File

@@ -20,12 +20,14 @@
width: 800
nodeAlignment: left
---
sankey-beta
Revenue,Expenses,10
Revenue,Profit,10
Expenses,Manufacturing,5
Expenses,Tax,3
Expenses,Research,2
sankey
a,b,8
b,c,8
c,d,8
d,e,8
x,c,4
c,y,4
</pre>
<h2>Energy flow</h2>
@@ -40,7 +42,7 @@
linkColor: gradient
nodeAlignment: justify
---
sankey-beta
sankey
Agricultural 'waste',Bio-conversion,124.729
Bio-conversion,Liquid,0.597

View File

@@ -16,7 +16,7 @@
<body>
<h1>XY Charts demos</h1>
<pre class="mermaid">
xychart-beta
xychart
title "Sales Revenue (in $)"
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -26,7 +26,7 @@
<hr />
<h1>XY Charts horizontal</h1>
<pre class="mermaid">
xychart-beta horizontal
xychart horizontal
title "Basic xychart"
x-axis "this is x axis" [category1, "category 2", category3, category4]
y-axis yaxisText 10 --> 150
@@ -36,7 +36,7 @@
<hr />
<h1>XY Charts only lines and bar</h1>
<pre class="mermaid">
xychart-beta
xychart
line [23, 46, 77, 34]
line [45, 32, 33, 12]
line [87, 54, 99, 85]
@@ -48,13 +48,13 @@
<hr />
<h1>XY Charts with +ve and -ve numbers</h1>
<pre class="mermaid">
xychart-beta
xychart
line [+1.3, .6, 2.4, -.34]
</pre>
<h1>XY Charts Bar with multiple category</h1>
<pre class="mermaid">
xychart-beta
xychart
title "Basic xychart with many categories"
x-axis "this is x axis" [category1, "category 2", category3, category4, category5, category6, category7]
y-axis yaxisText 10 --> 150
@@ -63,7 +63,7 @@
<h1>XY Charts line with multiple category</h1>
<pre class="mermaid">
xychart-beta
xychart
title "Line chart with many category"
x-axis "this is x axis" [category1, "category 2", category3, category4, category5, category6, category7]
y-axis yaxisText 10 --> 150
@@ -72,7 +72,7 @@
<h1>XY Charts category with large text</h1>
<pre class="mermaid">
xychart-beta
xychart
title "Basic xychart with many categories with category overlap"
x-axis "this is x axis" [category1, "Lorem ipsum dolor sit amet, qui minim labore adipisicing minim sint cillum sint consectetur cupidatat.", category3, category4, category5, category6, category7]
y-axis yaxisText 10 --> 150
@@ -89,7 +89,7 @@ config:
height: 20
plotReservedSpacePercent: 100
---
xychart-beta
xychart
line [5000, 9000, 7500, 6200, 9500, 5500, 11000, 8200, 9200, 9500, 7000, 8800]
</pre>
@@ -103,7 +103,7 @@ config:
height: 20
plotReservedSpacePercent: 100
---
xychart-beta
xychart
bar [5000, 9000, 7500, 6200, 9500, 5500, 11000, 8200, 9200, 9500, 7000, 8800]
</pre>
@@ -136,7 +136,7 @@ config:
chartOrientation: horizontal
plotReservedSpacePercent: 60
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -162,7 +162,7 @@ config:
xAxisLineColor: "#87ceeb"
plotColorPalette: "#008000, #faba63"
---
xychart-beta
xychart
title "Sales Revenue"
x-axis Months [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000

View File

@@ -29,7 +29,8 @@ In GitHub, you first [**fork a mermaid repository**](https://github.com/mermaid-
Then you **clone** a copy to your local development machine (e.g. where you code) to make a copy with all the files to work with.
> **💡 Tip** > [Here is a GitHub document that gives an overview of the process](https://docs.github.com/en/get-started/quickstart/fork-a-repo).
> **💡 Tip**
> [Here is a GitHub document that gives an overview of the process](https://docs.github.com/en/get-started/quickstart/fork-a-repo).
```bash
git clone git@github.com/your-fork/mermaid
@@ -301,7 +302,7 @@ If you are adding a feature, you will definitely need to add tests. Depending on
Unit tests are tests that test a single function or module. They are the easiest to write and the fastest to run.
Unit tests are mandatory for all code except the renderers. (The renderers are tested with integration tests.)
Unit tests are mandatory for all code except the layout tests. (The layouts are tested with integration tests.)
We use [Vitest](https://vitest.dev) to run unit tests.
@@ -327,6 +328,30 @@ When using Docker prepend your command with `./run`:
./run pnpm test
```
##### Testing the DOM
One can use `jsdomIt` to test any part of Mermaid that interacts with the DOM, as long as it is not related to the layout.
The function `jsdomIt` ([developed in utils.ts](../../tests/util.ts)) overrides `it` from `vitest`, and creates a pseudo-browser environment that works almost like the real deal for the duration of the test. It uses JSDOM to create a DOM, and adds objects `window` and `document` to `global` to mock the browser environment.
> \[!NOTE]
> The layout cannot work in `jsdomIt` tests because JSDOM has no rendering engine, hence the pseudo-browser environment.
Example :
```typescript
import { ensureNodeFromSelector, jsdomIt } from './tests/util.js';
jsdomIt('should add element "thing" in the SVG', ({ svg }) => {
// Code in this block runs in a pseudo-browser environment
addThing(svg); // The svg item is the D3 selection of the SVG node
const svgNode = ensureNodeFromSelector('svg'); // Retrieve the DOM node using the DOM API
expect(svgNode.querySelector('thing')).not.toBeNull(); // Test the structure of the SVG
});
```
They can be used to test any method that interacts with the DOM, including for testing renderers. For renderers, additional integration testing is necessary to test the layout though.
#### Integration / End-to-End (E2E) Tests
These test the rendering and visual appearance of the diagrams.

View File

@@ -33,7 +33,8 @@ mindmap
## Join the Development
> **💡 Tip** > **Check out our** [**detailed contribution guide**](./contributing.md).
> **💡 Tip**
> **Check out our** [**detailed contribution guide**](./contributing.md).
Where to start:
@@ -47,7 +48,8 @@ Where to start:
## A Question Or a Suggestion?
> **💡 Tip** > **Have a look at** [**how to open an issue**](./questions-and-suggestions.md).
> **💡 Tip**
> **Have a look at** [**how to open an issue**](./questions-and-suggestions.md).
If you have faced a vulnerability [report it to us](./security.md).

View File

@@ -22,7 +22,6 @@ While directives allow you to change most of the default configuration settings,
Mermaid basically supports two types of configuration options to be overridden by directives.
1. _General/Top Level configurations_ : These are the configurations that are available and applied to all the diagram. **Some of the most important top-level** configurations are:
- theme
- fontFamily
- logLevel

View File

@@ -10,10 +10,6 @@
# mermaid
## Classes
- [UnknownDiagramError](classes/UnknownDiagramError.md)
## Interfaces
- [DetailedError](interfaces/DetailedError.md)
@@ -27,6 +23,7 @@
- [RenderOptions](interfaces/RenderOptions.md)
- [RenderResult](interfaces/RenderResult.md)
- [RunOptions](interfaces/RunOptions.md)
- [UnknownDiagramError](interfaces/UnknownDiagramError.md)
## Type Aliases

View File

@@ -1,159 +0,0 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/setup/mermaid/classes/UnknownDiagramError.md](../../../../../packages/mermaid/src/docs/config/setup/mermaid/classes/UnknownDiagramError.md).
[**mermaid**](../../README.md)
---
# Class: UnknownDiagramError
Defined in: [packages/mermaid/src/errors.ts:1](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/errors.ts#L1)
## Extends
- `Error`
## Constructors
### new UnknownDiagramError()
> **new UnknownDiagramError**(`message`): [`UnknownDiagramError`](UnknownDiagramError.md)
Defined in: [packages/mermaid/src/errors.ts:2](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/errors.ts#L2)
#### Parameters
##### message
`string`
#### Returns
[`UnknownDiagramError`](UnknownDiagramError.md)
#### Overrides
`Error.constructor`
## Properties
### cause?
> `optional` **cause**: `unknown`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
#### Inherited from
`Error.cause`
---
### message
> **message**: `string`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es5.d.ts:1077
#### Inherited from
`Error.message`
---
### name
> **name**: `string`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es5.d.ts:1076
#### Inherited from
`Error.name`
---
### stack?
> `optional` **stack**: `string`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es5.d.ts:1078
#### Inherited from
`Error.stack`
---
### prepareStackTrace()?
> `static` `optional` **prepareStackTrace**: (`err`, `stackTraces`) => `any`
Defined in: node_modules/.pnpm/@types+node\@22.13.5/node_modules/@types/node/globals.d.ts:143
Optional override for formatting stack traces
#### Parameters
##### err
`Error`
##### stackTraces
`CallSite`\[]
#### Returns
`any`
#### See
<https://v8.dev/docs/stack-trace-api#customizing-stack-traces>
#### Inherited from
`Error.prepareStackTrace`
---
### stackTraceLimit
> `static` **stackTraceLimit**: `number`
Defined in: node_modules/.pnpm/@types+node\@22.13.5/node_modules/@types/node/globals.d.ts:145
#### Inherited from
`Error.stackTraceLimit`
## Methods
### captureStackTrace()
> `static` **captureStackTrace**(`targetObject`, `constructorOpt`?): `void`
Defined in: node_modules/.pnpm/@types+node\@22.13.5/node_modules/@types/node/globals.d.ts:136
Create .stack property on a target object
#### Parameters
##### targetObject
`object`
##### constructorOpt?
`Function`
#### Returns
`void`
#### Inherited from
`Error.captureStackTrace`

View File

@@ -10,7 +10,7 @@
# Interface: LayoutData
Defined in: [packages/mermaid/src/rendering-util/types.ts:145](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L145)
Defined in: [packages/mermaid/src/rendering-util/types.ts:170](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L170)
## Indexable
@@ -22,7 +22,7 @@ Defined in: [packages/mermaid/src/rendering-util/types.ts:145](https://github.co
> **config**: [`MermaidConfig`](MermaidConfig.md)
Defined in: [packages/mermaid/src/rendering-util/types.ts:148](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L148)
Defined in: [packages/mermaid/src/rendering-util/types.ts:173](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L173)
---
@@ -30,7 +30,7 @@ Defined in: [packages/mermaid/src/rendering-util/types.ts:148](https://github.co
> **edges**: `Edge`\[]
Defined in: [packages/mermaid/src/rendering-util/types.ts:147](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L147)
Defined in: [packages/mermaid/src/rendering-util/types.ts:172](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L172)
---
@@ -38,4 +38,4 @@ Defined in: [packages/mermaid/src/rendering-util/types.ts:147](https://github.co
> **nodes**: `Node`\[]
Defined in: [packages/mermaid/src/rendering-util/types.ts:146](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L146)
Defined in: [packages/mermaid/src/rendering-util/types.ts:171](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/rendering-util/types.ts#L171)

View File

@@ -32,7 +32,7 @@ page.
### detectType()
> **detectType**: (`text`, `config`?) => `string`
> **detectType**: (`text`, `config?`) => `string`
Defined in: [packages/mermaid/src/mermaid.ts:449](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L449)
@@ -105,7 +105,7 @@ An array of objects with the id of the diagram.
### ~~init()~~
> **init**: (`config`?, `nodes`?, `callback`?) => `Promise`<`void`>
> **init**: (`config?`, `nodes?`, `callback?`) => `Promise`<`void`>
Defined in: [packages/mermaid/src/mermaid.ts:442](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L442)
@@ -117,7 +117,7 @@ Defined in: [packages/mermaid/src/mermaid.ts:442](https://github.com/mermaid-js/
[`MermaidConfig`](MermaidConfig.md)
**Deprecated**, please set configuration in [initialize](Mermaid.md#initialize).
**Deprecated**, please set configuration in [initialize](#initialize).
##### nodes?
@@ -141,13 +141,13 @@ Called once for each rendered diagram's id.
#### Deprecated
Use [initialize](Mermaid.md#initialize) and [run](Mermaid.md#run) instead.
Use [initialize](#initialize) and [run](#run) instead.
Renders the mermaid diagrams
#### Deprecated
Use [initialize](Mermaid.md#initialize) and [run](Mermaid.md#run) instead.
Use [initialize](#initialize) and [run](#run) instead.
---
@@ -176,7 +176,7 @@ Configuration object for mermaid.
### ~~mermaidAPI~~
> **mermaidAPI**: `Readonly`<{ `defaultConfig`: [`MermaidConfig`](MermaidConfig.md); `getConfig`: () => [`MermaidConfig`](MermaidConfig.md); `getDiagramFromText`: (`text`, `metadata`) => `Promise`<`Diagram`>; `getSiteConfig`: () => [`MermaidConfig`](MermaidConfig.md); `globalReset`: () => `void`; `initialize`: (`userOptions`) => `void`; `parse`: (`text`, `parseOptions`) => `Promise`<`false` | [`ParseResult`](ParseResult.md)>(`text`, `parseOptions`?) => `Promise`<[`ParseResult`](ParseResult.md)>; `render`: (`id`, `text`, `svgContainingElement`?) => `Promise`<[`RenderResult`](RenderResult.md)>; `reset`: () => `void`; `setConfig`: (`conf`) => [`MermaidConfig`](MermaidConfig.md); `updateSiteConfig`: (`conf`) => [`MermaidConfig`](MermaidConfig.md); }>
> **mermaidAPI**: `Readonly`<{ `defaultConfig`: [`MermaidConfig`](MermaidConfig.md); `getConfig`: () => [`MermaidConfig`](MermaidConfig.md); `getDiagramFromText`: (`text`, `metadata`) => `Promise`<`Diagram`>; `getSiteConfig`: () => [`MermaidConfig`](MermaidConfig.md); `globalReset`: () => `void`; `initialize`: (`userOptions`) => `void`; `parse`: {(`text`, `parseOptions`): `Promise`<`false` | [`ParseResult`](ParseResult.md)>; (`text`, `parseOptions?`): `Promise`<[`ParseResult`](ParseResult.md)>; }; `render`: (`id`, `text`, `svgContainingElement?`) => `Promise`<[`RenderResult`](RenderResult.md)>; `reset`: () => `void`; `setConfig`: (`conf`) => [`MermaidConfig`](MermaidConfig.md); `updateSiteConfig`: (`conf`) => [`MermaidConfig`](MermaidConfig.md); }>
Defined in: [packages/mermaid/src/mermaid.ts:436](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L436)
@@ -184,73 +184,81 @@ Defined in: [packages/mermaid/src/mermaid.ts:436](https://github.com/mermaid-js/
#### Deprecated
Use [parse](Mermaid.md#parse) and [render](Mermaid.md#render) instead. Please [open a discussion](https://github.com/mermaid-js/mermaid/discussions) if your use case does not fit the new API.
Use [parse](#parse) and [render](#render) instead. Please [open a discussion](https://github.com/mermaid-js/mermaid/discussions) if your use case does not fit the new API.
---
### parse()
> **parse**: (`text`, `parseOptions`) => `Promise`<`false` | [`ParseResult`](ParseResult.md)>(`text`, `parseOptions`?) => `Promise`<[`ParseResult`](ParseResult.md)>
> **parse**: {(`text`, `parseOptions`): `Promise`<`false` | [`ParseResult`](ParseResult.md)>; (`text`, `parseOptions?`): `Promise`<[`ParseResult`](ParseResult.md)>; }
Defined in: [packages/mermaid/src/mermaid.ts:437](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L437)
#### Call Signature
> (`text`, `parseOptions`): `Promise`<`false` | [`ParseResult`](ParseResult.md)>
Parse the text and validate the syntax.
#### Parameters
##### Parameters
##### text
###### text
`string`
The mermaid diagram definition.
##### parseOptions
###### parseOptions
[`ParseOptions`](ParseOptions.md) & `object`
Options for parsing.
#### Returns
##### Returns
`Promise`<`false` | [`ParseResult`](ParseResult.md)>
An object with the `diagramType` set to type of the diagram if valid. Otherwise `false` if parseOptions.suppressErrors is `true`.
#### See
##### See
[ParseOptions](ParseOptions.md)
#### Throws
##### Throws
Error if the diagram is invalid and parseOptions.suppressErrors is false or not set.
#### Call Signature
> (`text`, `parseOptions?`): `Promise`<[`ParseResult`](ParseResult.md)>
Parse the text and validate the syntax.
#### Parameters
##### Parameters
##### text
###### text
`string`
The mermaid diagram definition.
##### parseOptions?
###### parseOptions?
[`ParseOptions`](ParseOptions.md)
Options for parsing.
#### Returns
##### Returns
`Promise`<[`ParseResult`](ParseResult.md)>
An object with the `diagramType` set to type of the diagram if valid. Otherwise `false` if parseOptions.suppressErrors is `true`.
#### See
##### See
[ParseOptions](ParseOptions.md)
#### Throws
##### Throws
Error if the diagram is invalid and parseOptions.suppressErrors is false or not set.
@@ -332,7 +340,7 @@ Defined in: [packages/mermaid/src/mermaid.ts:444](https://github.com/mermaid-js/
### render()
> **render**: (`id`, `text`, `svgContainingElement`?) => `Promise`<[`RenderResult`](RenderResult.md)>
> **render**: (`id`, `text`, `svgContainingElement?`) => `Promise`<[`RenderResult`](RenderResult.md)>
Defined in: [packages/mermaid/src/mermaid.ts:438](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/mermaid.ts#L438)

View File

@@ -10,7 +10,7 @@
# Interface: ParseOptions
Defined in: [packages/mermaid/src/types.ts:59](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L59)
Defined in: [packages/mermaid/src/types.ts:76](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L76)
## Properties
@@ -18,7 +18,7 @@ Defined in: [packages/mermaid/src/types.ts:59](https://github.com/mermaid-js/mer
> `optional` **suppressErrors**: `boolean`
Defined in: [packages/mermaid/src/types.ts:64](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L64)
Defined in: [packages/mermaid/src/types.ts:81](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L81)
If `true`, parse will return `false` instead of throwing error when the diagram is invalid.
The `parseError` function will not be called.

View File

@@ -10,7 +10,7 @@
# Interface: ParseResult
Defined in: [packages/mermaid/src/types.ts:67](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L67)
Defined in: [packages/mermaid/src/types.ts:84](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L84)
## Properties
@@ -18,7 +18,7 @@ Defined in: [packages/mermaid/src/types.ts:67](https://github.com/mermaid-js/mer
> **config**: [`MermaidConfig`](MermaidConfig.md)
Defined in: [packages/mermaid/src/types.ts:75](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L75)
Defined in: [packages/mermaid/src/types.ts:92](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L92)
The config passed as YAML frontmatter or directives
@@ -28,6 +28,6 @@ The config passed as YAML frontmatter or directives
> **diagramType**: `string`
Defined in: [packages/mermaid/src/types.ts:71](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L71)
Defined in: [packages/mermaid/src/types.ts:88](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L88)
The diagram type, e.g. 'flowchart', 'sequence', etc.

View File

@@ -10,7 +10,7 @@
# Interface: RenderResult
Defined in: [packages/mermaid/src/types.ts:85](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L85)
Defined in: [packages/mermaid/src/types.ts:102](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L102)
## Properties
@@ -18,7 +18,7 @@ Defined in: [packages/mermaid/src/types.ts:85](https://github.com/mermaid-js/mer
> `optional` **bindFunctions**: (`element`) => `void`
Defined in: [packages/mermaid/src/types.ts:103](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L103)
Defined in: [packages/mermaid/src/types.ts:120](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L120)
Bind function to be called after the svg has been inserted into the DOM.
This is necessary for adding event listeners to the elements in the svg.
@@ -45,7 +45,7 @@ bindFunctions?.(div); // To call bindFunctions only if it's present.
> **diagramType**: `string`
Defined in: [packages/mermaid/src/types.ts:93](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L93)
Defined in: [packages/mermaid/src/types.ts:110](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L110)
The diagram type, e.g. 'flowchart', 'sequence', etc.
@@ -55,6 +55,6 @@ The diagram type, e.g. 'flowchart', 'sequence', etc.
> **svg**: `string`
Defined in: [packages/mermaid/src/types.ts:89](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L89)
Defined in: [packages/mermaid/src/types.ts:106](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/types.ts#L106)
The svg code for the rendered graph.

View File

@@ -0,0 +1,65 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/setup/mermaid/interfaces/UnknownDiagramError.md](../../../../../packages/mermaid/src/docs/config/setup/mermaid/interfaces/UnknownDiagramError.md).
[**mermaid**](../../README.md)
---
# Interface: UnknownDiagramError
Defined in: [packages/mermaid/src/errors.ts:1](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/errors.ts#L1)
## Extends
- `Error`
## Properties
### cause?
> `optional` **cause**: `unknown`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
#### Inherited from
`Error.cause`
---
### message
> **message**: `string`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es5.d.ts:1077
#### Inherited from
`Error.message`
---
### name
> **name**: `string`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es5.d.ts:1076
#### Inherited from
`Error.name`
---
### stack?
> `optional` **stack**: `string`
Defined in: node_modules/.pnpm/typescript\@5.7.3/node_modules/typescript/lib/lib.es5.d.ts:1078
#### Inherited from
`Error.stack`

View File

@@ -10,6 +10,6 @@
# Type Alias: InternalHelpers
> **InternalHelpers**: _typeof_ `internalHelpers`
> **InternalHelpers** = _typeof_ `internalHelpers`
Defined in: [packages/mermaid/src/internals.ts:33](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/internals.ts#L33)

View File

@@ -10,7 +10,7 @@
# Type Alias: ParseErrorFunction()
> **ParseErrorFunction**: (`err`, `hash`?) => `void`
> **ParseErrorFunction** = (`err`, `hash?`) => `void`
Defined in: [packages/mermaid/src/Diagram.ts:10](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/Diagram.ts#L10)

View File

@@ -10,6 +10,6 @@
# Type Alias: SVG
> **SVG**: `d3.Selection`<`SVGSVGElement`, `unknown`, `Element` | `null`, `unknown`>
> **SVG** = `d3.Selection`<`SVGSVGElement`, `unknown`, `Element` | `null`, `unknown`>
Defined in: [packages/mermaid/src/diagram-api/types.ts:126](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L126)

View File

@@ -10,6 +10,6 @@
# Type Alias: SVGGroup
> **SVGGroup**: `d3.Selection`<`SVGGElement`, `unknown`, `Element` | `null`, `unknown`>
> **SVGGroup** = `d3.Selection`<`SVGGElement`, `unknown`, `Element` | `null`, `unknown`>
Defined in: [packages/mermaid/src/diagram-api/types.ts:128](https://github.com/mermaid-js/mermaid/blob/master/packages/mermaid/src/diagram-api/types.ts#L128)

63
docs/config/tidy-tree.md Normal file
View File

@@ -0,0 +1,63 @@
> **Warning**
>
> ## THIS IS AN AUTOGENERATED FILE. DO NOT EDIT.
>
> ## Please edit the corresponding file in [/packages/mermaid/src/docs/config/tidy-tree.md](../../packages/mermaid/src/docs/config/tidy-tree.md).
# Tidy-tree Layout Instructions
Instructions to use the Tidy-tree layout algorithm.
## Getting Started
### Installation
```bash
npm install non-layered-tidy-tree-layout
# or
yarn add non-layered-tidy-tree-layout
```
There's also a built version: `dist/non-layered-tidy-tree-layout.js` for use with browser `<script>` tag, or as a Javascript module.
## Tidy tree Layouts
Mermaid also supports a Tidy Tree layout for mindmaps.
```
---
config:
layout: tidy-tree
---
mindmap
root((mindmap is a long thing))
A
B
C
D
```
### With bundlers
```sh
npm install @mermaid-js/layout-tidy-tree
```
```ts
import mermaid from 'mermaid';
import tidyTreeLayouts from '@mermaid-js/layout-tidy-tree';
mermaid.registerLayoutLoaders(tidyTreeLayouts);
```
### With CDN
```html
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
import tidyTreeLayouts from 'https://cdn.jsdelivr.net/npm/@mermaid-js/layout-tidy-tree@0/dist/mermaid-layout-tidy-tree.esm.min.mjs';
mermaid.registerLayoutLoaders(tidyTreeLayouts);
</script>
```

View File

@@ -0,0 +1,189 @@
---
references:
- "File: /packages/mermaid/src/diagrams/flowchart/flowDiagram.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/flowDb.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/flowDetector.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/flowDetector-v2.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/flowRenderer-v3-unified.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/styles.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/types.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/flowChartShapes.js"
- "File: /packages/mermaid/src/diagrams/flowchart/parser/flowParser.ts"
- "File: /packages/mermaid/src/diagrams/flowchart/elk/detector.ts"
generationTime: 2025-07-23T10:31:53.266Z
---
flowchart TD
%% Entry Points and Detection
Input["User Input Text"] --> Detection{Detection Phase}
Detection --> flowDetector["flowDetector.ts<br/>detector(txt, config)"]
Detection --> flowDetectorV2["flowDetector-v2.ts<br/>detector(txt, config)"]
Detection --> elkDetector["elk/detector.ts<br/>detector(txt, config)"]
flowDetector --> |"Checks /^\s*graph/"| DetectLegacy{Legacy Flowchart?}
flowDetectorV2 --> |"Checks /^\s*flowchart/"| DetectNew{New Flowchart?}
elkDetector --> |"Checks /^\s*flowchart-elk/"| DetectElk{ELK Layout?}
DetectLegacy --> |Yes| LoadDiagram
DetectNew --> |Yes| LoadDiagram
DetectElk --> |Yes| LoadDiagram
%% Loading Phase
LoadDiagram["loader() function"] --> flowDiagram["flowDiagram.ts<br/>diagram object"]
flowDiagram --> DiagramStructure{Diagram Components}
DiagramStructure --> Parser["parser: flowParser"]
DiagramStructure --> Database["db: new FlowDB()"]
DiagramStructure --> Renderer["renderer: flowRenderer-v3-unified"]
DiagramStructure --> Styles["styles: flowStyles"]
DiagramStructure --> Init["init: (cnf: MermaidConfig)"]
%% Parser Phase
Parser --> flowParser["parser/flowParser.ts<br/>newParser.parse(src)"]
flowParser --> |"Preprocesses src"| RemoveWhitespace["Remove trailing whitespace<br/>src.replace(/}\s*\n/g, '}\n')"]
RemoveWhitespace --> flowJison["parser/flow.jison<br/>flowJisonParser.parse(newSrc)"]
flowJison --> ParseGraph["Parse Graph Structure"]
ParseGraph --> ParseVertices["Parse Vertices"]
ParseGraph --> ParseEdges["Parse Edges"]
ParseGraph --> ParseSubgraphs["Parse Subgraphs"]
ParseGraph --> ParseClasses["Parse Classes"]
ParseGraph --> ParseStyles["Parse Styles"]
%% Database Phase - FlowDB Class
Database --> FlowDBClass["flowDb.ts<br/>FlowDB class"]
FlowDBClass --> DBInit["constructor()<br/>- Initialize counters<br/>- Bind methods<br/>- Setup toolTips<br/>- Call clear()"]
DBInit --> DBMethods{FlowDB Methods}
DBMethods --> addVertex["addVertex(id, textObj, type, style,<br/>classes, dir, props, metadata)"]
DBMethods --> addLink["addLink(_start[], _end[], linkData)"]
DBMethods --> addSingleLink["addSingleLink(_start, _end, type, id)"]
DBMethods --> setDirection["setDirection(dir)"]
DBMethods --> addSubGraph["addSubGraph(nodes[], id, title)"]
DBMethods --> addClass["addClass(id, style)"]
DBMethods --> setClass["setClass(ids, className)"]
DBMethods --> setTooltip["setTooltip(ids, tooltip)"]
DBMethods --> setClickEvent["setClickEvent(id, functionName, args)"]
DBMethods --> setClickFun["setClickFun(id, functionName, args)"]
%% Vertex Processing
addVertex --> VertexProcess{Vertex Processing}
VertexProcess --> CreateVertex["Create FlowVertex object<br/>- id, labelType, domId<br/>- styles[], classes[]"]
VertexProcess --> SanitizeText["sanitizeText(textObj.text)"]
VertexProcess --> ParseMetadata["Parse YAML metadata<br/>yaml.load(yamlData)"]
VertexProcess --> SetVertexProps["Set vertex properties<br/>- shape, label, icon, form<br/>- pos, img, constraint, w, h"]
%% Edge Processing
addSingleLink --> EdgeProcess{Edge Processing}
EdgeProcess --> CreateEdge["Create FlowEdge object<br/>- start, end, type, text<br/>- labelType, classes[]"]
EdgeProcess --> ProcessLinkText["Process link text<br/>- sanitizeText()<br/>- strip quotes"]
EdgeProcess --> SetEdgeProps["Set edge properties<br/>- type, stroke, length"]
EdgeProcess --> GenerateEdgeId["Generate edge ID<br/>getEdgeId(start, end, counter)"]
EdgeProcess --> ValidateEdgeLimit["Validate edge limit<br/>maxEdges check"]
%% Data Collection
DBMethods --> GetData["getData()"]
GetData --> CollectNodes["Collect nodes[] from vertices"]
GetData --> CollectEdges["Collect edges[] from edges"]
GetData --> ProcessSubGraphs["Process subgraphs<br/>- parentDB Map<br/>- subGraphDB Map"]
GetData --> AddNodeFromVertex["addNodeFromVertex()<br/>for each vertex"]
GetData --> ProcessEdgeTypes["destructEdgeType()<br/>arrowTypeStart, arrowTypeEnd"]
%% Node Creation
AddNodeFromVertex --> NodeCreation{Node Creation}
NodeCreation --> FindExistingNode["findNode(nodes, vertex.id)"]
NodeCreation --> CreateBaseNode["Create base node<br/>- id, label, parentId<br/>- cssStyles, cssClasses<br/>- shape, domId, tooltip"]
NodeCreation --> GetCompiledStyles["getCompiledStyles(classDefs)"]
NodeCreation --> GetTypeFromVertex["getTypeFromVertex(vertex)"]
%% Rendering Phase
Renderer --> flowRendererV3["flowRenderer-v3-unified.ts<br/>draw(text, id, version, diag)"]
flowRendererV3 --> RenderInit["Initialize rendering<br/>- getConfig()<br/>- handle securityLevel<br/>- getDiagramElement()"]
RenderInit --> GetLayoutData["diag.db.getData()<br/>as LayoutData"]
GetLayoutData --> SetupLayoutData["Setup layout data<br/>- type, layoutAlgorithm<br/>- direction, spacing<br/>- markers, diagramId"]
SetupLayoutData --> CallRender["render(data4Layout, svg)"]
CallRender --> SetupViewPort["setupViewPortForSVG(svg, padding)"]
SetupViewPort --> ProcessLinks["Process vertex links<br/>- create anchor elements<br/>- handle click events"]
%% Shape Rendering
CallRender --> ShapeSystem["flowChartShapes.js<br/>Shape Functions"]
ShapeSystem --> ShapeFunctions{Shape Functions}
ShapeFunctions --> question["question(parent, bbox, node)"]
ShapeFunctions --> hexagon["hexagon(parent, bbox, node)"]
ShapeFunctions --> rect_left_inv_arrow["rect_left_inv_arrow(parent, bbox, node)"]
ShapeFunctions --> lean_right["lean_right(parent, bbox, node)"]
ShapeFunctions --> lean_left["lean_left(parent, bbox, node)"]
ShapeFunctions --> insertPolygonShape["insertPolygonShape(parent, w, h, points)"]
ShapeFunctions --> intersectPolygon["intersectPolygon(node, points, point)"]
ShapeFunctions --> intersectRect["intersectRect(node, point)"]
%% Styling System
Styles --> stylesTS["styles.ts<br/>getStyles(options)"]
stylesTS --> StyleOptions["FlowChartStyleOptions<br/>- arrowheadColor, border2<br/>- clusterBkg, mainBkg<br/>- fontFamily, textColor"]
StyleOptions --> GenerateCSS["Generate CSS styles<br/>- .label, .cluster-label<br/>- .node, .edgePath<br/>- .flowchart-link, .edgeLabel"]
GenerateCSS --> GetIconStyles["getIconStyles()"]
%% Type System
Parser --> TypeSystem["types.ts<br/>Type Definitions"]
TypeSystem --> FlowVertex["FlowVertex interface"]
TypeSystem --> FlowEdge["FlowEdge interface"]
TypeSystem --> FlowClass["FlowClass interface"]
TypeSystem --> FlowSubGraph["FlowSubGraph interface"]
TypeSystem --> FlowVertexTypeParam["FlowVertexTypeParam<br/>Shape types"]
%% Utility Functions
DBMethods --> UtilityFunctions{Utility Functions}
UtilityFunctions --> lookUpDomId["lookUpDomId(id)"]
UtilityFunctions --> getClasses["getClasses()"]
UtilityFunctions --> getDirection["getDirection()"]
UtilityFunctions --> getVertices["getVertices()"]
UtilityFunctions --> getEdges["getEdges()"]
UtilityFunctions --> getSubGraphs["getSubGraphs()"]
UtilityFunctions --> clear["clear()"]
UtilityFunctions --> defaultConfig["defaultConfig()"]
%% Event Handling
ProcessLinks --> EventHandling{Event Handling}
EventHandling --> setupToolTips["setupToolTips(element)"]
EventHandling --> bindFunctions["bindFunctions(element)"]
EventHandling --> runFunc["utils.runFunc(functionName, args)"]
%% Common Database Functions
DBMethods --> CommonDB["commonDb.js functions"]
CommonDB --> setAccTitle["setAccTitle()"]
CommonDB --> getAccTitle["getAccTitle()"]
CommonDB --> setAccDescription["setAccDescription()"]
CommonDB --> getAccDescription["getAccDescription()"]
CommonDB --> setDiagramTitle["setDiagramTitle()"]
CommonDB --> getDiagramTitle["getDiagramTitle()"]
CommonDB --> commonClear["clear()"]
%% Final Output
ProcessLinks --> FinalSVG["Final SVG Output"]
%% Layout Algorithm Selection
SetupLayoutData --> LayoutAlgorithm{Layout Algorithm}
LayoutAlgorithm --> Dagre["dagre<br/>(default)"]
LayoutAlgorithm --> DagreWrapper["dagre-wrapper<br/>(v2 renderer)"]
LayoutAlgorithm --> ELK["elk<br/>(external package)"]
%% Testing Components
FlowDBClass --> TestFiles["Test Files"]
TestFiles --> flowDbSpec["flowDb.spec.ts"]
TestFiles --> flowChartShapesSpec["flowChartShapes.spec.js"]
TestFiles --> ParserTests["parser/*.spec.js files<br/>- flow-text.spec.js<br/>- flow-edges.spec.js<br/>- flow-style.spec.js<br/>- subgraph.spec.js"]
%% Configuration
Init --> ConfigSetup["Configuration Setup"]
ConfigSetup --> FlowchartConfig["cnf.flowchart config"]
ConfigSetup --> ArrowMarkers["arrowMarkerAbsolute"]
ConfigSetup --> LayoutConfig["layout config"]
ConfigSetup --> SetConfig["setConfig() calls"]

View File

@@ -0,0 +1,307 @@
---
references:
- "File: /packages/mermaid/src/mermaidAPI.ts"
- "File: /packages/mermaid/src/mermaid.ts"
generationTime: 2025-01-28T16:30:00.000Z
---
sequenceDiagram
participant User as User/Browser
participant Mermaid as mermaid.ts
participant Queue as executionQueue
participant API as mermaidAPI.ts
participant Config as configApi
participant Preprocessor as preprocessDiagram
participant DiagramAPI as diagram-api
participant Diagram as Diagram.fromText
participant Renderer as diagram.renderer
participant Styles as Styling System
participant DOM as DOM/SVG
Note over User, DOM: Mermaid Complete API Flow
%% Initialization Phase
User->>+Mermaid: mermaid.initialize(config)
Mermaid->>+API: mermaidAPI.initialize(config)
API->>API: assignWithDepth({}, userOptions)
API->>API: handle legacy fontFamily config
API->>Config: saveConfigFromInitialize(options)
alt Theme Configuration Available
API->>API: check if theme in theme object
API->>API: set themeVariables from theme
else Default Theme
API->>API: use default theme variables
end
API->>Config: setSiteConfig(options) or getSiteConfig()
API->>API: setLogLevel(config.logLevel)
API->>DiagramAPI: addDiagrams()
API-->>-Mermaid: initialization complete
Mermaid-->>-User: ready to render
%% Content Loaded Event
User->>DOM: document.load event
DOM->>+Mermaid: contentLoaded()
opt startOnLoad is true
Mermaid->>Config: getConfig()
Config-->>Mermaid: { startOnLoad: true }
Mermaid->>Mermaid: run()
end
Mermaid-->>-DOM: event handling complete
%% Main Run Function
User->>+Mermaid: mermaid.run(options)
Mermaid->>Mermaid: runThrowsErrors(options)
Mermaid->>Config: getConfig()
Config-->>Mermaid: configuration object
alt nodes provided
Mermaid->>Mermaid: use provided nodes
else querySelector provided
Mermaid->>DOM: document.querySelectorAll(querySelector)
DOM-->>Mermaid: nodesToProcess
end
Mermaid->>Mermaid: new InitIDGenerator(deterministicIds, seed)
loop For each diagram element
Mermaid->>DOM: check element.getAttribute('data-processed')
opt not processed
Mermaid->>DOM: element.setAttribute('data-processed', 'true')
Mermaid->>Mermaid: generate unique id
Mermaid->>DOM: get element.innerHTML
Mermaid->>Mermaid: entityDecode and clean text
Mermaid->>Mermaid: detectInit(txt)
Mermaid->>Queue: render(id, txt, element)
end
end
Mermaid-->>-User: processing initiated
%% Render Function (Queued)
activate Queue
Queue->>+API: mermaidAPI.render(id, text, container)
API->>DiagramAPI: addDiagrams()
API->>+Preprocessor: processAndSetConfigs(text)
Preprocessor->>Preprocessor: preprocessDiagram(text)
Preprocessor->>Config: reset()
Preprocessor->>Config: addDirective(processed.config)
Preprocessor-->>-API: { code, config }
API->>Config: getConfig()
Config-->>API: current configuration
opt text length > maxTextSize
API->>API: text = MAX_TEXTLENGTH_EXCEEDED_MSG
end
API->>API: setup id selectors and element IDs
API->>API: determine security level (sandbox/loose)
%% DOM Setup
alt svgContainingElement provided
alt isSandboxed
API->>DOM: sandboxedIframe(select(svgContainingElement), iFrameID)
API->>DOM: select iframe contentDocument body
else
API->>DOM: select(svgContainingElement)
end
else no container
API->>API: removeExistingElements(document, id, divId, iFrameId)
alt isSandboxed
API->>DOM: sandboxedIframe(select('body'), iFrameID)
else
API->>DOM: select('body')
end
end
API->>DOM: appendDivSvgG(root, id, enclosingDivID, fontFamily, XMLNS_XLINK_STD)
%% Diagram Creation
API->>+Diagram: Diagram.fromText(text, { title: processed.title })
Diagram->>DiagramAPI: detect diagram type
Diagram->>DiagramAPI: load appropriate diagram
Diagram-->>-API: diagram instance
opt parsing error occurred
API->>+Diagram: Diagram.fromText('error')
Diagram-->>-API: error diagram
API->>API: store parseEncounteredException
end
%% Style Generation
API->>DOM: get svg element and firstChild
API->>Renderer: diag.renderer.getClasses(text, diag)
Renderer-->>API: diagramClassDefs
API->>+Styles: createUserStyles(config, diagramType, diagramClassDefs, idSelector)
Styles->>Styles: createCssStyles(config, classDefs)
opt config.themeCSS defined
Styles->>Styles: append themeCSS
end
opt fontFamily configured
Styles->>Styles: add CSS variables for fonts
end
opt classDefs exist
loop For each styleClassDef
opt has styles
Styles->>Styles: cssImportantStyles for each CSS element
end
opt has textStyles
Styles->>Styles: cssImportantStyles for tspan elements
end
end
end
Styles->>Styles: getStyles(graphType, userCSSstyles, themeVariables)
Styles->>Styles: serialize(compile(svgId{allStyles}), stringify)
Styles-->>-API: compiled CSS rules
API->>DOM: create style element
API->>DOM: style.innerHTML = rules
API->>DOM: svg.insertBefore(style, firstChild)
%% Diagram Rendering
API->>+Renderer: diag.renderer.draw(text, id, version, diag)
Renderer->>Renderer: diagram-specific rendering logic
Renderer->>DOM: create SVG elements
Renderer->>DOM: apply positioning and styling
Renderer-->>-API: rendered diagram
opt rendering error
alt suppressErrorRendering
API->>API: removeTempElements()
API->>Mermaid: throw error
else
API->>Renderer: errorRenderer.draw(text, id, version)
end
end
%% Accessibility and Cleanup
API->>DOM: select svg element
API->>Diagram: diag.db.getAccTitle()
API->>Diagram: diag.db.getAccDescription()
API->>API: addA11yInfo(diagramType, svgNode, a11yTitle, a11yDescr)
API->>DOM: set xmlns for foreignobject elements
API->>DOM: get innerHTML from enclosing div
API->>+API: cleanUpSvgCode(svgCode, isSandboxed, arrowMarkerAbsolute)
opt not useArrowMarkerUrls and not sandboxed
API->>API: replace marker-end URLs with anchors
end
API->>API: decodeEntities(svgCode)
API->>API: replace <br> with <br/>
API-->>-API: cleaned SVG code
alt isSandboxed
API->>+API: putIntoIFrame(svgCode, svgEl)
API->>API: calculate iframe height
API->>API: toBase64 encode SVG content
API->>API: create iframe with sandbox attributes
API-->>-API: iframe HTML
else not loose security
API->>API: DOMPurify.sanitize(svgCode, options)
end
API->>API: attachFunctions()
API->>API: removeTempElements()
opt parseEncounteredException
API->>Mermaid: throw parseEncounteredException
end
API-->>-Queue: { diagramType, svg: svgCode, bindFunctions }
%% Return to Web Integration
activate Mermaid
Queue-->>Mermaid: render result
Mermaid->>DOM: element.innerHTML = svg
opt postRenderCallback
Mermaid->>User: postRenderCallback(id)
end
opt bindFunctions exist
Mermaid->>DOM: bindFunctions(element)
end
deactivate Mermaid
%% Parse Function Flow
User->>+Mermaid: mermaid.parse(text, parseOptions)
activate Queue
Queue->>+API: mermaidAPI.parse(text, parseOptions)
API->>DiagramAPI: addDiagrams()
API->>Preprocessor: processAndSetConfigs(text)
Preprocessor-->>API: { code, config }
API->>Diagram: getDiagramFromText(code)
Diagram-->>API: diagram instance
API-->>-Queue: { diagramType: diagram.type, config }
Queue-->>-Mermaid: parse result
Mermaid-->>-User: ParseResult or false
%% External Diagram Registration
User->>+Mermaid: registerExternalDiagrams(diagrams, options)
Mermaid->>DiagramAPI: addDiagrams()
Mermaid->>DiagramAPI: registerLazyLoadedDiagrams(...diagrams)
opt lazyLoad is false
Mermaid->>DiagramAPI: loadRegisteredDiagrams()
end
Mermaid-->>-User: registration complete
%% Error Handling
Note over Mermaid, API: Error Handling Throughout
alt Error occurs
API->>Mermaid: throw error
Mermaid->>+Mermaid: handleError(error, errors, parseError)
Mermaid->>Mermaid: log.warn(error)
alt isDetailedError
Mermaid->>User: parseError(error.str, error.hash)
else
Mermaid->>User: parseError(error)
end
opt not suppressErrors
Mermaid->>User: throw error
end
Mermaid-->>-User: error handled
end
%% Configuration Details
Note over Config: Configuration Functions
Note right of Config: Functions:<br/>- reset()<br/>- getConfig()<br/>- setConfig()<br/>- getSiteConfig()<br/>- updateSiteConfig()<br/>- saveConfigFromInitialize()
Note over Styles: CSS Generation
Note right of Styles: Features:<br/>- createCssStyles()<br/>- createUserStyles()<br/>- cssImportantStyles()<br/>- Theme integration<br/>- Class definitions
Note over API: Security Levels
Note right of API: Modes:<br/>- sandbox: iframe isolation<br/>- loose: minimal sanitization<br/>- default: DOMPurify sanitization
Note over API: Helper Functions
Note right of API: Utilities:<br/>- cleanUpSvgCode()<br/>- putIntoIFrame()<br/>- appendDivSvgG()<br/>- removeExistingElements()

View File

@@ -0,0 +1,180 @@
---
references:
- "File: /packages/mermaid/src/diagrams/mindmap/mindmap-definition.ts"
- "File: /packages/mermaid/src/diagrams/mindmap/mindmapDb.ts"
- "File: /packages/mermaid/src/diagrams/mindmap/detector.ts"
- "File: /packages/mermaid/src/diagrams/mindmap/mindmapTypes.ts"
- "File: /packages/mermaid/src/diagrams/mindmap/mindmapRenderer.ts"
- "File: /packages/mermaid/src/diagrams/mindmap/styles.ts"
- "File: /packages/mermaid/src/diagrams/mindmap/svgDraw.ts"
generationTime: 2025-01-28T16:00:00.000Z
---
sequenceDiagram
participant User as User Input Text
participant Detector as detector.ts
participant Loader as DiagramLoader
participant Definition as mindmap-definition.ts
participant Parser as parser/mindmap.jison
participant DB as MindmapDB
participant Renderer as mindmapRenderer.ts
participant Cytoscape as cytoscape.js
participant SVGDraw as svgDraw.ts
participant Styles as styles.ts
participant Output as Final SVG
Note over User, Output: Mindmap Implementation Flow
%% Detection Phase
User->>Detector: /^\s*mindmap/ text input
activate Detector
Detector->>Detector: detector(txt) validates pattern
Detector->>Loader: loader() function called
deactivate Detector
activate Loader
Loader->>Definition: import mindmap-definition.js
deactivate Loader
%% Core Structure Setup
activate Definition
Definition->>DB: get db() → new MindmapDB()
Definition->>Renderer: setup renderer
Definition->>Parser: setup parser
Definition->>Styles: setup styles
deactivate Definition
%% Database Initialization
activate DB
Note over DB: MindmapDB Constructor
DB->>DB: initialize nodes array
DB->>DB: setup nodeType constants
DB->>DB: bind methods
DB->>DB: clear() state
%% Parsing Phase
activate Parser
User->>Parser: mindmap syntax text
loop For each node in hierarchy
Parser->>DB: addNode(level, id, descr, type)
activate DB
DB->>DB: sanitizeText(id, descr)
DB->>DB: getType(startStr, endStr)
Note right of DB: Shape Detection:<br/>[ → RECT<br/>( → ROUNDED_RECT<br/>(( → CIRCLE<br/>)) → BANG<br/>{{ → HEXAGON
DB->>DB: getParent(level)
DB->>DB: create MindmapNode
DB->>DB: add to hierarchy
deactivate DB
end
opt Icon/Class Decoration
Parser->>DB: decorateNode(decoration)
DB->>DB: set icon/class properties
end
deactivate Parser
%% Data Preparation
Renderer->>DB: getData() for layout
activate DB
DB->>DB: collect all nodes
DB->>DB: build parent-child relationships
DB-->>Renderer: return node hierarchy
deactivate DB
%% Rendering Pipeline
activate Renderer
Note over Renderer: Rendering Phase
Renderer->>Cytoscape: initialize cytoscape
activate Cytoscape
loop For each node in mindmap
Renderer->>Cytoscape: addNodes(mindmap, cy, conf, level)
Cytoscape->>Cytoscape: create node data
Cytoscape->>Cytoscape: set position (x, y)
end
loop For parent-child relationships
Renderer->>Cytoscape: add edges
Cytoscape->>Cytoscape: create edge data
end
Renderer->>Cytoscape: configure cose-bilkent layout
Cytoscape->>Cytoscape: calculate optimal positions
Cytoscape-->>Renderer: return positioned graph
deactivate Cytoscape
%% SVG Generation
Renderer->>SVGDraw: drawNodes(db, svg, mindmap, section, conf)
activate SVGDraw
loop For each node recursively
SVGDraw->>SVGDraw: select shape function
alt Default Shape
SVGDraw->>SVGDraw: defaultBkg() - rounded rectangle
else Rectangle Shape
SVGDraw->>SVGDraw: rectBkg() - sharp corners
else Circle Shape
SVGDraw->>SVGDraw: circleBkg() - perfect circle
else Cloud Shape
SVGDraw->>SVGDraw: cloudBkg() - organic curves
else Bang Shape
SVGDraw->>SVGDraw: bangBkg() - explosion style
else Hexagon Shape
SVGDraw->>SVGDraw: hexagonBkg() - six sides
end
SVGDraw->>SVGDraw: create SVG elements
SVGDraw->>SVGDraw: add text labels
SVGDraw->>SVGDraw: position node
opt Node has children
SVGDraw->>SVGDraw: drawNodes() recursive call
end
end
deactivate SVGDraw
%% Edge Rendering
Renderer->>Renderer: drawEdges(edgesEl, cy)
loop For each edge
Renderer->>Renderer: extract edge bounds
Renderer->>Renderer: draw SVG path
end
%% Styling Application
Renderer->>Styles: getStyles(options)
activate Styles
Styles->>Styles: genSections(options)
loop For THEME_COLOR_LIMIT sections
Styles->>Styles: generate color scale
Styles->>Styles: create CSS rules
Note right of Styles: .section-X fills<br/>.edge-depth-X widths<br/>.node-icon-X colors
end
Styles->>Styles: apply theme integration
Styles-->>Renderer: return compiled CSS
deactivate Styles
%% Final Assembly
Renderer->>Output: selectSvgElement()
Renderer->>Output: setupGraphViewbox()
Renderer->>Output: apply styles
Renderer->>Output: add interactive elements
deactivate Renderer
activate Output
Note over Output: Final Mindmap Features
Output->>Output: responsive layout
Output->>Output: accessibility attributes
Output->>Output: hover effects
Output->>Output: click handling
Output-->>User: rendered mindmap
deactivate Output
%% Configuration Details
Note over DB, Styles: Configuration Options
Note right of DB: Padding Calculations:<br/>Base padding from config<br/>RECT: ×2 padding<br/>ROUNDED_RECT: ×2 padding<br/>HEXAGON: ×2 padding
Note right of Styles: Section Management:<br/>MAX_SECTIONS = 12<br/>Dynamic color generation<br/>Git theme integration
Note right of Renderer: Layout Parameters:<br/>Cytoscape configuration<br/>coseBilkent settings<br/>Node spacing rules

View File

@@ -84,6 +84,7 @@ To add an integration to this list, see the [Integrations - create page](./integ
LLM integrations to create mermaid diagrams using AI from text descriptions.
- [HueHive - Create mermaid diagrams with text](https://huehive.co/tools/diagrams)
- [MCP Server Mermaid](https://github.com/hustcc/mcp-mermaid) - Generate mermaid diagram and chart with AI MCP dynamically.
### CRM/ERP
@@ -103,6 +104,7 @@ Blogging frameworks and platforms
- [Mermaid](https://nextra.site/docs/guide/mermaid)
- [WordPress](https://wordpress.org)
- [MerPRess](https://wordpress.org/plugins/merpress/)
- [WP Documentation](https://wordpress.org/themes/wp-documentation/)
### CMS/ECM

View File

@@ -16,9 +16,7 @@ Applications that support Mermaid files [SHOULD](https://datatracker.ietf.org/do
### MIME Type
The recommended [MIME type](https://www.iana.org/assignments/media-types/media-types.xhtml) for Mermaid media is `text/vnd.mermaid`.
Currently pending [IANA](https://www.iana.org/) recognition.
The recommended [MIME type](https://www.iana.org/assignments/media-types/media-types.xhtml) for Mermaid media is [`text/vnd.mermaid`](https://www.iana.org/assignments/media-types/application/vnd.mermaid).
## Showcase

View File

@@ -29,7 +29,6 @@ Try the Ultimate AI, Mermaid, and Visual Diagramming Suite by creating an accoun
- **Plugins** - A plugin system for extending the functionality of Mermaid.
Official Mermaid Chart plugins:
- [Mermaid Chart GPT](https://chatgpt.com/g/g-684cc36f30208191b21383b88650a45d-mermaid-chart-diagrams-and-charts)
- [Confluence](https://marketplace.atlassian.com/apps/1234056/mermaid-chart-for-confluence?hosting=cloud&tab=overview)
- [Jira](https://marketplace.atlassian.com/apps/1234810/mermaid-chart-for-jira?tab=overview&hosting=cloud)

View File

@@ -35,13 +35,11 @@ The Mermaid Chart team is excited to introduce a new Visual Editor for Flowchart
Learn more:
- Visual Editor For Flowcharts
- [Blog post](https://www.mermaidchart.com/blog/posts/mermaid-chart-releases-new-visual-editor-for-flowcharts)
- [Demo video](https://www.youtube.com/watch?v=5aja0gijoO0)
- Visual Editor For Sequence diagrams
- [Blog post](https://www.mermaidchart.com/blog/posts/mermaid-chart-unveils-visual-editor-for-sequence-diagrams)
- [Demo video](https://youtu.be/imc2u5_N6Dc)

View File

@@ -9,7 +9,7 @@
## Introduction to Block Diagrams
```mermaid-example
block-beta
block
columns 1
db(("DB"))
blockArrowId6<["&nbsp;&nbsp;&nbsp;"]>(down)
@@ -26,7 +26,7 @@ columns 1
```
```mermaid
block-beta
block
columns 1
db(("DB"))
blockArrowId6<["&nbsp;&nbsp;&nbsp;"]>(down)
@@ -80,12 +80,12 @@ At its core, a block diagram consists of blocks representing different entities
To create a simple block diagram with three blocks labeled 'a', 'b', and 'c', the syntax is as follows:
```mermaid-example
block-beta
block
a b c
```
```mermaid
block-beta
block
a b c
```
@@ -101,13 +101,13 @@ While simple block diagrams are linear and straightforward, more complex systems
In scenarios where you need to distribute blocks across multiple columns, you can specify the number of columns and arrange the blocks accordingly. Here's how to create a block diagram with three columns and four blocks, where the fourth block appears in a second row:
```mermaid-example
block-beta
block
columns 3
a b c d
```
```mermaid
block-beta
block
columns 3
a b c d
```
@@ -130,13 +130,13 @@ In more complex diagrams, you may need blocks that span multiple columns to emph
To create a block diagram where one block spans across two columns, you can specify the desired width for each block:
```mermaid-example
block-beta
block
columns 3
a["A label"] b:2 c:2 d
```
```mermaid
block-beta
block
columns 3
a["A label"] b:2 c:2 d
```
@@ -153,7 +153,7 @@ Composite blocks, or blocks within blocks, are an advanced feature in Mermaid's
Creating a composite block involves defining a parent block and then nesting other blocks within it. Here's how to define a composite block with nested elements:
```mermaid-example
block-beta
block
block
D
end
@@ -161,7 +161,7 @@ block-beta
```
```mermaid
block-beta
block
block
D
end
@@ -180,7 +180,7 @@ Mermaid also allows for dynamic adjustment of column widths based on the content
In diagrams with varying block sizes, Mermaid automatically adjusts the column widths to fit the largest block in each column. Here's an example:
```mermaid-example
block-beta
block
columns 3
a:3
block:group1:2
@@ -195,7 +195,7 @@ block-beta
```
```mermaid
block-beta
block
columns 3
a:3
block:group1:2
@@ -215,7 +215,7 @@ This example demonstrates how Mermaid dynamically adjusts the width of the colum
In scenarios where you need to stack blocks horizontally, you can use column width to accomplish the task. Blocks can be arranged vertically by putting them in a single column. Here is how you can create a block diagram in which 4 blocks are stacked on top of each other:
```mermaid-example
block-beta
block
block
columns 1
a["A label"] b c d
@@ -223,7 +223,7 @@ block-beta
```
```mermaid
block-beta
block
block
columns 1
a["A label"] b c d
@@ -247,12 +247,12 @@ Mermaid supports a range of block shapes to suit different diagramming needs, fr
To create a block with round edges, which can be used to represent a softer or more flexible component:
```mermaid-example
block-beta
block
id1("This is the text in the box")
```
```mermaid
block-beta
block
id1("This is the text in the box")
```
@@ -261,12 +261,12 @@ block-beta
A stadium-shaped block, resembling an elongated circle, can be used for components that are process-oriented:
```mermaid-example
block-beta
block
id1(["This is the text in the box"])
```
```mermaid
block-beta
block
id1(["This is the text in the box"])
```
@@ -275,12 +275,12 @@ block-beta
For representing subroutines or contained processes, a block with double vertical lines is useful:
```mermaid-example
block-beta
block
id1[["This is the text in the box"]]
```
```mermaid
block-beta
block
id1[["This is the text in the box"]]
```
@@ -289,12 +289,12 @@ block-beta
The cylindrical shape is ideal for representing databases or storage components:
```mermaid-example
block-beta
block
id1[("Database")]
```
```mermaid
block-beta
block
id1[("Database")]
```
@@ -303,12 +303,12 @@ block-beta
A circle can be used for centralized or pivotal components:
```mermaid-example
block-beta
block
id1(("This is the text in the circle"))
```
```mermaid
block-beta
block
id1(("This is the text in the circle"))
```
@@ -319,36 +319,36 @@ For decision points, use a rhombus, and for unique or specialized processes, asy
**Asymmetric**
```mermaid-example
block-beta
block
id1>"This is the text in the box"]
```
```mermaid
block-beta
block
id1>"This is the text in the box"]
```
**Rhombus**
```mermaid-example
block-beta
block
id1{"This is the text in the box"}
```
```mermaid
block-beta
block
id1{"This is the text in the box"}
```
**Hexagon**
```mermaid-example
block-beta
block
id1{{"This is the text in the box"}}
```
```mermaid
block-beta
block
id1{{"This is the text in the box"}}
```
@@ -357,7 +357,7 @@ block-beta
Parallelogram and trapezoid shapes are perfect for inputs/outputs and transitional processes:
```mermaid-example
block-beta
block
id1[/"This is the text in the box"/]
id2[\"This is the text in the box"\]
A[/"Christmas"\]
@@ -365,7 +365,7 @@ block-beta
```
```mermaid
block-beta
block
id1[/"This is the text in the box"/]
id2[\"This is the text in the box"\]
A[/"Christmas"\]
@@ -377,12 +377,12 @@ block-beta
For highlighting critical or high-priority components, a double circle can be effective:
```mermaid-example
block-beta
block
id1((("This is the text in the circle")))
```
```mermaid
block-beta
block
id1((("This is the text in the circle")))
```
@@ -395,7 +395,7 @@ Mermaid also offers unique shapes like block arrows and space blocks for directi
Block arrows can visually indicate direction or flow within a process:
```mermaid-example
block-beta
block
blockArrowId<["Label"]>(right)
blockArrowId2<["Label"]>(left)
blockArrowId3<["Label"]>(up)
@@ -406,7 +406,7 @@ block-beta
```
```mermaid
block-beta
block
blockArrowId<["Label"]>(right)
blockArrowId2<["Label"]>(left)
blockArrowId3<["Label"]>(up)
@@ -421,14 +421,14 @@ block-beta
Space blocks can be used to create intentional empty spaces in the diagram, which is useful for layout and readability:
```mermaid-example
block-beta
block
columns 3
a space b
c d e
```
```mermaid
block-beta
block
columns 3
a space b
c d e
@@ -437,12 +437,12 @@ block-beta
or
```mermaid-example
block-beta
block
ida space:3 idb idc
```
```mermaid
block-beta
block
ida space:3 idb idc
```
@@ -467,13 +467,13 @@ The most fundamental aspect of connecting blocks is the use of arrows or links.
A simple link with an arrow can be created to show direction or flow from one block to another:
```mermaid-example
block-beta
block
A space B
A-->B
```
```mermaid
block-beta
block
A space B
A-->B
```
@@ -490,13 +490,13 @@ Example - Text with Links
To add text to a link, the syntax includes the text within the link definition:
```mermaid-example
block-beta
block
A space:2 B
A-- "X" -->B
```
```mermaid
block-beta
block
A space:2 B
A-- "X" -->B
```
@@ -506,7 +506,7 @@ This example show how to add descriptive text to the links, enhancing the inform
Example - Edges and Styles:
```mermaid-example
block-beta
block
columns 1
db(("DB"))
blockArrowId6<["&nbsp;&nbsp;&nbsp;"]>(down)
@@ -523,7 +523,7 @@ columns 1
```
```mermaid
block-beta
block
columns 1
db(("DB"))
blockArrowId6<["&nbsp;&nbsp;&nbsp;"]>(down)
@@ -552,7 +552,7 @@ Mermaid enables detailed styling of individual blocks, allowing you to apply var
To apply custom styles to a block, you can use the `style` keyword followed by the block identifier and the desired CSS properties:
```mermaid-example
block-beta
block
id1 space id2
id1("Start")-->id2("Stop")
style id1 fill:#636,stroke:#333,stroke-width:4px
@@ -560,7 +560,7 @@ block-beta
```
```mermaid
block-beta
block
id1 space id2
id1("Start")-->id2("Stop")
style id1 fill:#636,stroke:#333,stroke-width:4px
@@ -574,7 +574,7 @@ Mermaid enables applying styling to classes, which could make styling easier if
#### Example - Styling a Single Class
```mermaid-example
block-beta
block
A space B
A-->B
classDef blue fill:#6e6ce6,stroke:#333,stroke-width:4px;
@@ -583,7 +583,7 @@ block-beta
```
```mermaid
block-beta
block
A space B
A-->B
classDef blue fill:#6e6ce6,stroke:#333,stroke-width:4px;
@@ -608,7 +608,7 @@ Combining the elements of structure, linking, and styling, we can create compreh
Illustrating a simple software system architecture with interconnected components:
```mermaid-example
block-beta
block
columns 3
Frontend blockArrowId6<[" "]>(right) Backend
space:2 down<[" "]>(down)
@@ -621,7 +621,7 @@ block-beta
```
```mermaid
block-beta
block
columns 3
Frontend blockArrowId6<[" "]>(right) Backend
space:2 down<[" "]>(down)
@@ -640,7 +640,7 @@ This example shows a basic architecture with a frontend, backend, and database.
Representing a business process flow with decision points and multiple stages:
```mermaid-example
block-beta
block
columns 3
Start(("Start")) space:2
down<[" "]>(down) space:2
@@ -653,7 +653,7 @@ block-beta
```
```mermaid
block-beta
block
columns 3
Start(("Start")) space:2
down<[" "]>(down) space:2
@@ -682,7 +682,7 @@ Understanding and avoiding common syntax errors is key to a smooth experience wi
A common mistake is incorrect linking syntax, which can lead to unexpected results or broken diagrams:
```
block-beta
block
A - B
```
@@ -690,13 +690,13 @@ block-beta
Ensure that links between blocks are correctly specified with arrows (--> or ---) to define the direction and type of connection. Also remember that one of the fundamentals for block diagram is to give the author full control of where the boxes are positioned so in the example you need to add a space between the boxes:
```mermaid-example
block-beta
block
A space B
A --> B
```
```mermaid
block-beta
block
A space B
A --> B
```
@@ -706,13 +706,13 @@ block-beta
Applying styles in the wrong context or with incorrect syntax can lead to blocks not being styled as intended:
```mermaid-example
block-beta
block
A
style A fill#969;
```
```mermaid
block-beta
block
A
style A fill#969;
```
@@ -721,14 +721,14 @@ Applying styles in the wrong context or with incorrect syntax can lead to blocks
Correct the syntax by ensuring proper separation of style properties with commas and using the correct CSS property format:
```mermaid-example
block-beta
block
A
style A fill:#969,stroke:#333;
```
```mermaid
block-beta
block
A
style A fill:#969,stroke:#333;

View File

@@ -139,7 +139,6 @@ The following unfinished features are not supported in the short term.
- [ ] Legend
- [x] System Context
- [x] Person(alias, label, ?descr, ?sprite, ?tags, $link)
- [x] Person_Ext
- [x] System(alias, label, ?descr, ?sprite, ?tags, $link)
@@ -153,7 +152,6 @@ The following unfinished features are not supported in the short term.
- [x] System_Boundary
- [x] Container diagram
- [x] Container(alias, label, ?techn, ?descr, ?sprite, ?tags, $link)
- [x] ContainerDb
- [x] ContainerQueue
@@ -163,7 +161,6 @@ The following unfinished features are not supported in the short term.
- [x] Container_Boundary(alias, label, ?tags, $link)
- [x] Component diagram
- [x] Component(alias, label, ?techn, ?descr, ?sprite, ?tags, $link)
- [x] ComponentDb
- [x] ComponentQueue
@@ -172,18 +169,15 @@ The following unfinished features are not supported in the short term.
- [x] ComponentQueue_Ext
- [x] Dynamic diagram
- [x] RelIndex(index, from, to, label, ?tags, $link)
- [x] Deployment diagram
- [x] Deployment_Node(alias, label, ?type, ?descr, ?sprite, ?tags, $link)
- [x] Node(alias, label, ?type, ?descr, ?sprite, ?tags, $link): short name of Deployment_Node()
- [x] Node_L(alias, label, ?type, ?descr, ?sprite, ?tags, $link): left aligned Node()
- [x] Node_R(alias, label, ?type, ?descr, ?sprite, ?tags, $link): right aligned Node()
- [x] Relationship Types
- [x] Rel(from, to, label, ?techn, ?descr, ?sprite, ?tags, $link)
- [x] BiRel (bidirectional relationship)
- [x] Rel_U, Rel_Up

View File

@@ -324,53 +324,56 @@ This syntax creates a node A as a rectangle. It renders in the same way as `A["A
Below is a comprehensive list of the newly introduced shapes and their corresponding semantic meanings, short names, and aliases:
| **Semantic Name** | **Shape Name** | **Short Name** | **Description** | **Alias Supported** |
| --------------------------------- | ---------------------- | -------------- | ------------------------------ | ---------------------------------------------------------------- |
| Card | Notched Rectangle | `notch-rect` | Represents a card | `card`, `notched-rectangle` |
| Collate | Hourglass | `hourglass` | Represents a collate operation | `collate`, `hourglass` |
| Com Link | Lightning Bolt | `bolt` | Communication link | `com-link`, `lightning-bolt` |
| Comment | Curly Brace | `brace` | Adds a comment | `brace-l`, `comment` |
| Comment Right | Curly Brace | `brace-r` | Adds a comment | |
| Comment with braces on both sides | Curly Braces | `braces` | Adds a comment | |
| Data Input/Output | Lean Right | `lean-r` | Represents input or output | `in-out`, `lean-right` |
| Data Input/Output | Lean Left | `lean-l` | Represents output or input | `lean-left`, `out-in` |
| Database | Cylinder | `cyl` | Database storage | `cylinder`, `database`, `db` |
| Decision | Diamond | `diam` | Decision-making step | `decision`, `diamond`, `question` |
| Delay | Half-Rounded Rectangle | `delay` | Represents a delay | `half-rounded-rectangle` |
| Direct Access Storage | Horizontal Cylinder | `h-cyl` | Direct access storage | `das`, `horizontal-cylinder` |
| Disk Storage | Lined Cylinder | `lin-cyl` | Disk storage | `disk`, `lined-cylinder` |
| Display | Curved Trapezoid | `curv-trap` | Represents a display | `curved-trapezoid`, `display` |
| Divided Process | Divided Rectangle | `div-rect` | Divided process shape | `div-proc`, `divided-process`, `divided-rectangle` |
| Document | Document | `doc` | Represents a document | `doc`, `document` |
| Event | Rounded Rectangle | `rounded` | Represents an event | `event` |
| Extract | Triangle | `tri` | Extraction process | `extract`, `triangle` |
| Fork/Join | Filled Rectangle | `fork` | Fork or join in process flow | `join` |
| Internal Storage | Window Pane | `win-pane` | Internal storage | `internal-storage`, `window-pane` |
| Junction | Filled Circle | `f-circ` | Junction point | `filled-circle`, `junction` |
| Lined Document | Lined Document | `lin-doc` | Lined document | `lined-document` |
| Lined/Shaded Process | Lined Rectangle | `lin-rect` | Lined process shape | `lin-proc`, `lined-process`, `lined-rectangle`, `shaded-process` |
| Loop Limit | Trapezoidal Pentagon | `notch-pent` | Loop limit step | `loop-limit`, `notched-pentagon` |
| Manual File | Flipped Triangle | `flip-tri` | Manual file operation | `flipped-triangle`, `manual-file` |
| Manual Input | Sloped Rectangle | `sl-rect` | Manual input step | `manual-input`, `sloped-rectangle` |
| Manual Operation | Trapezoid Base Top | `trap-t` | Represents a manual task | `inv-trapezoid`, `manual`, `trapezoid-top` |
| Multi-Document | Stacked Document | `docs` | Multiple documents | `documents`, `st-doc`, `stacked-document` |
| Multi-Process | Stacked Rectangle | `st-rect` | Multiple processes | `processes`, `procs`, `stacked-rectangle` |
| Odd | Odd | `odd` | Odd shape | |
| Paper Tape | Flag | `flag` | Paper tape | `paper-tape` |
| Prepare Conditional | Hexagon | `hex` | Preparation or condition step | `hexagon`, `prepare` |
| Priority Action | Trapezoid Base Bottom | `trap-b` | Priority action | `priority`, `trapezoid`, `trapezoid-bottom` |
| Process | Rectangle | `rect` | Standard process shape | `proc`, `process`, `rectangle` |
| Start | Circle | `circle` | Starting point | `circ` |
| Start | Small Circle | `sm-circ` | Small starting point | `small-circle`, `start` |
| Stop | Double Circle | `dbl-circ` | Represents a stop point | `double-circle` |
| Stop | Framed Circle | `fr-circ` | Stop point | `framed-circle`, `stop` |
| Stored Data | Bow Tie Rectangle | `bow-rect` | Stored data | `bow-tie-rectangle`, `stored-data` |
| Subprocess | Framed Rectangle | `fr-rect` | Subprocess | `framed-rectangle`, `subproc`, `subprocess`, `subroutine` |
| Summary | Crossed Circle | `cross-circ` | Summary | `crossed-circle`, `summary` |
| Tagged Document | Tagged Document | `tag-doc` | Tagged document | `tag-doc`, `tagged-document` |
| Tagged Process | Tagged Rectangle | `tag-rect` | Tagged process | `tag-proc`, `tagged-process`, `tagged-rectangle` |
| Terminal Point | Stadium | `stadium` | Terminal point | `pill`, `terminal` |
| Text Block | Text Block | `text` | Text block | |
| **Semantic Name** | **Shape Name** | **Short Name** | **Description** | **Alias Supported** |
| --------------------------------- | ---------------------- | ----------------- | ------------------------------ | ---------------------------------------------------------------- |
| Bang | Bang | `bang` | Bang | `bang` |
| Card | Notched Rectangle | `notch-rect` | Represents a card | `card`, `notched-rectangle` |
| Cloud | Cloud | `cloud` | cloud | `cloud` |
| Collate | Hourglass | `hourglass` | Represents a collate operation | `collate`, `hourglass` |
| Com Link | Lightning Bolt | `bolt` | Communication link | `com-link`, `lightning-bolt` |
| Comment | Curly Brace | `brace` | Adds a comment | `brace-l`, `comment` |
| Comment Right | Curly Brace | `brace-r` | Adds a comment | |
| Comment with braces on both sides | Curly Braces | `braces` | Adds a comment | |
| Data Input/Output | Lean Right | `lean-r` | Represents input or output | `in-out`, `lean-right` |
| Data Input/Output | Lean Left | `lean-l` | Represents output or input | `lean-left`, `out-in` |
| Database | Cylinder | `cyl` | Database storage | `cylinder`, `database`, `db` |
| Decision | Diamond | `diam` | Decision-making step | `decision`, `diamond`, `question` |
| Default Mindmap Node | defaultMindmapNode | `default-mindmap` | defaultMindmapNode | `default-mindmap`, `defaultMindmapNode` |
| Delay | Half-Rounded Rectangle | `delay` | Represents a delay | `half-rounded-rectangle` |
| Direct Access Storage | Horizontal Cylinder | `h-cyl` | Direct access storage | `das`, `horizontal-cylinder` |
| Disk Storage | Lined Cylinder | `lin-cyl` | Disk storage | `disk`, `lined-cylinder` |
| Display | Curved Trapezoid | `curv-trap` | Represents a display | `curved-trapezoid`, `display` |
| Divided Process | Divided Rectangle | `div-rect` | Divided process shape | `div-proc`, `divided-process`, `divided-rectangle` |
| Document | Document | `doc` | Represents a document | `doc`, `document` |
| Event | Rounded Rectangle | `rounded` | Represents an event | `event` |
| Extract | Triangle | `tri` | Extraction process | `extract`, `triangle` |
| Fork/Join | Filled Rectangle | `fork` | Fork or join in process flow | `join` |
| Internal Storage | Window Pane | `win-pane` | Internal storage | `internal-storage`, `window-pane` |
| Junction | Filled Circle | `f-circ` | Junction point | `filled-circle`, `junction` |
| Lined Document | Lined Document | `lin-doc` | Lined document | `lined-document` |
| Lined/Shaded Process | Lined Rectangle | `lin-rect` | Lined process shape | `lin-proc`, `lined-process`, `lined-rectangle`, `shaded-process` |
| Loop Limit | Trapezoidal Pentagon | `notch-pent` | Loop limit step | `loop-limit`, `notched-pentagon` |
| Manual File | Flipped Triangle | `flip-tri` | Manual file operation | `flipped-triangle`, `manual-file` |
| Manual Input | Sloped Rectangle | `sl-rect` | Manual input step | `manual-input`, `sloped-rectangle` |
| Manual Operation | Trapezoid Base Top | `trap-t` | Represents a manual task | `inv-trapezoid`, `manual`, `trapezoid-top` |
| Multi-Document | Stacked Document | `docs` | Multiple documents | `documents`, `st-doc`, `stacked-document` |
| Multi-Process | Stacked Rectangle | `st-rect` | Multiple processes | `processes`, `procs`, `stacked-rectangle` |
| Odd | Odd | `odd` | Odd shape | |
| Paper Tape | Flag | `flag` | Paper tape | `paper-tape` |
| Prepare Conditional | Hexagon | `hex` | Preparation or condition step | `hexagon`, `prepare` |
| Priority Action | Trapezoid Base Bottom | `trap-b` | Priority action | `priority`, `trapezoid`, `trapezoid-bottom` |
| Process | Rectangle | `rect` | Standard process shape | `proc`, `process`, `rectangle` |
| Start | Circle | `circle` | Starting point | `circ` |
| Start | Small Circle | `sm-circ` | Small starting point | `small-circle`, `start` |
| Stop | Double Circle | `dbl-circ` | Represents a stop point | `double-circle` |
| Stop | Framed Circle | `fr-circ` | Stop point | `framed-circle`, `stop` |
| Stored Data | Bow Tie Rectangle | `bow-rect` | Stored data | `bow-tie-rectangle`, `stored-data` |
| Subprocess | Framed Rectangle | `fr-rect` | Subprocess | `framed-rectangle`, `subproc`, `subprocess`, `subroutine` |
| Summary | Crossed Circle | `cross-circ` | Summary | `crossed-circle`, `summary` |
| Tagged Document | Tagged Document | `tag-doc` | Tagged document | `tag-doc`, `tagged-document` |
| Tagged Process | Tagged Rectangle | `tag-rect` | Tagged process | `tag-proc`, `tagged-process`, `tagged-rectangle` |
| Terminal Point | Stadium | `stadium` | Terminal point | `pill`, `terminal` |
| Text Block | Text Block | `text` | Text block | |
### Example Flowchart with New Shapes
@@ -1795,15 +1798,54 @@ It is possible to style the type of curve used for lines between items, if the d
Available curve styles include `basis`, `bumpX`, `bumpY`, `cardinal`, `catmullRom`, `linear`, `monotoneX`, `monotoneY`,
`natural`, `step`, `stepAfter`, and `stepBefore`.
For a full list of available curves, including an explanation of custom curves, refer to
the [Shapes](https://d3js.org/d3-shape/curve) documentation in the [d3-shape](https://github.com/d3/d3-shape/) project.
Line styling can be achieved in two ways:
1. Change the curve style of all the lines
2. Change the curve style of a particular line
#### Diagram level curve style
In this example, a left-to-right graph uses the `stepBefore` curve style:
```
%%{ init: { 'flowchart': { 'curve': 'stepBefore' } } }%%
---
config:
flowchart:
curve: stepBefore
---
graph LR
```
For a full list of available curves, including an explanation of custom curves, refer to
the [Shapes](https://d3js.org/d3-shape/curve) documentation in the [d3-shape](https://github.com/d3/d3-shape/) project.
#### Edge level curve style using Edge IDs (v\<MERMAID_RELEASE_VERSION>+)
You can assign IDs to [edges](#attaching-an-id-to-edges). After assigning an ID you can modify the line style by modifying the edge's `curve` property using the following syntax:
```mermaid-example
flowchart LR
A e1@==> B
A e2@--> C
e1@{ curve: linear }
e2@{ curve: natural }
```
```mermaid
flowchart LR
A e1@==> B
A e2@--> C
e1@{ curve: linear }
e2@{ curve: natural }
```
```info
Any edge curve style modified at the edge level overrides the diagram level style.
```
```info
If the same edge is modified multiple times the last modification will be rendered.
```
### Styling a node

View File

@@ -360,7 +360,8 @@ gantt
weekday monday
```
> **Warning** > `millisecond` and `second` support was added in v10.3.0
> **Warning**
> `millisecond` and `second` support was added in v10.3.0
## Output in compact mode

View File

@@ -314,3 +314,22 @@ You can also refer the [implementation in the live editor](https://github.com/me
cspell:locale en,en-gb
cspell:ignore Buzan
--->
## Layouts
Mermaid also supports a Tidy Tree layout for mindmaps.
```
---
config:
layout: tidy-tree
---
mindmap
root((mindmap is a long thing))
A
B
C
D
```
Instructions to add and register tidy-tree layout are present in [Tidy Tree Configuration](/config/tidy-tree)

View File

@@ -37,6 +37,11 @@ Drawing a pie chart is really simple in mermaid.
- Followed by `:` colon as separator
- Followed by `positive numeric value` (supported up to two decimal places)
**Note:**
> Pie chart values must be **positive numbers greater than zero**.\
> **Negative values are not allowed** and will result in an error.
\[pie] \[showData] (OPTIONAL)
\[title] \[titlevalue] (OPTIONAL)
"\[datakey1]" : \[dataValue1]

View File

@@ -23,7 +23,7 @@ config:
sankey:
showValues: false
---
sankey-beta
sankey
Agricultural 'waste',Bio-conversion,124.729
Bio-conversion,Liquid,0.597
@@ -101,7 +101,7 @@ config:
sankey:
showValues: false
---
sankey-beta
sankey
Agricultural 'waste',Bio-conversion,124.729
Bio-conversion,Liquid,0.597
@@ -175,7 +175,7 @@ Wind,Electricity grid,289.366
## Syntax
The idea behind syntax is that a user types `sankey-beta` keyword first, then pastes raw CSV below and get the result.
The idea behind syntax is that a user types `sankey` keyword first, then pastes raw CSV below and get the result.
It implements CSV standard as [described here](https://www.ietf.org/rfc/rfc4180.txt) with subtle **differences**:
@@ -187,7 +187,7 @@ It implements CSV standard as [described here](https://www.ietf.org/rfc/rfc4180.
It is implied that 3 columns inside CSV should represent `source`, `target` and `value` accordingly:
```mermaid-example
sankey-beta
sankey
%% source,target,value
Electricity grid,Over generation / exports,104.453
@@ -196,7 +196,7 @@ Electricity grid,H2 conversion,27.14
```
```mermaid
sankey-beta
sankey
%% source,target,value
Electricity grid,Over generation / exports,104.453
@@ -209,7 +209,7 @@ Electricity grid,H2 conversion,27.14
CSV does not support empty lines without comma delimiters by default. But you can add them if needed:
```mermaid-example
sankey-beta
sankey
Bio-conversion,Losses,26.862
@@ -219,7 +219,7 @@ Bio-conversion,Gas,81.144
```
```mermaid
sankey-beta
sankey
Bio-conversion,Losses,26.862
@@ -233,14 +233,14 @@ Bio-conversion,Gas,81.144
If you need to have a comma, wrap it in double quotes:
```mermaid-example
sankey-beta
sankey
Pumped heat,"Heating and cooling, homes",193.026
Pumped heat,"Heating and cooling, commercial",70.672
```
```mermaid
sankey-beta
sankey
Pumped heat,"Heating and cooling, homes",193.026
Pumped heat,"Heating and cooling, commercial",70.672
@@ -251,14 +251,14 @@ Pumped heat,"Heating and cooling, commercial",70.672
If you need to have double quote, put a pair of them inside quoted string:
```mermaid-example
sankey-beta
sankey
Pumped heat,"Heating and cooling, ""homes""",193.026
Pumped heat,"Heating and cooling, ""commercial""",70.672
```
```mermaid
sankey-beta
sankey
Pumped heat,"Heating and cooling, ""homes""",193.026
Pumped heat,"Heating and cooling, ""commercial""",70.672

View File

@@ -13,7 +13,7 @@
## Example
```mermaid-example
xychart-beta
xychart
title "Sales Revenue"
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -22,7 +22,7 @@ xychart-beta
```
```mermaid
xychart-beta
xychart
title "Sales Revenue"
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -40,7 +40,7 @@ xychart-beta
The chart can be drawn horizontal or vertical, default value is vertical.
```
xychart-beta horizontal
xychart horizontal
...
```
@@ -51,7 +51,7 @@ The title is a short description of the chart and it will always render on top o
#### Example
```
xychart-beta
xychart
title "This is a simple example"
...
```
@@ -98,10 +98,10 @@ A bar chart offers the capability to graphically depict bars.
#### Simplest example
The only two things required are the chart name (`xychart-beta`) and one data set. So you will be able to draw a chart with a simple config like
The only two things required are the chart name (`xychart`) and one data set. So you will be able to draw a chart with a simple config like
```
xychart-beta
xychart
line [+1.3, .6, 2.4, -.34]
```
@@ -176,7 +176,7 @@ config:
xyChart:
titleColor: "#ff0000"
---
xychart-beta
xychart
title "Sales Revenue"
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000
@@ -195,7 +195,7 @@ config:
xyChart:
titleColor: "#ff0000"
---
xychart-beta
xychart
title "Sales Revenue"
x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
y-axis "Revenue (in $)" 4000 --> 11000

View File

@@ -17,6 +17,7 @@ export default tseslint.config(
...tseslint.configs.stylisticTypeChecked,
{
ignores: [
'**/*.d.ts',
'**/dist/',
'**/node_modules/',
'.git/',

1
instructions.md Normal file
View File

@@ -0,0 +1 @@
The instructions for Tidy-Tree layout can be found in [Tidy Tree Configuration](/config/tidy-tree)

View File

@@ -67,7 +67,7 @@
"@argos-ci/cypress": "^5.0.2",
"@changesets/changelog-github": "^0.5.1",
"@changesets/cli": "^2.27.12",
"@cspell/eslint-plugin": "^8.19.3",
"@cspell/eslint-plugin": "^8.19.4",
"@cypress/code-coverage": "^3.12.49",
"@eslint/js": "^9.26.0",
"@rollup/plugin-typescript": "^12.1.2",
@@ -83,7 +83,7 @@
"@vitest/spy": "^3.0.6",
"@vitest/ui": "^3.0.6",
"ajv": "^8.17.1",
"chokidar": "4.0.3",
"chokidar": "3.6.0",
"concurrently": "^9.1.2",
"cors": "^2.8.5",
"cpy-cli": "^5.0.0",
@@ -94,17 +94,17 @@
"cypress-split": "^1.24.14",
"esbuild": "^0.25.0",
"eslint": "^9.26.0",
"eslint-config-prettier": "^10.1.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-cypress": "^4.3.0",
"eslint-plugin-html": "^8.1.2",
"eslint-plugin-jest": "^28.11.0",
"eslint-plugin-jsdoc": "^50.6.9",
"eslint-plugin-html": "^8.1.3",
"eslint-plugin-jest": "^28.14.0",
"eslint-plugin-jsdoc": "^50.8.0",
"eslint-plugin-json": "^4.0.1",
"eslint-plugin-lodash": "^8.0.0",
"eslint-plugin-markdown": "^5.1.0",
"eslint-plugin-no-only-tests": "^3.3.0",
"eslint-plugin-tsdoc": "^0.4.0",
"eslint-plugin-unicorn": "^59.0.0",
"eslint-plugin-unicorn": "^59.0.1",
"express": "^5.1.0",
"globals": "^16.0.0",
"globby": "^14.0.2",
@@ -112,7 +112,7 @@
"jest": "^30.0.4",
"jison": "^0.4.18",
"js-yaml": "^4.1.0",
"jsdom": "^26.0.0",
"jsdom": "^26.1.0",
"langium-cli": "3.3.0",
"lint-staged": "^16.1.2",
"markdown-table": "^3.0.4",
@@ -126,7 +126,7 @@
"tslib": "^2.8.1",
"tsx": "^4.7.3",
"typescript": "~5.7.3",
"typescript-eslint": "^8.32.0",
"typescript-eslint": "^8.38.0",
"vite": "^7.0.3",
"vite-plugin-istanbul": "^7.0.0",
"vitest": "^3.0.6"
@@ -139,8 +139,13 @@
"roughjs": "patches/roughjs.patch"
},
"onlyBuiltDependencies": [
"canvas",
"cypress",
"esbuild"
],
"ignoredBuiltDependencies": [
"sharp",
"vue-demi"
]
}
}

View File

@@ -0,0 +1,14 @@
# @mermaid-js/examples
## 1.0.0
### Minor Changes
- [#6453](https://github.com/mermaid-js/mermaid/pull/6453) [`4936ef5`](https://github.com/mermaid-js/mermaid/commit/4936ef5c306d2f892cca9a95a5deac4af6d4882b) Thanks [@sidharthv96](https://github.com/sidharthv96)! - feat: Add examples for diagrams in the `@mermaid-js/examples` package
### Patch Changes
- [#6510](https://github.com/mermaid-js/mermaid/pull/6510) [`7a38eb7`](https://github.com/mermaid-js/mermaid/commit/7a38eb715d795cd5c66cb59357d64ec197b432e6) Thanks [@sidharthv96](https://github.com/sidharthv96)! - chore: Move packet diagram out of beta
- Updated dependencies [[`5acbd7e`](https://github.com/mermaid-js/mermaid/commit/5acbd7e762469d9d89a9c77faf6617ee13367f3a), [`d90634b`](https://github.com/mermaid-js/mermaid/commit/d90634bf2b09e586b055729e07e9a1a31b21827c), [`7a38eb7`](https://github.com/mermaid-js/mermaid/commit/7a38eb715d795cd5c66cb59357d64ec197b432e6), [`3e3ae08`](https://github.com/mermaid-js/mermaid/commit/3e3ae089305e1c7b9948b9e149eba6854fe7f2d6), [`d3e2be3`](https://github.com/mermaid-js/mermaid/commit/d3e2be35be066adeb7fd502b4a24c223c3b53947), [`637680d`](https://github.com/mermaid-js/mermaid/commit/637680d4d9e39b4f8cb6f05b4cb261e8f5693ac3)]:
- mermaid@11.9.0

View File

@@ -0,0 +1,41 @@
# @mermaid-js/examples
The `@mermaid-js/examples` package contains a collection of examples used by tools like [mermaid.live](https://mermaid.live) to help users get started with new diagrams.
You can duplicate an existing diagram example file, e.g., `packages/examples/src/examples/flowchart.ts`, and modify it with details specific to your diagram.
Then, import the example in the `packages/examples/src/index.ts` file and add it to the `examples` array.
Each diagram should have at least one example, which should be marked as the default. It's a good idea to add more examples to showcase different features of the diagram.
## Usage
```bash
pnpm add @mermaid-js/examples
```
A sample usage of the package in mermaid.live, to get the default example for every diagram type:
```ts
import { diagramData } from '@mermaid-js/examples';
type DiagramDefinition = (typeof diagramData)[number];
const isValidDiagram = (diagram: DiagramDefinition): diagram is Required<DiagramDefinition> => {
return Boolean(diagram.name && diagram.examples && diagram.examples.length > 0);
};
export const getSampleDiagrams = () => {
const diagrams = diagramData
.filter((d) => isValidDiagram(d))
.map(({ examples, ...rest }) => ({
...rest,
example: examples?.filter(({ isDefault }) => isDefault)[0],
}));
const examples: Record<string, string> = {};
for (const diagram of diagrams) {
examples[diagram.name.replace(/ (Diagram|Chart|Graph)/, '')] = diagram.example.code;
}
return examples;
};
```

View File

@@ -1,6 +1,6 @@
{
"name": "@mermaid-js/examples",
"version": "0.0.1-beta.1",
"version": "1.0.0",
"description": "Mermaid examples package",
"author": "Sidharth Vinod",
"type": "module",
@@ -16,6 +16,10 @@
"files": [
"dist"
],
"repository": {
"type": "git",
"url": "https://github.com/mermaid-js/mermaid"
},
"scripts": {
"clean": "rimraf dist"
},

View File

@@ -2,7 +2,7 @@
This package provides a layout engine for Mermaid based on the [ELK](https://www.eclipse.org/elk/) layout engine.
> [!NOTE]
> [!NOTE]
> The ELK Layout engine will not be available in all providers that support mermaid by default.
> The websites will have to install the `@mermaid-js/layout-elk` package to use the ELK layout engine.
@@ -69,4 +69,4 @@ mermaid.registerLayoutLoaders(elkLayouts);
- `elk.mrtree`: Multi-root tree layout
- `elk.sporeOverlap`: Spore overlap layout
<!-- TODO: Add images for these layouts, as GitHub doesn't support natively -->
<!-- TODO: Add images for these layouts, as GitHub doesn't support natively. -->

View File

@@ -0,0 +1,9 @@
export interface TreeData {
parentById: Record<string, string>;
childrenById: Record<string, string[]>;
}
export declare const findCommonAncestor: (
id1: string,
id2: string,
{ parentById }: TreeData
) => string;

View File

@@ -4,7 +4,8 @@ import type { InternalHelpers, LayoutData, RenderOptions, SVG, SVGGroup } from '
import { type TreeData, findCommonAncestor } from './find-common-ancestor.js';
type Node = LayoutData['nodes'][number];
// Used to calculate distances in order to avoid floating number rounding issues when comparing floating numbers
const epsilon = 0.0001;
interface LabelData {
width: number;
height: number;
@@ -13,11 +14,20 @@ interface LabelData {
}
interface NodeWithVertex extends Omit<Node, 'domId'> {
children?: unknown[];
children?: LayoutData['nodes'];
labelData?: LabelData;
domId?: Node['domId'] | SVGGroup | d3.Selection<SVGAElement, unknown, Element | null, unknown>;
}
interface Point {
x: number;
y: number;
}
function distance(p1?: Point, p2?: Point): number {
if (!p1 || !p2) {
return 0;
}
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
export const render = async (
data4Layout: LayoutData,
svg: SVG,
@@ -51,15 +61,30 @@ export const render = async (
// Add the element to the DOM
if (!node.isGroup) {
// Create a clean node object for ELK with only the properties it expects
const child: NodeWithVertex = {
...node,
id: node.id,
width: node.width,
height: node.height,
// Store the original node data for later use
label: node.label,
isGroup: node.isGroup,
shape: node.shape,
padding: node.padding,
cssClasses: node.cssClasses,
cssStyles: node.cssStyles,
look: node.look,
// Include parentId for subgraph processing
parentId: node.parentId,
};
graph.children.push(child);
nodeDb[node.id] = child;
const childNodeEl = await insertNode(nodeEl, node, { config, dir: node.dir });
const boundingBox = childNodeEl.node()!.getBBox();
// Store the domId separately for rendering, not in the ELK graph
child.domId = childNodeEl;
child.calcIntersect = node.calcIntersect;
child.width = boundingBox.width;
child.height = boundingBox.height;
} else {
@@ -459,302 +484,6 @@ export const render = async (
}
}
function intersectLine(
p1: { y: number; x: number },
p2: { y: number; x: number },
q1: { x: any; y: any },
q2: { x: any; y: any }
) {
log.debug('UIO intersectLine', p1, p2, q1, q2);
// Algorithm from J. Avro, (ed.) Graphics Gems, No 2, Morgan Kaufmann, 1994,
// p7 and p473.
// let a1, a2, b1, b2, c1, c2;
// let r1, r2, r3, r4;
// let denom, offset, num;
// let x, y;
// Compute a1, b1, c1, where line joining points 1 and 2 is F(x,y) = a1 x +
// b1 y + c1 = 0.
const a1 = p2.y - p1.y;
const b1 = p1.x - p2.x;
const c1 = p2.x * p1.y - p1.x * p2.y;
// Compute r3 and r4.
const r3 = a1 * q1.x + b1 * q1.y + c1;
const r4 = a1 * q2.x + b1 * q2.y + c1;
const epsilon = 1e-6;
// Check signs of r3 and r4. If both point 3 and point 4 lie on
// same side of line 1, the line segments do not intersect.
if (r3 !== 0 && r4 !== 0 && sameSign(r3, r4)) {
return /*DON'T_INTERSECT*/;
}
// Compute a2, b2, c2 where line joining points 3 and 4 is G(x,y) = a2 x + b2 y + c2 = 0
const a2 = q2.y - q1.y;
const b2 = q1.x - q2.x;
const c2 = q2.x * q1.y - q1.x * q2.y;
// Compute r1 and r2
const r1 = a2 * p1.x + b2 * p1.y + c2;
const r2 = a2 * p2.x + b2 * p2.y + c2;
// Check signs of r1 and r2. If both point 1 and point 2 lie
// on same side of second line segment, the line segments do
// not intersect.
if (Math.abs(r1) < epsilon && Math.abs(r2) < epsilon && sameSign(r1, r2)) {
return /*DON'T_INTERSECT*/;
}
// Line segments intersect: compute intersection point.
const denom = a1 * b2 - a2 * b1;
if (denom === 0) {
return /*COLLINEAR*/;
}
const offset = Math.abs(denom / 2);
// The denom/2 is to get rounding instead of truncating. It
// is added or subtracted to the numerator, depending upon the
// sign of the numerator.
let num = b1 * c2 - b2 * c1;
const x = num < 0 ? (num - offset) / denom : (num + offset) / denom;
num = a2 * c1 - a1 * c2;
const y = num < 0 ? (num - offset) / denom : (num + offset) / denom;
return { x: x, y: y };
}
function sameSign(r1: number, r2: number) {
return r1 * r2 > 0;
}
const diamondIntersection = (
bounds: { x: any; y: any; width: any; height: any },
outsidePoint: { x: number; y: number },
insidePoint: any
) => {
const x1 = bounds.x;
const y1 = bounds.y;
const w = bounds.width; //+ bounds.padding;
const h = bounds.height; // + bounds.padding;
const polyPoints = [
{ x: x1, y: y1 - h / 2 },
{ x: x1 + w / 2, y: y1 },
{ x: x1, y: y1 + h / 2 },
{ x: x1 - w / 2, y: y1 },
];
log.debug(
`APA16 diamondIntersection calc abc89:
outsidePoint: ${JSON.stringify(outsidePoint)}
insidePoint : ${JSON.stringify(insidePoint)}
node-bounds : x:${bounds.x} y:${bounds.y} w:${bounds.width} h:${bounds.height}`,
JSON.stringify(polyPoints)
);
const intersections = [];
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
polyPoints.forEach(function (entry) {
minX = Math.min(minX, entry.x);
minY = Math.min(minY, entry.y);
});
const left = x1 - w / 2 - minX;
const top = y1 - h / 2 - minY;
for (let i = 0; i < polyPoints.length; i++) {
const p1 = polyPoints[i];
const p2 = polyPoints[i < polyPoints.length - 1 ? i + 1 : 0];
const intersect = intersectLine(
bounds,
outsidePoint,
{ x: left + p1.x, y: top + p1.y },
{ x: left + p2.x, y: top + p2.y }
);
if (intersect) {
intersections.push(intersect);
}
}
if (!intersections.length) {
return bounds;
}
log.debug('UIO intersections', intersections);
if (intersections.length > 1) {
// More intersections, find the one nearest to edge end point
intersections.sort(function (p, q) {
const pdx = p.x - outsidePoint.x;
const pdy = p.y - outsidePoint.y;
const distp = Math.sqrt(pdx * pdx + pdy * pdy);
const qdx = q.x - outsidePoint.x;
const qdy = q.y - outsidePoint.y;
const distq = Math.sqrt(qdx * qdx + qdy * qdy);
return distp < distq ? -1 : distp === distq ? 0 : 1;
});
}
return intersections[0];
};
const intersection = (
node: { x: any; y: any; width: number; height: number },
outsidePoint: { x: number; y: number },
insidePoint: { x: number; y: number }
) => {
log.debug(`intersection calc abc89:
outsidePoint: ${JSON.stringify(outsidePoint)}
insidePoint : ${JSON.stringify(insidePoint)}
node : x:${node.x} y:${node.y} w:${node.width} h:${node.height}`);
const x = node.x;
const y = node.y;
const dx = Math.abs(x - insidePoint.x);
// const dy = Math.abs(y - insidePoint.y);
const w = node.width / 2;
let r = insidePoint.x < outsidePoint.x ? w - dx : w + dx;
const h = node.height / 2;
const Q = Math.abs(outsidePoint.y - insidePoint.y);
const R = Math.abs(outsidePoint.x - insidePoint.x);
if (Math.abs(y - outsidePoint.y) * w > Math.abs(x - outsidePoint.x) * h) {
// Intersection is top or bottom of rect.
const q = insidePoint.y < outsidePoint.y ? outsidePoint.y - h - y : y - h - outsidePoint.y;
r = (R * q) / Q;
const res = {
x: insidePoint.x < outsidePoint.x ? insidePoint.x + r : insidePoint.x - R + r,
y: insidePoint.y < outsidePoint.y ? insidePoint.y + Q - q : insidePoint.y - Q + q,
};
if (r === 0) {
res.x = outsidePoint.x;
res.y = outsidePoint.y;
}
if (R === 0) {
res.x = outsidePoint.x;
}
if (Q === 0) {
res.y = outsidePoint.y;
}
log.debug(`abc89 topp/bott calc, Q ${Q}, q ${q}, R ${R}, r ${r}`, res); // cspell: disable-line
return res;
} else {
// Intersection on sides of rect
if (insidePoint.x < outsidePoint.x) {
r = outsidePoint.x - w - x;
} else {
// r = outsidePoint.x - w - x;
r = x - w - outsidePoint.x;
}
const q = (Q * r) / R;
// OK let _x = insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x + dx - w;
// OK let _x = insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : outsidePoint.x + r;
let _x = insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : insidePoint.x - R + r;
// let _x = insidePoint.x < outsidePoint.x ? insidePoint.x + R - r : outsidePoint.x + r;
let _y = insidePoint.y < outsidePoint.y ? insidePoint.y + q : insidePoint.y - q;
log.debug(`sides calc abc89, Q ${Q}, q ${q}, R ${R}, r ${r}`, { _x, _y });
if (r === 0) {
_x = outsidePoint.x;
_y = outsidePoint.y;
}
if (R === 0) {
_x = outsidePoint.x;
}
if (Q === 0) {
_y = outsidePoint.y;
}
return { x: _x, y: _y };
}
};
const outsideNode = (
node: { x: any; y: any; width: number; height: number },
point: { x: number; y: number }
) => {
const x = node.x;
const y = node.y;
const dx = Math.abs(point.x - x);
const dy = Math.abs(point.y - y);
const w = node.width / 2;
const h = node.height / 2;
if (dx >= w || dy >= h) {
return true;
}
return false;
};
/**
* This function will page a path and node where the last point(s) in the path is inside the node
* and return an update path ending by the border of the node.
*/
const cutPathAtIntersect = (
_points: any[],
bounds: { x: any; y: any; width: any; height: any; padding: any },
isDiamond: boolean
) => {
log.debug('APA18 cutPathAtIntersect Points:', _points, 'node:', bounds, 'isDiamond', isDiamond);
const points: any[] = [];
let lastPointOutside = _points[0];
let isInside = false;
_points.forEach((point: any) => {
// check if point is inside the boundary rect
if (!outsideNode(bounds, point) && !isInside) {
// First point inside the rect found
// Calc the intersection coord between the point and the last point outside the rect
let inter;
if (isDiamond) {
const inter2 = diamondIntersection(bounds, lastPointOutside, point);
const distance = Math.sqrt(
(lastPointOutside.x - inter2.x) ** 2 + (lastPointOutside.y - inter2.y) ** 2
);
if (distance > 1) {
inter = inter2;
}
}
if (!inter) {
inter = intersection(bounds, lastPointOutside, point);
}
// Check case where the intersection is the same as the last point
let pointPresent = false;
points.forEach((p) => {
pointPresent = pointPresent || (p.x === inter.x && p.y === inter.y);
});
// if (!pointPresent) {
if (!points.some((e) => e.x === inter.x && e.y === inter.y)) {
points.push(inter);
} else {
log.debug('abc88 no intersect', inter, points);
}
// points.push(inter);
isInside = true;
} else {
// Outside
log.debug('abc88 outside', point, lastPointOutside, points);
lastPointOutside = point;
// points.push(point);
if (!isInside) {
points.push(point);
}
}
});
return points;
};
// @ts-ignore - ELK is not typed
const elk = new ELK();
const element = svg.select('g');
@@ -866,11 +595,16 @@ export const render = async (
delete node.height;
}
});
elkGraph.edges.forEach((edge: any) => {
log.debug('APA01 processing edges, count:', elkGraph.edges.length);
elkGraph.edges.forEach((edge: any, index: number) => {
log.debug('APA01 processing edge', index, ':', edge);
const source = edge.sources[0];
const target = edge.targets[0];
log.debug('APA01 source:', source, 'target:', target);
log.debug('APA01 nodeDb[source]:', nodeDb[source]);
log.debug('APA01 nodeDb[target]:', nodeDb[target]);
if (nodeDb[source].parentId !== nodeDb[target].parentId) {
if (nodeDb[source] && nodeDb[target] && nodeDb[source].parentId !== nodeDb[target].parentId) {
const ancestorId = findCommonAncestor(source, target, parentLookupDb);
// an edge that breaks a subgraph has been identified, set configuration accordingly
setIncludeChildrenPolicy(source, ancestorId);
@@ -878,7 +612,37 @@ export const render = async (
}
});
const g = await elk.layout(elkGraph);
log.debug('APA01 before');
log.debug('APA01 elkGraph structure:', JSON.stringify(elkGraph, null, 2));
log.debug('APA01 elkGraph.children length:', elkGraph.children?.length);
log.debug('APA01 elkGraph.edges length:', elkGraph.edges?.length);
// Validate that all edge references exist as nodes
elkGraph.edges?.forEach((edge: any, index: number) => {
log.debug(`APA01 validating edge ${index}:`, edge);
if (edge.sources) {
edge.sources.forEach((sourceId: any) => {
const sourceExists = elkGraph.children?.some((child: any) => child.id === sourceId);
log.debug(`APA01 source ${sourceId} exists:`, sourceExists);
});
}
if (edge.targets) {
edge.targets.forEach((targetId: any) => {
const targetExists = elkGraph.children?.some((child: any) => child.id === targetId);
log.debug(`APA01 target ${targetId} exists:`, targetExists);
});
}
});
let g;
try {
g = await elk.layout(elkGraph);
log.debug('APA01 after - success');
log.debug('APA01 layout result:', JSON.stringify(g, null, 2));
} catch (error) {
log.error('APA01 ELK layout error:', error);
throw error;
}
// debugger;
await drawNodes(0, 0, g.children, svg, subGraphsEl, 0);
@@ -966,42 +730,37 @@ export const render = async (
startNode.innerHTML
);
}
if (startNode.shape === 'diamond' || startNode.shape === 'diam') {
edge.points.unshift({
x: startNode.offset.posX + startNode.width / 2,
y: startNode.offset.posY + startNode.height / 2,
});
}
if (endNode.shape === 'diamond' || endNode.shape === 'diam') {
edge.points.push({
x: endNode.offset.posX + endNode.width / 2,
y: endNode.offset.posY + endNode.height / 2,
});
}
edge.points = cutPathAtIntersect(
edge.points.reverse(),
{
x: startNode.offset.posX + startNode.width / 2,
y: startNode.offset.posY + startNode.height / 2,
width: sw,
height: startNode.height,
padding: startNode.padding,
},
startNode.shape === 'diamond' || startNode.shape === 'diam'
).reverse();
if (startNode.calcIntersect) {
const intersection = startNode.calcIntersect(
{
x: startNode.offset.posX + startNode.width / 2,
y: startNode.offset.posY + startNode.height / 2,
width: startNode.width,
height: startNode.height,
},
edge.points[0]
);
edge.points = cutPathAtIntersect(
edge.points,
{
x: endNode.offset.posX + endNode.width / 2,
y: endNode.offset.posY + endNode.height / 2,
width: ew,
height: endNode.height,
padding: endNode.padding,
},
endNode.shape === 'diamond' || endNode.shape === 'diam'
);
if (distance(intersection, edge.points[0]) > epsilon) {
edge.points.unshift(intersection);
}
}
if (endNode.calcIntersect) {
const intersection = endNode.calcIntersect(
{
x: endNode.offset.posX + endNode.width / 2,
y: endNode.offset.posY + endNode.height / 2,
width: endNode.width,
height: endNode.height,
},
edge.points[edge.points.length - 1]
);
if (distance(intersection, edge.points[edge.points.length - 1]) > epsilon) {
edge.points.push(intersection);
}
}
const paths = insertEdge(
edgesEl,
@@ -1012,7 +771,6 @@ export const render = async (
endNode,
data4Layout.diagramId
);
log.info('APA12 edge points after insert', JSON.stringify(edge.points));
edge.x = edge.labels[0].x + offset.x + edge.labels[0].width / 2;
edge.y = edge.labels[0].y + offset.y + edge.labels[0].height / 2;

View File

@@ -5,6 +5,6 @@
"outDir": "./dist",
"types": ["vitest/importMeta", "vitest/globals"]
},
"include": ["./src/**/*.ts"],
"include": ["./src/**/*.ts", "./src/**/*.d.ts"],
"typeRoots": ["./src/types"]
}

View File

@@ -0,0 +1,59 @@
# @mermaid-js/layout-tidy-tree
This package provides a bidirectional tidy tree layout engine for Mermaid based on the non-layered-tidy-tree-layout algorithm.
> [!NOTE]
> The Tidy Tree Layout engine will not be available in all providers that support mermaid by default.
> The websites will have to install the @mermaid-js/layout-tidy-tree package to use the Tidy Tree layout engine.
## Usage
```
---
config:
layout: tidy-tree
---
mindmap
root((mindmap))
A
B
```
### With bundlers
```sh
npm install @mermaid-js/layout-tidy-tree
```
```ts
import mermaid from 'mermaid';
import tidyTreeLayouts from '@mermaid-js/layout-tidy-tree';
mermaid.registerLayoutLoaders(tidyTreeLayouts);
```
### With CDN
```html
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
import tidyTreeLayouts from 'https://cdn.jsdelivr.net/npm/@mermaid-js/layout-tidy-tree@0/dist/mermaid-layout-tidy-tree.esm.min.mjs';
mermaid.registerLayoutLoaders(tidyTreeLayouts);
</script>
```
## Tidy Tree Layout Overview
tidy-tree: The bidirectional tidy tree layout
The bidirectional tidy tree layout algorithm creates two separate trees that grow horizontally in opposite directions from a central root node:
Left tree: grows horizontally to the left (children alternate: 1st, 3rd, 5th...)
Right tree: grows horizontally to the right (children alternate: 2nd, 4th, 6th...)
This creates a balanced, symmetric layout that is ideal for mindmaps, organizational charts, and other tree-based diagrams.
Layout Structure:
[Child 3] ← [Child 1] ← [Root] → [Child 2] → [Child 4]
↓ ↓ ↓ ↓
[GrandChild] [GrandChild] [GrandChild] [GrandChild]

View File

@@ -0,0 +1,46 @@
{
"name": "@mermaid-js/layout-tidy-tree",
"version": "0.1.0",
"description": "Tidy-tree layout engine for mermaid",
"module": "dist/mermaid-layout-tidy-tree.core.mjs",
"types": "dist/layouts.d.ts",
"type": "module",
"exports": {
".": {
"import": "./dist/mermaid-layout-tidy-tree.core.mjs",
"types": "./dist/layouts.d.ts"
},
"./": "./"
},
"keywords": [
"diagram",
"markdown",
"tidy-tree",
"mermaid",
"layout"
],
"scripts": {},
"repository": {
"type": "git",
"url": "https://github.com/mermaid-js/mermaid"
},
"contributors": [
"Knut Sveidqvist",
"Sidharth Vinod"
],
"license": "MIT",
"dependencies": {
"d3": "^7.9.0",
"non-layered-tidy-tree-layout": "^2.0.2"
},
"devDependencies": {
"@types/d3": "^7.4.3",
"mermaid": "workspace:^"
},
"peerDependencies": {
"mermaid": "^11.0.2"
},
"files": [
"dist"
]
}

View File

@@ -0,0 +1,50 @@
/**
* Bidirectional Tidy-Tree Layout Algorithm for Generic Diagrams
*
* This module provides a layout algorithm implementation using the
* non-layered-tidy-tree-layout algorithm for positioning nodes and edges
* in tree structures with a bidirectional approach.
*
* The algorithm creates two separate trees that grow horizontally in opposite
* directions from a central root node:
* - Left tree: grows horizontally to the left (children alternate: 1st, 3rd, 5th...)
* - Right tree: grows horizontally to the right (children alternate: 2nd, 4th, 6th...)
*
* This creates a balanced, symmetric layout that is ideal for mindmaps,
* organizational charts, and other tree-based diagrams.
*
* The algorithm follows the unified rendering pattern and can be used
* by any diagram type that provides compatible LayoutData.
*/
/**
* Render function for the bidirectional tidy-tree layout algorithm
*
* This function follows the unified rendering pattern used by all layout algorithms.
* It takes LayoutData, inserts nodes into DOM, runs the bidirectional tidy-tree layout algorithm,
* and renders the positioned elements to the SVG.
*
* Features:
* - Alternates root children between left and right trees
* - Left tree grows horizontally to the left (rotated 90° counterclockwise)
* - Right tree grows horizontally to the right (rotated 90° clockwise)
* - Uses tidy-tree algorithm for optimal spacing within each tree
* - Creates symmetric, balanced layouts
* - Maintains proper edge connections between all nodes
*
* Layout Structure:
* ```
* [Child 3] ← [Child 1] ← [Root] → [Child 2] → [Child 4]
* ↓ ↓ ↓ ↓
* [GrandChild] [GrandChild] [GrandChild] [GrandChild]
* ```
*
* @param layoutData - Layout data containing nodes, edges, and configuration
* @param svg - SVG element to render to
* @param helpers - Internal helper functions for rendering
* @param options - Rendering options
*/
export { default } from './layouts.js';
export * from './types.js';
export * from './layout.js';
export { render } from './render.js';

View File

@@ -0,0 +1,410 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
// Mock non-layered-tidy-tree-layout
vi.mock('non-layered-tidy-tree-layout', () => ({
BoundingBox: vi.fn().mockImplementation(() => ({})),
Layout: vi.fn().mockImplementation(() => ({
layout: vi.fn().mockImplementation((treeData) => {
const result = { ...treeData };
if (result.id?.toString().startsWith('virtual-root')) {
result.x = 0;
result.y = 0;
} else {
result.x = 100;
result.y = 50;
}
if (result.children) {
result.children.forEach((child: any, index: number) => {
child.x = 50 + index * 100;
child.y = 100;
if (child.children) {
child.children.forEach((grandchild: any, gIndex: number) => {
grandchild.x = 25 + gIndex * 50;
grandchild.y = 200;
});
}
});
}
return {
result,
boundingBox: {
left: 0,
right: 200,
top: 0,
bottom: 250,
},
};
}),
})),
}));
import { executeTidyTreeLayout, validateLayoutData } from './layout.js';
import type { LayoutResult } from './types.js';
import type { LayoutData, MermaidConfig } from 'mermaid';
describe('Tidy-Tree Layout Algorithm', () => {
let mockConfig: MermaidConfig;
let mockLayoutData: LayoutData;
beforeEach(() => {
mockConfig = {
theme: 'default',
} as MermaidConfig;
mockLayoutData = {
nodes: [
{
id: 'root',
label: 'Root',
isGroup: false,
shape: 'rect',
width: 100,
height: 50,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
{
id: 'child1',
label: 'Child 1',
isGroup: false,
shape: 'rect',
width: 80,
height: 40,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
{
id: 'child2',
label: 'Child 2',
isGroup: false,
shape: 'rect',
width: 80,
height: 40,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
{
id: 'child3',
label: 'Child 3',
isGroup: false,
shape: 'rect',
width: 80,
height: 40,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
{
id: 'child4',
label: 'Child 4',
isGroup: false,
shape: 'rect',
width: 80,
height: 40,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
],
edges: [
{
id: 'root_child1',
start: 'root',
end: 'child1',
type: 'edge',
classes: '',
style: [],
animate: false,
arrowTypeEnd: 'arrow_point',
arrowTypeStart: 'none',
},
{
id: 'root_child2',
start: 'root',
end: 'child2',
type: 'edge',
classes: '',
style: [],
animate: false,
arrowTypeEnd: 'arrow_point',
arrowTypeStart: 'none',
},
{
id: 'root_child3',
start: 'root',
end: 'child3',
type: 'edge',
classes: '',
style: [],
animate: false,
arrowTypeEnd: 'arrow_point',
arrowTypeStart: 'none',
},
{
id: 'root_child4',
start: 'root',
end: 'child4',
type: 'edge',
classes: '',
style: [],
animate: false,
arrowTypeEnd: 'arrow_point',
arrowTypeStart: 'none',
},
],
config: mockConfig,
direction: 'TB',
type: 'test',
diagramId: 'test-diagram',
markers: [],
};
});
describe('validateLayoutData', () => {
it('should validate correct layout data', () => {
expect(() => validateLayoutData(mockLayoutData)).not.toThrow();
});
it('should throw error for missing data', () => {
expect(() => validateLayoutData(null as any)).toThrow('Layout data is required');
});
it('should throw error for missing config', () => {
const invalidData = { ...mockLayoutData, config: null as any };
expect(() => validateLayoutData(invalidData)).toThrow('Configuration is required');
});
it('should throw error for invalid nodes array', () => {
const invalidData = { ...mockLayoutData, nodes: null as any };
expect(() => validateLayoutData(invalidData)).toThrow('Nodes array is required');
});
it('should throw error for invalid edges array', () => {
const invalidData = { ...mockLayoutData, edges: null as any };
expect(() => validateLayoutData(invalidData)).toThrow('Edges array is required');
});
});
describe('executeTidyTreeLayout function', () => {
it('should execute layout algorithm successfully', async () => {
const result: LayoutResult = await executeTidyTreeLayout(mockLayoutData, mockConfig);
expect(result).toBeDefined();
expect(result.nodes).toBeDefined();
expect(result.edges).toBeDefined();
expect(Array.isArray(result.nodes)).toBe(true);
expect(Array.isArray(result.edges)).toBe(true);
});
it('should return positioned nodes with coordinates', async () => {
const result: LayoutResult = await executeTidyTreeLayout(mockLayoutData, mockConfig);
expect(result.nodes.length).toBeGreaterThan(0);
result.nodes.forEach((node) => {
expect(node.x).toBeDefined();
expect(node.y).toBeDefined();
expect(typeof node.x).toBe('number');
expect(typeof node.y).toBe('number');
});
});
it('should return positioned edges with coordinates', async () => {
const result: LayoutResult = await executeTidyTreeLayout(mockLayoutData, mockConfig);
expect(result.edges.length).toBeGreaterThan(0);
result.edges.forEach((edge) => {
expect(edge.startX).toBeDefined();
expect(edge.startY).toBeDefined();
expect(edge.midX).toBeDefined();
expect(edge.midY).toBeDefined();
expect(edge.endX).toBeDefined();
expect(edge.endY).toBeDefined();
});
});
it('should handle empty layout data gracefully', async () => {
const emptyData: LayoutData = {
...mockLayoutData,
nodes: [],
edges: [],
};
await expect(executeTidyTreeLayout(emptyData, mockConfig)).rejects.toThrow(
'No nodes found in layout data'
);
});
it('should throw error for missing nodes', async () => {
const invalidData = { ...mockLayoutData, nodes: [] };
await expect(executeTidyTreeLayout(invalidData, mockConfig)).rejects.toThrow(
'No nodes found in layout data'
);
});
it('should handle empty edges (single node tree)', async () => {
const singleNodeData = {
...mockLayoutData,
edges: [],
nodes: [mockLayoutData.nodes[0]],
};
const result = await executeTidyTreeLayout(singleNodeData, mockConfig);
expect(result).toBeDefined();
expect(result.nodes).toHaveLength(1);
expect(result.edges).toHaveLength(0);
});
it('should create bidirectional dual-tree layout with alternating left/right children', async () => {
const result = await executeTidyTreeLayout(mockLayoutData, mockConfig);
expect(result).toBeDefined();
expect(result.nodes).toHaveLength(5);
const rootNode = result.nodes.find((node) => node.id === 'root');
expect(rootNode).toBeDefined();
expect(rootNode!.x).toBe(0);
expect(rootNode!.y).toBe(20);
const child1 = result.nodes.find((node) => node.id === 'child1');
const child2 = result.nodes.find((node) => node.id === 'child2');
const child3 = result.nodes.find((node) => node.id === 'child3');
const child4 = result.nodes.find((node) => node.id === 'child4');
expect(child1).toBeDefined();
expect(child2).toBeDefined();
expect(child3).toBeDefined();
expect(child4).toBeDefined();
expect(child1!.x).toBeLessThan(rootNode!.x);
expect(child2!.x).toBeGreaterThan(rootNode!.x);
expect(child3!.x).toBeLessThan(rootNode!.x);
expect(child4!.x).toBeGreaterThan(rootNode!.x);
expect(child1!.x).toBeLessThan(-100);
expect(child3!.x).toBeLessThan(-100);
expect(child2!.x).toBeGreaterThan(100);
expect(child4!.x).toBeGreaterThan(100);
});
it('should correctly transpose coordinates to prevent high nodes from covering nodes above them', async () => {
const testData = {
...mockLayoutData,
nodes: [
{
id: 'root',
label: 'Root',
isGroup: false,
shape: 'rect' as const,
width: 100,
height: 50,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
{
id: 'tall-child',
label: 'Tall Child',
isGroup: false,
shape: 'rect' as const,
width: 80,
height: 120,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
{
id: 'short-child',
label: 'Short Child',
isGroup: false,
shape: 'rect' as const,
width: 80,
height: 30,
padding: 10,
x: 0,
y: 0,
cssClasses: '',
cssStyles: [],
look: 'default',
},
],
edges: [
{
id: 'root_tall',
start: 'root',
end: 'tall-child',
type: 'edge',
classes: '',
style: [],
animate: false,
arrowTypeEnd: 'arrow_point',
arrowTypeStart: 'none',
},
{
id: 'root_short',
start: 'root',
end: 'short-child',
type: 'edge',
classes: '',
style: [],
animate: false,
arrowTypeEnd: 'arrow_point',
arrowTypeStart: 'none',
},
],
};
const result = await executeTidyTreeLayout(testData, mockConfig);
expect(result).toBeDefined();
expect(result.nodes).toHaveLength(3);
const rootNode = result.nodes.find((node) => node.id === 'root');
const tallChild = result.nodes.find((node) => node.id === 'tall-child');
const shortChild = result.nodes.find((node) => node.id === 'short-child');
expect(rootNode).toBeDefined();
expect(tallChild).toBeDefined();
expect(shortChild).toBeDefined();
expect(tallChild!.x).not.toBe(shortChild!.x);
expect(tallChild!.width).toBe(80);
expect(tallChild!.height).toBe(120);
expect(shortChild!.width).toBe(80);
expect(shortChild!.height).toBe(30);
const yDifference = Math.abs(tallChild!.y - shortChild!.y);
expect(yDifference).toBeGreaterThanOrEqual(0);
});
});
});

View File

@@ -0,0 +1,638 @@
import { BoundingBox, Layout } from 'non-layered-tidy-tree-layout';
import type { MermaidConfig, LayoutData } from 'mermaid';
import type {
LayoutResult,
TidyTreeNode,
PositionedNode,
PositionedEdge,
Node,
Edge,
} from './types.js';
/**
* Execute the tidy-tree layout algorithm on generic layout data
*
* This function takes layout data and uses the non-layered-tidy-tree-layout
* algorithm to calculate optimal node positions for tree structures.
*
* @param data - The layout data containing nodes, edges, and configuration
* @param config - Mermaid configuration object
* @returns Promise resolving to layout result with positioned nodes and edges
*/
export function executeTidyTreeLayout(
data: LayoutData,
_config: MermaidConfig
): Promise<LayoutResult> {
let intersectionShift = 50;
return new Promise((resolve, reject) => {
try {
if (!data.nodes || !Array.isArray(data.nodes) || data.nodes.length === 0) {
throw new Error('No nodes found in layout data');
}
if (!data.edges || !Array.isArray(data.edges)) {
data.edges = [];
}
const { leftTree, rightTree, rootNode } = convertToDualTreeFormat(data);
const gap = 20;
const bottomPadding = 40;
intersectionShift = 30;
const bb = new BoundingBox(gap, bottomPadding);
const layout = new Layout(bb);
let leftResult = null;
let rightResult = null;
let leftBoundingBox = null;
let rightBoundingBox = null;
if (leftTree) {
const leftLayoutResult = layout.layout(leftTree);
leftResult = leftLayoutResult.result;
leftBoundingBox = leftLayoutResult.boundingBox;
}
if (rightTree) {
const rightLayoutResult = layout.layout(rightTree);
rightResult = rightLayoutResult.result;
rightBoundingBox = rightLayoutResult.boundingBox;
}
const positionedNodes = combineAndPositionTrees(
rootNode,
leftResult,
rightResult,
leftBoundingBox,
rightBoundingBox,
data
);
const positionedEdges = calculateEdgePositions(
data.edges,
positionedNodes,
intersectionShift
);
resolve({
nodes: positionedNodes,
edges: positionedEdges,
});
} catch (error) {
reject(error);
}
});
}
/**
* Convert LayoutData to dual-tree format (left and right trees)
*
* This function builds two separate tree structures from the nodes and edges,
* alternating children between left and right trees.
*/
function convertToDualTreeFormat(data: LayoutData): {
leftTree: TidyTreeNode | null;
rightTree: TidyTreeNode | null;
rootNode: TidyTreeNode;
} {
const { nodes, edges } = data;
const nodeMap = new Map<string, Node>();
nodes.forEach((node) => nodeMap.set(node.id, node));
const children = new Map<string, string[]>();
const parents = new Map<string, string>();
edges.forEach((edge) => {
const parentId = edge.start;
const childId = edge.end;
if (parentId && childId) {
if (!children.has(parentId)) {
children.set(parentId, []);
}
children.get(parentId)!.push(childId);
parents.set(childId, parentId);
}
});
const rootNodeData = nodes.find((node) => !parents.has(node.id));
if (!rootNodeData && nodes.length === 0) {
throw new Error('No nodes available to create tree');
}
const actualRoot = rootNodeData ?? nodes[0];
const rootNode: TidyTreeNode = {
id: actualRoot.id,
width: actualRoot.width ?? 100,
height: actualRoot.height ?? 50,
_originalNode: actualRoot,
};
const rootChildren = children.get(actualRoot.id) ?? [];
const leftChildren: string[] = [];
const rightChildren: string[] = [];
rootChildren.forEach((childId, index) => {
if (index % 2 === 0) {
leftChildren.push(childId);
} else {
rightChildren.push(childId);
}
});
const leftTree = leftChildren.length > 0 ? buildSubTree(leftChildren, children, nodeMap) : null;
const rightTree =
rightChildren.length > 0 ? buildSubTree(rightChildren, children, nodeMap) : null;
return { leftTree, rightTree, rootNode };
}
/**
* Build a subtree from a list of root children
* For horizontal trees, we need to transpose width/height since the tree will be rotated 90°
*/
function buildSubTree(
rootChildren: string[],
children: Map<string, string[]>,
nodeMap: Map<string, Node>
): TidyTreeNode {
const virtualRoot: TidyTreeNode = {
id: `virtual-root-${Math.random()}`,
width: 1,
height: 1,
children: rootChildren
.map((childId) => nodeMap.get(childId))
.filter((child): child is Node => child !== undefined)
.map((child) => convertNodeToTidyTreeTransposed(child, children, nodeMap)),
};
return virtualRoot;
}
/**
* Recursively convert a node and its children to tidy-tree format
* This version transposes width/height for horizontal tree layout
*/
function convertNodeToTidyTreeTransposed(
node: Node,
children: Map<string, string[]>,
nodeMap: Map<string, Node>
): TidyTreeNode {
const childIds = children.get(node.id) ?? [];
const childNodes = childIds
.map((childId) => nodeMap.get(childId))
.filter((child): child is Node => child !== undefined)
.map((child) => convertNodeToTidyTreeTransposed(child, children, nodeMap));
return {
id: node.id,
width: node.height ?? 50,
height: node.width ?? 100,
children: childNodes.length > 0 ? childNodes : undefined,
_originalNode: node,
};
}
/**
* Combine and position the left and right trees around the root node
* Creates a bidirectional layout where left tree grows left and right tree grows right
*/
function combineAndPositionTrees(
rootNode: TidyTreeNode,
leftResult: TidyTreeNode | null,
rightResult: TidyTreeNode | null,
_leftBoundingBox: any,
_rightBoundingBox: any,
_data: LayoutData
): PositionedNode[] {
const positionedNodes: PositionedNode[] = [];
const rootX = 0;
const rootY = 0;
const treeSpacing = rootNode.width / 2 + 30;
const leftTreeNodes: PositionedNode[] = [];
const rightTreeNodes: PositionedNode[] = [];
if (leftResult?.children) {
positionLeftTreeBidirectional(leftResult.children, leftTreeNodes, rootX - treeSpacing, rootY);
}
if (rightResult?.children) {
positionRightTreeBidirectional(
rightResult.children,
rightTreeNodes,
rootX + treeSpacing,
rootY
);
}
let leftTreeCenterY = 0;
let rightTreeCenterY = 0;
if (leftTreeNodes.length > 0) {
const leftTreeXPositions = [...new Set(leftTreeNodes.map((node) => node.x))].sort(
(a, b) => b - a
);
const firstLevelLeftX = leftTreeXPositions[0];
const firstLevelLeftNodes = leftTreeNodes.filter((node) => node.x === firstLevelLeftX);
if (firstLevelLeftNodes.length > 0) {
const leftMinY = Math.min(
...firstLevelLeftNodes.map((node) => node.y - (node.height ?? 50) / 2)
);
const leftMaxY = Math.max(
...firstLevelLeftNodes.map((node) => node.y + (node.height ?? 50) / 2)
);
leftTreeCenterY = (leftMinY + leftMaxY) / 2;
}
}
if (rightTreeNodes.length > 0) {
const rightTreeXPositions = [...new Set(rightTreeNodes.map((node) => node.x))].sort(
(a, b) => a - b
);
const firstLevelRightX = rightTreeXPositions[0];
const firstLevelRightNodes = rightTreeNodes.filter((node) => node.x === firstLevelRightX);
if (firstLevelRightNodes.length > 0) {
const rightMinY = Math.min(
...firstLevelRightNodes.map((node) => node.y - (node.height ?? 50) / 2)
);
const rightMaxY = Math.max(
...firstLevelRightNodes.map((node) => node.y + (node.height ?? 50) / 2)
);
rightTreeCenterY = (rightMinY + rightMaxY) / 2;
}
}
const leftTreeOffset = -leftTreeCenterY;
const rightTreeOffset = -rightTreeCenterY;
positionedNodes.push({
id: String(rootNode.id),
x: rootX,
y: rootY + 20,
section: 'root',
width: rootNode._originalNode?.width ?? rootNode.width,
height: rootNode._originalNode?.height ?? rootNode.height,
originalNode: rootNode._originalNode,
});
const leftTreeNodesWithOffset = leftTreeNodes.map((node) => ({
id: node.id,
x: node.x - (node.width ?? 0) / 2,
y: node.y + leftTreeOffset + (node.height ?? 0) / 2,
section: 'left' as const,
width: node.width,
height: node.height,
originalNode: node.originalNode,
}));
const rightTreeNodesWithOffset = rightTreeNodes.map((node) => ({
id: node.id,
x: node.x + (node.width ?? 0) / 2,
y: node.y + rightTreeOffset + (node.height ?? 0) / 2,
section: 'right' as const,
width: node.width,
height: node.height,
originalNode: node.originalNode,
}));
positionedNodes.push(...leftTreeNodesWithOffset);
positionedNodes.push(...rightTreeNodesWithOffset);
return positionedNodes;
}
/**
* Position nodes from the left tree in a bidirectional layout (grows to the left)
* Rotates the tree 90 degrees counterclockwise so it grows horizontally to the left
*/
function positionLeftTreeBidirectional(
nodes: TidyTreeNode[],
positionedNodes: PositionedNode[],
offsetX: number,
offsetY: number
): void {
nodes.forEach((node) => {
const distanceFromRoot = node.y ?? 0;
const verticalPosition = node.x ?? 0;
const originalWidth = node._originalNode?.width ?? 100;
const originalHeight = node._originalNode?.height ?? 50;
const adjustedY = offsetY + verticalPosition;
positionedNodes.push({
id: String(node.id),
x: offsetX - distanceFromRoot,
y: adjustedY,
width: originalWidth,
height: originalHeight,
originalNode: node._originalNode,
});
if (node.children) {
positionLeftTreeBidirectional(node.children, positionedNodes, offsetX, offsetY);
}
});
}
/**
* Position nodes from the right tree in a bidirectional layout (grows to the right)
* Rotates the tree 90 degrees clockwise so it grows horizontally to the right
*/
function positionRightTreeBidirectional(
nodes: TidyTreeNode[],
positionedNodes: PositionedNode[],
offsetX: number,
offsetY: number
): void {
nodes.forEach((node) => {
const distanceFromRoot = node.y ?? 0;
const verticalPosition = node.x ?? 0;
const originalWidth = node._originalNode?.width ?? 100;
const originalHeight = node._originalNode?.height ?? 50;
const adjustedY = offsetY + verticalPosition;
positionedNodes.push({
id: String(node.id),
x: offsetX + distanceFromRoot,
y: adjustedY,
width: originalWidth,
height: originalHeight,
originalNode: node._originalNode,
});
if (node.children) {
positionRightTreeBidirectional(node.children, positionedNodes, offsetX, offsetY);
}
});
}
/**
* Calculate the intersection point of a line with a circle
* @param circle - Circle coordinates and radius
* @param lineStart - Starting point of the line
* @param lineEnd - Ending point of the line
* @returns The intersection point
*/
function computeCircleEdgeIntersection(
circle: { x: number; y: number; width: number; height: number },
lineStart: { x: number; y: number },
lineEnd: { x: number; y: number }
): { x: number; y: number } {
const radius = Math.min(circle.width, circle.height) / 2;
const dx = lineEnd.x - lineStart.x;
const dy = lineEnd.y - lineStart.y;
const length = Math.sqrt(dx * dx + dy * dy);
if (length === 0) {
return lineStart;
}
const nx = dx / length;
const ny = dy / length;
return {
x: circle.x - nx * radius,
y: circle.y - ny * radius,
};
}
/**
* Calculate intersection point of a line with a rectangle
* This is a simplified version that we'll use instead of importing from mermaid
*/
function intersection(
node: { x: number; y: number; width?: number; height?: number },
point1: { x: number; y: number },
point2: { x: number; y: number }
): { x: number; y: number } {
const nodeWidth = node.width ?? 100;
const nodeHeight = node.height ?? 50;
const centerX = node.x;
const centerY = node.y;
const dx = point2.x - point1.x;
const dy = point2.y - point1.y;
if (dx === 0 && dy === 0) {
return { x: centerX, y: centerY };
}
const halfWidth = nodeWidth / 2;
const halfHeight = nodeHeight / 2;
let intersectionX = centerX;
let intersectionY = centerY;
if (Math.abs(dx) > Math.abs(dy)) {
if (dx > 0) {
intersectionX = centerX + halfWidth;
intersectionY = centerY + (halfWidth * dy) / dx;
} else {
intersectionX = centerX - halfWidth;
intersectionY = centerY - (halfWidth * dy) / dx;
}
} else {
if (dy > 0) {
intersectionY = centerY + halfHeight;
intersectionX = centerX + (halfHeight * dx) / dy;
} else {
intersectionY = centerY - halfHeight;
intersectionX = centerX - (halfHeight * dx) / dy;
}
}
return { x: intersectionX, y: intersectionY };
}
/**
* Calculate edge positions based on positioned nodes
* Now includes tree membership and node dimensions for precise edge calculations
* Edges now stop at shape boundaries instead of extending to centers
*/
function calculateEdgePositions(
edges: Edge[],
positionedNodes: PositionedNode[],
intersectionShift: number
): PositionedEdge[] {
const nodeInfo = new Map<string, PositionedNode>();
positionedNodes.forEach((node) => {
nodeInfo.set(node.id, node);
});
return edges.map((edge) => {
const sourceNode = nodeInfo.get(edge.start ?? '');
const targetNode = nodeInfo.get(edge.end ?? '');
if (!sourceNode || !targetNode) {
return {
id: edge.id,
source: edge.start ?? '',
target: edge.end ?? '',
startX: 0,
startY: 0,
midX: 0,
midY: 0,
endX: 0,
endY: 0,
points: [{ x: 0, y: 0 }],
sourceSection: undefined,
targetSection: undefined,
sourceWidth: undefined,
sourceHeight: undefined,
targetWidth: undefined,
targetHeight: undefined,
};
}
const sourceCenter = { x: sourceNode.x, y: sourceNode.y };
const targetCenter = { x: targetNode.x, y: targetNode.y };
const isSourceRound = ['circle', 'cloud', 'bang'].includes(
sourceNode.originalNode?.shape ?? ''
);
const isTargetRound = ['circle', 'cloud', 'bang'].includes(
targetNode.originalNode?.shape ?? ''
);
let startPos = isSourceRound
? computeCircleEdgeIntersection(
{
x: sourceNode.x,
y: sourceNode.y,
width: sourceNode.width ?? 100,
height: sourceNode.height ?? 100,
},
targetCenter,
sourceCenter
)
: intersection(sourceNode, sourceCenter, targetCenter);
let endPos = isTargetRound
? computeCircleEdgeIntersection(
{
x: targetNode.x,
y: targetNode.y,
width: targetNode.width ?? 100,
height: targetNode.height ?? 100,
},
sourceCenter,
targetCenter
)
: intersection(targetNode, targetCenter, sourceCenter);
const midX = (startPos.x + endPos.x) / 2;
const midY = (startPos.y + endPos.y) / 2;
const points = [startPos];
if (sourceNode.section === 'left') {
points.push({
x: sourceNode.x - (sourceNode.width ?? 0) / 2 - intersectionShift,
y: sourceNode.y,
});
} else if (sourceNode.section === 'right') {
points.push({
x: sourceNode.x + (sourceNode.width ?? 0) / 2 + intersectionShift,
y: sourceNode.y,
});
}
if (targetNode.section === 'left') {
points.push({
x: targetNode.x + (targetNode.width ?? 0) / 2 + intersectionShift,
y: targetNode.y,
});
} else if (targetNode.section === 'right') {
points.push({
x: targetNode.x - (targetNode.width ?? 0) / 2 - intersectionShift,
y: targetNode.y,
});
}
points.push(endPos);
const secondPoint = points.length > 1 ? points[1] : targetCenter;
startPos = isSourceRound
? computeCircleEdgeIntersection(
{
x: sourceNode.x,
y: sourceNode.y,
width: sourceNode.width ?? 100,
height: sourceNode.height ?? 100,
},
secondPoint,
sourceCenter
)
: intersection(sourceNode, secondPoint, sourceCenter);
points[0] = startPos;
const secondLastPoint = points.length > 1 ? points[points.length - 2] : sourceCenter;
endPos = isTargetRound
? computeCircleEdgeIntersection(
{
x: targetNode.x,
y: targetNode.y,
width: targetNode.width ?? 100,
height: targetNode.height ?? 100,
},
secondLastPoint,
targetCenter
)
: intersection(targetNode, secondLastPoint, targetCenter);
points[points.length - 1] = endPos;
return {
id: edge.id,
source: edge.start ?? '',
target: edge.end ?? '',
startX: startPos.x,
startY: startPos.y,
midX,
midY,
endX: endPos.x,
endY: endPos.y,
points,
sourceSection: sourceNode?.section,
targetSection: targetNode?.section,
sourceWidth: sourceNode?.width,
sourceHeight: sourceNode?.height,
targetWidth: targetNode?.width,
targetHeight: targetNode?.height,
};
});
}
/**
* Validate layout data structure
* @param data - The data to validate
* @returns True if data is valid, throws error otherwise
*/
export function validateLayoutData(data: LayoutData): boolean {
if (!data) {
throw new Error('Layout data is required');
}
if (!data.config) {
throw new Error('Configuration is required in layout data');
}
if (!Array.isArray(data.nodes)) {
throw new Error('Nodes array is required in layout data');
}
if (!Array.isArray(data.edges)) {
throw new Error('Edges array is required in layout data');
}
return true;
}

View File

@@ -0,0 +1,13 @@
import type { LayoutLoaderDefinition } from 'mermaid';
const loader = async () => await import(`./render.js`);
const tidyTreeLayout: LayoutLoaderDefinition[] = [
{
name: 'tidy-tree',
loader,
algorithm: 'tidy-tree',
},
];
export default tidyTreeLayout;

View File

@@ -0,0 +1,18 @@
declare module 'non-layered-tidy-tree-layout' {
export class BoundingBox {
constructor(gap: number, bottomPadding: number);
}
export class Layout {
constructor(boundingBox: BoundingBox);
layout(data: any): {
result: any;
boundingBox: {
left: number;
right: number;
top: number;
bottom: number;
};
};
}
}

View File

@@ -0,0 +1,180 @@
import type { InternalHelpers, LayoutData, RenderOptions, SVG } from 'mermaid';
import { executeTidyTreeLayout } from './layout.js';
interface NodeWithPosition {
id: string;
x?: number;
y?: number;
width?: number;
height?: number;
domId?: any;
[key: string]: any;
}
/**
* Render function for bidirectional tidy-tree layout algorithm
*
* This follows the same pattern as ELK and dagre renderers:
* 1. Insert nodes into DOM to get their actual dimensions
* 2. Run the bidirectional tidy-tree layout algorithm to calculate positions
* 3. Position the nodes and edges based on layout results
*
* The bidirectional layout creates two trees that grow horizontally in opposite
* directions from a central root node:
* - Left tree: grows horizontally to the left (children: 1st, 3rd, 5th...)
* - Right tree: grows horizontally to the right (children: 2nd, 4th, 6th...)
*/
export const render = async (
data4Layout: LayoutData,
svg: SVG,
{
insertCluster,
insertEdge,
insertEdgeLabel,
insertMarkers,
insertNode,
log,
positionEdgeLabel,
}: InternalHelpers,
{ algorithm: _algorithm }: RenderOptions
) => {
const nodeDb: Record<string, NodeWithPosition> = {};
const clusterDb: Record<string, any> = {};
const element = svg.select('g');
insertMarkers(element, data4Layout.markers, data4Layout.type, data4Layout.diagramId);
const subGraphsEl = element.insert('g').attr('class', 'subgraphs');
const edgePaths = element.insert('g').attr('class', 'edgePaths');
const edgeLabels = element.insert('g').attr('class', 'edgeLabels');
const nodes = element.insert('g').attr('class', 'nodes');
// Step 1: Insert nodes into DOM to get their actual dimensions
log.debug('Inserting nodes into DOM for dimension calculation');
await Promise.all(
data4Layout.nodes.map(async (node) => {
if (node.isGroup) {
const clusterNode: NodeWithPosition = {
...node,
id: node.id,
width: node.width,
height: node.height,
};
clusterDb[node.id] = clusterNode;
nodeDb[node.id] = clusterNode;
await insertCluster(subGraphsEl, node);
} else {
const nodeWithPosition: NodeWithPosition = {
...node,
id: node.id,
width: node.width,
height: node.height,
};
nodeDb[node.id] = nodeWithPosition;
const nodeEl = await insertNode(nodes, node, {
config: data4Layout.config,
dir: data4Layout.direction || 'TB',
});
const boundingBox = nodeEl.node()!.getBBox();
nodeWithPosition.width = boundingBox.width;
nodeWithPosition.height = boundingBox.height;
nodeWithPosition.domId = nodeEl;
log.debug(`Node ${node.id} dimensions: ${boundingBox.width}x${boundingBox.height}`);
}
})
);
// Step 2: Run the bidirectional tidy-tree layout algorithm
log.debug('Running bidirectional tidy-tree layout algorithm');
const updatedLayoutData = {
...data4Layout,
nodes: data4Layout.nodes.map((node) => {
const nodeWithDimensions = nodeDb[node.id];
return {
...node,
width: nodeWithDimensions.width ?? node.width ?? 100,
height: nodeWithDimensions.height ?? node.height ?? 50,
};
}),
};
const layoutResult = await executeTidyTreeLayout(updatedLayoutData, data4Layout.config);
// Step 3: Position the nodes based on bidirectional layout results
log.debug('Positioning nodes based on bidirectional layout results');
layoutResult.nodes.forEach((positionedNode) => {
const node = nodeDb[positionedNode.id];
if (node?.domId) {
// Position the node at the calculated coordinates from bidirectional layout
// The layout algorithm has already calculated positions for:
// - Root node at center (0, 0)
// - Left tree nodes with negative x coordinates (growing left)
// - Right tree nodes with positive x coordinates (growing right)
node.domId.attr('transform', `translate(${positionedNode.x}, ${positionedNode.y})`);
// Store the final position
node.x = positionedNode.x;
node.y = positionedNode.y;
// Step 3: Position the nodes based on bidirectional layout results
log.debug(`Positioned node ${node.id} at (${positionedNode.x}, ${positionedNode.y})`);
}
});
log.debug('Inserting and positioning edges');
await Promise.all(
data4Layout.edges.map(async (edge) => {
await insertEdgeLabel(edgeLabels, edge);
const startNode = nodeDb[edge.start ?? ''];
const endNode = nodeDb[edge.end ?? ''];
if (startNode && endNode) {
const positionedEdge = layoutResult.edges.find((e) => e.id === edge.id);
if (positionedEdge) {
log.debug('APA01 positionedEdge', positionedEdge);
const edgeWithPath = {
...edge,
points: positionedEdge.points,
};
const paths = insertEdge(
edgePaths,
edgeWithPath,
clusterDb,
data4Layout.type,
startNode,
endNode,
data4Layout.diagramId
);
positionEdgeLabel(edgeWithPath, paths);
} else {
const edgeWithPath = {
...edge,
points: [
{ x: startNode.x ?? 0, y: startNode.y ?? 0 },
{ x: endNode.x ?? 0, y: endNode.y ?? 0 },
],
};
const paths = insertEdge(
edgePaths,
edgeWithPath,
clusterDb,
data4Layout.type,
startNode,
endNode,
data4Layout.diagramId
);
positionEdgeLabel(edgeWithPath, paths);
}
}
})
);
log.debug('Bidirectional tidy-tree rendering completed');
};

View File

@@ -0,0 +1,69 @@
import type { LayoutData } from 'mermaid';
export type Node = LayoutData['nodes'][number];
export type Edge = LayoutData['edges'][number];
/**
* Positioned node after layout calculation
*/
export interface PositionedNode {
id: string;
x: number;
y: number;
section?: 'root' | 'left' | 'right';
width?: number;
height?: number;
originalNode?: Node;
[key: string]: unknown;
}
/**
* Positioned edge after layout calculation
*/
export interface PositionedEdge {
id: string;
source: string;
target: string;
startX: number;
startY: number;
midX: number;
midY: number;
endX: number;
endY: number;
sourceSection?: 'root' | 'left' | 'right';
targetSection?: 'root' | 'left' | 'right';
sourceWidth?: number;
sourceHeight?: number;
targetWidth?: number;
targetHeight?: number;
[key: string]: unknown;
}
/**
* Result of layout algorithm execution
*/
export interface LayoutResult {
nodes: PositionedNode[];
edges: PositionedEdge[];
}
/**
* Tidy-tree node structure compatible with non-layered-tidy-tree-layout
*/
export interface TidyTreeNode {
id: string | number;
width: number;
height: number;
x?: number;
y?: number;
children?: TidyTreeNode[];
_originalNode?: Node;
}
/**
* Tidy-tree layout configuration
*/
export interface TidyTreeLayoutConfig {
gap: number;
bottomPadding: number;
}

View File

@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"types": ["vitest/importMeta", "vitest/globals"]
},
"include": ["./src/**/*.ts", "./src/**/*.d.ts"],
"typeRoots": ["./src/types"]
}

Some files were not shown because too many files have changed in this diff Show More