@diagrammo/dgmo 0.33.0 → 0.35.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 (59) hide show
  1. package/.claude/commands/dgmo.md +17 -32
  2. package/.github/copilot-instructions.md +1 -1
  3. package/README.md +7 -1
  4. package/SKILL.md +1 -1
  5. package/dist/advanced.cjs +791 -614
  6. package/dist/advanced.d.cts +8 -51
  7. package/dist/advanced.d.ts +8 -51
  8. package/dist/advanced.js +791 -615
  9. package/dist/auto.cjs +793 -292
  10. package/dist/auto.js +95 -95
  11. package/dist/auto.mjs +793 -292
  12. package/dist/cli.cjs +145 -328
  13. package/dist/index.cjs +792 -291
  14. package/dist/index.js +792 -291
  15. package/docs/ai-integration.md +46 -26
  16. package/docs/language-reference.md +2 -2
  17. package/package.json +3 -3
  18. package/src/advanced.ts +0 -12
  19. package/src/boxes-and-lines/label-placement.ts +339 -0
  20. package/src/boxes-and-lines/layout-search.ts +16 -2
  21. package/src/boxes-and-lines/layout.ts +32 -7
  22. package/src/boxes-and-lines/renderer.ts +67 -139
  23. package/src/c4/parser.ts +15 -6
  24. package/src/chart.ts +1 -1
  25. package/src/class/parser.ts +6 -2
  26. package/src/cli-banner.ts +2 -3
  27. package/src/cli.ts +539 -1223
  28. package/src/cycle/parser.ts +4 -1
  29. package/src/dgmo-router.ts +16 -2
  30. package/src/diagnostics.ts +0 -0
  31. package/src/echarts.ts +5 -1
  32. package/src/er/parser.ts +5 -1
  33. package/src/gantt/parser.ts +13 -4
  34. package/src/graph/flowchart-parser.ts +5 -1
  35. package/src/graph/state-parser.ts +5 -1
  36. package/src/infra/parser.ts +10 -6
  37. package/src/journey-map/parser.ts +5 -2
  38. package/src/kanban/parser.ts +6 -2
  39. package/src/map/context-labels.ts +29 -19
  40. package/src/map/layout.ts +403 -108
  41. package/src/map/legend-band.ts +28 -0
  42. package/src/map/parser.ts +13 -4
  43. package/src/map/renderer.ts +74 -23
  44. package/src/map/resolver.ts +2 -2
  45. package/src/org/parser.ts +8 -2
  46. package/src/pyramid/parser.ts +4 -1
  47. package/src/raci/parser.ts +4 -1
  48. package/src/ring/parser.ts +4 -1
  49. package/src/sequence/parser.ts +6 -3
  50. package/src/sitemap/parser.ts +12 -3
  51. package/src/tech-radar/parser.ts +6 -3
  52. package/src/utils/parsing.ts +2 -2
  53. package/src/utils/tag-groups.ts +3 -3
  54. package/src/visualizations/parse.ts +9 -3
  55. package/src/migrate/data-comma.ts +0 -117
  56. package/src/migrate/embedded.ts +0 -238
  57. package/src/migrate/index.ts +0 -295
  58. package/src/migrate/line-classifier.ts +0 -128
  59. package/src/migrate/line-transformer.ts +0 -218
@@ -4,44 +4,56 @@ Use AI coding tools to generate `.dgmo` diagrams. This guide covers Claude Code,
4
4
 
5
5
  ---
6
6
 
7
- ## MCP Server (recommended for Claude)
7
+ ## One-step setup (recommended)
8
8
 
9
- `@diagrammo/dgmo-mcp` provides an MCP server that gives Claude the ability to render, share, and look up DGMO diagrams directly — no file management needed.
9
+ Install the `dgmo` CLI, then run one command:
10
10
 
11
- **5 tools:** `render_diagram`, `share_diagram`, `open_in_app`, `list_chart_types`, `get_language_reference`
11
+ ```bash
12
+ brew install diagrammo/dgmo/dgmo # or: npm install -g @diagrammo/dgmo
13
+ dgmo install # auto-detects every AI assistant you have
14
+ ```
12
15
 
13
- Add to `~/.claude/settings.json` (global) or `.claude/settings.local.json` (project):
16
+ `dgmo install` with **no target** scans for Claude Code, Codex, Claude Desktop, Cursor, Windsurf, and Copilot, then configures each one non-interactively — no prompts, no second package to install. The only binary you ever need is `dgmo`; it provides the MCP server through its own `dgmo mcp` subcommand.
14
17
 
15
- ```json
16
- {
17
- "mcpServers": {
18
- "dgmo": {
19
- "command": "npx",
20
- "args": ["-y", "@diagrammo/dgmo-mcp"]
21
- }
22
- }
23
- }
18
+ Target a single assistant, or pick a scope, when you want to:
19
+
20
+ ```bash
21
+ dgmo install claude-code # just one surface
22
+ dgmo install codex --scope project # write config into the current repo
23
+ dgmo install --dry-run # preview every change, write nothing
24
24
  ```
25
25
 
26
- See `dgmo-mcp/README.md` for full configuration options.
26
+ For Claude Code this copies the `/dgmo` skill into `~/.claude/commands/` (full dgmo context — all chart types, CLI flags, workflow, and tips) and adds the MCP server to `~/.claude/settings.json`. Restart the assistant afterward.
27
+
28
+ **Keeping it current:**
29
+ - **Homebrew** bundles the MCP server, so `brew upgrade dgmo` upgrades the CLI *and* the server together. Re-run `dgmo install` afterward only to refresh the **skill files** (those are copies in your home dir).
30
+ - **npm global**: a plain `dgmo` upgrade doesn't touch the server or skill copies — re-run `dgmo install`, which overwrites the skills and upgrades the server to the latest.
31
+ - Either way, `DGMO_MCP_LATEST=1` in the environment makes `dgmo mcp` always fetch the newest server at launch (network round-trip on start), so it's never stale.
27
32
 
28
33
  ---
29
34
 
30
- ## Claude Code — Skill (slash command)
35
+ ## Manual MCP configuration
31
36
 
32
- Installs a `/dgmo` slash command that gives Claude full dgmo context — all chart types, CLI flags, workflow, and tips.
37
+ `dgmo install` is the easy path. To wire the MCP server by hand, point any MCP client at the `dgmo` binary's `mcp` subcommand:
33
38
 
34
- ```bash
35
- dgmo --install-claude-skill
39
+ ```json
40
+ {
41
+ "mcpServers": {
42
+ "dgmo": {
43
+ "command": "dgmo",
44
+ "args": ["mcp"]
45
+ }
46
+ }
47
+ }
36
48
  ```
37
49
 
38
- This copies a skill file into `~/.claude/commands/`, making `/dgmo` available in every Claude Code session.
50
+ **5 tools:** `render_diagram`, `share_diagram`, `open_in_app`, `list_chart_types`, `get_language_reference`. `dgmo mcp` execs the installed server, or fetches it on demand via `npx` if it isn't installed yet — so no separate `dgmo-mcp` step is required. (If you'd rather not install the CLI at all, `{ "command": "npx", "args": ["-y", "@diagrammo/dgmo-mcp"] }` still works.) See `dgmo-mcp/README.md` for full options.
39
51
 
40
52
  ---
41
53
 
42
54
  ## Claude Code — CLAUDE.md snippet
43
55
 
44
- To teach Claude about DGMO in a specific project without the global skill, paste the generated core below into your `CLAUDE.md`. It is the same single-sourced anti-patterns + 45-type index that every DGMO AI surface carries (see "How the AI core is generated"). Render with `dgmo file.dgmo` (PNG) or `dgmo file.dgmo -o url` (shareable link); full per-type syntax lives in `node_modules/@diagrammo/dgmo/docs/language-reference.md`.
56
+ To teach Claude about DGMO in a specific project without the global skill, paste the generated core below into your `CLAUDE.md`. It is the same single-sourced anti-patterns + 45-type index that every DGMO AI surface carries (see "How the AI core is generated"). Render with `dgmo file.dgmo` (PNG) or `dgmo share file.dgmo` (shareable link); full per-type syntax lives in `node_modules/@diagrammo/dgmo/docs/language-reference.md`.
45
57
 
46
58
  <!-- GENERATED by dgmo/scripts/gen-ai-core.mjs from docs/language-reference.md — DO NOT EDIT between the DGMO-AI-CORE markers; run `node scripts/gen-ai-core.mjs` (or sync-language-ref.sh) to regenerate. -->
47
59
  <!-- DGMO-AI-CORE:START -->
@@ -477,7 +489,15 @@ DGMO ships context files for popular AI coding tools, included in the npm packag
477
489
  | `.cursorrules` | Cursor | Auto-loaded when present in project root |
478
490
  | `.windsurfrules` | Windsurf | Auto-loaded when present in project root (byte-identical to `.cursorrules`) |
479
491
 
480
- Copy the relevant file into your project root:
492
+ The easiest way to set these up is `dgmo install` — it does the right thing per tool:
493
+
494
+ ```bash
495
+ dgmo install cursor # wires MCP (~/.cursor/mcp.json) + drops .cursorrules
496
+ dgmo install windsurf # wires MCP (~/.codeium/windsurf/mcp_config.json) + .windsurfrules
497
+ dgmo install copilot # writes ./.github/copilot-instructions.md (Copilot has no MCP)
498
+ ```
499
+
500
+ Cursor and Windsurf speak MCP, so `dgmo install` gives them the full render/share tools (pointed at `dgmo mcp`), plus the inline rules file. Copilot is guidance-only. `dgmo install` with no target also writes Copilot's file automatically when the current repo has a `.github` directory. To set the context files up by hand instead:
481
501
 
482
502
  ```bash
483
503
  # From node_modules (if installed as a dependency)
@@ -510,14 +530,14 @@ Regeneration runs inside `sync-language-ref.sh`; a Vitest gate parses every emit
510
530
  ```bash
511
531
  dgmo diagram.dgmo # PNG output
512
532
  dgmo diagram.dgmo -o output.svg # SVG output
513
- dgmo diagram.dgmo -o url # Shareable diagrammo.app URL
514
- dgmo diagram.dgmo -o url --copy # URL copied to clipboard
515
- dgmo --chart-types # List all supported chart types
516
- dgmo --chart-types --json # Machine-readable chart type list
533
+ dgmo share diagram.dgmo # Shareable diagrammo.app URL (copied to clipboard)
534
+ dgmo share diagram.dgmo --no-copy # Print URL without touching the clipboard
535
+ dgmo types # List all supported chart types
536
+ dgmo types --json # Machine-readable chart type list
517
537
  ```
518
538
 
519
539
  ---
520
540
 
521
541
  ## Supported chart types
522
542
 
523
- Run `dgmo --chart-types` for the full, authoritative list, call the MCP `list_chart_types` tool, or see the 45-type index in `docs/language-reference.md` (§0 AI Core). The list is intentionally not duplicated here — it drifts every time a chart type is added.
543
+ Run `dgmo types` for the full, authoritative list, call the MCP `list_chart_types` tool, or see the 45-type index in `docs/language-reference.md` (§0 AI Core). The list is intentionally not duplicated here — it drifts every time a chart type is added.
@@ -3188,7 +3188,7 @@ Markers in cells are always **rendered in canonical alphabet order** (`R A C I`,
3188
3188
  <!-- TYPE:map -->
3189
3189
 
3190
3190
  <!-- TIPS start -->
3191
- **Styling tips:** the zero-config map already looks good — name places and stop. When POIs fall into categories, tag them so each category gets its own color; keep place labels to the place name; leave region colorize and coastlines on unless the user asks to hide them. **For flights and airport routes, use IATA codes, not city names** — `LHR ~> JFK`, `LHR ~> DXB`, `LHR ~> SIN`, `LHR ~> HND` — the bundled airport set (large international hubs + all US commercial airports) resolves them to the right coordinates and labels them with the code. **For cities, use the exact canonical name**: "New York City" (NOT "New York"), "Washington, D.C.", etc. — a name the gazetteer doesn't have **silently drops that point** and the map just reframes around the rest, so it looks fine but is wrong. When unsure of the exact token, look it up: `dgmo map search "<place>"` (or the `lookup_map_location` MCP tool) returns the city name or airport code to paste; fall back to coordinates (`poi Name as 40.71,-74.0`) for anything not found. **For routes/flows from a hub** (an airport's daily flights, a distribution center's shipments), write ONE edge per line and repeat the origin — never indented edges (those error). Use **arcs** (`~>`) for flights and long-haul links so the spokes separate; the connector label carries the relationship (`~daily~>`, `~2x daily~>`). Endpoints auto-create POIs, so don't add separate `poi` lines for places already in an edge. Reach for a `route` block only when the trip is an **ordered voyage** that continues stop→stop (a cruise itinerary), not a set of independent routes from one origin.
3191
+ **Styling tips:** the zero-config map already looks good — name places and stop. When POIs fall into categories, tag them so each category gets its own color; keep place labels to the place name; leave region colorize and coastlines on unless the user asks to hide them. **For flights and airport routes, use IATA codes, not city names** — `LHR ~> JFK`, `LHR ~> DXB`, `LHR ~> SIN`, `LHR ~> HND` — the bundled airport set (large international hubs + all US commercial airports) resolves them to the right coordinates and labels them with the code. **For cities, use the exact canonical name**: "New York City" (NOT "New York"), "Washington, D.C.", etc. — a name the gazetteer doesn't have **silently drops that point** and the map just reframes around the rest, so it looks fine but is wrong. When unsure of the exact token, look it up: `dgmo map-search "<place>"` (or the `lookup_map_location` MCP tool) returns the city name or airport code to paste; fall back to coordinates (`poi Name as 40.71,-74.0`) for anything not found. **For routes/flows from a hub** (an airport's daily flights, a distribution center's shipments), write ONE edge per line and repeat the origin — never indented edges (those error). Use **arcs** (`~>`) for flights and long-haul links so the spokes separate; the connector label carries the relationship (`~daily~>`, `~2x daily~>`). Endpoints auto-create POIs, so don't add separate `poi` lines for places already in an edge. Reach for a `route` block only when the trip is an **ordered voyage** that continues stop→stop (a cruise itinerary), not a set of independent routes from one origin.
3192
3192
  <!-- TIPS end -->
3193
3193
 
3194
3194
  Geographic concept maps: highlight/shade political subdivisions, drop points of interest (POIs), and connect them with routes or edges. For "share a concept" business maps, not cartography. Renders at a fixed, auto-fit position — no pan/zoom. Basemap and viewport are **inferred from the content you reference** — most maps need no directives. v1 boundaries: world countries + US states.
@@ -3332,7 +3332,7 @@ cove -> hav l: March # the LINE turns green
3332
3332
  - The redundant `Georgia US-GA` still works but isn't needed (a mismatched code like `Georgia US-CA` is rejected). A bare ambiguous `Georgia` follows the inferred US-scope signal and warns with both fixes named.
3333
3333
  - **IATA airport codes** resolve to airport coordinates — `poi JFK`, `route JFK -> LAX` — with no new syntax (large international hubs + all US scheduled-commercial airports). Case-insensitive (`jfk`/`JFK`). Airports are the **lowest-precedence** identifier: a token that is both a city and a code resolves to the **city** (`Ufa` → the city, not UFA airport), with a hint naming the airport. Resolution is by **code only** (never by airport name); the POI label is the typed code. An unknown three-letter code errors with an `as <CODE>` coordinates hint.
3334
3334
  - **A city name must match the gazetteer's canonical form** — `New York City`, not `New York`; `Washington, D.C.`, not `Washington`. An unrecognized name is dropped (with a did-you-mean note) and the map reframes around the places that *did* resolve, so the result can look complete but be missing a point. Use the exact name or coordinates.
3335
- - **Discover the exact token** with the lookup surface rather than guessing — `dgmo map search "<place>"` (CLI; `--json` for machine output) or the `lookup_map_location` MCP tool. It substring-searches cities **and** the bundled airports and returns the precise token to paste (e.g. `york` → `New York City`; `heathrow` → `LHR`). There is intentionally **no exhaustive printed list** — the gazetteer holds thousands of cities plus ~1,500 airports; search is the interface.
3335
+ - **Discover the exact token** with the lookup surface rather than guessing — `dgmo map-search "<place>"` (CLI; `--json` for machine output) or the `lookup_map_location` MCP tool. It substring-searches cities **and** the bundled airports and returns the precise token to paste (e.g. `york` → `New York City`; `heathrow` → `LHR`). There is intentionally **no exhaustive printed list** — the gazetteer holds thousands of cities plus ~1,500 airports; search is the interface.
3336
3336
  - Positional coordinates are the escape hatch for anything missing/ambiguous (including forcing an airport over a colliding city: `poi 54.56 55.87 as UFA`).
3337
3337
 
3338
3338
  ### Directives & reserved keys
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagrammo/dgmo",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "DGMO diagram markup language — parser, renderer, and color system",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -134,13 +134,13 @@
134
134
  "check:deadcode": "knip",
135
135
  "check:spelling": "cspell \"src/**/*.ts\" \"tests/**/*.ts\"",
136
136
  "check:all": "pnpm check:deadcode && pnpm check:spelling && pnpm check:duplication && pnpm check:circular && pnpm check:deps && pnpm check:security && pnpm build && bash scripts/check-api.sh check && pnpm check:publish && pnpm check:types",
137
- "check:circular": "madge --circular --extensions ts src/ --json | node -e \"const c=JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')); const n=c.length; if(n>6){console.error('New circular deps found ('+n+' > 6 known type-only/dynamic cycles)');process.exit(1)}else if(n>0){console.log(n+' known type-only/dynamic cycles (safe)')}else{console.log('No circular dependencies')}\"",
137
+ "check:circular": "madge --circular --extensions ts src/ --json | node -e \"const c=JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')); const n=c.length; if(n>7){console.error('New circular deps found ('+n+' > 7 known type-only/dynamic cycles)');process.exit(1)}else if(n>0){console.log(n+' known type-only/dynamic cycles (safe)')}else{console.log('No circular dependencies')}\"",
138
138
  "check:deps": "depcheck --ignores='@diagrammo/dgmo,@codemirror/language,@lezer/*,husky,lint-staged,tsup,axe-core,type-coverage'",
139
139
  "check:security": "pnpm audit --prod",
140
140
  "check:publish": "publint",
141
141
  "check:size": "pnpm build && du -sh dist/ && echo '---' && ls -lh dist/*.js dist/*.cjs",
142
142
  "check:types": "attw --pack . --ignore-rules no-resolution false-export-default",
143
- "postinstall": "node -e \"console.log('\\n💡 Claude Code user? Run: dgmo --install-claude-skill\\n')\"",
143
+ "postinstall": "node -e \"console.log('\\n💡 Claude Code user? Run: dgmo install claude-code\\n')\"",
144
144
  "prepare": "husky"
145
145
  },
146
146
  "dependencies": {
package/src/advanced.ts CHANGED
@@ -797,15 +797,3 @@ export { themes, type Theme } from './themes';
797
797
 
798
798
  // Public-API alias for parseDgmo (also exported from the public root as `validate`)
799
799
  export { parseDgmo as validate } from './dgmo-router';
800
-
801
- // `dgmo migrate` — programmatic access to the 0.18.0 legacy `|` → §1.4
802
- // migration. Consumed by `@diagrammo/dgmo-mcp`'s `migrate_diagram` tool
803
- // and by external authoring tools that want to offer in-place migration.
804
- export {
805
- migrateContent,
806
- formatLineDiff,
807
- isLegacyMetadataLine,
808
- findUnsafePipePositions,
809
- transformLine,
810
- } from './migrate';
811
- export type { ContentMigration, TransformResult } from './migrate';
@@ -0,0 +1,339 @@
1
+ // ============================================================
2
+ // Boxes and Lines Diagram — Edge label placement
3
+ // ============================================================
4
+ //
5
+ // Makes edge/arrow labels legible regardless of length or layout via a priority
6
+ // ladder (each step only fires when the previous can't make the label legible):
7
+ //
8
+ // 1. WRAP — cap label width and wrap onto up to MAX_LABEL_LINES lines.
9
+ // 2. MOVE — if the wrapped box still overlaps a node box, slide it to a clear
10
+ // spot near its own line (along the polyline, then a small
11
+ // perpendicular offset), staying proximal. No leader line.
12
+ // 3. RELAYOUT (last resort, owned by layout.ts) — re-run the search reserving
13
+ // dagre label space so a gap opens; this module only reports which
14
+ // labels stayed unresolved so the caller can decide to escalate.
15
+ //
16
+ // Placement runs in layout (not the renderer) so it sees node/group boxes and so
17
+ // the relayout decision can re-invoke the search. The renderer is a pure consumer
18
+ // of the labelX/labelY/labelWidth/labelHeight/labelLines fields written here.
19
+
20
+ import type { BLLayoutResult } from './layout';
21
+ import {
22
+ measureText,
23
+ wrapTextToWidth,
24
+ truncateText,
25
+ } from '../utils/text-measure';
26
+
27
+ // Keep in sync with EDGE_LABEL_FONT_SIZE in renderer.ts (ScaleContext is identity
28
+ // there, so layout-space px == screen px for the unscaled diagram coords).
29
+ export const EDGE_LABEL_FONT_SIZE = 11;
30
+
31
+ const LABEL_MAX_WIDTH = 160; // ≈ DESC_NODE_WIDTH + slack; flat (not canvas-relative)
32
+ const MAX_LABEL_LINES = 3;
33
+ const LABEL_LINE_HEIGHT = 1.3;
34
+ const H_PAD = 6; // horizontal halo padding (each side)
35
+ const V_PAD = 3; // vertical halo padding (each side)
36
+ const BOX_CLEAR_PAD = 4; // min clearance kept between a label box and a node box
37
+ const PERP_STEP = 8; // perpendicular offset increment (px)
38
+ const PERP_MAX = 40; // max perpendicular offset before giving up
39
+ const SLIDE_SAMPLES = 9; // arc-length samples per side when sliding along the edge
40
+
41
+ type Pt = { readonly x: number; readonly y: number };
42
+
43
+ interface Rect {
44
+ readonly minX: number;
45
+ readonly minY: number;
46
+ readonly maxX: number;
47
+ readonly maxY: number;
48
+ }
49
+
50
+ export interface MeasuredLabel {
51
+ readonly lines: readonly string[];
52
+ /** Halo box width, including 2·H_PAD. */
53
+ readonly width: number;
54
+ /** Halo box height, including 2·V_PAD. */
55
+ readonly height: number;
56
+ }
57
+
58
+ /**
59
+ * Wrap + measure an edge label into a bounded multi-line box. Long unbreakable
60
+ * tokens are hard-broken at the char boundary; overflow past MAX_LABEL_LINES is
61
+ * ellipsized so the box is bounded in both axes.
62
+ */
63
+ export function measureEdgeLabel(
64
+ label: string,
65
+ fontSize: number = EDGE_LABEL_FONT_SIZE,
66
+ maxWidth: number = LABEL_MAX_WIDTH
67
+ ): MeasuredLabel {
68
+ let lines = wrapTextToWidth(label, fontSize, maxWidth, { hardBreak: true });
69
+ if (lines.length > MAX_LABEL_LINES) {
70
+ const kept = lines.slice(0, MAX_LABEL_LINES - 1);
71
+ const rest = lines.slice(MAX_LABEL_LINES - 1).join(' ');
72
+ kept.push(truncateText(rest, fontSize, maxWidth));
73
+ lines = kept;
74
+ }
75
+ let textW = 0;
76
+ for (const ln of lines) {
77
+ const w = measureText(ln, fontSize);
78
+ if (w > textW) textW = w;
79
+ }
80
+ return {
81
+ lines,
82
+ width: textW + 2 * H_PAD,
83
+ height: lines.length * fontSize * LABEL_LINE_HEIGHT + 2 * V_PAD,
84
+ };
85
+ }
86
+
87
+ /** Point at the half-way arc length along an edge polyline — the geometric
88
+ * centre of the connector, so a label seeds in the gap BETWEEN the two nodes
89
+ * rather than drifting under the target. Degenerate point lists fall back. */
90
+ export function edgePolylineMidpoint(points: ReadonlyArray<Pt>): Pt {
91
+ return pointAtArcFraction(points, 0.5).p;
92
+ }
93
+
94
+ /** Position + unit normal at arc-length fraction t∈[0,1] of a polyline. The
95
+ * normal is perpendicular to the local segment (for proximal perp offsets). */
96
+ function pointAtArcFraction(
97
+ points: ReadonlyArray<Pt>,
98
+ t: number
99
+ ): { p: Pt; nx: number; ny: number } {
100
+ if (points.length === 0) return { p: { x: 0, y: 0 }, nx: 0, ny: 1 };
101
+ if (points.length === 1)
102
+ return { p: { x: points[0]!.x, y: points[0]!.y }, nx: 0, ny: 1 };
103
+ const segLen: number[] = [];
104
+ let total = 0;
105
+ for (let k = 1; k < points.length; k++) {
106
+ const len = Math.hypot(
107
+ points[k]!.x - points[k - 1]!.x,
108
+ points[k]!.y - points[k - 1]!.y
109
+ );
110
+ segLen.push(len);
111
+ total += len;
112
+ }
113
+ let want = total * Math.max(0, Math.min(1, t));
114
+ for (let k = 1; k < points.length; k++) {
115
+ const len = segLen[k - 1]!;
116
+ if (want <= len || k === points.length - 1) {
117
+ const f = len === 0 ? 0 : Math.min(1, want / len);
118
+ const ax = points[k - 1]!.x;
119
+ const ay = points[k - 1]!.y;
120
+ const bx = points[k]!.x;
121
+ const by = points[k]!.y;
122
+ const dx = bx - ax;
123
+ const dy = by - ay;
124
+ const dlen = Math.hypot(dx, dy) || 1;
125
+ // Unit normal = perpendicular to the local tangent.
126
+ return {
127
+ p: { x: ax + dx * f, y: ay + dy * f },
128
+ nx: -dy / dlen,
129
+ ny: dx / dlen,
130
+ };
131
+ }
132
+ want -= len;
133
+ }
134
+ const last = points[points.length - 1]!;
135
+ return { p: { x: last.x, y: last.y }, nx: 0, ny: 1 };
136
+ }
137
+
138
+ function rectFromCenter(cx: number, cy: number, w: number, h: number): Rect {
139
+ return {
140
+ minX: cx - w / 2,
141
+ minY: cy - h / 2,
142
+ maxX: cx + w / 2,
143
+ maxY: cy + h / 2,
144
+ };
145
+ }
146
+
147
+ /** Does a label box centred at (cx,cy) overlap any obstacle (within pad)? */
148
+ function overlapsAny(
149
+ cx: number,
150
+ cy: number,
151
+ w: number,
152
+ h: number,
153
+ obstacles: readonly Rect[],
154
+ pad: number
155
+ ): boolean {
156
+ const minX = cx - w / 2 - pad;
157
+ const minY = cy - h / 2 - pad;
158
+ const maxX = cx + w / 2 + pad;
159
+ const maxY = cy + h / 2 + pad;
160
+ for (const o of obstacles) {
161
+ if (minX < o.maxX && maxX > o.minX && minY < o.maxY && maxY > o.minY)
162
+ return true;
163
+ }
164
+ return false;
165
+ }
166
+
167
+ /** Arc-length fractions sampled centre-outward (keeps the label proximal to the
168
+ * true midpoint), clamped away from the endpoints. */
169
+ function slideFractions(): number[] {
170
+ const out = [0.5];
171
+ for (let k = 1; k <= SLIDE_SAMPLES; k++) {
172
+ const off = k * 0.08;
173
+ if (0.5 - off >= 0.12) out.push(0.5 - off);
174
+ if (0.5 + off <= 0.88) out.push(0.5 + off);
175
+ }
176
+ return out;
177
+ }
178
+
179
+ /** Find the nearest clear centre for a label box of (w,h) along/near `points`.
180
+ * Pass 1 slides along the line; pass 2 offsets perpendicular. null = no clear
181
+ * spot found within the proximity budget. */
182
+ function findClearPosition(
183
+ w: number,
184
+ h: number,
185
+ points: ReadonlyArray<Pt>,
186
+ obstacles: readonly Rect[]
187
+ ): Pt | null {
188
+ const ts = slideFractions();
189
+ for (const t of ts) {
190
+ const { p } = pointAtArcFraction(points, t);
191
+ if (!overlapsAny(p.x, p.y, w, h, obstacles, BOX_CLEAR_PAD)) return p;
192
+ }
193
+ for (let mag = PERP_STEP; mag <= PERP_MAX; mag += PERP_STEP) {
194
+ for (const t of ts) {
195
+ const { p, nx, ny } = pointAtArcFraction(points, t);
196
+ for (const sign of [-1, 1]) {
197
+ const x = p.x + nx * mag * sign;
198
+ const y = p.y + ny * mag * sign;
199
+ if (!overlapsAny(x, y, w, h, obstacles, BOX_CLEAR_PAD)) return { x, y };
200
+ }
201
+ }
202
+ }
203
+ return null;
204
+ }
205
+
206
+ interface LabelBox {
207
+ edgeIdx: number;
208
+ cx: number;
209
+ cy: number;
210
+ w: number;
211
+ h: number;
212
+ lines: readonly string[];
213
+ resolved: boolean;
214
+ }
215
+
216
+ /** Separate overlapping label boxes vertically (variable sizes), mirroring the
217
+ * old renderer pass. Runs after node-collision resolution; the caller re-checks
218
+ * node overlap afterwards. */
219
+ function resolveLabelOverlaps(boxes: LabelBox[]): void {
220
+ const MAX_PASSES = 8;
221
+ const PAD = 4;
222
+ for (let pass = 0; pass < MAX_PASSES; pass++) {
223
+ let moved = false;
224
+ for (let i = 0; i < boxes.length; i++) {
225
+ for (let j = i + 1; j < boxes.length; j++) {
226
+ const a = boxes[i]!;
227
+ const b = boxes[j]!;
228
+ const dx = Math.abs(a.cx - b.cx);
229
+ const dy = Math.abs(a.cy - b.cy);
230
+ const overlapX = (a.w + b.w) / 2 + PAD - dx;
231
+ const overlapY = (a.h + b.h) / 2 + PAD - dy;
232
+ if (overlapX > 0 && overlapY > 0) {
233
+ const shift = overlapY / 2 + 1;
234
+ if (a.cy < b.cy) {
235
+ a.cy -= shift;
236
+ b.cy += shift;
237
+ } else {
238
+ a.cy += shift;
239
+ b.cy -= shift;
240
+ }
241
+ moved = true;
242
+ }
243
+ }
244
+ }
245
+ if (!moved) break;
246
+ }
247
+ }
248
+
249
+ export interface PlaceEdgeLabelsResult {
250
+ readonly layout: BLLayoutResult;
251
+ /** Edge indices whose label still overlaps a node box (escalate to relayout). */
252
+ readonly unresolved: number[];
253
+ }
254
+
255
+ /**
256
+ * Wrap, then collision-resolve every edge label against node boxes (steps 1–2),
257
+ * writing labelX/labelY/labelWidth/labelHeight/labelLines onto each edge. Returns
258
+ * the edge indices that could not be cleared so the caller can trigger a
259
+ * last-resort relayout.
260
+ */
261
+ export function placeEdgeLabels(
262
+ layout: BLLayoutResult,
263
+ opts?: { fontSize?: number; maxWidth?: number }
264
+ ): PlaceEdgeLabelsResult {
265
+ const fontSize = opts?.fontSize ?? EDGE_LABEL_FONT_SIZE;
266
+ const maxWidth = opts?.maxWidth ?? LABEL_MAX_WIDTH;
267
+
268
+ // Obstacles = real node boxes + collapsed groups (drawn as boxes). Expanded
269
+ // groups are containers — their interior is valid label space, so they are NOT
270
+ // obstacles.
271
+ const obstacles: Rect[] = [];
272
+ for (const n of layout.nodes)
273
+ obstacles.push(rectFromCenter(n.x, n.y, n.width, n.height));
274
+ for (const g of layout.groups)
275
+ if (g.collapsed)
276
+ obstacles.push(rectFromCenter(g.x, g.y, g.width, g.height));
277
+
278
+ const boxes: LabelBox[] = [];
279
+ layout.edges.forEach((e, idx) => {
280
+ if (!e.label || e.points.length < 2) return;
281
+ const m = measureEdgeLabel(e.label, fontSize, maxWidth);
282
+ const mid = edgePolylineMidpoint(e.points);
283
+ let cy = mid.y;
284
+ // Fold in the parallel-edge fan offset so each line's label clears its line.
285
+ if (e.parallelCount > 1 && e.yOffset !== 0)
286
+ cy += (e.yOffset < 0 ? -1 : 1) * (m.height / 2);
287
+ boxes.push({
288
+ edgeIdx: idx,
289
+ cx: mid.x,
290
+ cy,
291
+ w: m.width,
292
+ h: m.height,
293
+ lines: m.lines,
294
+ resolved: true,
295
+ });
296
+ });
297
+
298
+ // Step 2: reposition any box that overlaps a node.
299
+ for (const box of boxes) {
300
+ if (!overlapsAny(box.cx, box.cy, box.w, box.h, obstacles, BOX_CLEAR_PAD))
301
+ continue;
302
+ const e = layout.edges[box.edgeIdx]!;
303
+ const clear = findClearPosition(box.w, box.h, e.points, obstacles);
304
+ if (clear) {
305
+ box.cx = clear.x;
306
+ box.cy = clear.y;
307
+ } else {
308
+ box.resolved = false;
309
+ }
310
+ }
311
+
312
+ // Separate stacked labels, then re-check node overlap (a vertical nudge can
313
+ // push a label back onto a box — that becomes an unresolved escalation).
314
+ resolveLabelOverlaps(boxes);
315
+ for (const box of boxes) {
316
+ if (overlapsAny(box.cx, box.cy, box.w, box.h, obstacles, BOX_CLEAR_PAD))
317
+ box.resolved = false;
318
+ }
319
+
320
+ const boxByIdx = new Map<number, LabelBox>();
321
+ for (const b of boxes) boxByIdx.set(b.edgeIdx, b);
322
+ const edges = layout.edges.map((e, idx) => {
323
+ const b = boxByIdx.get(idx);
324
+ if (!b) return e;
325
+ return {
326
+ ...e,
327
+ labelX: b.cx,
328
+ labelY: b.cy,
329
+ labelWidth: b.w,
330
+ labelHeight: b.h,
331
+ labelLines: b.lines,
332
+ };
333
+ });
334
+
335
+ return {
336
+ layout: { ...layout, edges },
337
+ unresolved: boxes.filter((b) => !b.resolved).map((b) => b.edgeIdx),
338
+ };
339
+ }
@@ -23,6 +23,7 @@ import {
23
23
  } from './layout';
24
24
  import { layeredCandidates } from './layout-layered';
25
25
  import { groupedTierCandidates } from './layout-grouped';
26
+ import { measureEdgeLabel, EDGE_LABEL_FONT_SIZE } from './label-placement';
26
27
 
27
28
  type Pt = { x: number; y: number };
28
29
 
@@ -917,9 +918,14 @@ export async function layoutBoxesAndLinesSearch(
917
918
  * indicator. Omit it (CLI/export) and the search runs straight through with
918
919
  * no added latency. */
919
920
  onProgress?: (done: number, total: number, phase: string) => void;
921
+ /** Last-resort label legibility: reserve dagre label space for every labeled
922
+ * edge so the layout opens a gap wide enough for the (wrapped) label. Only
923
+ * set by layout.ts when steps 1–2 left a label overlapping a node box. */
924
+ reserveEdgeLabels?: boolean;
920
925
  }
921
926
  ): Promise<BLLayoutResult> {
922
927
  const hideDescriptions = opts?.hideDescriptions ?? false;
928
+ const reserveEdgeLabels = opts?.reserveEdgeLabels ?? false;
923
929
  const onProgress = opts?.onProgress;
924
930
  // Yield to a macrotask (lets the browser repaint between heavy placements);
925
931
  // no-op when there's no progress observer so non-interactive callers pay
@@ -1323,8 +1329,16 @@ export async function layoutBoxesAndLinesSearch(
1323
1329
  for (const e of ord(parsed.edges)) {
1324
1330
  const s = srcRep(e.source);
1325
1331
  const t = tgtRep(e.target);
1326
- if (s !== t && g.hasNode(s) && g.hasNode(t))
1327
- g.setEdge(s, t, {}, edgeKey(e));
1332
+ if (s !== t && g.hasNode(s) && g.hasNode(t)) {
1333
+ // Last-resort label legibility: reserve a virtual label node on the edge
1334
+ // so dagre widens the rank gap to fit the (wrapped) label.
1335
+ let edgeLabel: object = {};
1336
+ if (reserveEdgeLabels && e.label) {
1337
+ const m = measureEdgeLabel(e.label, EDGE_LABEL_FONT_SIZE);
1338
+ edgeLabel = { width: m.width, height: m.height, labelpos: 'c' };
1339
+ }
1340
+ g.setEdge(s, t, edgeLabel, edgeKey(e));
1341
+ }
1328
1342
  }
1329
1343
  dagre.layout(g);
1330
1344
 
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { ParsedBoxesAndLines, BLNode, BLGroup } from './types';
11
11
  import { measureText, wrapTextToWidth } from '../utils/text-measure';
12
+ import { placeEdgeLabels } from './label-placement';
12
13
  import {
13
14
  resolveNotes,
14
15
  buildPlacedNotes,
@@ -58,8 +59,14 @@ export interface BLLayoutEdge {
58
59
  readonly bidirectional: boolean;
59
60
  readonly lineNumber: number;
60
61
  readonly points: ReadonlyArray<{ readonly x: number; readonly y: number }>;
62
+ /** Centre of the label box (set by label-placement). */
61
63
  readonly labelX?: number;
62
64
  readonly labelY?: number;
65
+ /** Wrapped label box dimensions + lines (set by label-placement; the renderer
66
+ * draws the halo + tspans straight from these). */
67
+ readonly labelWidth?: number;
68
+ readonly labelHeight?: number;
69
+ readonly labelLines?: readonly string[];
63
70
  readonly yOffset: number;
64
71
  readonly parallelCount: number;
65
72
  readonly metadata: Readonly<Record<string, string>>;
@@ -205,7 +212,7 @@ export async function layoutBoxesAndLines(
205
212
  }
206
213
  ): Promise<BLLayoutResult> {
207
214
  const { layoutBoxesAndLinesSearch } = await import('./layout-search');
208
- const searched = await layoutBoxesAndLinesSearch(parsed, collapseInfo, {
215
+ const searchOpts = {
209
216
  ...(layoutOptions?.hideDescriptions !== undefined && {
210
217
  hideDescriptions: layoutOptions.hideDescriptions,
211
218
  }),
@@ -215,14 +222,31 @@ export async function layoutBoxesAndLines(
215
222
  ...(layoutOptions?.onProgress !== undefined && {
216
223
  onProgress: layoutOptions.onProgress,
217
224
  }),
218
- });
219
- // Engine-agnostic post-processing: fan parallel edges, then float notes
220
- // (and shift the canvas to fit them).
221
- return attachNotes(
222
- applyParallelEdgeOffsets(searched),
225
+ };
226
+ const searched = await layoutBoxesAndLinesSearch(
223
227
  parsed,
224
- layoutOptions?.collapsedNotes
228
+ collapseInfo,
229
+ searchOpts
225
230
  );
231
+
232
+ // Edge-label legibility (priority ladder): wrap + reposition labels on the
233
+ // chosen layout. If any label still can't clear a node box, escalate ONCE to a
234
+ // label-aware relayout that reserves dagre label space so a gap opens — and
235
+ // keep it only if it actually resolves more labels.
236
+ let placed = placeEdgeLabels(applyParallelEdgeOffsets(searched));
237
+ if (placed.unresolved.length > 0) {
238
+ const relaid = await layoutBoxesAndLinesSearch(parsed, collapseInfo, {
239
+ ...searchOpts,
240
+ reserveEdgeLabels: true,
241
+ });
242
+ const relaidPlaced = placeEdgeLabels(applyParallelEdgeOffsets(relaid));
243
+ if (relaidPlaced.unresolved.length < placed.unresolved.length)
244
+ placed = relaidPlaced;
245
+ }
246
+
247
+ // Engine-agnostic post-processing: float notes (and shift the canvas to fit
248
+ // them) on the label-placed layout.
249
+ return attachNotes(placed.layout, parsed, layoutOptions?.collapsedNotes);
226
250
  }
227
251
 
228
252
  /**
@@ -312,6 +336,7 @@ function attachNotes(
312
336
  points: e.points.map((pt) => ({ x: pt.x + shiftX, y: pt.y + shiftY })),
313
337
  ...(e.labelX !== undefined && { labelX: e.labelX + shiftX }),
314
338
  ...(e.labelY !== undefined && { labelY: e.labelY + shiftY }),
339
+ // labelWidth/labelHeight/labelLines are shift-invariant — carried via spread.
315
340
  }))
316
341
  : layout.edges;
317
342
  const finalGroups = shifted