@md2nativedocx/core 0.6.0 → 0.8.0

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 (242) hide show
  1. package/dist/diagrams/agentflow/parser.d.ts +20 -0
  2. package/dist/diagrams/agentflow/parser.js +155 -0
  3. package/dist/diagrams/agentflow/parser.js.map +1 -0
  4. package/dist/diagrams/architecture-diagram/icons.d.ts +24 -0
  5. package/dist/diagrams/architecture-diagram/icons.js +148 -0
  6. package/dist/diagrams/architecture-diagram/icons.js.map +1 -0
  7. package/dist/diagrams/architecture-diagram/layout.d.ts +71 -0
  8. package/dist/diagrams/architecture-diagram/layout.js +388 -0
  9. package/dist/diagrams/architecture-diagram/layout.js.map +1 -0
  10. package/dist/diagrams/architecture-diagram/parser.d.ts +14 -19
  11. package/dist/diagrams/architecture-diagram/parser.js +316 -113
  12. package/dist/diagrams/architecture-diagram/parser.js.map +1 -1
  13. package/dist/diagrams/architecture-diagram/translator.d.ts +26 -36
  14. package/dist/diagrams/architecture-diagram/translator.js +234 -147
  15. package/dist/diagrams/architecture-diagram/translator.js.map +1 -1
  16. package/dist/diagrams/architecture-diagram/types.d.ts +26 -16
  17. package/dist/diagrams/architecture-diagram/types.js +4 -14
  18. package/dist/diagrams/architecture-diagram/types.js.map +1 -1
  19. package/dist/diagrams/c4/parser.d.ts +11 -19
  20. package/dist/diagrams/c4/parser.js +242 -90
  21. package/dist/diagrams/c4/parser.js.map +1 -1
  22. package/dist/diagrams/c4/translator.d.ts +23 -43
  23. package/dist/diagrams/c4/translator.js +333 -204
  24. package/dist/diagrams/c4/translator.js.map +1 -1
  25. package/dist/diagrams/c4/types.d.ts +78 -45
  26. package/dist/diagrams/c4/types.js +17 -38
  27. package/dist/diagrams/c4/types.js.map +1 -1
  28. package/dist/diagrams/class-diagram/parser.d.ts +10 -11
  29. package/dist/diagrams/class-diagram/parser.js +322 -74
  30. package/dist/diagrams/class-diagram/parser.js.map +1 -1
  31. package/dist/diagrams/class-diagram/translator.d.ts +10 -10
  32. package/dist/diagrams/class-diagram/translator.js +305 -33
  33. package/dist/diagrams/class-diagram/translator.js.map +1 -1
  34. package/dist/diagrams/class-diagram/types.d.ts +61 -4
  35. package/dist/diagrams/er-diagram/parser.d.ts +22 -19
  36. package/dist/diagrams/er-diagram/parser.js +412 -89
  37. package/dist/diagrams/er-diagram/parser.js.map +1 -1
  38. package/dist/diagrams/er-diagram/translator.d.ts +8 -0
  39. package/dist/diagrams/er-diagram/translator.js +170 -38
  40. package/dist/diagrams/er-diagram/translator.js.map +1 -1
  41. package/dist/diagrams/er-diagram/types.d.ts +32 -5
  42. package/dist/diagrams/er-diagram/types.js +2 -5
  43. package/dist/diagrams/er-diagram/types.js.map +1 -1
  44. package/dist/diagrams/flowchart-source.d.ts +106 -0
  45. package/dist/diagrams/flowchart-source.js +272 -0
  46. package/dist/diagrams/flowchart-source.js.map +1 -0
  47. package/dist/diagrams/gantt/date-utils.d.ts +55 -33
  48. package/dist/diagrams/gantt/date-utils.js +147 -58
  49. package/dist/diagrams/gantt/date-utils.js.map +1 -1
  50. package/dist/diagrams/gantt/parser.d.ts +31 -22
  51. package/dist/diagrams/gantt/parser.js +259 -141
  52. package/dist/diagrams/gantt/parser.js.map +1 -1
  53. package/dist/diagrams/gantt/time-axis.d.ts +44 -0
  54. package/dist/diagrams/gantt/time-axis.js +158 -0
  55. package/dist/diagrams/gantt/time-axis.js.map +1 -0
  56. package/dist/diagrams/gantt/translator.d.ts +8 -5
  57. package/dist/diagrams/gantt/translator.js +72 -60
  58. package/dist/diagrams/gantt/translator.js.map +1 -1
  59. package/dist/diagrams/gantt/types.d.ts +25 -4
  60. package/dist/diagrams/gantt/types.js +4 -3
  61. package/dist/diagrams/gantt/types.js.map +1 -1
  62. package/dist/diagrams/mindmap/parser.d.ts +18 -14
  63. package/dist/diagrams/mindmap/parser.js +169 -69
  64. package/dist/diagrams/mindmap/parser.js.map +1 -1
  65. package/dist/diagrams/mindmap/translator.js +90 -35
  66. package/dist/diagrams/mindmap/translator.js.map +1 -1
  67. package/dist/diagrams/mindmap/types.d.ts +18 -0
  68. package/dist/diagrams/packet/parser.js +1 -1
  69. package/dist/diagrams/packet/parser.js.map +1 -1
  70. package/dist/diagrams/pie/translator.js +5 -4
  71. package/dist/diagrams/pie/translator.js.map +1 -1
  72. package/dist/diagrams/plantuml/class-parser.d.ts +2 -1
  73. package/dist/diagrams/plantuml/class-parser.js +19 -11
  74. package/dist/diagrams/plantuml/class-parser.js.map +1 -1
  75. package/dist/diagrams/plantuml/sequence-parser.d.ts +3 -2
  76. package/dist/diagrams/plantuml/sequence-parser.js +28 -12
  77. package/dist/diagrams/plantuml/sequence-parser.js.map +1 -1
  78. package/dist/diagrams/plantuml/state-parser.d.ts +5 -3
  79. package/dist/diagrams/plantuml/state-parser.js +141 -19
  80. package/dist/diagrams/plantuml/state-parser.js.map +1 -1
  81. package/dist/diagrams/quadrant/translator.js +5 -4
  82. package/dist/diagrams/quadrant/translator.js.map +1 -1
  83. package/dist/diagrams/railroad/layout.d.ts +89 -0
  84. package/dist/diagrams/railroad/layout.js +235 -0
  85. package/dist/diagrams/railroad/layout.js.map +1 -0
  86. package/dist/diagrams/railroad/parser.d.ts +37 -0
  87. package/dist/diagrams/railroad/parser.js +605 -0
  88. package/dist/diagrams/railroad/parser.js.map +1 -0
  89. package/dist/diagrams/railroad/translator.d.ts +11 -0
  90. package/dist/diagrams/railroad/translator.js +101 -0
  91. package/dist/diagrams/railroad/translator.js.map +1 -0
  92. package/dist/diagrams/railroad/types.d.ts +61 -0
  93. package/dist/diagrams/railroad/types.js +7 -0
  94. package/dist/diagrams/railroad/types.js.map +1 -0
  95. package/dist/diagrams/requirement-diagram/parser.d.ts +26 -19
  96. package/dist/diagrams/requirement-diagram/parser.js +249 -70
  97. package/dist/diagrams/requirement-diagram/parser.js.map +1 -1
  98. package/dist/diagrams/requirement-diagram/translator.d.ts +16 -11
  99. package/dist/diagrams/requirement-diagram/translator.js +170 -50
  100. package/dist/diagrams/requirement-diagram/translator.js.map +1 -1
  101. package/dist/diagrams/requirement-diagram/types.d.ts +30 -9
  102. package/dist/diagrams/requirement-diagram/types.js +7 -5
  103. package/dist/diagrams/requirement-diagram/types.js.map +1 -1
  104. package/dist/diagrams/sequence/parser.d.ts +8 -7
  105. package/dist/diagrams/sequence/parser.js +129 -32
  106. package/dist/diagrams/sequence/parser.js.map +1 -1
  107. package/dist/diagrams/sequence/participant-glyph.d.ts +38 -0
  108. package/dist/diagrams/sequence/participant-glyph.js +97 -0
  109. package/dist/diagrams/sequence/participant-glyph.js.map +1 -0
  110. package/dist/diagrams/sequence/participant-kind.d.ts +7 -0
  111. package/dist/diagrams/sequence/participant-kind.js +19 -0
  112. package/dist/diagrams/sequence/participant-kind.js.map +1 -0
  113. package/dist/diagrams/sequence/translator.d.ts +7 -3
  114. package/dist/diagrams/sequence/translator.js +140 -28
  115. package/dist/diagrams/sequence/translator.js.map +1 -1
  116. package/dist/diagrams/sequence/types.d.ts +24 -1
  117. package/dist/diagrams/state-diagram/parser.d.ts +24 -24
  118. package/dist/diagrams/state-diagram/parser.js +259 -73
  119. package/dist/diagrams/state-diagram/parser.js.map +1 -1
  120. package/dist/diagrams/state-diagram/translator.d.ts +13 -1
  121. package/dist/diagrams/state-diagram/translator.js +554 -72
  122. package/dist/diagrams/state-diagram/translator.js.map +1 -1
  123. package/dist/diagrams/state-diagram/types.d.ts +57 -11
  124. package/dist/diagrams/state-diagram/types.js +5 -7
  125. package/dist/diagrams/state-diagram/types.js.map +1 -1
  126. package/dist/diagrams/tree-view/implicit-root.d.ts +11 -0
  127. package/dist/diagrams/tree-view/implicit-root.js +14 -0
  128. package/dist/diagrams/tree-view/implicit-root.js.map +1 -0
  129. package/dist/diagrams/tree-view/parser.d.ts +23 -8
  130. package/dist/diagrams/tree-view/parser.js +242 -98
  131. package/dist/diagrams/tree-view/parser.js.map +1 -1
  132. package/dist/diagrams/tree-view/translator.d.ts +6 -5
  133. package/dist/diagrams/tree-view/translator.js +40 -23
  134. package/dist/diagrams/tree-view/translator.js.map +1 -1
  135. package/dist/diagrams/tree-view/types.d.ts +22 -6
  136. package/dist/diagrams/tree-view/types.js +2 -2
  137. package/dist/diagrams/treemap/parser.d.ts +2 -2
  138. package/dist/diagrams/treemap/parser.js +5 -12
  139. package/dist/diagrams/treemap/parser.js.map +1 -1
  140. package/dist/diagrams/usecase/parser.d.ts +24 -0
  141. package/dist/diagrams/usecase/parser.js +232 -0
  142. package/dist/diagrams/usecase/parser.js.map +1 -0
  143. package/dist/diagrams/venn/translator.js +5 -4
  144. package/dist/diagrams/venn/translator.js.map +1 -1
  145. package/dist/diagrams/zenuml/parser.d.ts +2 -2
  146. package/dist/diagrams/zenuml/parser.js +14 -7
  147. package/dist/diagrams/zenuml/parser.js.map +1 -1
  148. package/dist/index.d.ts +7 -1
  149. package/dist/index.js +5 -1
  150. package/dist/index.js.map +1 -1
  151. package/dist/layout/collapse-subgraphs.d.ts +18 -0
  152. package/dist/layout/collapse-subgraphs.js +80 -0
  153. package/dist/layout/collapse-subgraphs.js.map +1 -0
  154. package/dist/layout/layout.d.ts +11 -0
  155. package/dist/layout/layout.js +89 -17
  156. package/dist/layout/layout.js.map +1 -1
  157. package/dist/parser/css-named-colors.d.ts +7 -0
  158. package/dist/parser/css-named-colors.js +157 -0
  159. package/dist/parser/css-named-colors.js.map +1 -0
  160. package/dist/parser/css-style.d.ts +39 -0
  161. package/dist/parser/css-style.js +88 -0
  162. package/dist/parser/css-style.js.map +1 -0
  163. package/dist/parser/diagram-type.d.ts +12 -1
  164. package/dist/parser/diagram-type.js +4 -0
  165. package/dist/parser/diagram-type.js.map +1 -1
  166. package/dist/parser/entities.d.ts +5 -0
  167. package/dist/parser/entities.js +52 -0
  168. package/dist/parser/entities.js.map +1 -0
  169. package/dist/parser/frontmatter.d.ts +36 -0
  170. package/dist/parser/frontmatter.js +66 -0
  171. package/dist/parser/frontmatter.js.map +1 -0
  172. package/dist/parser/interactive.d.ts +13 -0
  173. package/dist/parser/interactive.js +17 -0
  174. package/dist/parser/interactive.js.map +1 -0
  175. package/dist/parser/label.d.ts +37 -0
  176. package/dist/parser/label.js +73 -0
  177. package/dist/parser/label.js.map +1 -0
  178. package/dist/parser/normalize-statements.d.ts +8 -0
  179. package/dist/parser/normalize-statements.js +17 -2
  180. package/dist/parser/normalize-statements.js.map +1 -1
  181. package/dist/parser/parser.d.ts +2 -1
  182. package/dist/parser/parser.js +345 -324
  183. package/dist/parser/parser.js.map +1 -1
  184. package/dist/render-diagram-odf.d.ts +2 -1
  185. package/dist/render-diagram-odf.js +39 -8
  186. package/dist/render-diagram-odf.js.map +1 -1
  187. package/dist/render-diagram.d.ts +11 -3
  188. package/dist/render-diagram.js +66 -23
  189. package/dist/render-diagram.js.map +1 -1
  190. package/dist/smartart/chain.js +1 -1
  191. package/dist/smartart/chain.js.map +1 -1
  192. package/dist/smartart/cycle.js +1 -1
  193. package/dist/smartart/cycle.js.map +1 -1
  194. package/dist/smartart/drawing.js +2 -10
  195. package/dist/smartart/drawing.js.map +1 -1
  196. package/dist/smartart/embed.d.ts +4 -3
  197. package/dist/smartart/embed.js +5 -4
  198. package/dist/smartart/embed.js.map +1 -1
  199. package/dist/smartart/from-graph.d.ts +13 -3
  200. package/dist/smartart/from-graph.js +39 -7
  201. package/dist/smartart/from-graph.js.map +1 -1
  202. package/dist/smartart/from-tree.d.ts +9 -5
  203. package/dist/smartart/from-tree.js +23 -11
  204. package/dist/smartart/from-tree.js.map +1 -1
  205. package/dist/smartart/text.d.ts +18 -4
  206. package/dist/smartart/text.js +32 -8
  207. package/dist/smartart/text.js.map +1 -1
  208. package/dist/smartart/tree-deep.js +1 -1
  209. package/dist/smartart/tree-deep.js.map +1 -1
  210. package/dist/smartart/tree.js +2 -2
  211. package/dist/smartart/tree.js.map +1 -1
  212. package/dist/translator/actor-figure.d.ts +45 -0
  213. package/dist/translator/actor-figure.js +46 -0
  214. package/dist/translator/actor-figure.js.map +1 -0
  215. package/dist/translator/boxes.d.ts +12 -1
  216. package/dist/translator/boxes.js +11 -6
  217. package/dist/translator/boxes.js.map +1 -1
  218. package/dist/translator/canvas.d.ts +28 -1
  219. package/dist/translator/canvas.js +83 -16
  220. package/dist/translator/canvas.js.map +1 -1
  221. package/dist/translator/custom-geometry.d.ts +28 -0
  222. package/dist/translator/custom-geometry.js +59 -0
  223. package/dist/translator/custom-geometry.js.map +1 -0
  224. package/dist/translator/elbow-connector.d.ts +52 -0
  225. package/dist/translator/elbow-connector.js +110 -0
  226. package/dist/translator/elbow-connector.js.map +1 -0
  227. package/dist/translator/graph-shapes.d.ts +40 -4
  228. package/dist/translator/graph-shapes.js +62 -10
  229. package/dist/translator/graph-shapes.js.map +1 -1
  230. package/dist/translator/label-runs.d.ts +14 -0
  231. package/dist/translator/label-runs.js +36 -0
  232. package/dist/translator/label-runs.js.map +1 -0
  233. package/dist/translator/odf-translator.js +56 -24
  234. package/dist/translator/odf-translator.js.map +1 -1
  235. package/dist/translator/ooxml-translator.d.ts +17 -11
  236. package/dist/translator/ooxml-translator.js +159 -146
  237. package/dist/translator/ooxml-translator.js.map +1 -1
  238. package/dist/translator/text-color.d.ts +9 -0
  239. package/dist/translator/text-color.js +17 -0
  240. package/dist/translator/text-color.js.map +1 -0
  241. package/dist/types.d.ts +27 -4
  242. package/package.json +1 -1
@@ -13,14 +13,29 @@
13
13
  * Pseudo-state shapes follow standard UML state-machine notation: a filled
14
14
  * circle for `start`, a filled circle inside a ring for `end`, a diamond for
15
15
  * `choice`, and a thin filled bar for `fork`/`join` (oriented perpendicular
16
- * to the diagram's flow direction — a horizontal bar for `TD`/`BT`, a
16
+ * to its block's flow direction — a horizontal bar for `TD`/`BT`, a
17
17
  * vertical one for `LR`/`RL`).
18
+ *
19
+ * Composite states are laid out from the inside out, one Dagre graph per block: a composite's content is
20
+ * laid out alone, in the composite's own direction (Mermaid's default, top to bottom, when it declares
21
+ * none), and the composite then enters its parent's graph as one box of that size. Mermaid lays out a
22
+ * composite the same way when no transition crosses its border. Laying out each block alone, rather than
23
+ * one compound Dagre graph, keeps clear of Dagre's failures on clusters holding cycles (see `layout.ts`),
24
+ * which state machines are full of, and makes a transition to a composite (`A --> Composite`) an ordinary
25
+ * edge. A transition that does cross a border (`Outside --> Inner`) is laid out as a link between the
26
+ * boxes holding its ends at the level where they meet, and drawn straight to the inner state.
27
+ *
28
+ * Concurrent regions (`--`) are laid out one by one too, then placed side by side across the composite's
29
+ * flow (in a row for a top-to-bottom composite, in a column for a left-to-right one), dashed lines between.
18
30
  */
19
31
  import dagre from 'dagre';
20
- import { layoutWithinLimits, nodeKey } from '../../layout/graph-limits.js';
32
+ import { assertWithinLimits, layoutWithinLimits, nodeKey } from '../../layout/graph-limits.js';
33
+ import { boxShape } from '../../translator/boxes.js';
34
+ import { validateHexColor } from '../../translator/xml-escape.js';
35
+ import { textColorFor } from '../../translator/text-color.js';
21
36
  import { estimateTextWidth } from '../../layout/layout.js';
22
37
  import { createIdAllocator, scaledExtent, scaledFontSizeHalfPt, scaledLineWidthEmu, wrapDrawingCanvas, } from '../../translator/canvas.js';
23
- import { connector, diamond, edgePoint, ellipse, rect, scalePt, textBoxLines } from '../../translator/graph-shapes.js';
38
+ import { connector, diamond, edgePoint, ellipse, parallelEdgeOffset, perpendicularUnit, rect, scalePt, shiftPoint, textBoxLines } from '../../translator/graph-shapes.js';
24
39
  const LINE_COLOR = '2F5496';
25
40
  const FILL = 'D9E2F3';
26
41
  const LABEL_FONT_PX = 11;
@@ -33,6 +48,25 @@ const DESC_SIZE_HALFPT = 16;
33
48
  const DESC_LINE_H = 15;
34
49
  const DESC_PAD = 6;
35
50
  const PAD_X = 12;
51
+ /** Composite state: title band height, padding around its content, inset of the white content area. */
52
+ const COMPOSITE_TITLE_H = 28;
53
+ const COMPOSITE_PAD = 14;
54
+ const COMPOSITE_INSET = 4;
55
+ /** A composite's corner radius, fixed: Word's default grows with the box and uncovers the content area's corners. */
56
+ const COMPOSITE_RADIUS = 8;
57
+ /** Gap between two concurrent regions, the dashed divider in its middle. */
58
+ const REGION_GAP = 24;
59
+ /** Note: the class diagram's look (Mermaid's default note colours, folded corner, left-aligned lines). */
60
+ const NOTE_FILL = 'FFF5AD';
61
+ const NOTE_LINE = 'AAAA33';
62
+ const NOTE_FONT_PX = 11;
63
+ const NOTE_LINE_H = 18;
64
+ const NOTE_PAD = 10;
65
+ /** Gap between a state and its notes, and between two notes on the same side. */
66
+ const NOTE_GAP = 16;
67
+ const NOTE_STACK_GAP = 8;
68
+ /** Gap between two transitions joining the same pair of states (`A --> B`, `B --> A`). */
69
+ const PARALLEL_GAP = 14;
36
70
  const START_END_SIZE = 18;
37
71
  const END_OUTER_SIZE = 26;
38
72
  const CHOICE_SIZE = 34;
@@ -64,6 +98,20 @@ function sizeForNode(node, direction) {
64
98
  }
65
99
  }
66
100
  }
101
+ /**
102
+ * A state's colours and emphasis: its `style` / `classDef` values, validated before they reach the XML
103
+ * (AGENTS.md rule 2), else the default look. Text is the `color:` given, else black or white to suit the fill.
104
+ */
105
+ function stateLook(node) {
106
+ const fill = validateHexColor(node.fill, FILL);
107
+ return {
108
+ fill,
109
+ line: validateHexColor(node.stroke, LINE_COLOR),
110
+ text: validateHexColor(node.textColor, textColorFor(fill)),
111
+ ...(node.bold !== undefined ? { bold: node.bold } : {}),
112
+ ...(node.italic !== undefined ? { italic: node.italic } : {}),
113
+ };
114
+ }
67
115
  function nodeShapes(nextId, node, size, x, y, s) {
68
116
  const bx = scalePt(x, s);
69
117
  const by = scalePt(y, s);
@@ -79,25 +127,40 @@ function nodeShapes(nextId, node, size, x, y, s) {
79
127
  ellipse(nextId(), bx + innerPad, by + innerPad, w - 2 * innerPad, h - 2 * innerPad, '000000'),
80
128
  ];
81
129
  }
82
- case 'choice':
83
- return [diamond(nextId(), bx, by, w, h, FILL, LINE_COLOR)];
130
+ case 'choice': {
131
+ const look = stateLook(node);
132
+ return [diamond(nextId(), bx, by, w, h, look.fill, look.line)];
133
+ }
84
134
  case 'fork':
85
135
  case 'join':
86
136
  return [rect(nextId(), bx, by, w, h, '000000', undefined, node.id)];
87
137
  default: {
88
138
  const lines = node.description ?? [];
139
+ const look = stateLook(node);
89
140
  if (lines.length === 0) {
90
141
  return [
91
- rect(nextId(), bx, by, w, h, FILL, LINE_COLOR, node.label, true),
92
- textBoxLines(nextId(), bx, by, w, h, [node.label], scaledFontSizeHalfPt(LABEL_SIZE_HALFPT, s), { align: 'ctr' }),
142
+ rect(nextId(), bx, by, w, h, look.fill, look.line, node.label, true),
143
+ textBoxLines(nextId(), bx, by, w, h, [node.label], scaledFontSizeHalfPt(LABEL_SIZE_HALFPT, s), {
144
+ align: 'ctr',
145
+ color: look.text,
146
+ bold: look.bold ?? false,
147
+ italic: look.italic ?? false,
148
+ }),
93
149
  ];
94
150
  }
95
- // Label in the top band, description lines below it, inside the same rounded box.
151
+ // Label in the top band (bold unless a style says otherwise), description lines below it, in the same box.
96
152
  const titleH = scalePt(NORMAL_H, s);
97
153
  return [
98
- rect(nextId(), bx, by, w, h, FILL, LINE_COLOR, node.label, true),
99
- textBoxLines(nextId(), bx, by, w, titleH, [node.label], scaledFontSizeHalfPt(LABEL_SIZE_HALFPT, s), { align: 'ctr', bold: true }),
100
- textBoxLines(nextId(), bx + scalePt(PAD_X / 2, s), by + titleH, w - scalePt(PAD_X, s), h - titleH, lines, scaledFontSizeHalfPt(DESC_SIZE_HALFPT, s)),
154
+ rect(nextId(), bx, by, w, h, look.fill, look.line, node.label, true),
155
+ textBoxLines(nextId(), bx, by, w, titleH, [node.label], scaledFontSizeHalfPt(LABEL_SIZE_HALFPT, s), {
156
+ align: 'ctr',
157
+ color: look.text,
158
+ bold: look.bold ?? true,
159
+ italic: look.italic ?? false,
160
+ }),
161
+ textBoxLines(nextId(), bx + scalePt(PAD_X / 2, s), by + titleH, w - scalePt(PAD_X, s), h - titleH, lines, scaledFontSizeHalfPt(DESC_SIZE_HALFPT, s), {
162
+ color: look.text,
163
+ }),
101
164
  ];
102
165
  }
103
166
  }
@@ -126,6 +189,385 @@ function selfLoop(nextId, cx, cy, size, label, s) {
126
189
  * arrowhead at the `to` end — unlike `classDiagram`'s 8 relationship types,
127
190
  * `stateDiagram` has no per-type marker/dash variation to encode. */
128
191
  const MARKER_SIZE = 'sm';
192
+ function centre(f) {
193
+ return { x: f.x + f.width / 2, y: f.y + f.height / 2 };
194
+ }
195
+ function offsetFrame(f, dx, dy) {
196
+ return { x: f.x + dx, y: f.y + dy, width: f.width, height: f.height };
197
+ }
198
+ /** Copy `inner`'s frames into `outer`, shifted by (`dx`, `dy`). */
199
+ function mergeInto(outer, inner, dx, dy) {
200
+ for (const [id, f] of inner.frames)
201
+ outer.frames.set(id, offsetFrame(f, dx, dy));
202
+ for (const d of inner.dividers)
203
+ outer.dividers.push({ x1: d.x1 + dx, y1: d.y1 + dy, x2: d.x2 + dx, y2: d.y2 + dy });
204
+ for (const [i, p] of inner.labels)
205
+ outer.labels.set(i, { x: p.x + dx, y: p.y + dy });
206
+ for (const [i, points] of inner.routes)
207
+ outer.routes.set(i, points.map((p) => ({ x: p.x + dx, y: p.y + dy })));
208
+ for (const [i, f] of inner.notes)
209
+ outer.notes.set(i, offsetFrame(f, dx, dy));
210
+ }
211
+ function emptyLayout() {
212
+ return { width: 0, height: 0, frames: new Map(), dividers: [], labels: new Map(), routes: new Map(), notes: new Map() };
213
+ }
214
+ /** The diagram's nesting: what each block holds. The key of the diagram itself is `undefined`. */
215
+ class Nesting {
216
+ children = new Map();
217
+ regions = new Map();
218
+ parentOf = new Map();
219
+ constructor(chart) {
220
+ const regionIds = new Set((chart.regions ?? []).map((r) => r.id));
221
+ const stateIds = new Set(chart.states.map((s) => s.id));
222
+ for (const node of chart.states) {
223
+ // A parent that names nothing drawn (hand-built AST) puts the state at the top level.
224
+ const parent = node.parent !== undefined && (stateIds.has(node.parent) || regionIds.has(node.parent)) && node.parent !== node.id ? node.parent : undefined;
225
+ this.parentOf.set(node.id, parent);
226
+ const list = this.children.get(parent) ?? [];
227
+ list.push(node);
228
+ this.children.set(parent, list);
229
+ }
230
+ for (const region of chart.regions ?? []) {
231
+ // An empty region has nothing to draw; a region of a state that does not exist is dropped.
232
+ if (!this.children.has(region.id) || !stateIds.has(region.parent))
233
+ continue;
234
+ this.parentOf.set(region.id, region.parent);
235
+ const list = this.regions.get(region.parent) ?? [];
236
+ list.push(region);
237
+ this.regions.set(region.parent, list);
238
+ }
239
+ // A cycle of parents (only a hand-built AST can have one) would recurse for ever: cut it at the top level.
240
+ for (const node of chart.states) {
241
+ const seen = new Set();
242
+ for (let at = node.id; at !== undefined; at = this.parentOf.get(at)) {
243
+ if (seen.has(at)) {
244
+ this.detach(node.id);
245
+ break;
246
+ }
247
+ seen.add(at);
248
+ }
249
+ }
250
+ }
251
+ detach(id) {
252
+ const parent = this.parentOf.get(id);
253
+ const list = this.children.get(parent) ?? [];
254
+ const node = list.find((n) => n.id === id);
255
+ this.children.set(parent, list.filter((n) => n.id !== id));
256
+ this.parentOf.set(id, undefined);
257
+ if (node)
258
+ this.children.set(undefined, [...(this.children.get(undefined) ?? []), node]);
259
+ }
260
+ isComposite(id) {
261
+ return (this.children.get(id)?.length ?? 0) > 0 || this.regions.has(id);
262
+ }
263
+ /** The composite states and regions that hold `id`, at any depth. */
264
+ ancestorsOf(id) {
265
+ const out = [];
266
+ for (let at = this.parentOf.get(id); at !== undefined && !out.includes(at); at = this.parentOf.get(at))
267
+ out.push(at);
268
+ return out;
269
+ }
270
+ /** The member of block `block` that holds `id` (`id` itself when it is one), or `undefined` if none does. */
271
+ memberOf(id, block) {
272
+ for (let at = id; at !== undefined; at = this.parentOf.get(at)) {
273
+ if (this.parentOf.get(at) === block && this.parentOf.has(at))
274
+ return at;
275
+ }
276
+ return undefined;
277
+ }
278
+ }
279
+ /** Room a self-transition's loop and label take on the right of its state. */
280
+ function selfLoopRooms(chart) {
281
+ const rooms = new Map();
282
+ for (const t of chart.transitions) {
283
+ if (t.from !== t.to)
284
+ continue;
285
+ const room = SELF_LOOP_W + (t.label ? estimateTextWidth(t.label, 8) + 8 : 0);
286
+ rooms.set(t.from, Math.max(rooms.get(t.from) ?? 0, room));
287
+ }
288
+ return rooms;
289
+ }
290
+ /** A note's box: its longest line, its line count, padding, and the folded corner's room. */
291
+ function noteSize(note) {
292
+ const widest = Math.max(0, ...note.lines.map((line) => estimateTextWidth(line, NOTE_FONT_PX)));
293
+ return { width: Math.max(60, widest + 2 * NOTE_PAD + 12), height: Math.max(1, note.lines.length) * NOTE_LINE_H + 2 * NOTE_PAD };
294
+ }
295
+ function memberBox(size, loopRoom, notes, direction) {
296
+ const vertical = direction === 'TD' || direction === 'BT';
297
+ const bySide = (side) => notes.filter(({ note }) => note.side === side).map(({ index, note }) => ({ index, size: noteSize(note) }));
298
+ const stackH = (list) => list.reduce((h, n) => h + n.size.height, 0) + Math.max(0, list.length - 1) * NOTE_STACK_GAP;
299
+ // Everything placed around the state, its top-left corner at (0, 0); the box is then fitted around it all.
300
+ const placed = [];
301
+ const cx = size.width / 2;
302
+ const cy = size.height / 2;
303
+ const stack = (list, x, top) => {
304
+ let y = top;
305
+ for (const n of list) {
306
+ placed.push({ index: n.index, frame: { x: x(n.size.width), y, width: n.size.width, height: n.size.height } });
307
+ y += n.size.height + NOTE_STACK_GAP;
308
+ }
309
+ };
310
+ const left = bySide('left');
311
+ const right = bySide('right');
312
+ const top = bySide('top');
313
+ const bottom = bySide('bottom');
314
+ // Left and right: centred on the state, or beneath its axis in a left-to-right block.
315
+ const sideTop = (list) => (vertical ? cy - stackH(list) / 2 : cy + NOTE_STACK_GAP);
316
+ stack(left, (w) => -NOTE_GAP - w, sideTop(left));
317
+ stack(right, () => size.width + loopRoom + NOTE_GAP, sideTop(right));
318
+ // Above and below: centred on the state, or right of its axis in a top-to-bottom block.
319
+ const across = (w) => (vertical ? cx + NOTE_STACK_GAP : cx - w / 2);
320
+ stack(top, across, -NOTE_GAP - stackH(top));
321
+ stack(bottom, across, size.height + NOTE_GAP);
322
+ let minX = 0;
323
+ let minY = 0;
324
+ let maxX = size.width + loopRoom;
325
+ let maxY = size.height;
326
+ for (const { frame: f } of placed) {
327
+ minX = Math.min(minX, f.x);
328
+ minY = Math.min(minY, f.y);
329
+ maxX = Math.max(maxX, f.x + f.width);
330
+ maxY = Math.max(maxY, f.y + f.height);
331
+ }
332
+ return {
333
+ width: maxX - minX,
334
+ height: maxY - minY,
335
+ state: { x: -minX, y: -minY },
336
+ notes: placed.map(({ index, frame }) => ({ index, frame: offsetFrame(frame, -minX, -minY) })),
337
+ };
338
+ }
339
+ /** Lays the diagram out block by block, from the inside out (see the module doc comment). */
340
+ class StateLayout {
341
+ chart;
342
+ nesting;
343
+ options;
344
+ loopRooms;
345
+ notesOf = new Map();
346
+ constructor(chart, nesting, options) {
347
+ this.chart = chart;
348
+ this.nesting = nesting;
349
+ this.options = options;
350
+ this.loopRooms = selfLoopRooms(chart);
351
+ (chart.notes ?? []).forEach((note, index) => {
352
+ const list = this.notesOf.get(note.for) ?? [];
353
+ list.push({ index, note });
354
+ this.notesOf.set(note.for, list);
355
+ });
356
+ }
357
+ /** The members of `block` laid out in one Dagre graph, in `direction`. */
358
+ layoutBlock(block, direction) {
359
+ const out = emptyLayout();
360
+ const members = this.nesting.children.get(block) ?? [];
361
+ if (members.length === 0)
362
+ return out;
363
+ // Each member's own box: a composite's from its laid-out content, any other state's from its text.
364
+ const inner = new Map();
365
+ const sizes = new Map();
366
+ for (const node of members) {
367
+ if (this.nesting.isComposite(node.id)) {
368
+ const content = this.layoutComposite(node);
369
+ inner.set(node.id, content);
370
+ sizes.set(node.id, { width: content.width, height: content.height });
371
+ }
372
+ else {
373
+ sizes.set(node.id, sizeForNode(node, direction));
374
+ }
375
+ }
376
+ const boxes = new Map();
377
+ for (const node of members)
378
+ boxes.set(node.id, memberBox(sizes.get(node.id), this.loopRooms.get(node.id) ?? 0, this.notesOf.get(node.id) ?? [], direction));
379
+ const g = new dagre.graphlib.Graph({ multigraph: true });
380
+ g.setGraph({ rankdir: RANKDIR[direction], nodesep: 40, ranksep: 60, marginx: 0, marginy: 0 });
381
+ g.setDefaultEdgeLabel(() => ({}));
382
+ for (const node of members) {
383
+ const box = boxes.get(node.id);
384
+ g.setNode(nodeKey(node.id), { width: box.width, height: box.height });
385
+ }
386
+ // A transition joins, at this level, the two members holding its ends; one inside a single member is laid
387
+ // out with that member's content. A label tells Dagre the room it takes, as the class diagram does.
388
+ this.chart.transitions.forEach((t, i) => {
389
+ const a = this.nesting.memberOf(t.from, block);
390
+ const b = this.nesting.memberOf(t.to, block);
391
+ if (a === undefined || b === undefined || a === b)
392
+ return;
393
+ const room = t.label ? { width: estimateTextWidth(t.label, 8) + 12, height: 20, labelpos: 'c' } : {};
394
+ g.setEdge(nodeKey(a), nodeKey(b), room, String(i));
395
+ });
396
+ layoutWithinLimits(g, this.options);
397
+ for (const node of members) {
398
+ const n = g.node(nodeKey(node.id));
399
+ const size = sizes.get(node.id);
400
+ const box = boxes.get(node.id);
401
+ const left = n.x - box.width / 2;
402
+ const top = n.y - box.height / 2;
403
+ const frame = { x: left + box.state.x, y: top + box.state.y, width: size.width, height: size.height };
404
+ out.frames.set(node.id, frame);
405
+ for (const { index, frame: f } of box.notes)
406
+ out.notes.set(index, offsetFrame(f, left, top));
407
+ const content = inner.get(node.id);
408
+ if (content)
409
+ mergeInto(out, content, frame.x, frame.y);
410
+ }
411
+ // Where Dagre put each label: a spot it kept clear of every box, beside the transition's route.
412
+ for (const e of g.edges()) {
413
+ const label = g.edge(e);
414
+ if (label.width !== undefined && label.x !== undefined && label.y !== undefined)
415
+ out.labels.set(Number(e.name), { x: label.x, y: label.y });
416
+ if (label.points && label.points.length >= 2)
417
+ out.routes.set(Number(e.name), label.points);
418
+ }
419
+ const graph = g.graph();
420
+ out.width = graph.width ?? 0;
421
+ out.height = graph.height ?? 0;
422
+ return out;
423
+ }
424
+ /** A composite state's box: title band, then its content (its states, or its regions side by side). */
425
+ layoutComposite(node) {
426
+ // Mermaid lays a composite's content out top to bottom unless the composite says otherwise.
427
+ const direction = node.direction ?? 'TD';
428
+ const regions = this.nesting.regions.get(node.id);
429
+ const content = regions ? this.layoutRegions(regions, direction) : this.layoutBlock(node.id, direction);
430
+ const titleWidth = estimateTextWidth(node.label, LABEL_FONT_PX) + 2 * PAD_X;
431
+ const width = Math.max(content.width + 2 * COMPOSITE_PAD, titleWidth, 70);
432
+ const height = COMPOSITE_TITLE_H + content.height + 2 * COMPOSITE_PAD;
433
+ const out = emptyLayout();
434
+ mergeInto(out, content, (width - content.width) / 2, COMPOSITE_TITLE_H + COMPOSITE_PAD);
435
+ out.width = width;
436
+ out.height = height;
437
+ return out;
438
+ }
439
+ /** Regions laid out one by one, then side by side across the flow, a divider in each gap. */
440
+ layoutRegions(regions, direction) {
441
+ const laid = regions.map((r) => ({ layout: this.layoutBlock(r.id, direction) }));
442
+ const inRow = direction === 'TD' || direction === 'BT';
443
+ const across = Math.max(...laid.map(({ layout }) => (inRow ? layout.height : layout.width)));
444
+ const out = emptyLayout();
445
+ let at = 0;
446
+ laid.forEach(({ layout }, i) => {
447
+ if (i > 0) {
448
+ const mid = at - REGION_GAP / 2;
449
+ out.dividers.push(inRow ? { x1: mid, y1: 0, x2: mid, y2: across } : { x1: 0, y1: mid, x2: across, y2: mid });
450
+ }
451
+ // Centred in its slot across the row (or column), as wide (or tall) as the widest region.
452
+ const dx = inRow ? at : (across - layout.width) / 2;
453
+ const dy = inRow ? (across - layout.height) / 2 : at;
454
+ mergeInto(out, layout, dx, dy);
455
+ at += (inRow ? layout.width : layout.height) + REGION_GAP;
456
+ });
457
+ const along = at - REGION_GAP;
458
+ out.width = inRow ? along : across;
459
+ out.height = inRow ? across : along;
460
+ return out;
461
+ }
462
+ }
463
+ /** Height of a transition label's text box. */
464
+ const LABEL_H = 20;
465
+ /** Gap between a label and the line it names. */
466
+ const LABEL_GAP = 4;
467
+ /**
468
+ * Where a transition label goes (top-left corner, alignment), from the centre Dagre kept for it. Dagre keeps
469
+ * that room on its own route, which the straight line drawn here does not follow: left there, a label floats
470
+ * away from its line or sits across it. So the spot is projected onto the drawn line (kept off its ends) and
471
+ * the label set against the line at that point, on the side Dagre chose, just far enough that its box does
472
+ * not touch the line: the box's half-extent along the line's normal, plus a gap. A line spread from a twin
473
+ * (`A --> B`, `B --> A`) takes its label to the side away from the twin, `away` (the perpendicular offset it
474
+ * was drawn with), whatever Dagre chose.
475
+ */
476
+ function labelBeside(kept, p1, p2, width, away) {
477
+ const lx = p2.x - p1.x;
478
+ const ly = p2.y - p1.y;
479
+ const length = Math.hypot(lx, ly);
480
+ if (length === 0)
481
+ return { x: kept.x - width / 2, y: kept.y - LABEL_H / 2, align: 'ctr' };
482
+ // Unit normal, turned to the right or, on a horizontal line, upwards: the default side.
483
+ let nx = -ly / length;
484
+ let ny = lx / length;
485
+ if (nx < -1e-9 || (Math.abs(nx) <= 1e-9 && ny > 0))
486
+ [nx, ny] = [-nx, -ny];
487
+ const t = Math.min(0.8, Math.max(0.2, ((kept.x - p1.x) * lx + (kept.y - p1.y) * ly) / (length * length)));
488
+ const q = { x: p1.x + t * lx, y: p1.y + t * ly };
489
+ const twin = away.x * nx + away.y * ny;
490
+ const chosen = (kept.x - q.x) * nx + (kept.y - q.y) * ny;
491
+ const side = Math.abs(twin) > 1 ? Math.sign(twin) : Math.abs(chosen) > 1 ? Math.sign(chosen) : 1;
492
+ const clearance = (width / 2) * Math.abs(nx) + (LABEL_H / 2) * Math.abs(ny) + LABEL_GAP;
493
+ const cx = q.x + side * nx * clearance;
494
+ const cy = q.y + side * ny * clearance;
495
+ // Right of a near-vertical line, the text starts at the line; elsewhere it is centred in a box sized to it.
496
+ return { x: cx - width / 2, y: cy - LABEL_H / 2, align: side * nx > 0.9 ? 'l' : 'ctr' };
497
+ }
498
+ /**
499
+ * Whether the segment `a`-`b` passes through the inside of `f` (shrunk by a pixel, so a line that only grazes
500
+ * a box does not count). Liang-Barsky clipping.
501
+ */
502
+ function segmentCrosses(a, b, f) {
503
+ const x0 = f.x + 1;
504
+ const x1 = f.x + f.width - 1;
505
+ const y0 = f.y + 1;
506
+ const y1 = f.y + f.height - 1;
507
+ if (x1 <= x0 || y1 <= y0)
508
+ return false;
509
+ let t0 = 0;
510
+ let t1 = 1;
511
+ const clip = (p, q) => {
512
+ if (p === 0)
513
+ return q >= 0;
514
+ const r = q / p;
515
+ if (p < 0) {
516
+ if (r > t1)
517
+ return false;
518
+ t0 = Math.max(t0, r);
519
+ }
520
+ else {
521
+ if (r < t0)
522
+ return false;
523
+ t1 = Math.min(t1, r);
524
+ }
525
+ return true;
526
+ };
527
+ const ddx = b.x - a.x;
528
+ const ddy = b.y - a.y;
529
+ return clip(-ddx, a.x - x0) && clip(ddx, x1 - a.x) && clip(-ddy, a.y - y0) && clip(ddy, y1 - a.y) && t0 < t1;
530
+ }
531
+ /** The segment of `path` nearest to `p`. */
532
+ function nearestSegment(path, p) {
533
+ let best = [path[0], path[1]];
534
+ let bestDistance = Infinity;
535
+ for (let k = 0; k + 1 < path.length; k++) {
536
+ const a = path[k];
537
+ const b = path[k + 1];
538
+ const lx = b.x - a.x;
539
+ const ly = b.y - a.y;
540
+ const t = lx === 0 && ly === 0 ? 0 : Math.min(1, Math.max(0, ((p.x - a.x) * lx + (p.y - a.y) * ly) / (lx * lx + ly * ly)));
541
+ const distance = Math.hypot(a.x + t * lx - p.x, a.y + t * ly - p.y);
542
+ if (distance < bestDistance) {
543
+ bestDistance = distance;
544
+ best = [a, b];
545
+ }
546
+ }
547
+ return best;
548
+ }
549
+ /** The shapes of a composite state: its box and title band, the white content area below the title. */
550
+ function compositeShapes(nextId, node, f, dx, dy, s) {
551
+ const x = scalePt(f.x + dx, s);
552
+ const y = scalePt(f.y + dy, s);
553
+ const w = scalePt(f.width, s);
554
+ const h = scalePt(f.height, s);
555
+ const titleH = scalePt(COMPOSITE_TITLE_H, s);
556
+ const inset = scalePt(COMPOSITE_INSET, s);
557
+ // A style colours the box and its title band; the content area stays white, so the states inside keep
558
+ // their own look.
559
+ const look = stateLook(node);
560
+ return [
561
+ rect(nextId(), x, y, w, h, look.fill, look.line, node.label, true, (COMPOSITE_RADIUS / Math.max(1, Math.min(f.width, f.height))) * 100000),
562
+ rect(nextId(), x + inset, y + titleH, w - 2 * inset, h - titleH - inset, 'FFFFFF', look.line, `${node.label} content`),
563
+ textBoxLines(nextId(), x, y, w, titleH, [node.label], scaledFontSizeHalfPt(LABEL_SIZE_HALFPT, s), {
564
+ align: 'ctr',
565
+ color: look.text,
566
+ bold: look.bold ?? true,
567
+ italic: look.italic ?? false,
568
+ }),
569
+ ];
570
+ }
129
571
  /** Translate a parsed state diagram into a self-contained WordprocessingML
130
572
  * paragraph. An empty diagram renders a visible note, matching the other
131
573
  * Family B/C translators' zero-content convention — never a silent blank
@@ -142,80 +584,120 @@ export function translateStateDiagramToOoxml(chart, options = {}) {
142
584
  '</w:p>',
143
585
  ].join('\n');
144
586
  }
145
- const sizes = new Map();
146
- const g = new dagre.graphlib.Graph();
147
- g.setGraph({ rankdir: RANKDIR[chart.direction], nodesep: 40, ranksep: 60, marginx: 0, marginy: 0 });
148
- g.setDefaultEdgeLabel(() => ({}));
149
- for (const node of chart.states) {
150
- const size = sizeForNode(node, chart.direction);
151
- sizes.set(node.id, size);
152
- g.setNode(nodeKey(node.id), { width: size.width, height: size.height });
153
- }
154
- for (const t of chart.transitions) {
155
- if (g.hasNode(nodeKey(t.from)) && g.hasNode(nodeKey(t.to)))
156
- g.setEdge(nodeKey(t.from), nodeKey(t.to));
157
- }
158
- layoutWithinLimits(g, options);
159
- let minX = Infinity;
160
- let maxX = -Infinity;
161
- let minY = Infinity;
162
- let maxY = -Infinity;
163
- // Self-transitions are drawn as a loop on the right of the state, with the label beyond it: room for both.
164
- const loopRoom = new Map();
165
- for (const t of chart.transitions) {
166
- if (t.from !== t.to)
167
- continue;
168
- const room = SELF_LOOP_W + (t.label ? estimateTextWidth(t.label, 8) + 8 : 0);
169
- loopRoom.set(t.from, Math.max(loopRoom.get(t.from) ?? 0, room));
170
- }
171
- for (const node of chart.states) {
172
- const n = g.node(nodeKey(node.id));
173
- const size = sizes.get(node.id);
174
- minX = Math.min(minX, n.x - size.width / 2);
175
- maxX = Math.max(maxX, n.x + size.width / 2 + (loopRoom.get(node.id) ?? 0));
176
- minY = Math.min(minY, n.y - size.height / 2);
177
- maxY = Math.max(maxY, n.y + size.height / 2);
178
- }
587
+ // The whole diagram is checked against the limits once, as one graph, before any block is laid out: the
588
+ // blocks are each small, but together they are the diagram the caps are about.
589
+ const whole = new dagre.graphlib.Graph({ multigraph: true });
590
+ for (const node of chart.states)
591
+ whole.setNode(nodeKey(node.id), {});
592
+ chart.transitions.forEach((t, i) => {
593
+ if (whole.hasNode(nodeKey(t.from)) && whole.hasNode(nodeKey(t.to)))
594
+ whole.setEdge(nodeKey(t.from), nodeKey(t.to), {}, String(i));
595
+ });
596
+ assertWithinLimits(whole, options);
597
+ const nesting = new Nesting(chart);
598
+ const laid = new StateLayout(chart, nesting, options).layoutBlock(undefined, chart.direction);
599
+ const frames = laid.frames;
179
600
  const PAD = 24;
180
- const canvasW = maxX - minX + 2 * PAD;
181
- const canvasH = maxY - minY + 2 * PAD;
182
- const dx = -minX + PAD;
183
- const dy = -minY + PAD;
601
+ const canvasW = laid.width + 2 * PAD;
602
+ const canvasH = laid.height + 2 * PAD;
603
+ const dx = PAD;
604
+ const dy = PAD;
184
605
  const { scale: s } = scaledExtent(canvasW, canvasH, options);
185
606
  const nextId = createIdAllocator();
186
607
  const parts = [];
187
- for (const t of chart.transitions) {
188
- const nFrom = g.node(nodeKey(t.from));
189
- const nTo = g.node(nodeKey(t.to));
190
- if (!nFrom || !nTo)
608
+ const lineWidth = scaledLineWidthEmu(9525, s);
609
+ // Composites first, outer before inner (a composite is listed before what it holds), so they stay behind;
610
+ // then the region dividers, the transitions, and the other states on top.
611
+ for (const node of chart.states) {
612
+ const f = frames.get(node.id);
613
+ if (f && nesting.isComposite(node.id))
614
+ parts.push(...compositeShapes(nextId, node, f, dx, dy, s));
615
+ }
616
+ // Notes: the dotted line to their state first, then the note itself.
617
+ for (const [index, f] of laid.notes) {
618
+ const note = chart.notes[index];
619
+ const target = frames.get(note.for);
620
+ if (target) {
621
+ const nc = centre(f);
622
+ const tc = centre(target);
623
+ const a = edgePoint(nc.x, nc.y, f.width / 2, f.height / 2, tc.x, tc.y);
624
+ const b = edgePoint(tc.x, tc.y, target.width / 2, target.height / 2, nc.x, nc.y);
625
+ parts.push(connector(nextId(), scalePt(a.x + dx, s), scalePt(a.y + dy, s), scalePt(b.x + dx, s), scalePt(b.y + dy, s), NOTE_LINE, lineWidth, 'dash', 'none', 'sm', 'none', 'sm'));
626
+ }
627
+ parts.push(boxShape(nextId(), scalePt(f.x + dx, s), scalePt(f.y + dy, s), scalePt(f.width, s), scalePt(f.height, s), note.lines.length > 0 ? note.lines : [''], { fill: NOTE_FILL, line: NOTE_LINE, color: '000000', align: 'left', prst: 'foldedCorner' }, NOTE_FONT_PX, s));
628
+ }
629
+ for (const d of laid.dividers) {
630
+ parts.push(connector(nextId(), scalePt(d.x1 + dx, s), scalePt(d.y1 + dy, s), scalePt(d.x2 + dx, s), scalePt(d.y2 + dy, s), LINE_COLOR, lineWidth, 'dash', 'none', 'sm', 'none', 'sm'));
631
+ }
632
+ // Transitions joining the same two states (`A --> B` and `B --> A`) are spread apart, not drawn on top of
633
+ // each other: an offset per transition within its pair, along one perpendicular per pair.
634
+ const pairKey = (t) => [t.from, t.to].sort().join('\u0000');
635
+ const pairCount = new Map();
636
+ for (const t of chart.transitions)
637
+ if (t.from !== t.to)
638
+ pairCount.set(pairKey(t), (pairCount.get(pairKey(t)) ?? 0) + 1);
639
+ const pairSeen = new Map();
640
+ for (const [transitionIndex, t] of chart.transitions.entries()) {
641
+ const fFrom = frames.get(t.from);
642
+ const fTo = frames.get(t.to);
643
+ if (!fFrom || !fTo)
191
644
  continue;
192
- const sizeFrom = sizes.get(t.from);
193
- const sizeTo = sizes.get(t.to);
645
+ const cFrom = centre(fFrom);
646
+ const cTo = centre(fTo);
194
647
  if (t.from === t.to) {
195
- parts.push(...selfLoop(nextId, nFrom.x + dx, nFrom.y + dy, sizeFrom, t.label, s));
648
+ parts.push(...selfLoop(nextId, cFrom.x + dx, cFrom.y + dy, fFrom, t.label, s));
196
649
  continue;
197
650
  }
198
- const p1 = edgePoint(nFrom.x, nFrom.y, sizeFrom.width / 2, sizeFrom.height / 2, nTo.x, nTo.y);
199
- const p2 = edgePoint(nTo.x, nTo.y, sizeTo.width / 2, sizeTo.height / 2, nFrom.x, nFrom.y);
200
- parts.push(connector(nextId(), scalePt(p1.x + dx, s), scalePt(p1.y + dy, s), scalePt(p2.x + dx, s), scalePt(p2.y + dy, s), LINE_COLOR, scaledLineWidthEmu(9525, s), 'solid', 'none', MARKER_SIZE, 'triangle', MARKER_SIZE));
651
+ const key = pairKey(t);
652
+ const index = pairSeen.get(key) ?? 0;
653
+ pairSeen.set(key, index + 1);
654
+ const offset = parallelEdgeOffset(index, pairCount.get(key) ?? 1, PARALLEL_GAP);
655
+ // One perpendicular per pair, from the pair's sorted order (see `perpendicularUnit`).
656
+ const [first, second] = t.from < t.to ? [cFrom, cTo] : [cTo, cFrom];
657
+ const { ux, uy } = perpendicularUnit(first, second);
658
+ const from = shiftPoint(cFrom, ux, uy, offset);
659
+ const to = shiftPoint(cTo, ux, uy, offset);
660
+ const p1 = edgePoint(from.x, from.y, fFrom.width / 2, fFrom.height / 2, to.x, to.y);
661
+ const p2 = edgePoint(to.x, to.y, fTo.width / 2, fTo.height / 2, from.x, from.y);
662
+ // A straight line, unless it would cross another box (a state, a composite that holds neither end, a
663
+ // note): then Dagre's route around the boxes, its ends brought onto the two states.
664
+ const skip = new Set([t.from, t.to, ...nesting.ancestorsOf(t.from), ...nesting.ancestorsOf(t.to)]);
665
+ const obstacles = [...[...frames].filter(([id]) => !skip.has(id)).map(([, f]) => f), ...laid.notes.values()];
666
+ const route = laid.routes.get(transitionIndex);
667
+ const routed = route !== undefined && route.length >= 3 && obstacles.some((f) => segmentCrosses(p1, p2, f));
668
+ let path = [p1, p2];
669
+ let away = { x: ux * offset, y: uy * offset };
670
+ if (routed) {
671
+ const inner = route.slice(1, -1);
672
+ const firstBend = inner[0];
673
+ const lastBend = inner[inner.length - 1];
674
+ path = [edgePoint(cFrom.x, cFrom.y, fFrom.width / 2, fFrom.height / 2, firstBend.x, firstBend.y), ...inner, edgePoint(cTo.x, cTo.y, fTo.width / 2, fTo.height / 2, lastBend.x, lastBend.y)];
675
+ away = { x: 0, y: 0 };
676
+ }
677
+ // One connector per segment, the arrowhead on the last.
678
+ for (let k = 0; k + 1 < path.length; k++) {
679
+ const a = path[k];
680
+ const b = path[k + 1];
681
+ const last = k + 2 === path.length;
682
+ parts.push(connector(nextId(), scalePt(a.x + dx, s), scalePt(a.y + dy, s), scalePt(b.x + dx, s), scalePt(b.y + dy, s), LINE_COLOR, lineWidth, 'solid', 'none', MARKER_SIZE, last ? 'triangle' : 'none', MARKER_SIZE));
683
+ }
201
684
  if (t.label) {
202
- const midX = (p1.x + p2.x) / 2;
203
- const midY = (p1.y + p2.y) / 2;
685
+ // In the room Dagre kept for it, set against the drawn segment nearest to it (`labelBeside`). A transition
686
+ // no single block laid out (between two regions of one composite) starts from the middle of its line.
687
+ const kept = laid.labels.get(transitionIndex) ?? { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
204
688
  const labelWidth = estimateTextWidth(t.label, 8) + 12;
205
- // Beside a slanted line rather than across it: on the side the line heads to, so the labels of two
206
- // transitions that diverge from one state end up on either side instead of on top of each other.
207
- const slope = p2.x - p1.x;
208
- const side = Math.abs(slope) < 4 ? 0 : Math.sign(slope);
209
- const x = side === 0 ? midX - labelWidth / 2 : side > 0 ? midX + 4 : midX - labelWidth - 4;
210
- parts.push(textBoxLines(nextId(), scalePt(x + dx, s), scalePt(midY + dy - 10, s), scalePt(labelWidth, s), scalePt(20, s), [t.label], scaledFontSizeHalfPt(EDGE_LABEL_SIZE_HALFPT, s),
211
- // Left of the line, the box is sized to the text, so centring in it reads as right-aligned.
212
- { align: side > 0 ? 'l' : 'ctr' }));
689
+ const [segA, segB] = nearestSegment(path, kept);
690
+ const at = labelBeside(kept, segA, segB, labelWidth, away);
691
+ parts.push(textBoxLines(nextId(), scalePt(at.x + dx, s), scalePt(at.y + dy, s), scalePt(labelWidth, s), scalePt(LABEL_H, s), [t.label], scaledFontSizeHalfPt(EDGE_LABEL_SIZE_HALFPT, s), {
692
+ align: at.align,
693
+ }));
213
694
  }
214
695
  }
215
696
  for (const node of chart.states) {
216
- const n = g.node(nodeKey(node.id));
217
- const size = sizes.get(node.id);
218
- parts.push(...nodeShapes(nextId, node, size, n.x - size.width / 2 + dx, n.y - size.height / 2 + dy, s));
697
+ const f = frames.get(node.id);
698
+ if (!f || nesting.isComposite(node.id))
699
+ continue;
700
+ parts.push(...nodeShapes(nextId, node, f, f.x + dx, f.y + dy, s));
219
701
  }
220
702
  const content = parts.join('\n');
221
703
  const docPrId = nextId();