@metronforge/concept-map 0.1.1 → 0.2.1

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 (199) hide show
  1. package/README.md +142 -91
  2. package/css/concept-map.css +31 -21
  3. package/dist/dom/badgeDom.d.ts +3 -0
  4. package/dist/dom/badgeDom.d.ts.map +1 -0
  5. package/dist/dom/badgeDom.js +23 -0
  6. package/dist/dom/badgeDom.js.map +1 -0
  7. package/dist/dom/geometry.d.ts.map +1 -1
  8. package/dist/dom/geometry.js +12 -2
  9. package/dist/dom/geometry.js.map +1 -1
  10. package/dist/dom/index.d.ts +6 -0
  11. package/dist/dom/index.d.ts.map +1 -0
  12. package/dist/dom/index.js +3 -0
  13. package/dist/dom/index.js.map +1 -0
  14. package/dist/dom/measureLabel.d.ts +4 -0
  15. package/dist/dom/measureLabel.d.ts.map +1 -0
  16. package/dist/dom/measureLabel.js +29 -0
  17. package/dist/dom/measureLabel.js.map +1 -0
  18. package/dist/dom/mount.d.ts +7 -0
  19. package/dist/dom/mount.d.ts.map +1 -0
  20. package/dist/dom/mount.js +37 -0
  21. package/dist/dom/mount.js.map +1 -0
  22. package/dist/dom/player.d.ts.map +1 -1
  23. package/dist/dom/player.js +3 -3
  24. package/dist/dom/player.js.map +1 -1
  25. package/dist/element/element.d.ts +26 -0
  26. package/dist/element/element.d.ts.map +1 -0
  27. package/dist/element/element.js +115 -0
  28. package/dist/element/element.js.map +1 -0
  29. package/dist/element/input.d.ts +7 -0
  30. package/dist/element/input.d.ts.map +1 -0
  31. package/dist/element/input.js +40 -0
  32. package/dist/element/input.js.map +1 -0
  33. package/dist/element/layout.d.ts +4 -0
  34. package/dist/element/layout.d.ts.map +1 -0
  35. package/dist/element/layout.js +14 -0
  36. package/dist/element/layout.js.map +1 -0
  37. package/dist/element.d.ts +9 -0
  38. package/dist/element.d.ts.map +1 -0
  39. package/dist/element.js +5 -0
  40. package/dist/element.js.map +1 -0
  41. package/dist/index.d.ts +4 -5
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +2 -2
  44. package/dist/index.js.map +1 -1
  45. package/dist/layout/badges.d.ts +4 -0
  46. package/dist/layout/badges.d.ts.map +1 -0
  47. package/dist/layout/badges.js +45 -0
  48. package/dist/layout/badges.js.map +1 -0
  49. package/dist/layout/check.d.ts +5 -0
  50. package/dist/layout/check.d.ts.map +1 -0
  51. package/dist/layout/check.js +61 -0
  52. package/dist/layout/check.js.map +1 -0
  53. package/dist/layout/dagre.d.ts +4 -0
  54. package/dist/layout/dagre.d.ts.map +1 -0
  55. package/dist/layout/dagre.js +62 -0
  56. package/dist/layout/dagre.js.map +1 -0
  57. package/dist/layout/elk.d.ts +4 -0
  58. package/dist/layout/elk.d.ts.map +1 -0
  59. package/dist/layout/elk.js +98 -0
  60. package/dist/layout/elk.js.map +1 -0
  61. package/dist/layout/font-metrics.d.ts +3 -0
  62. package/dist/layout/font-metrics.d.ts.map +1 -0
  63. package/dist/layout/font-metrics.js +128 -0
  64. package/dist/layout/font-metrics.js.map +1 -0
  65. package/dist/layout/geometry.d.ts +7 -0
  66. package/dist/layout/geometry.d.ts.map +1 -0
  67. package/dist/layout/geometry.js +56 -0
  68. package/dist/layout/geometry.js.map +1 -0
  69. package/dist/layout/graph.d.ts +6 -0
  70. package/dist/layout/graph.d.ts.map +1 -0
  71. package/dist/layout/graph.js +57 -0
  72. package/dist/layout/graph.js.map +1 -0
  73. package/dist/layout/index.d.ts +8 -0
  74. package/dist/layout/index.d.ts.map +1 -0
  75. package/dist/layout/index.js +21 -0
  76. package/dist/layout/index.js.map +1 -0
  77. package/dist/layout/lanes.d.ts +8 -0
  78. package/dist/layout/lanes.d.ts.map +1 -0
  79. package/dist/layout/lanes.js +78 -0
  80. package/dist/layout/lanes.js.map +1 -0
  81. package/dist/layout/measure.d.ts +4 -0
  82. package/dist/layout/measure.d.ts.map +1 -0
  83. package/dist/layout/measure.js +24 -0
  84. package/dist/layout/measure.js.map +1 -0
  85. package/dist/layout/resolve.d.ts +4 -0
  86. package/dist/layout/resolve.d.ts.map +1 -0
  87. package/dist/layout/resolve.js +114 -0
  88. package/dist/layout/resolve.js.map +1 -0
  89. package/dist/layout/self-route.d.ts +6 -0
  90. package/dist/layout/self-route.d.ts.map +1 -0
  91. package/dist/layout/self-route.js +110 -0
  92. package/dist/layout/self-route.js.map +1 -0
  93. package/dist/layout/types.d.ts +53 -0
  94. package/dist/layout/types.d.ts.map +1 -0
  95. package/dist/layout/types.js +2 -0
  96. package/dist/layout/types.js.map +1 -0
  97. package/dist/model/badge-placement.d.ts +10 -0
  98. package/dist/model/badge-placement.d.ts.map +1 -0
  99. package/dist/model/badge-placement.js +27 -0
  100. package/dist/model/badge-placement.js.map +1 -0
  101. package/dist/model/frame.d.ts +1 -1
  102. package/dist/model/frame.js +1 -1
  103. package/dist/model/input.d.ts +20 -0
  104. package/dist/model/input.d.ts.map +1 -0
  105. package/dist/model/input.js +15 -0
  106. package/dist/model/input.js.map +1 -0
  107. package/dist/model/labels.d.ts +1 -0
  108. package/dist/model/labels.d.ts.map +1 -1
  109. package/dist/model/labels.js +2 -0
  110. package/dist/model/labels.js.map +1 -1
  111. package/dist/render/concepts.d.ts.map +1 -1
  112. package/dist/render/concepts.js +6 -5
  113. package/dist/render/concepts.js.map +1 -1
  114. package/dist/render/data.d.ts +3 -0
  115. package/dist/render/data.d.ts.map +1 -0
  116. package/dist/render/data.js +7 -0
  117. package/dist/render/data.js.map +1 -0
  118. package/dist/render/figure.d.ts +10 -0
  119. package/dist/render/figure.d.ts.map +1 -0
  120. package/dist/render/figure.js +22 -0
  121. package/dist/render/figure.js.map +1 -0
  122. package/dist/render/hydration.d.ts +3 -0
  123. package/dist/render/hydration.d.ts.map +1 -0
  124. package/dist/render/hydration.js +13 -0
  125. package/dist/render/hydration.js.map +1 -0
  126. package/dist/render/panel.d.ts.map +1 -1
  127. package/dist/render/panel.js +7 -6
  128. package/dist/render/panel.js.map +1 -1
  129. package/dist/render/svg.d.ts.map +1 -1
  130. package/dist/render/svg.js +5 -4
  131. package/dist/render/svg.js.map +1 -1
  132. package/dist/schema/content.d.ts +90 -0
  133. package/dist/schema/content.d.ts.map +1 -0
  134. package/dist/schema/content.js +60 -0
  135. package/dist/schema/content.js.map +1 -0
  136. package/dist/schema/layout.d.ts +10 -0
  137. package/dist/schema/layout.d.ts.map +1 -0
  138. package/dist/schema/layout.js +8 -0
  139. package/dist/schema/layout.js.map +1 -0
  140. package/dist/schema/level.d.ts +3 -0
  141. package/dist/schema/level.d.ts.map +1 -0
  142. package/dist/schema/level.js +7 -0
  143. package/dist/schema/level.js.map +1 -0
  144. package/dist/schema/primitives.d.ts +61 -0
  145. package/dist/schema/primitives.d.ts.map +1 -0
  146. package/dist/schema/primitives.js +46 -0
  147. package/dist/schema/primitives.js.map +1 -0
  148. package/dist/schema/references.d.ts +6 -0
  149. package/dist/schema/references.d.ts.map +1 -0
  150. package/dist/schema/references.js +81 -0
  151. package/dist/schema/references.js.map +1 -0
  152. package/dist/schema.d.ts +357 -192
  153. package/dist/schema.d.ts.map +1 -1
  154. package/dist/schema.js +51 -119
  155. package/dist/schema.js.map +1 -1
  156. package/package.json +53 -9
  157. package/resolved-map.schema.json +184 -212
  158. package/source-map.schema.json +606 -0
  159. package/src/dom/badgeDom.ts +32 -0
  160. package/src/dom/geometry.ts +24 -2
  161. package/src/dom/index.ts +5 -0
  162. package/src/dom/measureLabel.ts +28 -0
  163. package/src/dom/mount.ts +46 -0
  164. package/src/dom/player.ts +3 -3
  165. package/src/element/element.ts +128 -0
  166. package/src/element/input.ts +60 -0
  167. package/src/element/layout.ts +18 -0
  168. package/src/element.ts +11 -0
  169. package/src/index.ts +10 -5
  170. package/src/layout/FONT-LICENSE.txt +78 -0
  171. package/src/layout/badges.ts +71 -0
  172. package/src/layout/check.ts +81 -0
  173. package/src/layout/dagre.ts +81 -0
  174. package/src/layout/elk.ts +113 -0
  175. package/src/layout/font-metrics.ts +127 -0
  176. package/src/layout/geometry.ts +72 -0
  177. package/src/layout/graph.ts +88 -0
  178. package/src/layout/index.ts +29 -0
  179. package/src/layout/lanes.ts +114 -0
  180. package/src/layout/measure.ts +25 -0
  181. package/src/layout/resolve.ts +155 -0
  182. package/src/layout/self-route.ts +168 -0
  183. package/src/layout/types.ts +50 -0
  184. package/src/model/badge-placement.ts +43 -0
  185. package/src/model/frame.ts +2 -2
  186. package/src/model/input.ts +26 -0
  187. package/src/model/labels.ts +3 -0
  188. package/src/render/concepts.ts +7 -5
  189. package/src/render/data.ts +10 -0
  190. package/src/render/figure.ts +35 -0
  191. package/src/render/hydration.ts +11 -0
  192. package/src/render/panel.ts +7 -6
  193. package/src/render/svg.ts +5 -4
  194. package/src/schema/content.ts +91 -0
  195. package/src/schema/layout.ts +10 -0
  196. package/src/schema/level.ts +6 -0
  197. package/src/schema/primitives.ts +55 -0
  198. package/src/schema/references.ts +106 -0
  199. package/src/schema.ts +73 -134
@@ -0,0 +1,155 @@
1
+ import type { SourceMap, ResolvedMap } from "../schema.js";
2
+ import { ResolvedMapSchema } from "../schema.js";
3
+ import type {
4
+ LabelMeasurer,
5
+ LayoutBox,
6
+ LayoutGraph,
7
+ LayoutResult,
8
+ LayoutPoint,
9
+ } from "./types.js";
10
+ import { bounds, midpoint } from "./geometry.js";
11
+ import { badgePositions } from "./badges.js";
12
+ import { measured } from "./graph.js";
13
+ function frameBoxes(
14
+ map: SourceMap,
15
+ result: LayoutResult,
16
+ measure: LabelMeasurer,
17
+ ): Record<string, LayoutBox> {
18
+ return Object.fromEntries(
19
+ Object.entries(map.frames).map(([id, f]) => {
20
+ const b = bounds(f.showWith.map((n) => result.nodes[n]));
21
+ const label = measured(measure, f.label, {
22
+ fontSize: 10.5,
23
+ mono: true,
24
+ letterSpacing: 0.63,
25
+ });
26
+ return [
27
+ id,
28
+ [
29
+ b[0] - 12,
30
+ b[1] - 28,
31
+ Math.max(b[2] + 24, label.width + 24),
32
+ b[3] + 40,
33
+ ],
34
+ ];
35
+ }),
36
+ );
37
+ }
38
+ function viewport(
39
+ graph: LayoutGraph,
40
+ result: LayoutResult,
41
+ frames: Record<string, LayoutBox>,
42
+ badges: Record<string, LayoutPoint>,
43
+ ): LayoutBox {
44
+ const boxes = [
45
+ ...Object.values(result.nodes),
46
+ ...Object.values(result.lanes),
47
+ ...Object.values(frames),
48
+ ...Object.values(badges).map(([x, y]): LayoutBox => [x - 8, y - 8, 16, 16]),
49
+ ];
50
+ for (const e of graph.edges) {
51
+ const r = result.edges[e.id];
52
+ boxes.push(...r.points.map(([x, y]): LayoutBox => [x, y, 0, 0]));
53
+ if (e.label) {
54
+ const p = r.label ?? midpoint(r.points);
55
+ boxes.push([
56
+ p[0] - e.label.width / 2,
57
+ p[1] - e.label.height / 2,
58
+ e.label.width,
59
+ e.label.height,
60
+ ]);
61
+ }
62
+ }
63
+ return bounds(boxes);
64
+ }
65
+ function edgeGeometry(
66
+ map: SourceMap,
67
+ graph: LayoutGraph,
68
+ result: LayoutResult,
69
+ move: (p: LayoutPoint) => LayoutPoint,
70
+ badges: Record<string, LayoutPoint>,
71
+ ) {
72
+ return Object.fromEntries(
73
+ graph.edges.map((e) => {
74
+ const source = map.edges[e.id],
75
+ r = result.edges[e.id];
76
+ const points = r.points.map(move),
77
+ badge = move(badges[e.id]);
78
+ const label = move(r.label ?? midpoint(r.points));
79
+ return [
80
+ e.id,
81
+ {
82
+ ...source,
83
+ path: points
84
+ .map(([x, y], i) => `${i ? "L" : "M"}${x},${y}`)
85
+ .join(" "),
86
+ badge,
87
+ ...(e.label
88
+ ? {
89
+ label: {
90
+ text: source.label!,
91
+ at: [
92
+ label[0] - e.label.width / 2,
93
+ label[1] + e.label.height / 3,
94
+ ],
95
+ },
96
+ }
97
+ : {}),
98
+ },
99
+ ];
100
+ }),
101
+ );
102
+ }
103
+ function resolvedScenarios(map: SourceMap, badge: (id: string) => LayoutPoint) {
104
+ return map.scenarios.map((s) => ({
105
+ ...s,
106
+ ...(s.repeatBadges
107
+ ? {
108
+ repeatBadges: s.repeatBadges.map((r) => ({
109
+ ...r,
110
+ at: badge(r.edge),
111
+ })),
112
+ }
113
+ : {}),
114
+ }));
115
+ }
116
+ export function resolveGeometry(
117
+ map: SourceMap,
118
+ graph: LayoutGraph,
119
+ result: LayoutResult,
120
+ measure: LabelMeasurer,
121
+ ): ResolvedMap {
122
+ const frames = frameBoxes(map, result, measure),
123
+ badges = badgePositions(graph, result),
124
+ b = viewport(graph, result, frames, badges);
125
+ const move = ([x, y]: LayoutPoint): LayoutPoint => [
126
+ x - b[0] + 16,
127
+ y - b[1] + 16,
128
+ ];
129
+ const box = ([x, y, w, h]: LayoutBox): LayoutBox => [...move([x, y]), w, h];
130
+ const edges = edgeGeometry(map, graph, result, move, badges);
131
+ return ResolvedMapSchema.parse({
132
+ ...map,
133
+ viewBox: [b[2] + 32, b[3] + 32],
134
+ nodes: Object.fromEntries(
135
+ Object.entries(map.nodes).map(([id, n]) => [
136
+ id,
137
+ { ...n, box: box(result.nodes[id]) },
138
+ ]),
139
+ ),
140
+ lanes: Object.fromEntries(
141
+ Object.entries(map.lanes).map(([id, l]) => {
142
+ const [x, y, w, h] = box(result.lanes[id]);
143
+ return [id, { ...l, x, y, w, h }];
144
+ }),
145
+ ),
146
+ frames: Object.fromEntries(
147
+ Object.entries(map.frames).map(([id, f]) => [
148
+ id,
149
+ { ...f, box: box(frames[id]) },
150
+ ]),
151
+ ),
152
+ edges,
153
+ scenarios: resolvedScenarios(map, (id) => edges[id].badge),
154
+ });
155
+ }
@@ -0,0 +1,168 @@
1
+ import type {
2
+ LayoutBox,
3
+ LayoutPoint,
4
+ LayoutGraph,
5
+ LayoutResult,
6
+ LayoutRoute,
7
+ LabelSize,
8
+ } from "./types.js";
9
+ import { bounds } from "./geometry.js";
10
+
11
+ /** Compact side loops use final node positions, including relocated partitions. */
12
+ export function routeSelfEdges(
13
+ graph: LayoutGraph,
14
+ result: LayoutResult,
15
+ ): LayoutResult {
16
+ const reserved: LayoutBox[] = [];
17
+ const edges = { ...result.edges };
18
+ for (const edge of graph.edges) {
19
+ if (edge.from !== edge.to) continue;
20
+ const box = result.nodes[edge.from];
21
+ const neighbors = Object.entries(result.nodes)
22
+ .filter(([id]) => id !== edge.from)
23
+ .map(([, b]) => b)
24
+ .concat(reserved);
25
+ const candidates = [
26
+ ...[1, -1].map((side) => selfRoute(box, edge.label, side)),
27
+ ...[-1, 1].map((side) => verticalRoute(box, edge.label, side)),
28
+ ];
29
+ const selected = candidates.find(
30
+ (route) => interference(route, edge.label, neighbors) === 0,
31
+ );
32
+ if (!selected) return originalRoutes(graph, result);
33
+ edges[edge.id] = selected;
34
+ reserved.push(routeBounds(selected, edge.label));
35
+ }
36
+ result.edges = edges;
37
+ return result;
38
+ }
39
+
40
+ /** A crowded graph keeps its engine routing, rather than receiving known collisions. */
41
+ function originalRoutes(
42
+ graph: LayoutGraph,
43
+ result: LayoutResult,
44
+ ): LayoutResult {
45
+ for (const edge of graph.edges)
46
+ if (!result.edges[edge.id])
47
+ throw new Error(
48
+ `Self-edge “${edge.id}”: no clear compact route and no original engine route`,
49
+ );
50
+ return result;
51
+ }
52
+
53
+ function selfRoute(
54
+ box: LayoutBox,
55
+ label: LabelSize | undefined,
56
+ side: number,
57
+ reach = 24,
58
+ ): LayoutRoute {
59
+ const [x, y, w, h] = box;
60
+ const start = x + (side > 0 ? w : 0);
61
+ const outside = start + side * reach;
62
+ return {
63
+ points: [
64
+ [start, y + h / 4],
65
+ [outside, y + h / 4],
66
+ [outside, y + (3 * h) / 4],
67
+ [start, y + (3 * h) / 4],
68
+ ],
69
+ ...(label
70
+ ? {
71
+ label: [outside + side * (12 + label.width / 2), y + h / 2] as [
72
+ number,
73
+ number,
74
+ ],
75
+ }
76
+ : {}),
77
+ };
78
+ }
79
+
80
+ /** Swap the route axes while keeping measured label dimensions unrotated. */
81
+ function verticalRoute(
82
+ box: LayoutBox,
83
+ label: LabelSize | undefined,
84
+ side: number,
85
+ ): LayoutRoute {
86
+ const [x, y, w, h] = box;
87
+ const route = selfRoute(
88
+ [y, x, h, w],
89
+ label ? { width: label.height, height: label.width } : undefined,
90
+ side,
91
+ Math.min(24, h),
92
+ );
93
+ return {
94
+ points: route.points.map(([px, py]) => [py, px]),
95
+ ...(route.label
96
+ ? { label: [route.label[1], route.label[0]] as [number, number] }
97
+ : {}),
98
+ };
99
+ }
100
+
101
+ function routeBounds(
102
+ route: LayoutRoute,
103
+ label: LabelSize | undefined,
104
+ ): LayoutBox {
105
+ const boxes: LayoutBox[] = route.points.map(([x, y]) => [x, y, 0, 0]);
106
+ if (route.label && label)
107
+ boxes.push([
108
+ route.label[0] - label.width / 2,
109
+ route.label[1] - label.height / 2,
110
+ label.width,
111
+ label.height,
112
+ ]);
113
+ return bounds(boxes);
114
+ }
115
+
116
+ function interference(
117
+ route: LayoutRoute,
118
+ label: LabelSize | undefined,
119
+ neighbors: LayoutBox[],
120
+ ): number {
121
+ const [x, y, w, h] = routeBounds(route, label);
122
+ return neighbors.reduce(
123
+ (area, [nx, ny, nw, nh]) =>
124
+ area +
125
+ Math.max(0, Math.min(x + w + 12, nx + nw) - Math.max(x - 12, nx)) *
126
+ Math.max(0, Math.min(y + h + 12, ny + nh) - Math.max(y - 12, ny)),
127
+ 0,
128
+ );
129
+ }
130
+
131
+ /** Dagre 3 returns a folded path for self-edges; use its reserved label lane. */
132
+ export function reservedSelfRoute(
133
+ box: LayoutBox,
134
+ center: LayoutPoint,
135
+ label: LabelSize | undefined,
136
+ right: boolean,
137
+ ): LayoutRoute {
138
+ const [x, y, w, h] = box;
139
+ if (right) {
140
+ const bottom = Math.max(
141
+ y + h + 24,
142
+ center[1] - (label?.height ?? 0) / 2 - 12,
143
+ );
144
+ return {
145
+ points: [
146
+ [x + w / 3, y + h],
147
+ [x + w / 3, bottom],
148
+ [x + (w * 2) / 3, bottom],
149
+ [x + (w * 2) / 3, y + h],
150
+ ],
151
+ ...(label
152
+ ? { label: [center[0], bottom + 12 + label.height / 2] as LayoutPoint }
153
+ : {}),
154
+ };
155
+ }
156
+ const side = Math.max(x + w + 24, center[0] - (label?.width ?? 0) / 2 - 12);
157
+ return {
158
+ points: [
159
+ [x + w, y + h / 3],
160
+ [side, y + h / 3],
161
+ [side, y + (h * 2) / 3],
162
+ [x + w, y + (h * 2) / 3],
163
+ ],
164
+ ...(label
165
+ ? { label: [side + 12 + label.width / 2, center[1]] as LayoutPoint }
166
+ : {}),
167
+ };
168
+ }
@@ -0,0 +1,50 @@
1
+ /** Coordinates in SVG user units, relative to the graph origin. */
2
+ export type LayoutPoint = [number, number];
3
+ export type LayoutBox = [number, number, number, number];
4
+ export interface LabelSize {
5
+ width: number;
6
+ height: number;
7
+ }
8
+ export interface LabelStyle {
9
+ fontSize: number;
10
+ mono: boolean;
11
+ letterSpacing?: number;
12
+ }
13
+ export type LabelMeasurer = (text: string, style: LabelStyle) => LabelSize;
14
+ export interface LayoutNode extends LabelSize {
15
+ id: string;
16
+ lane?: string;
17
+ }
18
+ export interface LayoutEdge {
19
+ id: string;
20
+ from: string;
21
+ to: string;
22
+ label?: LabelSize & { text?: string };
23
+ }
24
+ /** Lanes follow the layout direction. Unassigned nodes follow the last lane. */
25
+ export interface LayoutLane {
26
+ id: string;
27
+ label: LabelSize;
28
+ }
29
+ export interface LayoutGraph {
30
+ direction?: "down" | "right";
31
+ nodes: readonly LayoutNode[];
32
+ edges: readonly LayoutEdge[];
33
+ lanes: readonly LayoutLane[];
34
+ }
35
+ export interface LayoutRoute {
36
+ points: LayoutPoint[];
37
+ label?: LayoutPoint;
38
+ }
39
+ /** Every graph id must have exactly one geometry entry; label points are centres. */
40
+ export interface LayoutResult {
41
+ nodes: Record<string, LayoutBox>;
42
+ edges: Record<string, LayoutRoute>;
43
+ lanes: Record<string, LayoutBox>;
44
+ }
45
+ export interface LayoutEngine {
46
+ layout(graph: LayoutGraph): Promise<LayoutResult>;
47
+ }
48
+ export interface LayoutOptions {
49
+ measureLabel?: LabelMeasurer;
50
+ }
@@ -0,0 +1,43 @@
1
+ import type { Point } from "./path.js";
2
+ export interface BadgeObstacle {
3
+ x: number;
4
+ y: number;
5
+ width: number;
6
+ height: number;
7
+ }
8
+ function clearOf([x, y]: Point, radius: number, box: BadgeObstacle): boolean {
9
+ return (
10
+ Math.hypot(
11
+ Math.max(box.x - x, 0, x - box.x - box.width),
12
+ Math.max(box.y - y, 0, y - box.y - box.height),
13
+ ) >=
14
+ radius + 3
15
+ );
16
+ }
17
+ /** Keep intentional node/edge attachments unless actual label text overlaps. */
18
+ export function placeBadge(
19
+ origin: Point,
20
+ radius: number,
21
+ labels: BadgeObstacle[],
22
+ bounds: BadgeObstacle,
23
+ obstacles: BadgeObstacle[] = [],
24
+ ): Point {
25
+ if (labels.every((box) => clearOf(origin, radius, box))) return origin;
26
+ const clear = ([x, y]: Point) =>
27
+ x - radius >= bounds.x &&
28
+ y - radius >= bounds.y &&
29
+ x + radius <= bounds.x + bounds.width &&
30
+ y + radius <= bounds.y + bounds.height &&
31
+ [...labels, ...obstacles].every((box) => clearOf([x, y], radius, box));
32
+ const limit = Math.hypot(bounds.width, bounds.height);
33
+ for (let distance = 4; distance <= limit; distance += 4)
34
+ for (let angle = 0; angle < 16; angle++) {
35
+ const radians = (angle * Math.PI) / 8;
36
+ const candidate: Point = [
37
+ origin[0] + Math.cos(radians) * distance,
38
+ origin[1] + Math.sin(radians) * distance,
39
+ ];
40
+ if (clear(candidate)) return candidate;
41
+ }
42
+ return origin;
43
+ }
@@ -14,7 +14,7 @@ export type StepPanel = {
14
14
  kind: "step";
15
15
  count: string;
16
16
  title: string;
17
- html: string;
17
+ text: string;
18
18
  log: LogLine[];
19
19
  fix?: string;
20
20
  code?: ResolvedMap["code"][string];
@@ -146,7 +146,7 @@ export function derive(map: ResolvedMap, state: PlayerState): Frame {
146
146
  kind: "step",
147
147
  count: `${s.display.counterLabel ? s.label + " · " : ""}Step ${state.step + 1} of ${steps.length}`,
148
148
  title: t.title,
149
- html: t.text,
149
+ text: t.text,
150
150
  log: [
151
151
  ...before.map((text) => ({ text, kind: "old" as const })),
152
152
  ...(t.log ?? []).map((text) => ({
@@ -0,0 +1,26 @@
1
+ export interface MapInputs {
2
+ assigned?: unknown;
3
+ src?: string | null;
4
+ direct?: string;
5
+ inline?: unknown;
6
+ server?: string;
7
+ }
8
+ export type SelectedMapInput =
9
+ | { kind: "value"; value: unknown }
10
+ | { kind: "url"; url: string }
11
+ | { kind: "json"; text: string };
12
+
13
+ /** Choose before parsing, so invalid preferred data never falls back. */
14
+ export function selectMapInput(
15
+ inputs: MapInputs,
16
+ ): SelectedMapInput | undefined {
17
+ if (inputs.assigned !== undefined)
18
+ return { kind: "value", value: inputs.assigned };
19
+ if (inputs.src !== undefined && inputs.src !== null)
20
+ return { kind: "url", url: inputs.src };
21
+ if (inputs.direct !== undefined) return { kind: "json", text: inputs.direct };
22
+ if (inputs.inline !== undefined)
23
+ return { kind: "value", value: inputs.inline };
24
+ if (inputs.server !== undefined) return { kind: "json", text: inputs.server };
25
+ return undefined;
26
+ }
@@ -1,4 +1,7 @@
1
1
  import type { Point } from "./path.js";
2
+ // Layout measures edge labels at 10.5 units; scale the drawing to page text.
3
+ export const naturalMapWidth = (viewBoxWidth: number, fontSize = 16) =>
4
+ (viewBoxWidth * fontSize) / 10.5;
2
5
  export const labelMinimum = (viewBoxWidth: number, renderedWidth: number) =>
3
6
  (10.55 * viewBoxWidth) / renderedWidth;
4
7
  export function fitNodeLabels(
@@ -1,21 +1,23 @@
1
1
  import type { ResolvedMap } from "../schema.js";
2
- import { escapeHtml as esc } from "./inline.js";
2
+ import { escapeHtml as esc, renderInline } from "./inline.js";
3
3
  export function renderConcepts(map: ResolvedMap): string {
4
4
  return `<div class="concepts">${map.concepts
5
5
  .map(
6
6
  (g) =>
7
- `<section class="cgroup" style="--c:var(--pw-${esc(g.layer === "app" ? "test" : g.layer)})"><h3><span class="dot" aria-hidden="true"></span>${esc(g.label)}</h3><ul>${g.items
7
+ `<section class="cgroup" style="--c:var(--cmap-layer-${esc(g.layer)},var(--cmap-layer))"><h3><span class="dot" aria-hidden="true"></span>${esc(g.label)}</h3><ul>${g.items
8
8
  .map((c) => {
9
9
  const scenario = map.scenarios.find(
10
- (s) => s.id === (c.step.scenario ?? map.conceptScenario),
10
+ (s) =>
11
+ s.id ===
12
+ (c.step.scenario ?? map.conceptScenario ?? map.scenarios[0].id),
11
13
  )!;
12
14
  const index = scenario.steps.findIndex((s) => s.id === c.step.step);
13
- return `<li data-nodes="${esc(c.nodes.join(" "))}"><span class="term">${esc(map.definitions[c.definition].term)}</span><span class="def">${c.short}</span><span class="meta"><a href="${esc(c.source.url)}" title="${esc(c.source.label)}">Source ↗</a><button type="button" data-step="${index}"${c.step.scenario ? ` data-concept-scenario="${esc(c.step.scenario)}"` : ""}>Step ${index + 1}</button></span></li>`;
15
+ return `<li data-nodes="${esc(c.nodes.join(" "))}"><span class="term">${esc(map.definitions[c.definition].term)}</span><span class="def">${renderInline(c.short)}</span><span class="meta">${c.source ? `<a href="${esc(c.source.url)}" title="${esc(c.source.label)}">Source ↗</a>` : ""}<button type="button" data-step="${index}"${c.step.scenario ? ` data-concept-scenario="${esc(c.step.scenario)}"` : ""}>Step ${index + 1}</button></span></li>`;
14
16
  })
15
17
  .join("")}</ul></section>`,
16
18
  )
17
19
  .join("")}</div>`;
18
20
  }
19
21
  export function renderDeeper(map: ResolvedMap): string {
20
- return `<ul class="deeper">${map.deeper.map((d) => `<li><a href="${esc(d.href)}">${esc(d.title)}</a><span>${d.why}</span></li>`).join("")}</ul>`;
22
+ return `<ul class="deeper">${map.deeper.map((d) => `<li><a href="${esc(d.href)}">${esc(d.title)}</a><span>${renderInline(d.why)}</span></li>`).join("")}</ul>`;
21
23
  }
@@ -0,0 +1,10 @@
1
+ /** Stable JSON lets server and browser compare map data independent of key order. */
2
+ export function mapData(value: unknown): string {
3
+ return JSON.stringify(value, (_, item) =>
4
+ item && typeof item === "object" && !Array.isArray(item)
5
+ ? Object.fromEntries(
6
+ Object.entries(item).sort(([a], [b]) => a.localeCompare(b)),
7
+ )
8
+ : item,
9
+ ).replaceAll("<", "\\u003c");
10
+ }
@@ -0,0 +1,35 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ import { derive } from "../model/frame.js";
3
+ import { initialState } from "../model/state.js";
4
+ import { renderSvg } from "./svg.js";
5
+ import { renderPanelParts, statusText, type UiStrings } from "./panel.js";
6
+ import { renderConcepts, renderDeeper } from "./concepts.js";
7
+ import { escapeHtml as esc } from "./inline.js";
8
+
9
+ export interface FigureOptions {
10
+ /** Unique document id, also used for the server-rendered SVG marker. */
11
+ id?: string;
12
+ strings?: Partial<UiStrings>;
13
+ }
14
+
15
+ /** Complete light-DOM figure, including the data needed to hydrate it. */
16
+ export function renderFigure(
17
+ map: ResolvedMap,
18
+ options: FigureOptions = {},
19
+ ): string {
20
+ const frame = derive(map, initialState);
21
+ const panel = renderPanelParts(map, frame, options.strings);
22
+ const id = options.id ? ` id="${esc(options.id)}"` : "";
23
+ const scenarios = map.scenarios
24
+ .map(
25
+ (s, i) =>
26
+ `<button type="button" data-scenario="${esc(s.id)}" aria-pressed="${i === 0}">${esc(s.label)}</button>`,
27
+ )
28
+ .join("");
29
+ const svg = renderSvg(map, {
30
+ frame,
31
+ markerId: options.id ? `${options.id}-arrow` : undefined,
32
+ });
33
+ const data = JSON.stringify(map).replaceAll("<", "\\u003c");
34
+ return `<figure class="map-figure map-ui"${id} data-figure="map" data-map-id="${esc(map.id)}" tabindex="0" aria-label="${esc(map.title)}"><section aria-label="Concept map"><div class="bar"><div class="seg scenarios" role="group" aria-label="Scenario" data-role="scenarios">${scenarios}</div><div class="seg" role="group" aria-label="View"><button type="button" data-mode="step" aria-pressed="true">Step by step</button><button type="button" data-mode="all" aria-pressed="false">Whole map</button></div></div><div class="map">${svg}</div></section><p class="map-status" role="status" data-map-status>${esc(statusText(frame))}</p><div class="panel head" data-role="panel">${panel.head}</div><div class="panel more" data-role="more">${panel.more}</div><div data-map-concepts>${renderConcepts(map)}</div>${renderDeeper(map)}<script type="application/json" data-map-data>${data}</script></figure>`;
35
+ }
@@ -0,0 +1,11 @@
1
+ import { mapData } from "./data.js";
2
+
3
+ /** Reuse a figure only when its embedded data matches the requested map. */
4
+ export function canHydrate(data: string | undefined, map: unknown): boolean {
5
+ if (data === undefined) return false;
6
+ try {
7
+ return mapData(JSON.parse(data)) === mapData(map);
8
+ } catch {
9
+ return false;
10
+ }
11
+ }
@@ -1,6 +1,6 @@
1
1
  import type { ResolvedMap } from "../schema.js";
2
2
  import type { Frame } from "../model/frame.js";
3
- import { escapeHtml as esc } from "./inline.js";
3
+ import { escapeHtml as esc, renderInline } from "./inline.js";
4
4
  export const defaultStrings = {
5
5
  replay: "Replay the flow",
6
6
  callLog: "Call log",
@@ -27,7 +27,7 @@ function parts(map: ResolvedMap, frame: Frame, overrides: Partial<UiStrings>) {
27
27
  p = frame.panel;
28
28
  if (p.kind === "all")
29
29
  return {
30
- lead: `<div class="count">${esc(p.count)}</div><h2>${esc(p.title)}</h2><p>${p.text}</p><div class="flowbar"><button type="button" data-role="replay">${esc(ui.replay)}</button></div>`,
30
+ lead: `<div class="count">${esc(p.count)}</div><h2>${esc(p.title)}</h2><p>${renderInline(p.text)}</p><div class="flowbar"><button type="button" data-role="replay">${esc(ui.replay)}</button></div>`,
31
31
  details: `<div class="all"><ol>${p.steps.map((title, n) => `<li data-li="${n}"><button type="button" data-go="${n}"><span class="n">${n + 1}</span><span>${esc(title)}</span></button></li>`).join("")}</ol></div><div class="log" data-role="flowlog"${p.hasFlowLog ? "" : " hidden"}><h3>${esc(ui.callLog)}</h3></div>`,
32
32
  controls: "",
33
33
  };
@@ -35,18 +35,19 @@ function parts(map: ResolvedMap, frame: Frame, overrides: Partial<UiStrings>) {
35
35
  ? `<div class="log"><h3>${esc(ui.callLog)}</h3>${p.log.map((l) => `<div class="${l.kind}">${esc(l.text)}</div>`).join("")}</div>`
36
36
  : "";
37
37
  if (p.fix)
38
- details += `<p class="fix"><strong>${esc(ui.fix)}</strong> ${p.fix}</p>`;
38
+ details += `<p class="fix"><strong>${esc(ui.fix)}</strong> ${renderInline(p.fix)}</p>`;
39
39
  if (p.code) {
40
40
  const c = p.code;
41
41
  details += `<div class="code"><div class="ttl"><span>${esc(c.title)}</span>${c.source ? `<a href="${esc(c.source.url)}">${esc(ui.sourceLink)}</a>` : ""}</div><pre>${c.lines.map((l) => `<span class="${l.trim().startsWith("// ✗") ? "bad" : l.trim().startsWith("// ✓") ? "good" : l.trim().startsWith("//") ? "cm" : ""}">${esc(l)}</span>`).join("\n")}</pre></div>`;
42
42
  }
43
43
  if (p.defs.length)
44
- details += `<div class="defs"><h3>${esc(ui.newOnMap)}</h3><dl>${p.defs.map((d) => `<div><dt>${esc(d.term)}</dt><dd>${d.text}</dd></div>`).join("")}</dl></div>`;
45
- details += `<div class="refs"><div class="src"><h3>${esc(ui.source)}</h3><ul>${p.sources.map((s) => `<li><a href="${esc(s.url)}" target="_blank" rel="noopener">${esc(s.label)}</a></li>`).join("")}</ul></div>${p.deeper.length ? `<div><h3>${esc(ui.goDeeper)}</h3><ul>${p.deeper.map((d) => `<li><a href="${esc(d.href)}" target="_blank" rel="noopener">${esc(d.title)}</a></li>`).join("")}</ul></div>` : ""}</div>`;
44
+ details += `<div class="defs"><h3>${esc(ui.newOnMap)}</h3><dl>${p.defs.map((d) => `<div><dt>${esc(d.term)}</dt><dd>${renderInline(d.text)}</dd></div>`).join("")}</dl></div>`;
45
+ if (p.sources.length || p.deeper.length)
46
+ details += `<div class="refs">${p.sources.length ? `<div class="src"><h3>${esc(ui.source)}</h3><ul>${p.sources.map((s) => `<li><a href="${esc(s.url)}" target="_blank" rel="noopener">${esc(s.label)}</a></li>`).join("")}</ul></div>` : ""}${p.deeper.length ? `<div><h3>${esc(ui.goDeeper)}</h3><ul>${p.deeper.map((d) => `<li><a href="${esc(d.href)}" target="_blank" rel="noopener">${esc(d.title)}</a></li>`).join("")}</ul></div>` : ""}</div>`;
46
47
  const steps = map.scenarios[frame.state.scenario].steps.map((t) => t.title),
47
48
  index = frame.state.step;
48
49
  return {
49
- lead: `<div class="count">${esc(p.count)}</div><h2>${esc(p.title)}</h2><p>${p.html}</p>`,
50
+ lead: `<div class="count">${esc(p.count)}</div><h2>${esc(p.title)}</h2><p>${renderInline(p.text)}</p>`,
50
51
  details,
51
52
  controls: `<div class="stepper" role="group" aria-label="${esc(ui.stepsGroup)}"><button type="button" class="sbtn" data-role="back" aria-label="${esc(ui.previousStep)}"${p.canBack ? "" : " disabled"}><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3 5 8l5 5"/></svg></button><ol class="segs">${steps.map((title, n) => `<li><button type="button" data-seg="${n}" aria-label="${esc(ui.step)} ${n + 1}: ${esc(title)}"${n === index ? ' aria-current="step"' : ""} class="${n < index ? "done" : n === index ? "now" : ""}"></button></li>`).join("")}</ol><button type="button" class="sbtn fwd" data-role="next" aria-label="${esc(ui.nextStep)}"${p.canNext ? "" : " disabled"}><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 3l5 5-5 5"/></svg></button></div><div class="hint">${p.nextScenario ? `${esc(ui.nextScenario)} <button type="button" class="linkbtn" data-role="nextscenario">${esc(p.nextScenario)}</button>. ` : ""}${esc(ui.hint)}</div>`,
52
53
  };
package/src/render/svg.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { naturalMapWidth } from "../model/labels.js";
1
2
  import type { ResolvedMap } from "../schema.js";
2
3
  import { derive, type Frame, type Badge } from "../model/frame.js";
3
4
  import { initialState } from "../model/state.js";
@@ -16,11 +17,11 @@ export function renderSvg(
16
17
  ): string {
17
18
  const frame = options.frame ?? derive(map, initialState),
18
19
  marker = esc(
19
- options.markerId ?? `map-arrow-${map.spread.replaceAll(".", "-")}`,
20
+ options.markerId ?? `map-arrow-${map.id.replaceAll(".", "-")}`,
20
21
  );
21
- let html = `<svg viewBox="0 0 ${map.viewBox.join(" ")}" role="img" aria-label="${esc(map.title)}"><defs><marker id="${marker}" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 z" fill="var(--muted-fg)"></path></marker></defs><g data-map-layers>`;
22
+ let html = `<svg width="${naturalMapWidth(map.viewBox[0])}" viewBox="0 0 ${map.viewBox.join(" ")}" role="img" aria-label="${esc(map.title)}"><defs><marker id="${marker}" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8 z" fill="var(--muted-fg)"></path></marker></defs><g data-map-layers>`;
22
23
  for (const [id, l] of Object.entries(map.lanes))
23
- html += `<g class="lane${frame.lanes[id].revealed ? "" : " ghost"}" data-lane="${esc(id)}" style="--c:var(--${esc(l.layer)})"><rect x="${l.x ?? 6}" y="${l.y}" width="${l.w ?? map.viewBox[0] - 12}" height="${l.h}" rx="6"></rect><text x="16" y="${l.y + 16}">${esc(l.label)}</text></g>`;
24
+ html += `<g class="lane${frame.lanes[id].revealed ? "" : " ghost"}" data-lane="${esc(id)}" style="--c:var(--cmap-layer-${esc(l.layer)},var(--cmap-layer))"><rect x="${l.x ?? 6}" y="${l.y}" width="${l.w ?? map.viewBox[0] - 12}" height="${l.h}" rx="6"></rect><text x="${map.direction === "right" ? (l.x ?? 6) + 10 : 16}" y="${l.y + 16}">${esc(l.label)}</text></g>`;
24
25
  for (const [id, f] of Object.entries(map.frames)) {
25
26
  const [x, y, w, h] = f.box;
26
27
  html += `<g class="frame${frame.frames[id].revealed ? "" : " ghost"}" data-frame="${esc(id)}"><rect x="${x}" y="${y}" width="${w}" height="${h}" rx="5"></rect><text x="${x + w - 8}" y="${y + 16}" text-anchor="end">${esc(f.label)}</text></g>`;
@@ -35,7 +36,7 @@ export function renderSvg(
35
36
  const numbers = Object.entries(map.callouts)
36
37
  .filter(([, ids]) => ids.includes(id))
37
38
  .map(([number]) => number);
38
- html += `<g class="node${n.custom ? " custom" : ""}${n.fail ? " fail" : ""}${f.revealed ? "" : " ghost"}${f.current ? " cur" : ""}" style="--c:var(--${esc(n.layer)})" data-node="${esc(id)}"${numbers.length ? ` data-callout="${esc(numbers.join(" "))}"` : ""}><rect x="${x}" y="${y}" width="${w}" height="${h}" rx="5"></rect><text x="${x + 10}" y="${y + (n.tag ? 17 : h / 2 + 4.5)}" class="${n.mono ? "mono" : ""}">${esc(f.label)}</text>${n.tag ? `<text x="${x + 10}" y="${y + 32}" class="tag">${esc(n.tag)}</text>` : ""}</g>`;
39
+ html += `<g class="node${n.custom ? " custom" : ""}${n.fail ? " fail" : ""}${f.revealed ? "" : " ghost"}${f.current ? " cur" : ""}" style="--c:var(--cmap-layer-${esc(n.layer)},var(--cmap-layer))" data-node="${esc(id)}"${numbers.length ? ` data-callout="${esc(numbers.join(" "))}"` : ""}><rect x="${x}" y="${y}" width="${w}" height="${h}" rx="5"></rect><text x="${x + 10}" y="${y + (n.tag ? 17 : h / 2 + 4.5)}" class="${n.mono ? "mono" : ""}">${esc(f.label)}</text>${n.tag ? `<text x="${x + 10}" y="${y + 32}" class="tag">${esc(n.tag)}</text>` : ""}</g>`;
39
40
  }
40
41
  html += `</g><g data-map-edge-labels>`;
41
42
  for (const [id, e] of Object.entries(map.edges))