@diagrammo/dgmo 0.47.0 → 0.48.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 (319) hide show
  1. package/dist/auto.js +1 -1
  2. package/dist/auto.mjs +1 -1
  3. package/dist/element.js +1 -1
  4. package/dist/element.mjs +1 -1
  5. package/package.json +19 -70
  6. package/dist/advanced.cjs +0 -71648
  7. package/dist/advanced.d.cts +0 -5719
  8. package/dist/auto.cjs +0 -70648
  9. package/dist/auto.d.cts +0 -54
  10. package/dist/block.cjs +0 -70208
  11. package/dist/block.d.cts +0 -115
  12. package/dist/editor.cjs +0 -526
  13. package/dist/editor.d.cts +0 -26
  14. package/dist/element.cjs +0 -70530
  15. package/dist/element.d.cts +0 -62
  16. package/dist/highlight.cjs +0 -852
  17. package/dist/highlight.d.cts +0 -49
  18. package/dist/index.cjs +0 -70491
  19. package/dist/index.d.cts +0 -160
  20. package/dist/pert.cjs +0 -325
  21. package/dist/pert.d.cts +0 -559
  22. package/dist/themes-1-CuKpeH.d.cts +0 -908
  23. package/src/advanced.ts +0 -873
  24. package/src/arc/parser.ts +0 -15
  25. package/src/arc/renderer.ts +0 -633
  26. package/src/auto/index.ts +0 -621
  27. package/src/auto/shared.ts +0 -370
  28. package/src/auto/styles.ts +0 -73
  29. package/src/block/layout.ts +0 -198
  30. package/src/block/parser.ts +0 -427
  31. package/src/block/renderer.ts +0 -484
  32. package/src/block/types.ts +0 -67
  33. package/src/boxes-and-lines/collapse.ts +0 -96
  34. package/src/boxes-and-lines/focus.ts +0 -257
  35. package/src/boxes-and-lines/label-placement.ts +0 -339
  36. package/src/boxes-and-lines/layout-grouped.ts +0 -912
  37. package/src/boxes-and-lines/layout-layered.ts +0 -722
  38. package/src/boxes-and-lines/layout-search.ts +0 -1678
  39. package/src/boxes-and-lines/layout.ts +0 -398
  40. package/src/boxes-and-lines/parser.ts +0 -1181
  41. package/src/boxes-and-lines/renderer.ts +0 -1465
  42. package/src/boxes-and-lines/types.ts +0 -66
  43. package/src/c4/layout.ts +0 -2441
  44. package/src/c4/parser.ts +0 -1158
  45. package/src/c4/renderer.ts +0 -2008
  46. package/src/c4/types.ts +0 -89
  47. package/src/chart-type-registry.ts +0 -529
  48. package/src/chart-types.ts +0 -225
  49. package/src/chart.ts +0 -685
  50. package/src/charts-d3/bar.ts +0 -338
  51. package/src/charts-d3/chord.ts +0 -140
  52. package/src/charts-d3/function.ts +0 -147
  53. package/src/charts-d3/funnel.ts +0 -104
  54. package/src/charts-d3/heatmap.ts +0 -145
  55. package/src/charts-d3/index.ts +0 -337
  56. package/src/charts-d3/interactions.ts +0 -477
  57. package/src/charts-d3/line.ts +0 -344
  58. package/src/charts-d3/mount.ts +0 -151
  59. package/src/charts-d3/pie.ts +0 -117
  60. package/src/charts-d3/polar.ts +0 -89
  61. package/src/charts-d3/radar.ts +0 -0
  62. package/src/charts-d3/sankey.ts +0 -0
  63. package/src/charts-d3/scatter.ts +0 -185
  64. package/src/charts-d3/shared.ts +0 -208
  65. package/src/class/layout.ts +0 -326
  66. package/src/class/parser.ts +0 -635
  67. package/src/class/renderer.ts +0 -793
  68. package/src/class/types.ts +0 -58
  69. package/src/cli-banner.ts +0 -106
  70. package/src/cli.ts +0 -1080
  71. package/src/colors-diagnostics.ts +0 -35
  72. package/src/colors.ts +0 -379
  73. package/src/completion-types.ts +0 -27
  74. package/src/completion.ts +0 -2668
  75. package/src/cycle/layout.ts +0 -1026
  76. package/src/cycle/parser.ts +0 -387
  77. package/src/cycle/renderer.ts +0 -653
  78. package/src/cycle/types.ts +0 -101
  79. package/src/d3.ts +0 -1434
  80. package/src/data-chart-parser.ts +0 -1007
  81. package/src/dgmo-router.ts +0 -296
  82. package/src/diagnostics-registry.ts +0 -108
  83. package/src/diagnostics.ts +0 -0
  84. package/src/dimensions.ts +0 -20
  85. package/src/directives-registry.ts +0 -396
  86. package/src/editor/dgmo.grammar +0 -76
  87. package/src/editor/dgmo.grammar.d.ts +0 -2
  88. package/src/editor/dgmo.grammar.js +0 -18
  89. package/src/editor/dgmo.grammar.terms.d.ts +0 -5
  90. package/src/editor/dgmo.grammar.terms.js +0 -35
  91. package/src/editor/highlight-api.ts +0 -596
  92. package/src/editor/highlight.ts +0 -36
  93. package/src/editor/index.ts +0 -27
  94. package/src/editor/keywords.ts +0 -128
  95. package/src/editor/tokens.ts +0 -30
  96. package/src/element/index.ts +0 -432
  97. package/src/embed/css.ts +0 -312
  98. package/src/embed/escape.ts +0 -15
  99. package/src/embed/index.ts +0 -280
  100. package/src/er/classify.ts +0 -228
  101. package/src/er/layout.ts +0 -530
  102. package/src/er/parser.ts +0 -750
  103. package/src/er/renderer.ts +0 -725
  104. package/src/er/types.ts +0 -52
  105. package/src/error-card.ts +0 -269
  106. package/src/event-line/diagnostics.ts +0 -117
  107. package/src/event-line/parser.ts +0 -643
  108. package/src/event-line/renderer.ts +0 -1742
  109. package/src/event-line/types.ts +0 -74
  110. package/src/fonts.ts +0 -3
  111. package/src/gantt/calculator.ts +0 -979
  112. package/src/gantt/parser.ts +0 -1641
  113. package/src/gantt/renderer.ts +0 -3787
  114. package/src/gantt/resolver.ts +0 -172
  115. package/src/gantt/types.ts +0 -206
  116. package/src/graph/diagnostics.ts +0 -64
  117. package/src/graph/edge-spline.ts +0 -29
  118. package/src/graph/flowchart-parser.ts +0 -759
  119. package/src/graph/flowchart-renderer.ts +0 -817
  120. package/src/graph/layout.ts +0 -472
  121. package/src/graph/notes.ts +0 -21
  122. package/src/graph/state-collapse.ts +0 -78
  123. package/src/graph/state-parser.ts +0 -574
  124. package/src/graph/state-renderer.ts +0 -653
  125. package/src/graph/types.ts +0 -65
  126. package/src/index.ts +0 -261
  127. package/src/infra/compute.ts +0 -1385
  128. package/src/infra/layout.ts +0 -888
  129. package/src/infra/parser.ts +0 -1234
  130. package/src/infra/renderer.ts +0 -2534
  131. package/src/infra/roles.ts +0 -75
  132. package/src/infra/types.ts +0 -216
  133. package/src/infra/validation.ts +0 -201
  134. package/src/journey-map/layout.ts +0 -490
  135. package/src/journey-map/parser.ts +0 -557
  136. package/src/journey-map/renderer.ts +0 -1580
  137. package/src/journey-map/types.ts +0 -47
  138. package/src/kanban/mutations.ts +0 -175
  139. package/src/kanban/parser.ts +0 -509
  140. package/src/kanban/renderer.ts +0 -1449
  141. package/src/kanban/types.ts +0 -39
  142. package/src/label-layout.ts +0 -368
  143. package/src/map/colorize.ts +0 -54
  144. package/src/map/completion.ts +0 -316
  145. package/src/map/context-labels.ts +0 -609
  146. package/src/map/data/PROVENANCE.json +0 -1
  147. package/src/map/data/README.md +0 -40
  148. package/src/map/data/airport-collisions.json +0 -1
  149. package/src/map/data/airports.json +0 -1
  150. package/src/map/data/gazetteer.json +0 -1
  151. package/src/map/data/lakes.json +0 -1
  152. package/src/map/data/mountain-ranges.json +0 -1
  153. package/src/map/data/na-lakes.json +0 -1
  154. package/src/map/data/na-land.json +0 -1
  155. package/src/map/data/region-names.json +0 -1
  156. package/src/map/data/rivers.json +0 -1
  157. package/src/map/data/types.ts +0 -121
  158. package/src/map/data/us-states.json +0 -1
  159. package/src/map/data/water-bodies.json +0 -1
  160. package/src/map/data/world-coarse.json +0 -1
  161. package/src/map/data/world-detail.json +0 -1
  162. package/src/map/diagnostics.ts +0 -134
  163. package/src/map/dimensions.ts +0 -150
  164. package/src/map/geo-query.ts +0 -295
  165. package/src/map/geo.ts +0 -438
  166. package/src/map/invert.ts +0 -111
  167. package/src/map/layout.ts +0 -5069
  168. package/src/map/legend-band.ts +0 -127
  169. package/src/map/load-data.ts +0 -186
  170. package/src/map/parser.ts +0 -783
  171. package/src/map/renderer.ts +0 -1445
  172. package/src/map/resolved-types.ts +0 -160
  173. package/src/map/resolver.ts +0 -1146
  174. package/src/map/types.ts +0 -194
  175. package/src/mindmap/collapse.ts +0 -67
  176. package/src/mindmap/layout.ts +0 -649
  177. package/src/mindmap/parser.ts +0 -430
  178. package/src/mindmap/renderer.ts +0 -637
  179. package/src/mindmap/text-wrap.ts +0 -218
  180. package/src/mindmap/types.ts +0 -56
  181. package/src/org/collapse.ts +0 -151
  182. package/src/org/layout.ts +0 -1262
  183. package/src/org/parser.ts +0 -519
  184. package/src/org/renderer.ts +0 -866
  185. package/src/org/resolver.ts +0 -636
  186. package/src/palettes/atlas.ts +0 -77
  187. package/src/palettes/blueprint.ts +0 -73
  188. package/src/palettes/catppuccin.ts +0 -84
  189. package/src/palettes/color-utils.ts +0 -443
  190. package/src/palettes/index.ts +0 -67
  191. package/src/palettes/nord.ts +0 -67
  192. package/src/palettes/registry.ts +0 -114
  193. package/src/palettes/slate.ts +0 -73
  194. package/src/palettes/tidewater.ts +0 -73
  195. package/src/palettes/tokyo-night.ts +0 -86
  196. package/src/palettes/types.ts +0 -88
  197. package/src/pert/analyzer.ts +0 -1183
  198. package/src/pert/diagnostics.ts +0 -110
  199. package/src/pert/index.ts +0 -43
  200. package/src/pert/internal.ts +0 -252
  201. package/src/pert/layout.ts +0 -971
  202. package/src/pert/monte-carlo.ts +0 -446
  203. package/src/pert/parser.ts +0 -1606
  204. package/src/pert/renderer.ts +0 -4009
  205. package/src/pert/share-normalize.ts +0 -62
  206. package/src/pert/types.ts +0 -604
  207. package/src/pyramid/parser.ts +0 -185
  208. package/src/pyramid/renderer.ts +0 -768
  209. package/src/pyramid/types.ts +0 -28
  210. package/src/quadrant/parser.ts +0 -18
  211. package/src/quadrant/renderer.ts +0 -638
  212. package/src/raci/diagnostics.ts +0 -213
  213. package/src/raci/index.ts +0 -23
  214. package/src/raci/mutations.ts +0 -321
  215. package/src/raci/parser.ts +0 -699
  216. package/src/raci/renderer.ts +0 -1627
  217. package/src/raci/types.ts +0 -82
  218. package/src/raci/variants.ts +0 -320
  219. package/src/render.ts +0 -268
  220. package/src/ring/parser.ts +0 -212
  221. package/src/ring/renderer.ts +0 -490
  222. package/src/ring/types.ts +0 -27
  223. package/src/sequence/collapse.ts +0 -174
  224. package/src/sequence/parser.ts +0 -1596
  225. package/src/sequence/participant-inference.ts +0 -152
  226. package/src/sequence/renderer.ts +0 -3168
  227. package/src/sequence/tag-resolution.ts +0 -164
  228. package/src/sharing.ts +0 -211
  229. package/src/sitemap/collapse.ts +0 -100
  230. package/src/sitemap/layout.ts +0 -925
  231. package/src/sitemap/parser.ts +0 -755
  232. package/src/sitemap/renderer.ts +0 -828
  233. package/src/sitemap/types.ts +0 -42
  234. package/src/slope/parser.ts +0 -18
  235. package/src/slope/renderer.ts +0 -378
  236. package/src/swimlane/diagnostics.ts +0 -94
  237. package/src/swimlane/layout.ts +0 -597
  238. package/src/swimlane/parser.ts +0 -613
  239. package/src/swimlane/renderer.ts +0 -681
  240. package/src/swimlane/types.ts +0 -151
  241. package/src/tech-radar/interactive.ts +0 -1129
  242. package/src/tech-radar/layout.ts +0 -197
  243. package/src/tech-radar/parser.ts +0 -436
  244. package/src/tech-radar/renderer.ts +0 -1239
  245. package/src/tech-radar/shared.ts +0 -151
  246. package/src/tech-radar/types.ts +0 -86
  247. package/src/themes.ts +0 -22
  248. package/src/timeline/parser.ts +0 -472
  249. package/src/timeline/renderer.ts +0 -3024
  250. package/src/timeline/types.ts +0 -33
  251. package/src/timeline/viz-parser.ts +0 -21
  252. package/src/treemap/diagnostics.ts +0 -62
  253. package/src/treemap/layout-radial.ts +0 -233
  254. package/src/treemap/layout.ts +0 -189
  255. package/src/treemap/parser.ts +0 -463
  256. package/src/treemap/renderer-radial.ts +0 -438
  257. package/src/treemap/renderer.ts +0 -572
  258. package/src/treemap/treemap-shared.ts +0 -309
  259. package/src/treemap/types.ts +0 -60
  260. package/src/utils/arrow-markers.ts +0 -51
  261. package/src/utils/arrows-diagnostics.ts +0 -62
  262. package/src/utils/arrows.ts +0 -227
  263. package/src/utils/brand.ts +0 -61
  264. package/src/utils/card.ts +0 -183
  265. package/src/utils/collapse-engine/tree-edges.ts +0 -115
  266. package/src/utils/collapse-engine/tree.ts +0 -117
  267. package/src/utils/d3-helpers.ts +0 -219
  268. package/src/utils/d3-types.ts +0 -9
  269. package/src/utils/description-helpers.ts +0 -38
  270. package/src/utils/duration.ts +0 -312
  271. package/src/utils/export-container.ts +0 -41
  272. package/src/utils/expr-eval.ts +0 -27
  273. package/src/utils/fit-canvas.ts +0 -64
  274. package/src/utils/hover-styles.ts +0 -673
  275. package/src/utils/inline-markdown.ts +0 -96
  276. package/src/utils/legend-constants.ts +0 -48
  277. package/src/utils/legend-d3.ts +0 -618
  278. package/src/utils/legend-integration.ts +0 -107
  279. package/src/utils/legend-layout.ts +0 -776
  280. package/src/utils/legend-svg.ts +0 -214
  281. package/src/utils/legend-types.ts +0 -272
  282. package/src/utils/name-normalize.ts +0 -163
  283. package/src/utils/note-box/constants.ts +0 -25
  284. package/src/utils/note-box/index.ts +0 -11
  285. package/src/utils/note-box/metrics.ts +0 -90
  286. package/src/utils/note-box/svg.ts +0 -331
  287. package/src/utils/notes/bounds.ts +0 -30
  288. package/src/utils/notes/build.ts +0 -131
  289. package/src/utils/notes/index.ts +0 -18
  290. package/src/utils/notes/model.ts +0 -19
  291. package/src/utils/notes/parse.ts +0 -131
  292. package/src/utils/notes/place.ts +0 -177
  293. package/src/utils/notes/resolve.ts +0 -88
  294. package/src/utils/number-format.ts +0 -36
  295. package/src/utils/parsing.ts +0 -953
  296. package/src/utils/reserved-key-registry.ts +0 -239
  297. package/src/utils/safe-href.ts +0 -38
  298. package/src/utils/scaling.ts +0 -97
  299. package/src/utils/svg-embed.ts +0 -251
  300. package/src/utils/tag-groups.ts +0 -607
  301. package/src/utils/text-measure.ts +0 -122
  302. package/src/utils/time-ticks.ts +0 -253
  303. package/src/utils/title-constants.ts +0 -24
  304. package/src/utils/visual-conventions.ts +0 -61
  305. package/src/utils/wrapped-desc.ts +0 -87
  306. package/src/venn/parser.ts +0 -18
  307. package/src/venn/renderer.ts +0 -1047
  308. package/src/version-control/diagnostics.ts +0 -67
  309. package/src/version-control/parser.ts +0 -544
  310. package/src/version-control/renderer.ts +0 -724
  311. package/src/version-control/types.ts +0 -100
  312. package/src/visualizations/parse.ts +0 -1560
  313. package/src/visualizations/types.ts +0 -262
  314. package/src/wireframe/layout.ts +0 -479
  315. package/src/wireframe/parser.ts +0 -1114
  316. package/src/wireframe/renderer.ts +0 -1318
  317. package/src/wireframe/types.ts +0 -110
  318. package/src/wordcloud/parser.ts +0 -18
  319. package/src/wordcloud/renderer.ts +0 -357
@@ -1,1026 +0,0 @@
1
- // ============================================================
2
- // Cycle Diagram — Layout Engine
3
- // ============================================================
4
-
5
- import {
6
- DEFAULT_EDGE_WIDTH,
7
- MIN_EDGE_WIDTH,
8
- arrowHeadLength,
9
- type ParsedCycle,
10
- type CycleLayoutNode,
11
- type CycleLayoutEdge,
12
- type CycleLayoutResult,
13
- } from './types';
14
- import type { Writable } from '../utils/brand';
15
- import {
16
- wrapDescriptionLines,
17
- type WrappedDescLine,
18
- } from '../utils/wrapped-desc';
19
- import { measureText, wrapTextToWidth } from '../utils/text-measure';
20
-
21
- /** Minimum arc angle in radians (~15°) to keep arcs readable. */
22
- const MIN_ARC_ANGLE = (15 * Math.PI) / 180;
23
-
24
- // ── Font sizes (must match cycle/renderer.ts) ──
25
- // Layout sizes nodes/labels from text; the renderer draws them. Both measure
26
- // the same string at the same font size so reserved space matches ink.
27
- const LABEL_FONT_SIZE = 13;
28
- const CIRCLE_LABEL_FONT_SIZE = 16;
29
- const DESC_FONT_SIZE = 11;
30
- const EDGE_LABEL_FONT_SIZE = 11;
31
-
32
- /** Minimum node width. */
33
- const MIN_NODE_WIDTH = 70;
34
-
35
- /** Maximum node width. */
36
- const MAX_NODE_WIDTH = 260;
37
-
38
- /** Minimum width to consider for described nodes (avoid ultra-narrow columns). */
39
- const DESC_MIN_WIDTH = 140;
40
-
41
- /** Width sweep step when choosing the best aspect ratio for described nodes. */
42
- const DESC_WIDTH_STEP = 20;
43
-
44
- /** Target width:height ratio for described rectangular nodes. */
45
- const DESC_TARGET_RATIO = 1.6;
46
-
47
- /** Node height for label-only nodes. */
48
- const PLAIN_NODE_HEIGHT = 50;
49
-
50
- /** Header height (label zone) in described nodes. */
51
- const HEADER_HEIGHT = 36;
52
-
53
- /** Extra height per wrapped description line. */
54
- const DESC_LINE_HEIGHT = 16;
55
-
56
- /** Vertical padding around description zone. */
57
- const DESC_PAD_Y = 14;
58
-
59
- /** Horizontal padding inside node for text. */
60
- const NODE_PAD_X = 20;
61
-
62
- /** Minimum circle-node radius. */
63
- const MIN_CIRCLE_RADIUS = 35;
64
-
65
- /** Padding inside circle for text. */
66
- const CIRCLE_PAD = 14;
67
-
68
- /**
69
- * Compute cycle diagram layout: positions nodes equidistant (or span-weighted)
70
- * on a circle, and generates curved edge paths between consecutive nodes.
71
- */
72
- export function computeCycleLayout(
73
- parsed: ParsedCycle,
74
- options?: { width?: number; height?: number; hideDescriptions?: boolean }
75
- ): CycleLayoutResult {
76
- const width = options?.width ?? 800;
77
- const height = options?.height ?? 600;
78
- const hideDescriptions = options?.hideDescriptions ?? false;
79
-
80
- if (parsed.nodes.length === 0) {
81
- return {
82
- nodes: [],
83
- edges: [],
84
- cx: width / 2,
85
- cy: height / 2,
86
- radius: 0,
87
- width,
88
- height,
89
- scale: 1,
90
- };
91
- }
92
-
93
- const nodeCount = parsed.nodes.length;
94
- const cx = width / 2;
95
- const cy = height / 2;
96
- const circleNodes = parsed.options['circle-nodes'] === 'true';
97
-
98
- // ── Compute node dimensions with word wrapping ──
99
- const nodeDims = parsed.nodes.map((node) => {
100
- const hasDesc = !hideDescriptions && node.description.length > 0;
101
- const labelWidth = Math.max(
102
- MIN_NODE_WIDTH,
103
- measureText(node.label, LABEL_FONT_SIZE) + NODE_PAD_X * 2
104
- );
105
-
106
- if (circleNodes) {
107
- return computeCircleNodeDims(node, hasDesc);
108
- }
109
-
110
- if (!hasDesc) {
111
- return {
112
- width: Math.min(MAX_NODE_WIDTH, labelWidth),
113
- height: PLAIN_NODE_HEIGHT,
114
- wrappedDesc: [] as WrappedDescLine[],
115
- };
116
- }
117
-
118
- return chooseDescribedRectDims(node.description, labelWidth);
119
- });
120
-
121
- // ── Uniform circle sizing: all circles match the largest ──
122
- if (circleNodes) {
123
- const maxDiam = Math.max(...nodeDims.map((d) => d.width));
124
- for (const d of nodeDims) {
125
- d.width = maxDiam;
126
- d.height = maxDiam;
127
- // Re-wrap descriptions to fit the larger circle
128
- const nodeIdx = nodeDims.indexOf(d);
129
- // In-bounds: nodeDims is built 1:1 from parsed.nodes.
130
- const node = parsed.nodes[nodeIdx]!;
131
- const hasDesc = !hideDescriptions && node.description.length > 0;
132
- if (hasDesc) {
133
- d.wrappedDesc = wrapLinesForCircle(node.description, maxDiam / 2).map(
134
- (text) => ({ text, kind: 'plain' as const })
135
- );
136
- }
137
- }
138
- }
139
-
140
- // ── Compute angles using span weights ──
141
- const totalSpan = parsed.nodes.reduce((sum, n) => sum + n.span, 0);
142
-
143
- // Clamp: ensure no arc angle falls below MIN_ARC_ANGLE
144
- let rawAngles = parsed.nodes.map((n) => (n.span / totalSpan) * 2 * Math.PI);
145
- const tooSmall = rawAngles.filter((a) => a < MIN_ARC_ANGLE);
146
- if (tooSmall.length > 0 && tooSmall.length < nodeCount) {
147
- const deficit = tooSmall.reduce((sum, a) => sum + (MIN_ARC_ANGLE - a), 0);
148
- const largeTotal = rawAngles
149
- .filter((a) => a >= MIN_ARC_ANGLE)
150
- .reduce((sum, a) => sum + a, 0);
151
-
152
- rawAngles = rawAngles.map((a) => {
153
- if (a < MIN_ARC_ANGLE) return MIN_ARC_ANGLE;
154
- return a - (a / largeTotal) * deficit;
155
- });
156
- }
157
-
158
- // ── Compute radius that prevents node overlap ──
159
- const isClockwise = parsed.direction === 'clockwise';
160
-
161
- // For each pair of adjacent nodes, compute the minimum radius so they
162
- // don't overlap: the chord between adjacent centers must be >= sum of
163
- // their half-diagonals + a gap.
164
- const GAP = 20;
165
- let minRadiusForNodes = 0;
166
- for (let i = 0; i < nodeCount; i++) {
167
- const j = (i + 1) % nodeCount;
168
- // In-bounds: i and j are within [0, nodeCount), nodeDims.length === nodeCount.
169
- const diA =
170
- Math.sqrt(nodeDims[i]!.width ** 2 + nodeDims[i]!.height ** 2) / 2;
171
- const diB =
172
- Math.sqrt(nodeDims[j]!.width ** 2 + nodeDims[j]!.height ** 2) / 2;
173
- const neededChord = diA + diB + GAP;
174
- // chord = 2 * r * sin(angle/2) → r = chord / (2 * sin(angle/2))
175
- const halfAngle = rawAngles[i]! / 2;
176
- if (halfAngle > 0.001) {
177
- const r = neededChord / (2 * Math.sin(halfAngle));
178
- minRadiusForNodes = Math.max(minRadiusForNodes, r);
179
- }
180
- }
181
-
182
- // Max radius that fits in the canvas (leave room for the largest node)
183
- const maxNodeHalf = Math.max(
184
- ...nodeDims.map((d) => Math.max(d.width, d.height) / 2)
185
- );
186
- const maxRadius = Math.min(cx, cy) - maxNodeHalf - 10;
187
-
188
- let radius: number;
189
- let scale = 1;
190
-
191
- if (minRadiusForNodes <= maxRadius) {
192
- // Fill the available canvas — use maxRadius so the diagram scales up
193
- radius = Math.max(100, maxRadius);
194
- } else {
195
- // Nodes are too big to fit without overlap — shrink them
196
- radius = Math.max(80, maxRadius);
197
- scale = radius / minRadiusForNodes;
198
- // Scale down all node dimensions and re-wrap descriptions so text always
199
- // fits inside the shrunk rectangle (font scales linearly in the renderer,
200
- // so chars-per-line stays roughly constant — but line *count* must match
201
- // the new height budget).
202
- for (let i = 0; i < nodeDims.length; i++) {
203
- // In-bounds by loop guard; nodeDims and parsed.nodes are parallel arrays.
204
- const d = nodeDims[i]!;
205
- const node = parsed.nodes[i]!;
206
- const hasDesc = !hideDescriptions && node.description.length > 0;
207
- const newW = Math.max(50, d.width * scale);
208
- if (circleNodes) {
209
- d.width = newW;
210
- d.height = newW;
211
- if (hasDesc) {
212
- d.wrappedDesc = wrapLinesForCircle(node.description, newW / 2).map(
213
- (text) => ({ text, kind: 'plain' as const })
214
- );
215
- }
216
- } else if (hasDesc) {
217
- d.width = newW;
218
- // Re-wrap at the unscaled width: layout-space char count stays
219
- // constant under uniform font scaling, so wrap on d.width / scale,
220
- // which equals the original chosen width in pre-scale units.
221
- const layoutWidth = newW / scale;
222
- d.wrappedDesc = wrapDescForWidth(node.description, layoutWidth);
223
- d.height = renderedDescNodeHeight(d.wrappedDesc.length, scale);
224
- } else {
225
- d.width = newW;
226
- d.height = Math.max(30, d.height * scale);
227
- }
228
- }
229
- }
230
-
231
- // ── Compute angular footprints for uniform edge-gap spacing ──
232
- // Iteratively refine: estimate footprints at current positions, redistribute
233
- // with uniform gaps, then recompute footprints at the new positions. Converges
234
- // in 2-3 iterations so positions and footprints are self-consistent.
235
- const nodeAngles = new Array(nodeCount);
236
- for (let i = 0; i < nodeCount; i++) {
237
- nodeAngles[i] =
238
- -Math.PI / 2 + i * ((2 * Math.PI) / nodeCount) * (isClockwise ? 1 : -1);
239
- }
240
-
241
- const ITERATIONS = 3;
242
- const footprints = new Array(nodeCount);
243
-
244
- for (let iter = 0; iter < ITERATIONS; iter++) {
245
- // Compute footprints at current estimated positions
246
- for (let i = 0; i < nodeCount; i++) {
247
- const theta = nodeAngles[i];
248
- const approxX = cx + radius * Math.cos(theta);
249
- const approxY = cy + radius * Math.sin(theta);
250
- // In-bounds by loop guard.
251
- const hw = nodeDims[i]!.width / 2;
252
- const hh = nodeDims[i]!.height / 2;
253
- let exitCW: number, exitCCW: number;
254
- if (circleNodes) {
255
- const nodeR = hw; // width === height for circles
256
- exitCW = circleNodeExitAngle(nodeR, radius, theta, 1);
257
- exitCCW = circleNodeExitAngle(nodeR, radius, theta, -1);
258
- } else {
259
- exitCW = circleRectExitAngle(
260
- approxX,
261
- approxY,
262
- hw,
263
- hh,
264
- cx,
265
- cy,
266
- radius,
267
- theta,
268
- 1
269
- );
270
- exitCCW = circleRectExitAngle(
271
- approxX,
272
- approxY,
273
- hw,
274
- hh,
275
- cx,
276
- cy,
277
- radius,
278
- theta,
279
- -1
280
- );
281
- }
282
- footprints[i] = Math.abs(exitCW - exitCCW);
283
- }
284
-
285
- // Distribute remaining arc as gaps (weighted by span)
286
- const totalFootprint = footprints.reduce(
287
- (s: number, f: number) => s + f,
288
- 0
289
- );
290
- const totalGapAngle = Math.max(0, 2 * Math.PI - totalFootprint);
291
- const gapAngles = parsed.nodes.map(
292
- (n) => (n.span / totalSpan) * totalGapAngle
293
- );
294
-
295
- // Reposition nodes
296
- let cumAngle = -Math.PI / 2;
297
- for (let i = 0; i < nodeCount; i++) {
298
- nodeAngles[i] = cumAngle;
299
- const nextIdx = (i + 1) % nodeCount;
300
- // In-bounds: i, nextIdx in [0, nodeCount); arrays sized to nodeCount.
301
- const advance =
302
- footprints[i] / 2 + gapAngles[i]! + footprints[nextIdx] / 2;
303
- cumAngle += isClockwise ? advance : -advance;
304
- }
305
- }
306
-
307
- // ── Build layout nodes at converged positions ──
308
- const layoutNodes: Writable<CycleLayoutNode>[] = [];
309
- for (let i = 0; i < nodeCount; i++) {
310
- // In-bounds by loop guard; all arrays sized to nodeCount.
311
- const angle = nodeAngles[i];
312
- layoutNodes.push({
313
- label: parsed.nodes[i]!.label,
314
- x: cx + radius * Math.cos(angle),
315
- y: cy + radius * Math.sin(angle),
316
- angle,
317
- width: nodeDims[i]!.width,
318
- height: nodeDims[i]!.height,
319
- wrappedDesc: nodeDims[i]!.wrappedDesc,
320
- isCircle: circleNodes,
321
- });
322
- }
323
-
324
- // ── Compute edge paths ──
325
- let layoutEdges = computeEdgePaths(
326
- layoutNodes,
327
- parsed,
328
- cx,
329
- cy,
330
- radius,
331
- isClockwise
332
- );
333
-
334
- // ── Fit-to-canvas: shrink if edge labels overflow ──
335
- const fitResult = fitToCanvas(
336
- layoutNodes,
337
- layoutEdges,
338
- parsed,
339
- cx,
340
- cy,
341
- radius,
342
- width,
343
- height,
344
- isClockwise
345
- );
346
- if (fitResult) {
347
- radius = fitResult.radius;
348
- // Reposition nodes on the smaller circle
349
- for (let i = 0; i < nodeCount; i++) {
350
- // In-bounds by loop guard.
351
- layoutNodes[i]!.x = cx + radius * Math.cos(nodeAngles[i]);
352
- layoutNodes[i]!.y = cy + radius * Math.sin(nodeAngles[i]);
353
- }
354
- layoutEdges = computeEdgePaths(
355
- layoutNodes,
356
- parsed,
357
- cx,
358
- cy,
359
- radius,
360
- isClockwise
361
- );
362
- }
363
-
364
- return {
365
- nodes: layoutNodes,
366
- edges: layoutEdges,
367
- cx,
368
- cy,
369
- radius,
370
- width,
371
- height,
372
- scale,
373
- };
374
- }
375
-
376
- /**
377
- * Choose width + height for a described rectangular node by sweeping candidate
378
- * widths and picking the one whose resulting aspect ratio is closest to
379
- * DESC_TARGET_RATIO. Width grows with content so long descriptions get wider
380
- * boxes instead of tall thin columns.
381
- */
382
- function chooseDescribedRectDims(
383
- description: readonly string[],
384
- labelWidth: number
385
- ): { width: number; height: number; wrappedDesc: WrappedDescLine[] } {
386
- const minW = Math.min(
387
- MAX_NODE_WIDTH,
388
- Math.max(MIN_NODE_WIDTH, labelWidth, DESC_MIN_WIDTH)
389
- );
390
- let best: {
391
- width: number;
392
- height: number;
393
- wrappedDesc: WrappedDescLine[];
394
- } | null = null;
395
- let bestScore = Infinity;
396
- for (let w = minW; w <= MAX_NODE_WIDTH; w += DESC_WIDTH_STEP) {
397
- const wrapped = wrapDescForWidth(description, w);
398
- const h = HEADER_HEIGHT + wrapped.length * DESC_LINE_HEIGHT + DESC_PAD_Y;
399
- const ratio = w / h;
400
- const score = Math.abs(Math.log(ratio / DESC_TARGET_RATIO));
401
- if (score < bestScore) {
402
- bestScore = score;
403
- best = { width: w, height: h, wrappedDesc: wrapped };
404
- }
405
- }
406
- if (best) return best;
407
- const wrapped = wrapDescForWidth(description, minW);
408
- return {
409
- width: minW,
410
- height: HEADER_HEIGHT + wrapped.length * DESC_LINE_HEIGHT + DESC_PAD_Y,
411
- wrappedDesc: wrapped,
412
- };
413
- }
414
-
415
- /** Wrap description lines for a rect node of the given total width. */
416
- function wrapDescForWidth(
417
- description: readonly string[],
418
- nodeWidth: number
419
- ): WrappedDescLine[] {
420
- // Wrap to a real pixel budget. `wrapDescriptionLines` is bullet-aware (it
421
- // emits bullet-first/cont kinds the renderer relies on), so feed it a pixel
422
- // `lengthFn` + pixel limit instead of a character count.
423
- const textWidth = Math.max(40, nodeWidth - NODE_PAD_X * 2);
424
- return wrapDescriptionLines([...description], textWidth, (s) =>
425
- measureText(s, DESC_FONT_SIZE)
426
- );
427
- }
428
-
429
- // ── Renderer-aligned font/line-height clamps ──
430
- // These mirror the floor clamps in cycle/renderer.ts so the layout's reserved
431
- // height always matches what the renderer actually draws — preventing the
432
- // "text spills out the bottom of the box" bug at small scales.
433
- const RENDERER_DESC_FONT = 11;
434
- const RENDERER_DESC_FONT_MIN = 8;
435
- const RENDERER_DESC_LINE_H = 15;
436
- const RENDERER_DESC_LINE_H_MIN = 11;
437
-
438
- /**
439
- * Reserved height for a rectangular described node at the given scale,
440
- * computed using the renderer's clamped font + line-height so text always
441
- * fits inside the rectangle even when scale is small enough to trigger the
442
- * renderer's minimum-size clamps.
443
- */
444
- function renderedDescNodeHeight(numLines: number, scale: number): number {
445
- const headerH = HEADER_HEIGHT * scale;
446
- const descFont = Math.max(
447
- RENDERER_DESC_FONT_MIN,
448
- Math.round(RENDERER_DESC_FONT * scale)
449
- );
450
- const descLineH = Math.max(
451
- RENDERER_DESC_LINE_H_MIN,
452
- Math.round(RENDERER_DESC_LINE_H * scale)
453
- );
454
- // Renderer: descStartY = sepY + 4 + scaledDescFont, then (N-1) more lines
455
- // at scaledDescLineH. Add a small bottom pad so the last descender clears
456
- // the box border.
457
- const textBlockH = 4 + descFont + (numLines - 1) * descLineH;
458
- const bottomPad = 8;
459
- return headerH + textBlockH + bottomPad;
460
- }
461
-
462
- // ── Edge-label wrapping (shared with renderer) ──
463
-
464
- /**
465
- * Maximum pixel width per line for edge labels and edge descriptions.
466
- * Long single-line text gets wrapped to multiple lines so it doesn't
467
- * shoot off-canvas when positioned at a cycle quadrant. ~197px ≈ the old
468
- * 32-char budget at the 11px edge-label font.
469
- */
470
- export const EDGE_LABEL_MAX_WIDTH = 197;
471
-
472
- /**
473
- * Wrap an edge label string + description lines into rendered lines.
474
- * Used by both layout (for fit-to-canvas sizing) and renderer (for drawing).
475
- * The label, if present, is the first wrapped block; each description string
476
- * is its own wrapped block. Empty strings are filtered.
477
- */
478
- export function wrapEdgeLabelText(
479
- label: string | undefined,
480
- description: readonly string[],
481
- maxWidth: number = EDGE_LABEL_MAX_WIDTH
482
- ): { labelLines: string[]; descLines: string[] } {
483
- const labelLines = label
484
- ? wrapTextToWidth(label, EDGE_LABEL_FONT_SIZE, maxWidth)
485
- : [];
486
- const descLines: string[] = [];
487
- for (const d of description) {
488
- descLines.push(...wrapTextToWidth(d, EDGE_LABEL_FONT_SIZE, maxWidth));
489
- }
490
- return { labelLines, descLines };
491
- }
492
-
493
- // ── Helper: circle node dimensions ──
494
-
495
- function computeCircleNodeDims(
496
- node: { label: string; description: readonly string[] },
497
- hasDesc: boolean
498
- ): { width: number; height: number; wrappedDesc: WrappedDescLine[] } {
499
- if (!hasDesc) {
500
- const textW = measureText(node.label, CIRCLE_LABEL_FONT_SIZE);
501
- const r = Math.max(MIN_CIRCLE_RADIUS, textW / 2 + CIRCLE_PAD);
502
- return { width: r * 2, height: r * 2, wrappedDesc: [] };
503
- }
504
-
505
- let r = MIN_CIRCLE_RADIUS;
506
-
507
- for (let attempt = 0; attempt < 10; attempt++) {
508
- const wrappedDesc = wrapLinesForCircle(node.description, r);
509
- const totalLines = 1 + wrappedDesc.length;
510
- const textBlockH = totalLines * DESC_LINE_HEIGHT + CIRCLE_PAD;
511
-
512
- if (textBlockH / 2 <= r * 0.85) {
513
- const labelW = measureText(node.label, CIRCLE_LABEL_FONT_SIZE);
514
- const labelY = -textBlockH / 2 + DESC_LINE_HEIGHT;
515
- const availW = 2 * Math.sqrt(Math.max(0, r * r - labelY * labelY));
516
- if (labelW <= availW - CIRCLE_PAD) {
517
- return {
518
- width: r * 2,
519
- height: r * 2,
520
- wrappedDesc: wrappedDesc.map((text) => ({
521
- text,
522
- kind: 'plain' as const,
523
- })),
524
- };
525
- }
526
- }
527
- r += 10;
528
- }
529
-
530
- const wrappedDesc = wrapLinesForCircle(node.description, r);
531
- return {
532
- width: r * 2,
533
- height: r * 2,
534
- wrappedDesc: wrappedDesc.map((text) => ({ text, kind: 'plain' as const })),
535
- };
536
- }
537
-
538
- /**
539
- * Wrap description lines to fit inside a circle of given radius.
540
- * Each line gets a different max width based on its vertical position
541
- * within the circle — wider at the center, narrower near edges.
542
- */
543
- function wrapLinesForCircle(
544
- descriptions: readonly string[],
545
- radius: number
546
- ): string[] {
547
- // First pass: wrap to the center pixel-width to estimate line count.
548
- const centerWidth = radius * 2 * 0.75;
549
- const roughWrapped = descriptions.flatMap((d) =>
550
- wrapTextToWidth(d, DESC_FONT_SIZE, centerWidth)
551
- );
552
- const totalLines = 1 + roughWrapped.length; // +1 for label line
553
- const blockH = totalLines * DESC_LINE_HEIGHT;
554
-
555
- // Second pass: re-wrap each source line with a position-aware pixel width —
556
- // wider near the circle's vertical center, narrower toward the edges.
557
- const result: string[] = [];
558
- let lineIdx = 1; // start after label line
559
- for (const srcLine of descriptions) {
560
- const words = srcLine.split(/\s+/).filter((w) => w.length > 0);
561
- let current = '';
562
- for (const word of words) {
563
- // Compute available pixel width at this line's y position.
564
- const y = -blockH / 2 + (lineIdx + 0.5) * DESC_LINE_HEIGHT;
565
- const rSq = radius * radius;
566
- const availPx = Math.max(
567
- 20,
568
- y * y < rSq ? 2 * Math.sqrt(rSq - y * y) - CIRCLE_PAD * 2 : centerWidth
569
- );
570
-
571
- const test = current ? `${current} ${word}` : word;
572
- if (measureText(test, DESC_FONT_SIZE) > availPx && current) {
573
- result.push(current);
574
- lineIdx++;
575
- current = word;
576
- } else {
577
- current = test;
578
- }
579
- }
580
- if (current) {
581
- result.push(current);
582
- lineIdx++;
583
- }
584
- }
585
- return result;
586
- }
587
-
588
- // ── Circle-circle intersection exit angle ──
589
-
590
- /**
591
- * For a circular node of radius `nodeR` centered on the cycle circle of radius
592
- * `cycleR`, compute the angle where the cycle circle exits the node boundary.
593
- * Uses the law of cosines: the half-angle subtended at the cycle center is
594
- * arccos(1 - nodeR²/(2·cycleR²)).
595
- */
596
- function circleNodeExitAngle(
597
- nodeR: number,
598
- cycleR: number,
599
- nodeAngle: number,
600
- direction: number
601
- ): number {
602
- // Law of cosines in the triangle: cycle-center, node-center, intersection-point
603
- // sides: R (to intersection), R (to node center), nodeR (node center to intersection)
604
- // cos(α) = (R² + R² - nodeR²) / (2·R·R) = 1 - nodeR²/(2·R²)
605
- const cosAlpha = Math.max(
606
- -1,
607
- Math.min(1, 1 - (nodeR * nodeR) / (2 * cycleR * cycleR))
608
- );
609
- const halfAngle = Math.acos(cosAlpha);
610
- return nodeAngle + direction * halfAngle;
611
- }
612
-
613
- /** Is the point (px, py) inside the rect centered at (rx, ry) with half-dims (hw, hh)? */
614
- function insideRect(
615
- px: number,
616
- py: number,
617
- rx: number,
618
- ry: number,
619
- hw: number,
620
- hh: number
621
- ): boolean {
622
- return Math.abs(px - rx) < hw && Math.abs(py - ry) < hh;
623
- }
624
-
625
- /**
626
- * Find the exact angle where the circle exits the node rect boundary.
627
- * Uses coarse walk + binary search refinement for pixel-accurate results.
628
- */
629
- function circleRectExitAngle(
630
- nodeCx: number,
631
- nodeCy: number,
632
- halfW: number,
633
- halfH: number,
634
- circleCx: number,
635
- circleCy: number,
636
- radius: number,
637
- nodeAngle: number,
638
- direction: number // +1 or -1
639
- ): number {
640
- // Coarse walk to find the first angle outside the rect
641
- const steps = 90;
642
- const maxSweep = Math.PI;
643
- const step = maxSweep / steps;
644
- let insideAngle = nodeAngle;
645
- let outsideAngle = nodeAngle + direction * step;
646
-
647
- for (let i = 1; i <= steps; i++) {
648
- const angle = nodeAngle + direction * step * i;
649
- const px = circleCx + radius * Math.cos(angle);
650
- const py = circleCy + radius * Math.sin(angle);
651
- if (!insideRect(px, py, nodeCx, nodeCy, halfW, halfH)) {
652
- outsideAngle = angle;
653
- insideAngle = nodeAngle + direction * step * (i - 1);
654
- break;
655
- }
656
- }
657
-
658
- // Binary search between insideAngle and outsideAngle for exact boundary
659
- for (let i = 0; i < 16; i++) {
660
- const mid = (insideAngle + outsideAngle) / 2;
661
- const px = circleCx + radius * Math.cos(mid);
662
- const py = circleCy + radius * Math.sin(mid);
663
- if (insideRect(px, py, nodeCx, nodeCy, halfW, halfH)) {
664
- insideAngle = mid;
665
- } else {
666
- outsideAngle = mid;
667
- }
668
- }
669
-
670
- // Return the boundary crossing point (midpoint of final bracket)
671
- return (insideAngle + outsideAngle) / 2;
672
- }
673
-
674
- /** Compute edge paths for all edges in the parsed diagram. */
675
- function computeEdgePaths(
676
- layoutNodes: CycleLayoutNode[],
677
- parsed: ParsedCycle,
678
- cx: number,
679
- cy: number,
680
- radius: number,
681
- isClockwise: boolean
682
- ): CycleLayoutEdge[] {
683
- return parsed.edges.map((edge) => {
684
- // In-bounds: sourceIndex/targetIndex are validated by the parser to point into nodes.
685
- const src = layoutNodes[edge.sourceIndex]!;
686
- const tgt = layoutNodes[edge.targetIndex]!;
687
- const strokeWidth = Math.max(
688
- edge.width ?? DEFAULT_EDGE_WIDTH,
689
- MIN_EDGE_WIDTH
690
- );
691
- // Arrowhead effective reach: full length minus the 10% overlap that
692
- // slides the marker back to cover the stroke/arrowhead junction line.
693
- const arrowLen = arrowHeadLength(strokeWidth) * 0.9;
694
- const { path, midAngle } = buildEdgeArc(
695
- src,
696
- tgt,
697
- cx,
698
- cy,
699
- radius,
700
- isClockwise,
701
- arrowLen
702
- );
703
-
704
- // Smart label placement: scale offset with label size and pick whichever
705
- // side of the arc (outward toward canvas edge, inward toward center) has
706
- // the most clearance from node bounding boxes.
707
- const { labelLines, descLines } = wrapEdgeLabelText(
708
- edge.label,
709
- edge.description
710
- );
711
- const lineCount = labelLines.length + descLines.length;
712
- let labelPxW = 0;
713
- for (const l of labelLines)
714
- labelPxW = Math.max(labelPxW, measureText(l, EDGE_LABEL_FONT_SIZE));
715
- for (const l of descLines)
716
- labelPxW = Math.max(labelPxW, measureText(l, EDGE_LABEL_FONT_SIZE));
717
- const { labelX, labelY, labelAngle } = computeEdgeLabelPosition(
718
- midAngle,
719
- radius,
720
- cx,
721
- cy,
722
- lineCount,
723
- labelPxW,
724
- layoutNodes
725
- );
726
- const layoutEdge: CycleLayoutEdge = {
727
- sourceIndex: edge.sourceIndex,
728
- targetIndex: edge.targetIndex,
729
- path,
730
- labelX,
731
- labelY,
732
- labelAngle,
733
- ...(edge.label !== undefined && { label: edge.label }),
734
- };
735
- return layoutEdge;
736
- });
737
- }
738
-
739
- /**
740
- * Position an edge label so its inner corner (the corner of the text bbox
741
- * closest to the cycle center) sits exactly `EDGE_LABEL_CORNER_OFFSET`
742
- * pixels radially outward from the arc midpoint. The bbox extends from that
743
- * corner *away* from the cycle, into the empty quadrant between adjacent
744
- * nodes — so the label visibly belongs to the arrow, not to either node.
745
- *
746
- * For mostly-vertical arc midpoints (top/bottom of the cycle) the bbox is
747
- * centered horizontally on the radial axis. If the resulting placement still
748
- * overlaps a node, we flip to inward placement (corner toward center) and
749
- * adjust labelAngle so the renderer's text-anchor logic points text away
750
- * from the ring.
751
- */
752
- function computeEdgeLabelPosition(
753
- midAngle: number,
754
- radius: number,
755
- cx: number,
756
- cy: number,
757
- lineCount: number,
758
- labelPxW: number,
759
- layoutNodes: CycleLayoutNode[]
760
- ): { labelX: number; labelY: number; labelAngle: number } {
761
- if (lineCount === 0 || labelPxW === 0) {
762
- return {
763
- labelX: cx + radius * Math.cos(midAngle),
764
- labelY: cy + radius * Math.sin(midAngle),
765
- labelAngle: midAngle,
766
- };
767
- }
768
-
769
- const EDGE_LABEL_CORNER_OFFSET = 10;
770
- const labelW = labelPxW;
771
- const labelH = lineCount * 15;
772
- const cosT = Math.cos(midAngle);
773
- const sinT = Math.sin(midAngle);
774
-
775
- type Placement = {
776
- labelX: number;
777
- labelY: number;
778
- labelAngle: number;
779
- bbX1: number;
780
- bbX2: number;
781
- bbY1: number;
782
- bbY2: number;
783
- overlap: number;
784
- };
785
-
786
- function place(sign: 1 | -1): Placement {
787
- // Inner corner of bbox = arc midpoint M + sign * offset along radial.
788
- // sign=+1: bbox extends outward (corner inside the cycle, body outside).
789
- // sign=-1: bbox extends inward (corner outside the cycle, body toward
790
- // center) — used as fallback when outward overlaps a node.
791
- const cornerX = cx + (radius + sign * EDGE_LABEL_CORNER_OFFSET) * cosT;
792
- const cornerY = cy + (radius + sign * EDGE_LABEL_CORNER_OFFSET) * sinT;
793
-
794
- // Bbox extends from inner corner in the direction opposite the cycle
795
- // center (when sign=+1) or toward the center (sign=-1). Treated axis-
796
- // aligned: x extends in sign(cosT), y extends in sign(sinT), each scaled
797
- // by `sign`.
798
- const ROUND_THRESH = 0.3;
799
- const radialX = sign * cosT;
800
- const radialY = sign * sinT;
801
- const sx = Math.abs(radialX) < ROUND_THRESH ? 0 : Math.sign(radialX);
802
- const sy = Math.abs(radialY) < ROUND_THRESH ? 0 : Math.sign(radialY);
803
-
804
- const bboxCx = cornerX + (sx * labelW) / 2;
805
- const bboxCy = cornerY + (sy * labelH) / 2;
806
-
807
- // Map bbox sx → text-anchor: +1 right (start), -1 left (end), 0 middle.
808
- let labelX: number;
809
- if (sx > 0) labelX = bboxCx - labelW / 2;
810
- else if (sx < 0) labelX = bboxCx + labelW / 2;
811
- else labelX = bboxCx;
812
-
813
- // First-line baseline ≈ top of bbox + 12 (font ascent).
814
- const labelY = bboxCy - labelH / 2 + 12;
815
-
816
- const bbX1 = bboxCx - labelW / 2;
817
- const bbX2 = bboxCx + labelW / 2;
818
- const bbY1 = bboxCy - labelH / 2;
819
- const bbY2 = bboxCy + labelH / 2;
820
-
821
- let overlap = 0;
822
- for (const n of layoutNodes) {
823
- const nx1 = n.x - n.width / 2;
824
- const nx2 = n.x + n.width / 2;
825
- const ny1 = n.y - n.height / 2;
826
- const ny2 = n.y + n.height / 2;
827
- const ox = Math.max(0, Math.min(bbX2, nx2) - Math.max(bbX1, nx1));
828
- const oy = Math.max(0, Math.min(bbY2, ny2) - Math.max(bbY1, ny1));
829
- overlap += ox * oy;
830
- }
831
-
832
- // For inward placement, flip labelAngle by π so the renderer's anchor
833
- // logic (driven by labelAngle quadrant) picks an anchor consistent with
834
- // text growing toward the cycle center rather than away.
835
- const labelAngle = sign === 1 ? midAngle : midAngle + Math.PI;
836
- return { labelX, labelY, labelAngle, bbX1, bbX2, bbY1, bbY2, overlap };
837
- }
838
-
839
- const outward = place(1);
840
- if (outward.overlap === 0) {
841
- return {
842
- labelX: outward.labelX,
843
- labelY: outward.labelY,
844
- labelAngle: outward.labelAngle,
845
- };
846
- }
847
- const inward = place(-1);
848
- const best = inward.overlap < outward.overlap ? inward : outward;
849
- return {
850
- labelX: best.labelX,
851
- labelY: best.labelY,
852
- labelAngle: best.labelAngle,
853
- };
854
- }
855
-
856
- /**
857
- * Check if edge labels overflow the canvas and return a reduced radius if needed.
858
- * Returns null if everything fits.
859
- */
860
- function fitToCanvas(
861
- nodes: CycleLayoutNode[],
862
- edges: CycleLayoutEdge[],
863
- parsed: ParsedCycle,
864
- _cx: number,
865
- _cy: number,
866
- radius: number,
867
- width: number,
868
- height: number,
869
- _isClockwise: boolean
870
- ): { radius: number } | null {
871
- const PADDING = 30;
872
- let contentMinX = Infinity,
873
- contentMaxX = -Infinity;
874
- let contentMinY = Infinity,
875
- contentMaxY = -Infinity;
876
-
877
- // Node extents
878
- for (const n of nodes) {
879
- contentMinX = Math.min(contentMinX, n.x - n.width / 2);
880
- contentMaxX = Math.max(contentMaxX, n.x + n.width / 2);
881
- contentMinY = Math.min(contentMinY, n.y - n.height / 2);
882
- contentMaxY = Math.max(contentMaxY, n.y + n.height / 2);
883
- }
884
-
885
- // Edge label extents (estimate text width from character count, accounting
886
- // for line-wrapping that the renderer will apply to long edge labels).
887
- for (let i = 0; i < edges.length; i++) {
888
- // In-bounds by loop guard; edges and parsed.edges are parallel arrays.
889
- const le = edges[i]!;
890
- const edge = parsed.edges[i]!;
891
-
892
- const { labelLines, descLines } = wrapEdgeLabelText(
893
- le.label,
894
- edge.description
895
- );
896
- let textWidth = 0;
897
- for (const l of labelLines)
898
- textWidth = Math.max(textWidth, measureText(l, EDGE_LABEL_FONT_SIZE));
899
- for (const l of descLines)
900
- textWidth = Math.max(textWidth, measureText(l, EDGE_LABEL_FONT_SIZE));
901
- if (textWidth === 0) continue;
902
-
903
- // Determine text-anchor direction from label angle (mirrors renderer logic)
904
- const normAngle =
905
- ((le.labelAngle % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
906
- const isRight = normAngle < Math.PI * 0.4 || normAngle > Math.PI * 1.6;
907
- const isLeft = normAngle > Math.PI * 0.6 && normAngle < Math.PI * 1.4;
908
-
909
- let labelLeft: number, labelRight: number;
910
- if (isRight) {
911
- labelLeft = le.labelX;
912
- labelRight = le.labelX + textWidth;
913
- } else if (isLeft) {
914
- labelLeft = le.labelX - textWidth;
915
- labelRight = le.labelX;
916
- } else {
917
- labelLeft = le.labelX - textWidth / 2;
918
- labelRight = le.labelX + textWidth / 2;
919
- }
920
-
921
- contentMinX = Math.min(contentMinX, labelLeft);
922
- contentMaxX = Math.max(contentMaxX, labelRight);
923
-
924
- // Vertical: account for wrapped label + description line counts
925
- const lineCount = labelLines.length + descLines.length;
926
- contentMinY = Math.min(contentMinY, le.labelY - 12);
927
- contentMaxY = Math.max(contentMaxY, le.labelY + (lineCount - 1) * 15);
928
- }
929
-
930
- // Check overflow
931
- const overflowX =
932
- Math.max(0, PADDING - contentMinX) +
933
- Math.max(0, contentMaxX - (width - PADDING));
934
- const overflowY =
935
- Math.max(0, PADDING - contentMinY) +
936
- Math.max(0, contentMaxY - (height - PADDING));
937
-
938
- if (overflowX <= 0 && overflowY <= 0) return null;
939
-
940
- // Shrink radius proportionally to eliminate overflow
941
- const contentW = contentMaxX - contentMinX;
942
- const contentH = contentMaxY - contentMinY;
943
- const availW = width - 2 * PADDING;
944
- const availH = height - 2 * PADDING;
945
- const shrink = Math.min(availW / contentW, availH / contentH);
946
- const newRadius = Math.max(80, radius * shrink);
947
-
948
- return { radius: newRadius };
949
- }
950
-
951
- /**
952
- * Build an SVG arc path that follows the circle circumference between two nodes.
953
- * Uses SVG `A` (arc) command so the edge traces the actual circle, not a chord.
954
- * Start/end points are computed as the exact intersection of the circle with
955
- * each node's boundary (rect or circle) — no gaps.
956
- */
957
- function buildEdgeArc(
958
- src: CycleLayoutNode,
959
- tgt: CycleLayoutNode,
960
- cx: number,
961
- cy: number,
962
- radius: number,
963
- isClockwise: boolean,
964
- arrowLength: number = 0
965
- ): { path: string; midAngle: number } {
966
- const dir = isClockwise ? 1 : -1;
967
-
968
- // Path starts at source center (covered by source node), but the *visible*
969
- // arrow starts where the ring exits the source's boundary. Compute both:
970
- // the path's startAngle for SVG, and srcExitAngle for the visible midpoint.
971
- const startAngle = src.angle;
972
- const srcExitAngle = src.isCircle
973
- ? circleNodeExitAngle(src.width / 2, radius, src.angle, dir)
974
- : circleRectExitAngle(
975
- src.x,
976
- src.y,
977
- src.width / 2,
978
- src.height / 2,
979
- cx,
980
- cy,
981
- radius,
982
- src.angle,
983
- dir
984
- );
985
-
986
- // Where the cycle circle enters the target node (visible end of arrow).
987
- const nodeEndAngle = tgt.isCircle
988
- ? circleNodeExitAngle(tgt.width / 2, radius, tgt.angle, -dir)
989
- : circleRectExitAngle(
990
- tgt.x,
991
- tgt.y,
992
- tgt.width / 2,
993
- tgt.height / 2,
994
- cx,
995
- cy,
996
- radius,
997
- tgt.angle,
998
- -dir
999
- );
1000
-
1001
- // Pull back the path endpoint by the arrowhead length so the stroke
1002
- // stops at the arrow base.
1003
- const arrowPullback = arrowLength > 0 ? arrowLength / radius : 0;
1004
- const endAngle = nodeEndAngle - dir * arrowPullback;
1005
-
1006
- const startX = cx + radius * Math.cos(startAngle);
1007
- const startY = cy + radius * Math.sin(startAngle);
1008
- const endX = cx + radius * Math.cos(endAngle);
1009
- const endY = cy + radius * Math.sin(endAngle);
1010
-
1011
- let effectiveSweep = (endAngle - startAngle) * dir;
1012
- if (effectiveSweep <= 0) effectiveSweep += 2 * Math.PI;
1013
-
1014
- const largeArc = effectiveSweep > Math.PI ? 1 : 0;
1015
- const sweepFlag = isClockwise ? 1 : 0;
1016
-
1017
- const path = `M ${startX} ${startY} A ${radius} ${radius} 0 ${largeArc} ${sweepFlag} ${endX} ${endY}`;
1018
-
1019
- // Visible-arrow midpoint: between where the ring leaves the source rectangle
1020
- // and where it enters the target rectangle (after arrow pullback). For
1021
- // asymmetric nodes this differs noticeably from the geometric path midpoint.
1022
- let visibleSweep = (nodeEndAngle - srcExitAngle) * dir;
1023
- if (visibleSweep <= 0) visibleSweep += 2 * Math.PI;
1024
- const midAngle = srcExitAngle + (dir * visibleSweep) / 2;
1025
- return { path, midAngle };
1026
- }