zombie-mermaid 2.2.3 → 2.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. package/README.md +4 -4
  2. package/dist/ascii.cjs +1 -11
  3. package/dist/ascii.d.cts +1 -167
  4. package/dist/ascii.d.ts +1 -167
  5. package/dist/ascii.js +1 -6591
  6. package/dist/cli.js +836 -10946
  7. package/dist/index.cjs +2 -81
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +42 -680
  10. package/dist/index.d.ts +42 -680
  11. package/dist/index.js +408 -10002
  12. package/dist/index.js.map +1 -1
  13. package/dist/mcp.cjs +1 -17909
  14. package/dist/mcp.d.cts +1 -11
  15. package/dist/mcp.d.ts +1 -11
  16. package/dist/mcp.js +1 -17884
  17. package/package.json +29 -29
  18. package/src/__tests__/workspace-package-boundaries.test.ts +15 -16
  19. package/src/__tests__/xychart-parser-categories.test.ts +78 -0
  20. package/src/ascii-entry.ts +14 -0
  21. package/src/cli/html-viewer.ts +5 -0
  22. package/src/mcp-entry.ts +21 -0
  23. package/dist/ascii.cjs.map +0 -1
  24. package/dist/ascii.js.map +0 -1
  25. package/dist/mcp.cjs.map +0 -1
  26. package/dist/mcp.js.map +0 -1
  27. package/packages/ascii-renderer/LICENSE +0 -22
  28. package/packages/ascii-renderer/src/ansi.ts +0 -490
  29. package/packages/ascii-renderer/src/canvas.ts +0 -658
  30. package/packages/ascii-renderer/src/class-diagram.ts +0 -2001
  31. package/packages/ascii-renderer/src/converter.ts +0 -446
  32. package/packages/ascii-renderer/src/coords.ts +0 -58
  33. package/packages/ascii-renderer/src/display-width.ts +0 -151
  34. package/packages/ascii-renderer/src/draw-arrows.ts +0 -549
  35. package/packages/ascii-renderer/src/draw-boxes.ts +0 -267
  36. package/packages/ascii-renderer/src/draw-bundles.ts +0 -611
  37. package/packages/ascii-renderer/src/draw-lines.ts +0 -174
  38. package/packages/ascii-renderer/src/draw-subgraphs.ts +0 -108
  39. package/packages/ascii-renderer/src/draw.ts +0 -337
  40. package/packages/ascii-renderer/src/edge-bundling.ts +0 -435
  41. package/packages/ascii-renderer/src/edge-cell-styles.ts +0 -81
  42. package/packages/ascii-renderer/src/edge-routing.ts +0 -1049
  43. package/packages/ascii-renderer/src/er-diagram.ts +0 -1488
  44. package/packages/ascii-renderer/src/flowchart.ts +0 -94
  45. package/packages/ascii-renderer/src/grid-occupancy.ts +0 -234
  46. package/packages/ascii-renderer/src/grid.ts +0 -1267
  47. package/packages/ascii-renderer/src/hyperlinks.ts +0 -248
  48. package/packages/ascii-renderer/src/index.ts +0 -163
  49. package/packages/ascii-renderer/src/lane-search.ts +0 -68
  50. package/packages/ascii-renderer/src/multiline-utils.ts +0 -82
  51. package/packages/ascii-renderer/src/pathfinder.ts +0 -448
  52. package/packages/ascii-renderer/src/registry.ts +0 -88
  53. package/packages/ascii-renderer/src/sequence.ts +0 -1318
  54. package/packages/ascii-renderer/src/shapes/circle.ts +0 -31
  55. package/packages/ascii-renderer/src/shapes/corners.ts +0 -273
  56. package/packages/ascii-renderer/src/shapes/diamond.ts +0 -31
  57. package/packages/ascii-renderer/src/shapes/hexagon.ts +0 -31
  58. package/packages/ascii-renderer/src/shapes/index.ts +0 -123
  59. package/packages/ascii-renderer/src/shapes/rectangle.ts +0 -199
  60. package/packages/ascii-renderer/src/shapes/rounded.ts +0 -31
  61. package/packages/ascii-renderer/src/shapes/special.ts +0 -352
  62. package/packages/ascii-renderer/src/shapes/stadium.ts +0 -122
  63. package/packages/ascii-renderer/src/shapes/state.ts +0 -204
  64. package/packages/ascii-renderer/src/shapes/types.ts +0 -78
  65. package/packages/ascii-renderer/src/territory.ts +0 -136
  66. package/packages/ascii-renderer/src/types.ts +0 -454
  67. package/packages/ascii-renderer/src/validate.ts +0 -189
  68. package/packages/ascii-renderer/src/xychart.ts +0 -1085
  69. package/packages/core/LICENSE +0 -22
  70. package/packages/core/src/click-directive.ts +0 -106
  71. package/packages/core/src/color-utils.ts +0 -205
  72. package/packages/core/src/diagram-type.ts +0 -35
  73. package/packages/core/src/direction-override.ts +0 -46
  74. package/packages/core/src/direction.ts +0 -56
  75. package/packages/core/src/index.ts +0 -34
  76. package/packages/core/src/init-directive.ts +0 -248
  77. package/packages/core/src/multiline-utils.ts +0 -275
  78. package/packages/core/src/statements.ts +0 -197
  79. package/packages/core/src/style-directives.ts +0 -214
  80. package/packages/core/src/text-metrics.ts +0 -498
  81. package/packages/core/src/theme.ts +0 -696
  82. package/packages/core/src/types.ts +0 -670
  83. package/packages/mcp/LICENSE +0 -22
  84. package/packages/mcp/src/index.ts +0 -17
  85. package/packages/mcp/src/server.ts +0 -135
  86. package/packages/mcp/src/tools/check-sequence-activations.ts +0 -91
  87. package/packages/mcp/src/tools/fix-sequence-activations.ts +0 -77
  88. package/packages/mcp/src/tools/render-ascii.ts +0 -99
  89. package/packages/mcp/src/tools/render-svg.ts +0 -95
  90. package/packages/mermaid-parser/LICENSE +0 -22
  91. package/packages/mermaid-parser/src/class/format.ts +0 -15
  92. package/packages/mermaid-parser/src/class/parser.ts +0 -593
  93. package/packages/mermaid-parser/src/class/types.ts +0 -166
  94. package/packages/mermaid-parser/src/er/parser.ts +0 -286
  95. package/packages/mermaid-parser/src/er/types.ts +0 -99
  96. package/packages/mermaid-parser/src/expanded-shapes.ts +0 -376
  97. package/packages/mermaid-parser/src/index.ts +0 -48
  98. package/packages/mermaid-parser/src/sequence/activation-check.ts +0 -149
  99. package/packages/mermaid-parser/src/sequence/activation-fix.ts +0 -112
  100. package/packages/mermaid-parser/src/sequence/box-color.ts +0 -85
  101. package/packages/mermaid-parser/src/sequence/parser.ts +0 -613
  102. package/packages/mermaid-parser/src/sequence/types.ts +0 -242
  103. package/packages/mermaid-parser/src/xychart/colors.ts +0 -177
  104. package/packages/mermaid-parser/src/xychart/parser.ts +0 -203
  105. package/packages/mermaid-parser/src/xychart/types.ts +0 -150
  106. package/packages/svg-renderer/LICENSE +0 -22
  107. package/packages/svg-renderer/src/class/layout.ts +0 -360
  108. package/packages/svg-renderer/src/class/renderer.ts +0 -636
  109. package/packages/svg-renderer/src/edge-curves.ts +0 -204
  110. package/packages/svg-renderer/src/elk-instance.ts +0 -292
  111. package/packages/svg-renderer/src/er/layout.ts +0 -200
  112. package/packages/svg-renderer/src/er/renderer.ts +0 -493
  113. package/packages/svg-renderer/src/index.ts +0 -58
  114. package/packages/svg-renderer/src/layout-engine/constants.ts +0 -19
  115. package/packages/svg-renderer/src/layout-engine/edge-bundling.ts +0 -379
  116. package/packages/svg-renderer/src/layout-engine/elk-adapter-utils.ts +0 -81
  117. package/packages/svg-renderer/src/layout-engine/elk-graph-builder.ts +0 -240
  118. package/packages/svg-renderer/src/layout-engine/from-elk.ts +0 -685
  119. package/packages/svg-renderer/src/layout-engine/layer-alignment.ts +0 -174
  120. package/packages/svg-renderer/src/layout-engine/to-elk.ts +0 -695
  121. package/packages/svg-renderer/src/layout-engine.ts +0 -74
  122. package/packages/svg-renderer/src/layout.ts +0 -8
  123. package/packages/svg-renderer/src/renderer.ts +0 -1485
  124. package/packages/svg-renderer/src/resolve-colors.ts +0 -339
  125. package/packages/svg-renderer/src/sequence/layout.ts +0 -698
  126. package/packages/svg-renderer/src/sequence/renderer.ts +0 -546
  127. package/packages/svg-renderer/src/shape-clipping.ts +0 -197
  128. package/packages/svg-renderer/src/styles.ts +0 -118
  129. package/packages/svg-renderer/src/xychart/layout.ts +0 -682
  130. package/packages/svg-renderer/src/xychart/renderer.ts +0 -684
  131. package/src/__tests__/ascii-canvas-write.test.ts +0 -137
  132. package/src/__tests__/ascii-charset-border-junctions.test.ts +0 -63
  133. package/src/__tests__/ascii-cjk-width.test.ts +0 -150
  134. package/src/__tests__/ascii-class-box-occupancy.test.ts +0 -462
  135. package/src/__tests__/ascii-class-column-width-488-489.test.ts +0 -639
  136. package/src/__tests__/ascii-class-cross-level-jog-corruption.test.ts +0 -187
  137. package/src/__tests__/ascii-class-detour-label-routing-487.test.ts +0 -114
  138. package/src/__tests__/ascii-class-diagram-compartments.test.ts +0 -70
  139. package/src/__tests__/ascii-class-label-box-collision.test.ts +0 -60
  140. package/src/__tests__/ascii-class-label-row-collision-531.test.ts +0 -135
  141. package/src/__tests__/ascii-class-label-territory-row-awareness.test.ts +0 -57
  142. package/src/__tests__/ascii-class-padding.test.ts +0 -104
  143. package/src/__tests__/ascii-class-parent-alignment-971.test.ts +0 -139
  144. package/src/__tests__/ascii-class-parent-alignment-972.test.ts +0 -208
  145. package/src/__tests__/ascii-class-reciprocal-relationships-448.test.ts +0 -169
  146. package/src/__tests__/ascii-combining-mark-width.test.ts +0 -70
  147. package/src/__tests__/ascii-coords-overlay.test.ts +0 -64
  148. package/src/__tests__/ascii-decision-lr-box-start.test.ts +0 -106
  149. package/src/__tests__/ascii-display-width-unit.test.ts +0 -154
  150. package/src/__tests__/ascii-draw-arrows-coverage.test.ts +0 -171
  151. package/src/__tests__/ascii-draw-arrows-single-point-path.test.ts +0 -112
  152. package/src/__tests__/ascii-edge-bundling-rank-violation-454.test.ts +0 -72
  153. package/src/__tests__/ascii-edge-ending-glyphs.test.ts +0 -206
  154. package/src/__tests__/ascii-edge-label-diagonal-fallback-418.test.ts +0 -95
  155. package/src/__tests__/ascii-edge-routing-fixes.test.ts +0 -178
  156. package/src/__tests__/ascii-edge-routing-single-point-path.test.ts +0 -107
  157. package/src/__tests__/ascii-edge-styles.test.ts +0 -149
  158. package/src/__tests__/ascii-emoji-cluster-width.test.ts +0 -101
  159. package/src/__tests__/ascii-er-box-occupancy.test.ts +0 -251
  160. package/src/__tests__/ascii-er-cardinality.test.ts +0 -40
  161. package/src/__tests__/ascii-er-corner-glyphs.test.ts +0 -249
  162. package/src/__tests__/ascii-er-jog-stray-line.test.ts +0 -111
  163. package/src/__tests__/ascii-er-label-padding.test.ts +0 -118
  164. package/src/__tests__/ascii-er-padding.test.ts +0 -114
  165. package/src/__tests__/ascii-er-relationship-label-corruption-350.test.ts +0 -458
  166. package/src/__tests__/ascii-er-relationship-overwrite.test.ts +0 -325
  167. package/src/__tests__/ascii-er-stray-connectors.test.ts +0 -347
  168. package/src/__tests__/ascii-er-unrelated-stem-separation-411.test.ts +0 -98
  169. package/src/__tests__/ascii-er-vertical-one-marker.test.ts +0 -110
  170. package/src/__tests__/ascii-label-line-terminal-fallback.test.ts +0 -172
  171. package/src/__tests__/ascii-lane-search.test.ts +0 -207
  172. package/src/__tests__/ascii-multibox-cjk-width.test.ts +0 -184
  173. package/src/__tests__/ascii-multiline.test.ts +0 -291
  174. package/src/__tests__/ascii-padding-edge-cases.test.ts +0 -154
  175. package/src/__tests__/ascii-pathfinder-route-edge.test.ts +0 -194
  176. package/src/__tests__/ascii-sequence-alt-else-label.test.ts +0 -236
  177. package/src/__tests__/ascii-sequence-block-wall-clearance.test.ts +0 -217
  178. package/src/__tests__/ascii-sequence-box-group.test.ts +0 -159
  179. package/src/__tests__/ascii-sequence-cjk-width.test.ts +0 -235
  180. package/src/__tests__/ascii-sequence-create-destroy.test.ts +0 -114
  181. package/src/__tests__/ascii-sequence-form-invariants.test.ts +0 -432
  182. package/src/__tests__/ascii-sequence-mermaid-parity.test.ts +0 -219
  183. package/src/__tests__/ascii-sequence-notes.test.ts +0 -61
  184. package/src/__tests__/ascii-sequence-padding.test.ts +0 -119
  185. package/src/__tests__/ascii-sequence-self-arrow.test.ts +0 -206
  186. package/src/__tests__/ascii-shape-diamond.test.ts +0 -38
  187. package/src/__tests__/ascii-shape-rectangle.test.ts +0 -258
  188. package/src/__tests__/ascii-shape-rounded.test.ts +0 -36
  189. package/src/__tests__/ascii-shapes-circle.test.ts +0 -41
  190. package/src/__tests__/ascii-shapes-hexagon.test.ts +0 -42
  191. package/src/__tests__/ascii-shapes-special.test.ts +0 -349
  192. package/src/__tests__/ascii-shapes-stadium.test.ts +0 -217
  193. package/src/__tests__/ascii-shapes-state.test.ts +0 -234
  194. package/src/__tests__/ascii-state-bidirectional-label-swap-530.test.ts +0 -130
  195. package/src/__tests__/ascii-subgraph-direction-honored-445.test.ts +0 -90
  196. package/src/__tests__/ascii-subgraph-label-border-clip.test.ts +0 -152
  197. package/src/__tests__/ascii-subgraph-title-padding.test.ts +0 -77
  198. package/src/__tests__/ascii-territory-unit.test.ts +0 -219
  199. package/src/__tests__/ascii-validate.test.ts +0 -220
  200. package/src/__tests__/ascii.test.ts +0 -328
  201. package/src/__tests__/box-color.test.ts +0 -80
  202. package/src/__tests__/class-arrow-directions.test.ts +0 -505
  203. package/src/__tests__/click-directive.test.ts +0 -63
  204. package/src/__tests__/color-utils.test.ts +0 -186
  205. package/src/__tests__/diagram-type.test.ts +0 -28
  206. package/src/__tests__/draw-lines.test.ts +0 -93
  207. package/src/__tests__/edge-cell-styles.test.ts +0 -180
  208. package/src/__tests__/elk-adapter-utils.test.ts +0 -166
  209. package/src/__tests__/grid-occupancy.test.ts +0 -240
  210. package/src/__tests__/helpers/ascii-form.ts +0 -142
  211. package/src/__tests__/helpers/terminal-display-width.ts +0 -74
  212. package/src/__tests__/mcp-check-sequence-activations-tool.test.ts +0 -85
  213. package/src/__tests__/mcp-fix-sequence-activations-tool.test.ts +0 -134
  214. package/src/__tests__/mcp-server.test.ts +0 -163
  215. package/src/__tests__/pathfinder.test.ts +0 -246
  216. package/src/__tests__/sequence-activation-fix.test.ts +0 -91
  217. package/src/__tests__/testdata/ascii/ampersand_lhs.txt +0 -18
  218. package/src/__tests__/testdata/ascii/ampersand_lhs_and_rhs.txt +0 -18
  219. package/src/__tests__/testdata/ascii/ampersand_rhs.txt +0 -18
  220. package/src/__tests__/testdata/ascii/ampersand_td_fanin.txt +0 -18
  221. package/src/__tests__/testdata/ascii/ampersand_td_fanout.txt +0 -18
  222. package/src/__tests__/testdata/ascii/ampersand_without_edge.txt +0 -18
  223. package/src/__tests__/testdata/ascii/back_reference_from_child.txt +0 -10
  224. package/src/__tests__/testdata/ascii/backlink_from_bottom.txt +0 -22
  225. package/src/__tests__/testdata/ascii/backlink_from_top.txt +0 -22
  226. package/src/__tests__/testdata/ascii/backlink_with_short_y_padding.txt +0 -20
  227. package/src/__tests__/testdata/ascii/cls_all_relationships.txt +0 -19
  228. package/src/__tests__/testdata/ascii/cls_annotation.txt +0 -29
  229. package/src/__tests__/testdata/ascii/cls_association.txt +0 -14
  230. package/src/__tests__/testdata/ascii/cls_basic.txt +0 -15
  231. package/src/__tests__/testdata/ascii/cls_dependency.txt +0 -14
  232. package/src/__tests__/testdata/ascii/cls_inheritance.txt +0 -20
  233. package/src/__tests__/testdata/ascii/cls_methods.txt +0 -21
  234. package/src/__tests__/testdata/ascii/comments.txt +0 -23
  235. package/src/__tests__/testdata/ascii/custom_padding.txt +0 -10
  236. package/src/__tests__/testdata/ascii/duplicate_labels.txt +0 -19
  237. package/src/__tests__/testdata/ascii/er_attributes.txt +0 -21
  238. package/src/__tests__/testdata/ascii/er_basic.txt +0 -8
  239. package/src/__tests__/testdata/ascii/er_identifying.txt +0 -18
  240. package/src/__tests__/testdata/ascii/flowchart_tb_simple.txt +0 -29
  241. package/src/__tests__/testdata/ascii/graph_bt_direction.txt +0 -28
  242. package/src/__tests__/testdata/ascii/graph_tb_direction.txt +0 -26
  243. package/src/__tests__/testdata/ascii/nested_subgraphs_with_labels.txt +0 -36
  244. package/src/__tests__/testdata/ascii/preserve_order_of_definition.txt +0 -23
  245. package/src/__tests__/testdata/ascii/self_reference.txt +0 -10
  246. package/src/__tests__/testdata/ascii/self_reference_with_edge.txt +0 -10
  247. package/src/__tests__/testdata/ascii/seq_basic.txt +0 -17
  248. package/src/__tests__/testdata/ascii/seq_multiple_messages.txt +0 -25
  249. package/src/__tests__/testdata/ascii/seq_self_message.txt +0 -18
  250. package/src/__tests__/testdata/ascii/single_node.txt +0 -8
  251. package/src/__tests__/testdata/ascii/single_node_longer_name.txt +0 -8
  252. package/src/__tests__/testdata/ascii/subgraph_complex_mixed.txt +0 -38
  253. package/src/__tests__/testdata/ascii/subgraph_complex_nested.txt +0 -49
  254. package/src/__tests__/testdata/ascii/subgraph_direction_override.txt +0 -47
  255. package/src/__tests__/testdata/ascii/subgraph_empty.txt +0 -10
  256. package/src/__tests__/testdata/ascii/subgraph_mixed_nodes.txt +0 -20
  257. package/src/__tests__/testdata/ascii/subgraph_mixed_nodes_td.txt +0 -48
  258. package/src/__tests__/testdata/ascii/subgraph_multiple_edges.txt +0 -32
  259. package/src/__tests__/testdata/ascii/subgraph_multiple_nodes.txt +0 -16
  260. package/src/__tests__/testdata/ascii/subgraph_nested.txt +0 -24
  261. package/src/__tests__/testdata/ascii/subgraph_nested_with_external.txt +0 -30
  262. package/src/__tests__/testdata/ascii/subgraph_node_outside_lr.txt +0 -17
  263. package/src/__tests__/testdata/ascii/subgraph_single_node.txt +0 -16
  264. package/src/__tests__/testdata/ascii/subgraph_td_direction.txt +0 -26
  265. package/src/__tests__/testdata/ascii/subgraph_td_multiple.txt +0 -44
  266. package/src/__tests__/testdata/ascii/subgraph_td_multiple_paddingy.txt +0 -42
  267. package/src/__tests__/testdata/ascii/subgraph_three_levels_nested.txt +0 -32
  268. package/src/__tests__/testdata/ascii/subgraph_three_separate.txt +0 -24
  269. package/src/__tests__/testdata/ascii/subgraph_two_separate.txt +0 -20
  270. package/src/__tests__/testdata/ascii/subgraph_with_labels.txt +0 -20
  271. package/src/__tests__/testdata/ascii/three_nodes.txt +0 -9
  272. package/src/__tests__/testdata/ascii/three_nodes_single_line.txt +0 -8
  273. package/src/__tests__/testdata/ascii/two_layer_single_graph.txt +0 -19
  274. package/src/__tests__/testdata/ascii/two_layer_single_graph_longer_names.txt +0 -19
  275. package/src/__tests__/testdata/ascii/two_nodes_linked.txt +0 -8
  276. package/src/__tests__/testdata/ascii/two_nodes_longer_names.txt +0 -8
  277. package/src/__tests__/testdata/ascii/two_root_nodes.txt +0 -19
  278. package/src/__tests__/testdata/ascii/two_root_nodes_longer_names.txt +0 -19
  279. package/src/__tests__/testdata/ascii/two_single_root_nodes.txt +0 -19
  280. package/src/__tests__/testdata/unicode/ampersand_lhs.txt +0 -18
  281. package/src/__tests__/testdata/unicode/ampersand_lhs_and_rhs.txt +0 -18
  282. package/src/__tests__/testdata/unicode/ampersand_rhs.txt +0 -18
  283. package/src/__tests__/testdata/unicode/ampersand_without_edge.txt +0 -18
  284. package/src/__tests__/testdata/unicode/back_reference_from_child.txt +0 -10
  285. package/src/__tests__/testdata/unicode/backlink_from_bottom.txt +0 -22
  286. package/src/__tests__/testdata/unicode/backlink_from_top.txt +0 -22
  287. package/src/__tests__/testdata/unicode/cls_all_relationships.txt +0 -19
  288. package/src/__tests__/testdata/unicode/cls_annotation.txt +0 -29
  289. package/src/__tests__/testdata/unicode/cls_association.txt +0 -14
  290. package/src/__tests__/testdata/unicode/cls_basic.txt +0 -15
  291. package/src/__tests__/testdata/unicode/cls_dependency.txt +0 -14
  292. package/src/__tests__/testdata/unicode/cls_inheritance.txt +0 -20
  293. package/src/__tests__/testdata/unicode/cls_methods.txt +0 -21
  294. package/src/__tests__/testdata/unicode/comments.txt +0 -23
  295. package/src/__tests__/testdata/unicode/duplicate_labels.txt +0 -19
  296. package/src/__tests__/testdata/unicode/er_attributes.txt +0 -21
  297. package/src/__tests__/testdata/unicode/er_basic.txt +0 -8
  298. package/src/__tests__/testdata/unicode/er_identifying.txt +0 -18
  299. package/src/__tests__/testdata/unicode/graph_bt_direction.txt +0 -28
  300. package/src/__tests__/testdata/unicode/preserve_order_of_definition.txt +0 -23
  301. package/src/__tests__/testdata/unicode/self_reference.txt +0 -10
  302. package/src/__tests__/testdata/unicode/self_reference_with_edge.txt +0 -10
  303. package/src/__tests__/testdata/unicode/seq_basic.txt +0 -17
  304. package/src/__tests__/testdata/unicode/seq_multiple_messages.txt +0 -25
  305. package/src/__tests__/testdata/unicode/seq_self_message.txt +0 -18
  306. package/src/__tests__/testdata/unicode/single_node.txt +0 -8
  307. package/src/__tests__/testdata/unicode/single_node_longer_name.txt +0 -8
  308. package/src/__tests__/testdata/unicode/three_nodes.txt +0 -9
  309. package/src/__tests__/testdata/unicode/three_nodes_single_line.txt +0 -8
  310. package/src/__tests__/testdata/unicode/two_layer_single_graph.txt +0 -19
  311. package/src/__tests__/testdata/unicode/two_layer_single_graph_longer_names.txt +0 -19
  312. package/src/__tests__/testdata/unicode/two_nodes_linked.txt +0 -8
  313. package/src/__tests__/testdata/unicode/two_nodes_longer_names.txt +0 -8
  314. package/src/__tests__/testdata/unicode/two_root_nodes.txt +0 -19
  315. package/src/__tests__/testdata/unicode/two_root_nodes_longer_names.txt +0 -19
  316. package/src/__tests__/testdata/unicode/two_single_root_nodes.txt +0 -19
  317. package/src/__tests__/text-metrics.test.ts +0 -473
  318. package/src/__tests__/theme-palette-contrast.test.ts +0 -84
  319. package/src/__tests__/theme.test.ts +0 -132
  320. package/src/__tests__/xychart-ascii.test.ts +0 -376
  321. package/src/__tests__/xychart-colors.test.ts +0 -149
@@ -1,1267 +0,0 @@
1
- // ============================================================================
2
- // ASCII renderer — grid-based layout
3
- //
4
- // Ported from AlexanderGrooff/mermaid-ascii cmd/graph.go + cmd/mapping_node.go.
5
- // Places nodes on a logical grid, computes column/row sizes,
6
- // converts grid coordinates to character-level drawing coordinates,
7
- // and handles subgraph bounding boxes.
8
- // ============================================================================
9
-
10
- import type {
11
- GridCoord,
12
- DrawingCoord,
13
- Direction,
14
- AsciiEdge,
15
- AsciiGraph,
16
- AsciiNode,
17
- AsciiSubgraph,
18
- } from './types.ts'
19
- import { gridKey, requireGridCoord } from './types.ts'
20
- import { setCanvasSizeToGrid, setRoleCanvasSizeToGrid } from './canvas.ts'
21
- import {
22
- determinePath,
23
- determineLabelLine,
24
- assignParallelEdgeLanes,
25
- } from './edge-routing.ts'
26
- import { analyzeEdgeBundles, processBundles } from './edge-bundling.ts'
27
- import { createPathBudget } from './pathfinder.ts'
28
- import {
29
- isBlockFree,
30
- placeBlock,
31
- cloneGrid,
32
- NODE_BLOCK_SIZE,
33
- type Grid,
34
- } from './grid-occupancy.ts'
35
- import {
36
- createEdgeCellStyles,
37
- claimPathCells,
38
- findStyleConflict,
39
- type EdgeCellStyles,
40
- } from './edge-cell-styles.ts'
41
- import { drawBox } from './draw.ts'
42
- import { getShapeDimensions } from './shapes/index.ts'
43
- import { splitLines } from './multiline-utils.ts'
44
- import { displayWidth } from './display-width.ts'
45
-
46
- // `requireGridCoord` is defined in types.ts (a pure predicate over
47
- // AsciiNode with no grid-state dependency) and re-exported here so the two
48
- // existing call sites that import it from this module (edge-routing.ts,
49
- // edge-bundling.ts) don't need to change.
50
- export { requireGridCoord }
51
-
52
- // ============================================================================
53
- // Grid coordinate → drawing coordinate conversion
54
- // ============================================================================
55
-
56
- /**
57
- * Convert a grid coordinate to a drawing (character) coordinate.
58
- * Sums column widths up to the target column, and row heights up to the target row,
59
- * then centers within the cell.
60
- */
61
- export function gridToDrawingCoord(
62
- graph: AsciiGraph,
63
- c: GridCoord,
64
- dir?: Direction,
65
- ): DrawingCoord {
66
- const target: GridCoord = dir ? { x: c.x + dir.x, y: c.y + dir.y } : c
67
-
68
- let x = 0
69
- for (let col = 0; col < target.x; col++) {
70
- x += graph.columnWidth.get(col) ?? 0
71
- }
72
-
73
- let y = 0
74
- for (let row = 0; row < target.y; row++) {
75
- y += graph.rowHeight.get(row) ?? 0
76
- }
77
-
78
- const colW = graph.columnWidth.get(target.x) ?? 0
79
- const rowH = graph.rowHeight.get(target.y) ?? 0
80
- return {
81
- x: x + Math.floor(colW / 2) + graph.offsetX,
82
- y: y + Math.floor(rowH / 2) + graph.offsetY,
83
- }
84
- }
85
-
86
- /** Convert a path of grid coords to drawing coords. */
87
- export function lineToDrawing(
88
- graph: AsciiGraph,
89
- line: GridCoord[],
90
- ): DrawingCoord[] {
91
- return line.map((c) => gridToDrawingCoord(graph, c))
92
- }
93
-
94
- // ============================================================================
95
- // Node placement on the grid
96
- // ============================================================================
97
-
98
- /**
99
- * Reserve a 3x3 block in the grid for a node.
100
- * If the requested position is occupied, recursively shift by 4 grid units
101
- * (in the perpendicular direction based on effective direction) until a free spot is found.
102
- *
103
- * @param effectiveDir - Optional direction override. If not provided, uses the node's
104
- * effective direction (subgraph direction if in a subgraph with override,
105
- * otherwise graph direction).
106
- */
107
- export function reserveSpotInGrid(
108
- graph: AsciiGraph,
109
- node: AsciiNode,
110
- requested: GridCoord,
111
- effectiveDir?: 'LR' | 'TD',
112
- ): GridCoord {
113
- // Determine direction for collision handling
114
- const dir = effectiveDir ?? getEffectiveDirection(graph, node)
115
-
116
- if (!isBlockFree(graph.grid, requested, NODE_BLOCK_SIZE)) {
117
- // Collision — shift perpendicular to main flow direction
118
- if (dir === 'LR') {
119
- return reserveSpotInGrid(
120
- graph,
121
- node,
122
- { x: requested.x, y: requested.y + 4 },
123
- dir,
124
- )
125
- } else {
126
- return reserveSpotInGrid(
127
- graph,
128
- node,
129
- { x: requested.x + 4, y: requested.y },
130
- dir,
131
- )
132
- }
133
- }
134
-
135
- placeBlock(graph.grid, requested, NODE_BLOCK_SIZE)
136
-
137
- node.gridCoord = requested
138
- return requested
139
- }
140
-
141
- // ============================================================================
142
- // Column width / row height computation
143
- // ============================================================================
144
-
145
- /**
146
- * Set column widths and row heights for a node's 3x3 grid block.
147
- * Each node occupies 3 columns (border, content, border) and 3 rows.
148
- * Uses shape-aware dimensions to properly size non-rectangular shapes.
149
- */
150
- export function setColumnWidth(graph: AsciiGraph, node: AsciiNode): void {
151
- const gc = requireGridCoord(node)
152
- const padding = graph.config.boxBorderPadding
153
-
154
- // Get shape-aware dimensions
155
- const shapeDims = getShapeDimensions(node.shape, node.displayLabel, {
156
- useAscii: graph.config.useAscii,
157
- padding,
158
- })
159
-
160
- // Use shape-provided grid dimensions
161
- const colWidths = shapeDims.gridColumns
162
- const rowHeights = shapeDims.gridRows
163
-
164
- for (let idx = 0; idx < colWidths.length; idx++) {
165
- const xCoord = gc.x + idx
166
- const current = graph.columnWidth.get(xCoord) ?? 0
167
- graph.columnWidth.set(xCoord, Math.max(current, colWidths[idx]!))
168
- }
169
-
170
- for (let idx = 0; idx < rowHeights.length; idx++) {
171
- const yCoord = gc.y + idx
172
- const current = graph.rowHeight.get(yCoord) ?? 0
173
- graph.rowHeight.set(yCoord, Math.max(current, rowHeights[idx]!))
174
- }
175
-
176
- // Padding column/row before the node (spacing between nodes)
177
- if (gc.x > 0) {
178
- const current = graph.columnWidth.get(gc.x - 1) ?? 0
179
- graph.columnWidth.set(gc.x - 1, Math.max(current, graph.config.paddingX))
180
- }
181
-
182
- if (gc.y > 0) {
183
- let basePadding = graph.config.paddingY
184
- // Extra vertical padding for nodes with incoming edges from outside their subgraph
185
- if (hasIncomingEdgeFromOutsideSubgraph(graph, node)) {
186
- const subgraphOverhead = 4
187
- basePadding += subgraphOverhead
188
- }
189
- const current = graph.rowHeight.get(gc.y - 1) ?? 0
190
- graph.rowHeight.set(gc.y - 1, Math.max(current, basePadding))
191
- }
192
- }
193
-
194
- /** Ensure grid has width/height entries for all cells along an edge path. */
195
- export function increaseGridSizeForPath(
196
- graph: AsciiGraph,
197
- path: GridCoord[],
198
- ): void {
199
- for (const c of path) {
200
- if (!graph.columnWidth.has(c.x)) {
201
- graph.columnWidth.set(c.x, Math.floor(graph.config.paddingX / 2))
202
- }
203
- if (!graph.rowHeight.has(c.y)) {
204
- graph.rowHeight.set(c.y, Math.floor(graph.config.paddingY / 2))
205
- }
206
- }
207
- }
208
-
209
- /**
210
- * Cap on re-route attempts for a single edge's cross-style conflicts.
211
- *
212
- * `determinePath`'s A* attempts respect the blocked cells added below, but
213
- * its Case-4 direct-fallback (used when both A* attempts fail outright)
214
- * draws a straight line ignoring occupancy entirely — so a pathological
215
- * layout where every route is blocked could keep "finding" the same
216
- * conflict forever. This bounds that to a handful of tries; if a genuine
217
- * conflict survives them, the edge keeps its last-routed (still
218
- * overlapping) path rather than looping — the same "graceful degradation
219
- * over a hard failure" the render-wide `PathBudget` already applies to A*
220
- * itself.
221
- */
222
- const MAX_STYLE_CONFLICT_REROUTES = 8
223
-
224
- /**
225
- * After `edge` has been routed, check whether its path crosses a cell
226
- * already claimed by a *different*-style edge (see edge-cell-styles.ts) and,
227
- * if so, re-route it around the conflicting cell(s).
228
- *
229
- * Works by temporarily adding the conflicting cell to `graph.grid` — the
230
- * same occupancy map A* already treats node cells as blocked through — so
231
- * `determinePath`'s A* search avoids it on the next attempt, then removing
232
- * that temporary block again once this edge is done (it must not
233
- * permanently block the cell for other, unrelated edges; only *style*
234
- * conflicts are meant to be avoided, not all future overlap).
235
- *
236
- * `nodeOnlyGrid` — not `graph.grid` — is what gets passed to
237
- * `findStyleConflict`'s "is this cell node-owned, and therefore not a real
238
- * conflict" check. This must be a separate, frozen-at-node-placement-time
239
- * grid: `graph.grid` gets `add`ed to right below for A*'s benefit, and if
240
- * the *conflict check* used that same live grid, a cell temporarily
241
- * blocked on attempt 1 would look node-occupied on attempt 2 — so if A*'s
242
- * direct-fallback (which ignores occupancy) routes right back through it,
243
- * the loop would wrongly see "no conflict" and stop, leaving the two
244
- * differently-styled edges still overlapping there. See
245
- * ascii-edge-cross-style-overlap.test.ts's regression test for this exact
246
- * scenario.
247
- */
248
- function rerouteAroundStyleConflicts(
249
- graph: AsciiGraph,
250
- edge: AsciiEdge,
251
- cellStyles: EdgeCellStyles,
252
- nodeOnlyGrid: Grid,
253
- ): void {
254
- const temporarilyBlocked: GridCoord[] = []
255
- try {
256
- for (let i = 0; i < MAX_STYLE_CONFLICT_REROUTES; i++) {
257
- const conflict = findStyleConflict(
258
- nodeOnlyGrid,
259
- cellStyles,
260
- edge.path,
261
- edge.style,
262
- )
263
- if (!conflict) return
264
- graph.grid.add(gridKey(conflict))
265
- temporarilyBlocked.push(conflict)
266
- determinePath(graph, edge)
267
- }
268
- } finally {
269
- for (const cell of temporarilyBlocked) graph.grid.delete(gridKey(cell))
270
- }
271
- }
272
-
273
- // ============================================================================
274
- // Subgraph helpers
275
- // ============================================================================
276
-
277
- function isNodeInAnySubgraph(graph: AsciiGraph, node: AsciiNode): boolean {
278
- return graph.subgraphs.some((sg) => sg.nodes.includes(node))
279
- }
280
-
281
- /**
282
- * Get the innermost subgraph that directly contains this node.
283
- * Returns null if node is not in any subgraph.
284
- */
285
- export function getNodeSubgraph(
286
- graph: AsciiGraph,
287
- node: AsciiNode,
288
- ): AsciiSubgraph | null {
289
- // Find the innermost (most deeply nested) subgraph containing the node
290
- let innermost: AsciiSubgraph | null = null
291
- for (const sg of graph.subgraphs) {
292
- if (sg.nodes.includes(node)) {
293
- // Check if this subgraph is deeper (more nested) than current innermost
294
- if (!innermost || isAncestorOrSelf(innermost, sg)) {
295
- innermost = sg
296
- }
297
- }
298
- }
299
- return innermost
300
- }
301
-
302
- /** Check if `candidate` is the same as or an ancestor of `target`. */
303
- function isAncestorOrSelf(
304
- candidate: AsciiSubgraph,
305
- target: AsciiSubgraph,
306
- ): boolean {
307
- let current: AsciiSubgraph | null = target
308
- while (current !== null) {
309
- if (current === candidate) return true
310
- current = current.parent
311
- }
312
- return false
313
- }
314
-
315
- /**
316
- * Get the outermost (top-level, unnested) subgraph ancestor for a node.
317
- * Returns null if the node isn't in any subgraph.
318
- *
319
- * Used to group nodes for bounding-box-disjointness purposes: sibling
320
- * subgraphs nested under different top-level subgraphs are unrelated and
321
- * must never be allowed to overlap (#90), while a subgraph's own nested
322
- * children are already folded into its box via calculateSubgraphBoundingBox.
323
- */
324
- function getTopLevelSubgraph(
325
- graph: AsciiGraph,
326
- node: AsciiNode,
327
- ): AsciiSubgraph | null {
328
- const sg = getNodeSubgraph(graph, node)
329
- if (!sg) return null
330
- let top = sg
331
- while (top.parent) top = top.parent
332
- return top
333
- }
334
-
335
- /** Recursively collect every node belonging to a subgraph, including nodes in nested subgraphs. */
336
- function collectSubgraphMembers(sg: AsciiSubgraph): AsciiNode[] {
337
- const members = [...sg.nodes]
338
- for (const child of sg.children) {
339
- members.push(...collectSubgraphMembers(child))
340
- }
341
- return members
342
- }
343
-
344
- /** Whether `to` is reachable from `from` by following outgoing edges (BFS). */
345
- function isReachableViaEdges(
346
- graph: AsciiGraph,
347
- from: AsciiNode,
348
- to: AsciiNode,
349
- ): boolean {
350
- if (from === to) return true
351
- const visited = new Set<AsciiNode>([from])
352
- const queue: AsciiNode[] = [from]
353
- while (queue.length > 0) {
354
- const current = queue.shift()!
355
- for (const child of getChildren(graph, current)) {
356
- if (child === to) return true
357
- if (!visited.has(child)) {
358
- visited.add(child)
359
- queue.push(child)
360
- }
361
- }
362
- }
363
- return false
364
- }
365
-
366
- /**
367
- * Get the effective direction for a node's layout.
368
- * Returns the subgraph's direction override if the node is in a subgraph with one,
369
- * otherwise returns the graph-level direction.
370
- */
371
- export function getEffectiveDirection(
372
- graph: AsciiGraph,
373
- node: AsciiNode,
374
- ): 'LR' | 'TD' {
375
- const sg = getNodeSubgraph(graph, node)
376
- if (sg?.direction) {
377
- return sg.direction
378
- }
379
- return graph.config.graphDirection
380
- }
381
-
382
- /**
383
- * Check if a node has an incoming edge from outside its subgraph
384
- * AND is the topmost such node in its subgraph.
385
- * Used to add extra vertical padding for subgraph borders.
386
- */
387
- function hasIncomingEdgeFromOutsideSubgraph(
388
- graph: AsciiGraph,
389
- node: AsciiNode,
390
- ): boolean {
391
- const nodeSg = getNodeSubgraph(graph, node)
392
- if (!nodeSg) return false
393
-
394
- let hasExternalEdge = false
395
- for (const edge of graph.edges) {
396
- if (edge.to === node) {
397
- const sourceSg = getNodeSubgraph(graph, edge.from)
398
- if (sourceSg !== nodeSg) {
399
- hasExternalEdge = true
400
- break
401
- }
402
- }
403
- }
404
-
405
- if (!hasExternalEdge) return false
406
-
407
- // Only return true for the topmost node with an external incoming edge
408
- const nodeY = requireGridCoord(node).y
409
- for (const otherNode of nodeSg.nodes) {
410
- if (otherNode === node || !otherNode.gridCoord) continue
411
- let otherHasExternal = false
412
- for (const edge of graph.edges) {
413
- if (edge.to === otherNode) {
414
- const sourceSg = getNodeSubgraph(graph, edge.from)
415
- if (sourceSg !== nodeSg) {
416
- otherHasExternal = true
417
- break
418
- }
419
- }
420
- }
421
- if (otherHasExternal && otherNode.gridCoord.y < nodeY) {
422
- return false
423
- }
424
- }
425
-
426
- return true
427
- }
428
-
429
- // ============================================================================
430
- // Subgraph bounding boxes
431
- // ============================================================================
432
-
433
- function calculateSubgraphBoundingBox(
434
- graph: AsciiGraph,
435
- sg: AsciiSubgraph,
436
- ): void {
437
- if (sg.nodes.length === 0) return
438
-
439
- let minX = 1_000_000
440
- let minY = 1_000_000
441
- let maxX = -1_000_000
442
- let maxY = -1_000_000
443
-
444
- // Include children's bounding boxes
445
- for (const child of sg.children) {
446
- calculateSubgraphBoundingBox(graph, child)
447
- if (child.nodes.length > 0) {
448
- minX = Math.min(minX, child.minX)
449
- minY = Math.min(minY, child.minY)
450
- maxX = Math.max(maxX, child.maxX)
451
- maxY = Math.max(maxY, child.maxY)
452
- }
453
- }
454
-
455
- // Include node positions
456
- for (const node of sg.nodes) {
457
- if (!node.drawingCoord || !node.drawing) continue
458
- const nodeMinX = node.drawingCoord.x
459
- const nodeMinY = node.drawingCoord.y
460
- const nodeMaxX = nodeMinX + node.drawing.length - 1
461
- const nodeMaxY = nodeMinY + node.drawing[0]!.length - 1
462
- minX = Math.min(minX, nodeMinX)
463
- minY = Math.min(minY, nodeMinY)
464
- maxX = Math.max(maxX, nodeMaxX)
465
- maxY = Math.max(maxY, nodeMaxY)
466
- }
467
-
468
- const subgraphPadding = 2
469
- const subgraphLabelSpace = 2
470
- sg.minX = minX - subgraphPadding
471
- sg.minY = minY - subgraphPadding - subgraphLabelSpace
472
- sg.maxX = maxX + subgraphPadding
473
- sg.maxY = maxY + subgraphPadding
474
-
475
- // Widen the box, if necessary, so the subgraph's own cluster label fits
476
- // without truncation. `drawSubgraphLabel` (draw-subgraphs.ts) writes the
477
- // label into the interior columns `1..width-1` (width = maxX - minX), so
478
- // the box needs `width >= labelWidth + 1` to avoid clipping the label
479
- // against its own right border. Widening symmetrically (splitting any
480
- // extra columns across both sides) keeps the child nodes visually
481
- // centered inside the enlarged box rather than skewing it to one side.
482
- const labelWidth = Math.max(
483
- 0,
484
- ...splitLines(sg.name).map((line) => displayWidth(line)),
485
- )
486
- const currentWidth = sg.maxX - sg.minX
487
- const requiredWidth = labelWidth + 1
488
- if (requiredWidth > currentWidth) {
489
- const extra = requiredWidth - currentWidth
490
- const extraLeft = Math.floor(extra / 2)
491
- const extraRight = extra - extraLeft
492
- sg.minX -= extraLeft
493
- sg.maxX += extraRight
494
- }
495
- }
496
-
497
- /** Ensure non-overlapping root subgraphs have minimum spacing. */
498
- function ensureSubgraphSpacing(graph: AsciiGraph): void {
499
- const minSpacing = 1
500
- const rootSubgraphs = graph.subgraphs.filter(
501
- (sg) => sg.parent === null && sg.nodes.length > 0,
502
- )
503
-
504
- for (let i = 0; i < rootSubgraphs.length; i++) {
505
- for (let j = i + 1; j < rootSubgraphs.length; j++) {
506
- const sg1 = rootSubgraphs[i]!
507
- const sg2 = rootSubgraphs[j]!
508
-
509
- // Horizontal overlap → adjust vertical
510
- if (sg1.minX < sg2.maxX && sg1.maxX > sg2.minX) {
511
- if (sg1.maxY >= sg2.minY - minSpacing && sg1.minY < sg2.minY) {
512
- sg2.minY = sg1.maxY + minSpacing + 1
513
- } else if (sg2.maxY >= sg1.minY - minSpacing && sg2.minY < sg1.minY) {
514
- sg1.minY = sg2.maxY + minSpacing + 1
515
- }
516
- }
517
- // Vertical overlap → adjust horizontal
518
- if (sg1.minY < sg2.maxY && sg1.maxY > sg2.minY) {
519
- if (sg1.maxX >= sg2.minX - minSpacing && sg1.minX < sg2.minX) {
520
- sg2.minX = sg1.maxX + minSpacing + 1
521
- } else if (sg2.maxX >= sg1.minX - minSpacing && sg2.minX < sg1.minX) {
522
- sg1.minX = sg2.maxX + minSpacing + 1
523
- }
524
- }
525
- }
526
- }
527
- }
528
-
529
- export function calculateSubgraphBoundingBoxes(graph: AsciiGraph): void {
530
- for (const sg of graph.subgraphs) {
531
- calculateSubgraphBoundingBox(graph, sg)
532
- }
533
- ensureSubgraphSpacing(graph)
534
- }
535
-
536
- /**
537
- * Offset all drawing coordinates so subgraph borders don't go negative.
538
- * If any subgraph has negative min coordinates, shift everything positive.
539
- */
540
- export function offsetDrawingForSubgraphs(graph: AsciiGraph): void {
541
- if (graph.subgraphs.length === 0) return
542
-
543
- let minX = 0
544
- let minY = 0
545
- for (const sg of graph.subgraphs) {
546
- minX = Math.min(minX, sg.minX)
547
- minY = Math.min(minY, sg.minY)
548
- }
549
-
550
- const offsetX = -minX
551
- const offsetY = -minY
552
- if (offsetX === 0 && offsetY === 0) return
553
-
554
- graph.offsetX = offsetX
555
- graph.offsetY = offsetY
556
-
557
- for (const sg of graph.subgraphs) {
558
- sg.minX += offsetX
559
- sg.minY += offsetY
560
- sg.maxX += offsetX
561
- sg.maxY += offsetY
562
- }
563
-
564
- for (const node of graph.nodes) {
565
- if (node.drawingCoord) {
566
- node.drawingCoord.x += offsetX
567
- node.drawingCoord.y += offsetY
568
- }
569
- }
570
- }
571
-
572
- /**
573
- * Group root nodes by which downstream target they feed into, preserving a
574
- * stable order: groups appear in the order their shared target was first
575
- * seen among `roots`, and a root with no children (or whose target no other
576
- * root shares) keeps its original relative position.
577
- *
578
- * Fixes fan-in root placement: without this, `createMapping` places roots
579
- * sequentially in whatever order they were discovered, so e.g. `A1, B1, A2,
580
- * B2` (all roots, A1/A2 feeding A and B1/B2 feeding B) land interleaved on
581
- * the grid instead of grouped as `A1, A2, B1, B2` — causing the two fan-in
582
- * bundles' trunk edges to share a row and visually cross.
583
- */
584
- function groupRootsByDownstreamTarget(
585
- graph: AsciiGraph,
586
- roots: AsciiNode[],
587
- ): AsciiNode[] {
588
- const primaryTargetKey = (node: AsciiNode): string | null => {
589
- const children = getChildren(graph, node)
590
- return children.length > 0 ? children[0]!.name : null
591
- }
592
-
593
- // For each root, find the index (within `roots`) of the first root that
594
- // shares its primary target — that's this root's sort anchor.
595
- const firstIndexForTarget = new Map<string, number>()
596
- const anchorIndex: number[] = roots.map((node, i) => {
597
- const key = primaryTargetKey(node)
598
- if (key === null) return i // no downstream target: anchor to self
599
- const existing = firstIndexForTarget.get(key)
600
- if (existing !== undefined) return existing
601
- firstIndexForTarget.set(key, i)
602
- return i
603
- })
604
-
605
- return roots
606
- .map((node, i) => ({ node, i }))
607
- .sort((a, b) => anchorIndex[a.i]! - anchorIndex[b.i]! || a.i - b.i)
608
- .map(({ node }) => node)
609
- }
610
-
611
- /**
612
- * A node whose every incoming path loops back through itself (e.g. `A -->
613
- * B --> C --> A`, or a lone self-loop `A --> A`) is, correctly, never a
614
- * "root" — every node in the cycle has a real incoming edge. But the grid
615
- * layout still needs at least one seed node per such component to place
616
- * anything at all; with zero roots feeding it, that component would never
617
- * get a gridCoord and later crash (setColumnWidth calls `requireGridCoord`).
618
- *
619
- * The old order-dependent detection accidentally provided this seed — the
620
- * first node the scan reached "looked like" a root simply because it
621
- * hadn't been visited as a target *yet* — which is the exact bug fixed
622
- * above. This restores just the useful part of that behavior for genuine
623
- * cycles: for each weakly-connected component not reachable from any real
624
- * root, seed it with its first-declared (graph.nodes order) node.
625
- */
626
- function addPseudoRootsForUnreachableCycles(
627
- graph: AsciiGraph,
628
- roots: AsciiNode[],
629
- ): AsciiNode[] {
630
- const reachable = new Set<string>()
631
- const floodFrom = (start: AsciiNode): void => {
632
- const queue: AsciiNode[] = [start]
633
- while (queue.length > 0) {
634
- const n = queue.shift()!
635
- if (reachable.has(n.name)) continue
636
- reachable.add(n.name)
637
- for (const child of getChildren(graph, n)) queue.push(child)
638
- }
639
- }
640
- for (const root of roots) floodFrom(root)
641
-
642
- const result = [...roots]
643
- for (const node of graph.nodes) {
644
- if (reachable.has(node.name)) continue
645
- result.push(node)
646
- floodFrom(node)
647
- }
648
- return result
649
- }
650
-
651
- /**
652
- * Find the node whose grid block originates at `coord`, if any.
653
- *
654
- * Only meaningful before edge routing starts: every reserved grid cell at
655
- * that point belongs to a placed node's block (edges haven't claimed any
656
- * cells yet), and every block's origin sits on the 4-unit lattice that
657
- * `reserveSpotInGrid` allocates from — so matching by exact origin equality
658
- * is safe; there's no partial-overlap case to worry about yet.
659
- */
660
- function findNodeAtGridOrigin(
661
- graph: AsciiGraph,
662
- coord: GridCoord,
663
- ): AsciiNode | undefined {
664
- return graph.nodes.find(
665
- (n) =>
666
- n.gridCoord !== null &&
667
- n.gridCoord.x === coord.x &&
668
- n.gridCoord.y === coord.y,
669
- )
670
- }
671
-
672
- /**
673
- * Find a free grid slot adjacent to `anchor` along `axis`, without walking
674
- * through a node that belongs to a *different* top-level subgraph than
675
- * `ownTopSg`.
676
- *
677
- * A deferred subgraph root (see the module doc above createMapping) anchors
678
- * next to an already-placed sibling and slides along the shared axis until
679
- * it finds free space. Sliding blindly — the naive approach, via
680
- * `reserveSpotInGrid`'s generic collision handling — can walk straight
681
- * through an unrelated sibling subgraph's node that already occupies the
682
- * next slot over, landing the deferred node on the *far* side of that
683
- * foreign node. That foreign node then sits between the anchor and the
684
- * deferred node, so it falls inside this subgraph's bounding box and its own
685
- * frame/title is dropped (#301).
686
- *
687
- * Tries `preferredSign` first (the direction the old blind slide always
688
- * used), then the opposite sign. In each direction, stops — without
689
- * accepting the enclosure — the moment it would have to step past a node
690
- * belonging to a different top-level subgraph, and only continues past
691
- * nodes belonging to the *same* one. Returns null if both directions are
692
- * immediately foreign-blocked, so the caller can fall back to the old
693
- * (occasionally imperfect but non-looping) blind-slide behavior.
694
- */
695
- function findSubgraphAdjacentSlot(
696
- graph: AsciiGraph,
697
- anchor: GridCoord,
698
- ownTopSg: AsciiSubgraph,
699
- axis: 'x' | 'y',
700
- preferredSign: 1 | -1,
701
- ): GridCoord | null {
702
- const other: 'x' | 'y' = axis === 'x' ? 'y' : 'x'
703
-
704
- const tryDirection = (sign: 1 | -1): GridCoord | null => {
705
- let offset = 4
706
- for (;;) {
707
- const axisVal = anchor[axis] + sign * offset
708
- if (axisVal < 0) return null
709
- const candidate: GridCoord =
710
- axis === 'x'
711
- ? { x: axisVal, y: anchor[other] }
712
- : { x: anchor[other], y: axisVal }
713
- if (isBlockFree(graph.grid, candidate, NODE_BLOCK_SIZE)) return candidate
714
- const occupant = findNodeAtGridOrigin(graph, candidate)
715
- if (!occupant || getTopLevelSubgraph(graph, occupant) !== ownTopSg) {
716
- return null // a foreign subgraph (or unexpected gap) blocks this side
717
- }
718
- offset += 4
719
- }
720
- }
721
-
722
- return (
723
- tryDirection(preferredSign) ?? tryDirection((preferredSign * -1) as 1 | -1)
724
- )
725
- }
726
-
727
- /**
728
- * Place any deferred nodes waiting on `rootNode`'s top-level subgraph
729
- * immediately adjacent to it, before returning control to the root-
730
- * placement loop — so an unrelated subgraph's root can never claim the slot
731
- * a deferred sibling needs first (#301). Removes the subgraph's entry from
732
- * `deferredByTopSg` once handled (a subgraph's deferred nodes attach to
733
- * whichever of its roots is placed *first*, not every one), and records each
734
- * placed node in `resolvedDeferred` so the later fallback pass (for deferred
735
- * nodes whose anchor turns out to be a non-root, only available after the
736
- * reachable-children traversal) skips them.
737
- */
738
- function placeDeferredSiblingsNextToRoot(
739
- graph: AsciiGraph,
740
- rootNode: AsciiNode,
741
- deferredByTopSg: Map<AsciiSubgraph, AsciiNode[]>,
742
- resolvedDeferred: Set<AsciiNode>,
743
- ): void {
744
- const topSg = getTopLevelSubgraph(graph, rootNode)
745
- if (!topSg) return
746
- const waiting = deferredByTopSg.get(topSg)
747
- if (!waiting) return
748
- deferredByTopSg.delete(topSg)
749
-
750
- const anchor = requireGridCoord(rootNode)
751
- const axis: 'x' | 'y' =
752
- getEffectiveDirection(graph, rootNode) === 'LR' ? 'y' : 'x'
753
-
754
- for (const deferred of waiting) {
755
- const nodeDir = getEffectiveDirection(graph, deferred)
756
- const slot = findSubgraphAdjacentSlot(graph, anchor, topSg, axis, 1)
757
- reserveSpotInGrid(
758
- graph,
759
- graph.nodes[deferred.index]!,
760
- slot ?? anchor,
761
- nodeDir,
762
- )
763
- resolvedDeferred.add(deferred)
764
- }
765
- }
766
-
767
- /**
768
- * Place all currently-reachable, still-unplaced children of already-placed
769
- * nodes, level by level, mutating `highestPositionPerLevel` as it goes.
770
- * Multi-pass: iterates until no more progress can be made in a full pass
771
- * (handles non-topological node order, and simply leaves anything
772
- * unreachable from an already-placed node untouched).
773
- */
774
- function placeReachableChildren(
775
- graph: AsciiGraph,
776
- highestPositionPerLevel: number[],
777
- ): void {
778
- let progressed = true
779
- while (progressed) {
780
- progressed = false
781
-
782
- // Visit already-placed nodes in cross-axis order (left-to-right for TD,
783
- // top-to-bottom for LR) rather than raw `graph.nodes` declaration
784
- // order. `highestPositionPerLevel[level]` hands out each level's next
785
- // free slot in visiting order, so a parent that's actually positioned
786
- // further along the cross axis must also be visited later — otherwise
787
- // its children claim an earlier (visually misaligned) slot than a
788
- // parent positioned before it, decoupling a child's column/row from its
789
- // own parent's. This matters once sibling placement order can diverge
790
- // from `graph.nodes` order — e.g. `compareBySiblingSubgraphOrder`
791
- // above, which places a later-declared sibling subgraph's root before
792
- // an earlier-declared one's (see issue #444).
793
- const crossAxisOf = (n: AsciiNode): number =>
794
- graph.config.graphDirection === 'LR'
795
- ? (n.gridCoord?.y ?? 0)
796
- : (n.gridCoord?.x ?? 0)
797
- const placedNodes = graph.nodes
798
- .filter((n) => n.gridCoord !== null)
799
- .sort((a, b) => crossAxisOf(a) - crossAxisOf(b))
800
-
801
- for (const node of placedNodes) {
802
- const gc = node.gridCoord
803
- if (gc === null) continue // unreachable: `placedNodes` is pre-filtered
804
-
805
- // Sort children so siblings that land in different subgraphs get
806
- // mermaid.js's reversed-declaration-order sibling placement (see
807
- // compareBySiblingSubgraphOrder) instead of raw edge-declaration
808
- // order — the sort is stable, so pairs with no subgraph-order
809
- // preference (the common case) keep their original relative order.
810
- const children = [...getChildren(graph, node)].sort((x, y) =>
811
- compareBySiblingSubgraphOrder(graph, x, y),
812
- )
813
- for (const child of children) {
814
- if (child.gridCoord !== null) continue // already placed
815
-
816
- // Determine direction for this edge (parent -> child)
817
- // Use subgraph direction only if both are in the same subgraph with override
818
- const parentSg = getNodeSubgraph(graph, node)
819
- const childSg = getNodeSubgraph(graph, child)
820
- const edgeDir =
821
- parentSg && parentSg === childSg && parentSg.direction
822
- ? parentSg.direction
823
- : graph.config.graphDirection
824
-
825
- const childLevel = edgeDir === 'LR' ? gc.x + 4 : gc.y + 4
826
-
827
- // Determine position based on direction context
828
- let highestPosition: number
829
- if (edgeDir !== graph.config.graphDirection) {
830
- // Cross-direction: use parent's perpendicular coordinate
831
- // This keeps children aligned with parent when direction changes
832
- highestPosition = edgeDir === 'LR' ? gc.y : gc.x
833
- } else {
834
- // Same direction: use level tracker
835
- highestPosition = highestPositionPerLevel[childLevel] ?? 0
836
- }
837
-
838
- const requested: GridCoord =
839
- edgeDir === 'LR'
840
- ? { x: childLevel, y: highestPosition }
841
- : { x: highestPosition, y: childLevel }
842
- reserveSpotInGrid(graph, graph.nodes[child.index]!, requested, edgeDir)
843
-
844
- // Only update level tracker for same-direction placements
845
- if (edgeDir === graph.config.graphDirection) {
846
- highestPositionPerLevel[childLevel] = highestPosition + 4
847
- }
848
- progressed = true
849
- }
850
- }
851
- }
852
- }
853
-
854
- // ============================================================================
855
- // Main layout orchestrator
856
- // ============================================================================
857
-
858
- /**
859
- * createMapping performs the full grid layout:
860
- * 1. Place root nodes on the grid
861
- * 2. Place child nodes level by level
862
- * 3. Compute column widths and row heights
863
- * 4. Run A* pathfinding for all edges
864
- * 5. Determine label placement
865
- * 6. Convert grid coords → drawing coords
866
- * 7. Generate node box drawings
867
- * 8. Calculate subgraph bounding boxes
868
- */
869
- export function createMapping(graph: AsciiGraph): void {
870
- const dir = graph.config.graphDirection
871
- // A sparse array, not a fixed-size preallocation: level indices grow with
872
- // chain depth (each level adds 4 to the coordinate), and a long enough
873
- // chain would silently read past a fixed bound. Reads default missing
874
- // levels to 0 via `?? 0` below instead.
875
- const highestPositionPerLevel: number[] = []
876
-
877
- // Identify root nodes — nodes that are never the target of any edge.
878
- //
879
- // This must be order-independent: a single forward pass over graph.nodes
880
- // (in Map-insertion / first-mention order) incorrectly treats a node as a
881
- // root whenever it hasn't been seen as an edge target *yet* at the point
882
- // it's visited. That misclassifies nodes when a `child -> parent` edge
883
- // appears in the source *after* a `parent -> grandchild` edge (e.g. `A -->
884
- // C` is declared before `A1 --> A`), since `A` looks unvisited-as-target
885
- // when the loop reaches it.
886
- //
887
- // Two-pass fix: first collect every node that appears as the target of a
888
- // non-self-loop edge (a self-loop shouldn't disqualify a node from being a
889
- // root — see edge-bundling.ts's identical self-loop skip), then anything
890
- // never targeted is a genuine root, independent of source order.
891
- const targetedNames = new Set<string>()
892
- for (const edge of graph.edges) {
893
- if (edge.from === edge.to) continue // self-loop: doesn't count as "targeted"
894
- targetedNames.add(edge.to.name)
895
- }
896
- const targetBasedRoots: AsciiNode[] = graph.nodes.filter(
897
- (node) => !targetedNames.has(node.name),
898
- )
899
-
900
- // A weakly-connected component that's entirely a cycle (e.g. `A --> B -->
901
- // C --> A`) correctly has zero target-based roots — every node in it has
902
- // a real incoming edge — but the grid layout still needs one seed node
903
- // per component to place anything at all. See
904
- // addPseudoRootsForUnreachableCycles for why and how.
905
- const initialRoots = addPseudoRootsForUnreachableCycles(
906
- graph,
907
- targetBasedRoots,
908
- )
909
-
910
- // Filter out subgraph nodes that have incoming edges from external sources.
911
- // This handles the case where subgraph is declared before external nodes
912
- // (e.g., `subgraph s; A-->B; end; X-->A` - A shouldn't be a root, X should).
913
- const rootNodes = initialRoots.filter((node) => {
914
- const nodeSg = getNodeSubgraph(graph, node)
915
- if (!nodeSg) return true // external nodes: keep as roots
916
-
917
- // Check if this subgraph node has incoming edges from outside its subgraph
918
- for (const edge of graph.edges) {
919
- if (edge.to === node) {
920
- const sourceSg = getNodeSubgraph(graph, edge.from)
921
- if (sourceSg !== nodeSg) {
922
- return false // has external incoming edge → not a root
923
- }
924
- }
925
- }
926
- return true
927
- })
928
-
929
- // Defer root nodes that belong to a subgraph which has OTHER members that
930
- // are (a) not roots themselves and (b) not even reachable from this root
931
- // via its own edges — i.e. members whose placement is driven by some
932
- // completely unrelated part of the graph. Placing such a node at the
933
- // generic root level — shared with roots of unrelated sibling subgraphs —
934
- // can scatter its own subgraph's members across disjoint regions of the
935
- // grid, making that subgraph's bounding box balloon out to enclose
936
- // unrelated sibling content (#90). Instead, anchor these nodes next to
937
- // their already-placed subgraph siblings once the normal placement pass
938
- // below has run.
939
- //
940
- // A sibling that *is* reachable from this root (e.g. a subgraph root with
941
- // its own intra-subgraph child) is left alone: the normal traversal below
942
- // already positions it correctly relative to this root, so deferring would
943
- // be both unnecessary and wrong.
944
- const rootNodeSet = new Set(rootNodes)
945
- const deferredRoots: AsciiNode[] = []
946
- const placementRoots: AsciiNode[] = []
947
- for (const node of rootNodes) {
948
- const topSg = getTopLevelSubgraph(graph, node)
949
- const hasUnrelatedNonRootSibling =
950
- topSg !== null &&
951
- collectSubgraphMembers(topSg).some(
952
- (m) =>
953
- m !== node &&
954
- !rootNodeSet.has(m) &&
955
- !isReachableViaEdges(graph, node, m),
956
- )
957
- if (hasUnrelatedNonRootSibling) {
958
- deferredRoots.push(node)
959
- } else {
960
- placementRoots.push(node)
961
- }
962
- }
963
-
964
- // Group the non-deferred root nodes by which downstream target they feed
965
- // into, so a fan-in cluster (e.g. A1, A2 -> A) is placed contiguously
966
- // instead of interleaving with roots that feed a *different* target (e.g.
967
- // B1 -> B landing between A1 and A2). Without this, unrelated fan-in
968
- // bundles can end up on the same grid row and their trunk edges visually
969
- // cross.
970
- //
971
- // Stable: each root's sort key is the position of the *first* root that
972
- // shares its primary (first) downstream target, so groups appear in the
973
- // order their target was first seen, and a root with no children (or a
974
- // target no other root shares) keeps its original relative position.
975
- const groupedRootNodes = groupRootsByDownstreamTarget(graph, placementRoots)
976
-
977
- // Deferred nodes grouped by their top-level subgraph, so the placement
978
- // loops below can attach each subgraph's deferred members to whichever of
979
- // its roots gets placed first — before any *other* subgraph's root gets a
980
- // chance to claim the adjacent slot (#301). Entries are removed as they're
981
- // resolved; `resolvedDeferred` then lets the later fallback pass skip
982
- // anything already placed this way.
983
- const deferredByTopSg = new Map<AsciiSubgraph, AsciiNode[]>()
984
- for (const node of deferredRoots) {
985
- const topSg = getTopLevelSubgraph(graph, node)!
986
- const list = deferredByTopSg.get(topSg)
987
- if (list) list.push(node)
988
- else deferredByTopSg.set(topSg, [node])
989
- }
990
- const resolvedDeferred = new Set<AsciiNode>()
991
-
992
- // In LR mode with both external and subgraph roots, separate them
993
- // so subgraph roots are placed one level deeper
994
- let hasExternalRoots = false
995
- let hasSubgraphRootsWithEdges = false
996
- for (const node of groupedRootNodes) {
997
- if (isNodeInAnySubgraph(graph, node)) {
998
- if (getChildren(graph, node).length > 0) hasSubgraphRootsWithEdges = true
999
- } else {
1000
- hasExternalRoots = true
1001
- }
1002
- }
1003
- const shouldSeparate =
1004
- dir === 'LR' && hasExternalRoots && hasSubgraphRootsWithEdges
1005
-
1006
- let externalRootNodes: AsciiNode[]
1007
- let subgraphRootNodes: AsciiNode[] = []
1008
-
1009
- if (shouldSeparate) {
1010
- externalRootNodes = groupedRootNodes.filter(
1011
- (n) => !isNodeInAnySubgraph(graph, n),
1012
- )
1013
- subgraphRootNodes = groupedRootNodes.filter((n) =>
1014
- isNodeInAnySubgraph(graph, n),
1015
- )
1016
- } else {
1017
- externalRootNodes = groupedRootNodes
1018
- }
1019
-
1020
- // Place external root nodes
1021
- for (const node of externalRootNodes) {
1022
- const requested: GridCoord =
1023
- dir === 'LR'
1024
- ? { x: 0, y: highestPositionPerLevel[0] ?? 0 }
1025
- : { x: highestPositionPerLevel[0] ?? 0, y: 0 }
1026
- reserveSpotInGrid(graph, graph.nodes[node.index]!, requested)
1027
- highestPositionPerLevel[0] = (highestPositionPerLevel[0] ?? 0) + 4
1028
- placeDeferredSiblingsNextToRoot(
1029
- graph,
1030
- node,
1031
- deferredByTopSg,
1032
- resolvedDeferred,
1033
- )
1034
- }
1035
-
1036
- // Place subgraph root nodes at level 4 (one level in from the edge)
1037
- if (shouldSeparate && subgraphRootNodes.length > 0) {
1038
- const subgraphLevel = 4
1039
- for (const node of subgraphRootNodes) {
1040
- const requested: GridCoord =
1041
- dir === 'LR'
1042
- ? { x: subgraphLevel, y: highestPositionPerLevel[subgraphLevel] ?? 0 }
1043
- : { x: highestPositionPerLevel[subgraphLevel] ?? 0, y: subgraphLevel }
1044
- reserveSpotInGrid(graph, graph.nodes[node.index]!, requested)
1045
- highestPositionPerLevel[subgraphLevel] =
1046
- (highestPositionPerLevel[subgraphLevel] ?? 0) + 4
1047
- placeDeferredSiblingsNextToRoot(
1048
- graph,
1049
- node,
1050
- deferredByTopSg,
1051
- resolvedDeferred,
1052
- )
1053
- }
1054
- }
1055
-
1056
- // Place child nodes level by level (reachable from the roots placed so far).
1057
- placeReachableChildren(graph, highestPositionPerLevel)
1058
-
1059
- // Now place whatever deferred subgraph-orphan roots weren't already
1060
- // resolved above (anchored to a root placed in this same subgraph) —
1061
- // these are the ones whose anchor is itself a non-root, only placed by
1062
- // the reachable-children traversal just above.
1063
- for (const node of deferredRoots) {
1064
- if (resolvedDeferred.has(node)) continue
1065
- const topSg = getTopLevelSubgraph(graph, node)!
1066
- const nodeDir = getEffectiveDirection(graph, node)
1067
- // Type predicate narrows `gridCoord` to non-null on every element, so the
1068
- // loop below can read `.gridCoord.x`/`.y` directly instead of trusting
1069
- // that this filter and the access stay in sync via a bare `!`.
1070
- const placedSiblings = collectSubgraphMembers(topSg).filter(
1071
- (m): m is AsciiNode & { gridCoord: GridCoord } =>
1072
- m !== node && m.gridCoord !== null,
1073
- )
1074
-
1075
- let requested: GridCoord
1076
- if (placedSiblings.length > 0) {
1077
- // Anchor to whichever placed sibling sits at the shallowest level
1078
- // (topmost row for TD, leftmost column for LR).
1079
- let anchor = placedSiblings[0]!
1080
- for (const sibling of placedSiblings) {
1081
- const isShallower =
1082
- nodeDir === 'LR'
1083
- ? sibling.gridCoord.x < anchor.gridCoord.x
1084
- : sibling.gridCoord.y < anchor.gridCoord.y
1085
- if (isShallower) anchor = sibling
1086
- }
1087
- // Slide along the shared axis to find free space next to the anchor,
1088
- // staying clear of unrelated sibling subgraphs (#301) rather than
1089
- // reserveSpotInGrid's subgraph-agnostic blind slide. Falls back to the
1090
- // anchor's own coordinate (triggering the old blind slide inside
1091
- // reserveSpotInGrid below) only when both directions are immediately
1092
- // foreign-blocked.
1093
- const axis: 'x' | 'y' = nodeDir === 'LR' ? 'y' : 'x'
1094
- requested = findSubgraphAdjacentSlot(
1095
- graph,
1096
- anchor.gridCoord,
1097
- topSg,
1098
- axis,
1099
- 1,
1100
- ) ?? { x: anchor.gridCoord.x, y: anchor.gridCoord.y }
1101
- } else {
1102
- // Defensive fallback — shouldn't normally happen, since we only defer
1103
- // a node when it has a sibling that's guaranteed to be placed by the
1104
- // traversal above. Fall back to ordinary root-level placement.
1105
- requested =
1106
- nodeDir === 'LR'
1107
- ? { x: 0, y: highestPositionPerLevel[0] ?? 0 }
1108
- : { x: highestPositionPerLevel[0] ?? 0, y: 0 }
1109
- /* v8 ignore next */
1110
- highestPositionPerLevel[0] = (highestPositionPerLevel[0] ?? 0) + 4
1111
- }
1112
-
1113
- reserveSpotInGrid(graph, graph.nodes[node.index]!, requested, nodeDir)
1114
- }
1115
-
1116
- // A deferred root may itself have children (edges) that couldn't be placed
1117
- // above since it wasn't on the grid yet — give the traversal another pass.
1118
- placeReachableChildren(graph, highestPositionPerLevel)
1119
-
1120
- // Compute column widths and row heights
1121
- for (const node of graph.nodes) {
1122
- setColumnWidth(graph, node)
1123
- }
1124
-
1125
- // Fresh render-wide A* iteration budget for this layout pass. Shared by
1126
- // every getPath call below (both bundled-edge routing and per-edge
1127
- // determinePath), so total pathfinding work for the whole render is
1128
- // hard-bounded regardless of edge count — a per-call iteration cap alone
1129
- // isn't enough for dense fan-in/out graphs with hundreds of edges, since
1130
- // each call is independently allowed to spend up to its own cap. See
1131
- // pathfinder.ts's PathBudget for details.
1132
- graph.pathBudget = createPathBudget()
1133
-
1134
- // Tag true parallel/multi-edges (same source AND target, e.g. two
1135
- // separately-labeled A-->B edges) with a lane index before bundling
1136
- // analysis runs, so determinePath below can route sibling edges past the
1137
- // first through distinct offset lanes instead of all computing the
1138
- // identical center path (see #329).
1139
- assignParallelEdgeLanes(graph)
1140
-
1141
- // Analyze edges for bundling (parallel links like A & B --> C)
1142
- // This groups edges that share sources or targets for cleaner visualization
1143
- graph.bundles = analyzeEdgeBundles(graph)
1144
-
1145
- // Route bundled edges through junction points
1146
- processBundles(graph)
1147
-
1148
- // Route non-bundled edges via A* and determine label positions.
1149
- //
1150
- // `cellStyles` tracks which line style has claimed each cell an edge's
1151
- // path has passed through so far. After routing a non-bundled edge,
1152
- // `rerouteAroundStyleConflicts` checks whether its path crosses a cell
1153
- // already claimed by a *different*-style edge — e.g. a solid edge and a
1154
- // dotted back-edge with no shared source or target, independently
1155
- // finding the same empty column — and if so, re-routes just that edge
1156
- // around the conflicting cell(s). Same-style overlap is left completely
1157
- // untouched: it's how sibling/bundled edges are meant to share a trunk
1158
- // (see edge-cell-styles.ts's module doc).
1159
- //
1160
- // `nodeOnlyGrid` snapshots `graph.grid` right here — after all node
1161
- // placement and bundle routing (which doesn't itself reserve into
1162
- // `graph.grid`; see routeBundledEdges), before any per-edge temporary
1163
- // reroute reservations start mutating the live `graph.grid` below. See
1164
- // `rerouteAroundStyleConflicts`'s doc for why the conflict check needs
1165
- // this frozen copy instead of the live grid.
1166
- const cellStyles = createEdgeCellStyles()
1167
- const nodeOnlyGrid = cloneGrid(graph.grid)
1168
- for (const edge of graph.edges) {
1169
- // Skip edges that were already routed as part of a bundle
1170
- if (edge.bundle && edge.path.length > 0) {
1171
- increaseGridSizeForPath(graph, edge.path)
1172
- claimPathCells(nodeOnlyGrid, cellStyles, edge.path, edge.style)
1173
- determineLabelLine(graph, edge)
1174
- continue
1175
- }
1176
-
1177
- determinePath(graph, edge)
1178
- rerouteAroundStyleConflicts(graph, edge, cellStyles, nodeOnlyGrid)
1179
- increaseGridSizeForPath(graph, edge.path)
1180
- claimPathCells(nodeOnlyGrid, cellStyles, edge.path, edge.style)
1181
- determineLabelLine(graph, edge)
1182
- }
1183
-
1184
- // Convert grid coords → drawing coords and generate box drawings
1185
- for (const node of graph.nodes) {
1186
- node.drawingCoord = gridToDrawingCoord(graph, requireGridCoord(node))
1187
- node.drawing = drawBox(node, graph)
1188
- }
1189
-
1190
- // Set canvas size and compute subgraph bounding boxes
1191
- setCanvasSizeToGrid(graph.canvas, graph.columnWidth, graph.rowHeight)
1192
- setRoleCanvasSizeToGrid(graph.roleCanvas, graph.columnWidth, graph.rowHeight)
1193
- calculateSubgraphBoundingBoxes(graph)
1194
- offsetDrawingForSubgraphs(graph)
1195
- }
1196
-
1197
- // ============================================================================
1198
- // Graph traversal helpers
1199
- // ============================================================================
1200
-
1201
- /** Get all edges originating from a node. */
1202
- function getEdgesFromNode(
1203
- graph: AsciiGraph,
1204
- node: AsciiNode,
1205
- ): AsciiGraph['edges'] {
1206
- return graph.edges.filter((e) => e.from.name === node.name)
1207
- }
1208
-
1209
- /**
1210
- * Outermost-to-innermost chain of subgraphs directly containing `node`
1211
- * (empty if the node isn't in any subgraph).
1212
- */
1213
- function subgraphChain(graph: AsciiGraph, node: AsciiNode): AsciiSubgraph[] {
1214
- const innermost = getNodeSubgraph(graph, node)
1215
- const chain: AsciiSubgraph[] = []
1216
- let current: AsciiSubgraph | null = innermost
1217
- while (current !== null) {
1218
- chain.unshift(current)
1219
- current = current.parent
1220
- }
1221
- return chain
1222
- }
1223
-
1224
- /**
1225
- * Order two nodes the way real mermaid.js orders the sibling subgraphs they
1226
- * (transitively) belong to, when they diverge into *different* subgraphs
1227
- * under a shared subgraph ancestor (or both at the top level) — otherwise 0
1228
- * (no preference; the caller's sort is stable, so original edge-declaration
1229
- * order is preserved).
1230
- *
1231
- * Verified against mermaid@11.17.2's bundled flowDb.getData()
1232
- * (node_modules/mermaid/dist/mermaid.min.js): it builds the layout node list
1233
- * by iterating the parsed `subGraphs` array *backwards* to emit cluster
1234
- * nodes, so sibling subgraphs end up in reversed declaration order in the
1235
- * graph the layout engine actually sees — see the matching comment in
1236
- * `../layout-engine/to-elk.ts`'s `mermaidToElk`, and issue #444. The ASCII
1237
- * grid has no compound-node concept for the layout engine to order — node
1238
- * position here is driven entirely by BFS descent from edges (see
1239
- * `placeReachableChildren`) — so this comparator recovers the same visual
1240
- * left-right order by reordering sibling children at the point they'd
1241
- * otherwise be placed in raw edge-declaration order.
1242
- */
1243
- function compareBySiblingSubgraphOrder(
1244
- graph: AsciiGraph,
1245
- a: AsciiNode,
1246
- b: AsciiNode,
1247
- ): number {
1248
- const chainA = subgraphChain(graph, a)
1249
- const chainB = subgraphChain(graph, b)
1250
- let i = 0
1251
- while (i < chainA.length && i < chainB.length && chainA[i] === chainB[i]) {
1252
- i++
1253
- }
1254
- const sgA = chainA[i]
1255
- const sgB = chainB[i]
1256
- if (!sgA || !sgB || sgA === sgB) return 0
1257
- // Reversed declaration order: later-declared sibling sorts first. Sibling
1258
- // relative declaration order is recovered from each one's position in the
1259
- // flat `graph.subgraphs` list, which preserves source order (see
1260
- // `convertSubgraph`'s pre-order-DFS push in converter.ts).
1261
- return graph.subgraphs.indexOf(sgB) - graph.subgraphs.indexOf(sgA)
1262
- }
1263
-
1264
- /** Get all direct children of a node (targets of outgoing edges). */
1265
- function getChildren(graph: AsciiGraph, node: AsciiNode): AsciiNode[] {
1266
- return getEdgesFromNode(graph, node).map((e) => e.to)
1267
- }