@motionscript/math 0.0.0-stage → 0.1.0-alpha.10

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 (335) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +49 -0
  4. package/README.md +389 -2
  5. package/dist/annotate/angle-mark.d.ts +96 -0
  6. package/dist/annotate/angle-mark.d.ts.map +1 -0
  7. package/dist/annotate/angle-mark.js +97 -0
  8. package/dist/annotate/angle-mark.js.map +1 -0
  9. package/dist/annotate/curly-brace.d.ts +115 -0
  10. package/dist/annotate/curly-brace.d.ts.map +1 -0
  11. package/dist/annotate/curly-brace.js +99 -0
  12. package/dist/annotate/curly-brace.js.map +1 -0
  13. package/dist/annotate/emphasis-mark.d.ts +80 -0
  14. package/dist/annotate/emphasis-mark.d.ts.map +1 -0
  15. package/dist/annotate/emphasis-mark.js +80 -0
  16. package/dist/annotate/emphasis-mark.js.map +1 -0
  17. package/dist/browser/THIRD_PARTY_LICENSES.txt +420 -0
  18. package/dist/browser/chunks/chunk-IRZCG6PM.js +2 -0
  19. package/dist/browser/chunks/chunk-IRZCG6PM.js.map +7 -0
  20. package/dist/browser/chunks/chunk-WMVW6ZIV.js +2 -0
  21. package/dist/browser/chunks/chunk-WMVW6ZIV.js.map +7 -0
  22. package/dist/browser/chunks/mathjax-WV55AC2P.js +61 -0
  23. package/dist/browser/chunks/mathjax-WV55AC2P.js.map +7 -0
  24. package/dist/browser/index.js +2 -0
  25. package/dist/browser/index.js.map +7 -0
  26. package/dist/browser/kit.js +2 -0
  27. package/dist/browser/kit.js.map +7 -0
  28. package/dist/browser/manifest.json +30 -0
  29. package/dist/browser/tex.js +2 -0
  30. package/dist/browser/tex.js.map +7 -0
  31. package/dist/engine.d.ts +71 -0
  32. package/dist/engine.d.ts.map +1 -0
  33. package/dist/engine.js +45 -0
  34. package/dist/engine.js.map +1 -0
  35. package/dist/index.d.ts +30 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +30 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/kit/brace.d.ts +8 -0
  40. package/dist/kit/brace.d.ts.map +1 -0
  41. package/dist/kit/brace.js +36 -0
  42. package/dist/kit/brace.js.map +1 -0
  43. package/dist/kit/cache.d.ts +30 -0
  44. package/dist/kit/cache.d.ts.map +1 -0
  45. package/dist/kit/cache.js +53 -0
  46. package/dist/kit/cache.js.map +1 -0
  47. package/dist/kit/component.d.ts +51 -0
  48. package/dist/kit/component.d.ts.map +1 -0
  49. package/dist/kit/component.js +30 -0
  50. package/dist/kit/component.js.map +1 -0
  51. package/dist/kit/contour.d.ts +8 -0
  52. package/dist/kit/contour.d.ts.map +1 -0
  53. package/dist/kit/contour.js +93 -0
  54. package/dist/kit/contour.js.map +1 -0
  55. package/dist/kit/coords.d.ts +69 -0
  56. package/dist/kit/coords.d.ts.map +1 -0
  57. package/dist/kit/coords.js +224 -0
  58. package/dist/kit/coords.js.map +1 -0
  59. package/dist/kit/curve.d.ts +28 -0
  60. package/dist/kit/curve.d.ts.map +1 -0
  61. package/dist/kit/curve.js +29 -0
  62. package/dist/kit/curve.js.map +1 -0
  63. package/dist/kit/equation.d.ts +61 -0
  64. package/dist/kit/equation.d.ts.map +1 -0
  65. package/dist/kit/equation.js +168 -0
  66. package/dist/kit/equation.js.map +1 -0
  67. package/dist/kit/equation3d.d.ts +50 -0
  68. package/dist/kit/equation3d.d.ts.map +1 -0
  69. package/dist/kit/equation3d.js +103 -0
  70. package/dist/kit/equation3d.js.map +1 -0
  71. package/dist/kit/expression.d.ts +35 -0
  72. package/dist/kit/expression.d.ts.map +1 -0
  73. package/dist/kit/expression.js +124 -0
  74. package/dist/kit/expression.js.map +1 -0
  75. package/dist/kit/field-mark.d.ts +79 -0
  76. package/dist/kit/field-mark.d.ts.map +1 -0
  77. package/dist/kit/field-mark.js +109 -0
  78. package/dist/kit/field-mark.js.map +1 -0
  79. package/dist/kit/field.d.ts +14 -0
  80. package/dist/kit/field.d.ts.map +1 -0
  81. package/dist/kit/field.js +46 -0
  82. package/dist/kit/field.js.map +1 -0
  83. package/dist/kit/follow.d.ts +109 -0
  84. package/dist/kit/follow.d.ts.map +1 -0
  85. package/dist/kit/follow.js +163 -0
  86. package/dist/kit/follow.js.map +1 -0
  87. package/dist/kit/furniture.d.ts +32 -0
  88. package/dist/kit/furniture.d.ts.map +1 -0
  89. package/dist/kit/furniture.js +92 -0
  90. package/dist/kit/furniture.js.map +1 -0
  91. package/dist/kit/geometry.d.ts +13 -0
  92. package/dist/kit/geometry.d.ts.map +1 -0
  93. package/dist/kit/geometry.js +54 -0
  94. package/dist/kit/geometry.js.map +1 -0
  95. package/dist/kit/graph.d.ts +46 -0
  96. package/dist/kit/graph.d.ts.map +1 -0
  97. package/dist/kit/graph.js +90 -0
  98. package/dist/kit/graph.js.map +1 -0
  99. package/dist/kit/mark.d.ts +72 -0
  100. package/dist/kit/mark.d.ts.map +1 -0
  101. package/dist/kit/mark.js +87 -0
  102. package/dist/kit/mark.js.map +1 -0
  103. package/dist/kit/part-fills.d.ts +23 -0
  104. package/dist/kit/part-fills.d.ts.map +1 -0
  105. package/dist/kit/part-fills.js +46 -0
  106. package/dist/kit/part-fills.js.map +1 -0
  107. package/dist/kit/place.d.ts +20 -0
  108. package/dist/kit/place.d.ts.map +1 -0
  109. package/dist/kit/place.js +66 -0
  110. package/dist/kit/place.js.map +1 -0
  111. package/dist/kit/sampler.d.ts +17 -0
  112. package/dist/kit/sampler.d.ts.map +1 -0
  113. package/dist/kit/sampler.js +250 -0
  114. package/dist/kit/sampler.js.map +1 -0
  115. package/dist/kit/scale.d.ts +12 -0
  116. package/dist/kit/scale.d.ts.map +1 -0
  117. package/dist/kit/scale.js +37 -0
  118. package/dist/kit/scale.js.map +1 -0
  119. package/dist/kit/source.d.ts +22 -0
  120. package/dist/kit/source.d.ts.map +1 -0
  121. package/dist/kit/source.js +45 -0
  122. package/dist/kit/source.js.map +1 -0
  123. package/dist/kit/system.d.ts +31 -0
  124. package/dist/kit/system.d.ts.map +1 -0
  125. package/dist/kit/system.js +71 -0
  126. package/dist/kit/system.js.map +1 -0
  127. package/dist/kit/ticks.d.ts +19 -0
  128. package/dist/kit/ticks.d.ts.map +1 -0
  129. package/dist/kit/ticks.js +78 -0
  130. package/dist/kit/ticks.js.map +1 -0
  131. package/dist/kit/withdrawn.d.ts +9 -0
  132. package/dist/kit/withdrawn.d.ts.map +1 -0
  133. package/dist/kit/withdrawn.js +9 -0
  134. package/dist/kit/withdrawn.js.map +1 -0
  135. package/dist/marks/curve-area.d.ts +51 -0
  136. package/dist/marks/curve-area.d.ts.map +1 -0
  137. package/dist/marks/curve-area.js +59 -0
  138. package/dist/marks/curve-area.js.map +1 -0
  139. package/dist/marks/drop-lines.d.ts +57 -0
  140. package/dist/marks/drop-lines.d.ts.map +1 -0
  141. package/dist/marks/drop-lines.js +43 -0
  142. package/dist/marks/drop-lines.js.map +1 -0
  143. package/dist/marks/plot-point.d.ts +71 -0
  144. package/dist/marks/plot-point.d.ts.map +1 -0
  145. package/dist/marks/plot-point.js +71 -0
  146. package/dist/marks/plot-point.js.map +1 -0
  147. package/dist/marks/riemann-sum.d.ts +58 -0
  148. package/dist/marks/riemann-sum.d.ts.map +1 -0
  149. package/dist/marks/riemann-sum.js +63 -0
  150. package/dist/marks/riemann-sum.js.map +1 -0
  151. package/dist/marks/tangent-line.d.ts +71 -0
  152. package/dist/marks/tangent-line.d.ts.map +1 -0
  153. package/dist/marks/tangent-line.js +89 -0
  154. package/dist/marks/tangent-line.js.map +1 -0
  155. package/dist/marks/vector-arrow.d.ts +60 -0
  156. package/dist/marks/vector-arrow.d.ts.map +1 -0
  157. package/dist/marks/vector-arrow.js +67 -0
  158. package/dist/marks/vector-arrow.js.map +1 -0
  159. package/dist/nodes.d.ts +43 -0
  160. package/dist/nodes.d.ts.map +1 -0
  161. package/dist/nodes.js +57 -0
  162. package/dist/nodes.js.map +1 -0
  163. package/dist/plots/function-plot.d.ts +159 -0
  164. package/dist/plots/function-plot.d.ts.map +1 -0
  165. package/dist/plots/function-plot.js +184 -0
  166. package/dist/plots/function-plot.js.map +1 -0
  167. package/dist/plots/points-plot.d.ts +64 -0
  168. package/dist/plots/points-plot.d.ts.map +1 -0
  169. package/dist/plots/points-plot.js +72 -0
  170. package/dist/plots/points-plot.js.map +1 -0
  171. package/dist/plots/stream-lines.d.ts +76 -0
  172. package/dist/plots/stream-lines.d.ts.map +1 -0
  173. package/dist/plots/stream-lines.js +122 -0
  174. package/dist/plots/stream-lines.js.map +1 -0
  175. package/dist/plots/traced-path.d.ts +70 -0
  176. package/dist/plots/traced-path.d.ts.map +1 -0
  177. package/dist/plots/traced-path.js +41 -0
  178. package/dist/plots/traced-path.js.map +1 -0
  179. package/dist/plots/vector-field.d.ts +60 -0
  180. package/dist/plots/vector-field.d.ts.map +1 -0
  181. package/dist/plots/vector-field.js +77 -0
  182. package/dist/plots/vector-field.js.map +1 -0
  183. package/dist/structures/graph-layout.d.ts +11 -0
  184. package/dist/structures/graph-layout.d.ts.map +1 -0
  185. package/dist/structures/graph-layout.js +135 -0
  186. package/dist/structures/graph-layout.js.map +1 -0
  187. package/dist/structures/network-graph.d.ts +174 -0
  188. package/dist/structures/network-graph.d.ts.map +1 -0
  189. package/dist/structures/network-graph.js +240 -0
  190. package/dist/structures/network-graph.js.map +1 -0
  191. package/dist/structures/sample-space.d.ts +114 -0
  192. package/dist/structures/sample-space.d.ts.map +1 -0
  193. package/dist/structures/sample-space.js +161 -0
  194. package/dist/structures/sample-space.js.map +1 -0
  195. package/dist/systems/axes2d.d.ts +197 -0
  196. package/dist/systems/axes2d.d.ts.map +1 -0
  197. package/dist/systems/axes2d.js +157 -0
  198. package/dist/systems/axes2d.js.map +1 -0
  199. package/dist/systems/number-line.d.ts +101 -0
  200. package/dist/systems/number-line.d.ts.map +1 -0
  201. package/dist/systems/number-line.js +91 -0
  202. package/dist/systems/number-line.js.map +1 -0
  203. package/dist/systems/number-plane.d.ts +168 -0
  204. package/dist/systems/number-plane.d.ts.map +1 -0
  205. package/dist/systems/number-plane.js +186 -0
  206. package/dist/systems/number-plane.js.map +1 -0
  207. package/dist/systems/polar-plane.d.ts +98 -0
  208. package/dist/systems/polar-plane.d.ts.map +1 -0
  209. package/dist/systems/polar-plane.js +139 -0
  210. package/dist/systems/polar-plane.js.map +1 -0
  211. package/dist/tex/geometry.d.ts +85 -0
  212. package/dist/tex/geometry.d.ts.map +1 -0
  213. package/dist/tex/geometry.js +632 -0
  214. package/dist/tex/geometry.js.map +1 -0
  215. package/dist/tex/index.d.ts +11 -0
  216. package/dist/tex/index.d.ts.map +1 -0
  217. package/dist/tex/index.js +10 -0
  218. package/dist/tex/index.js.map +1 -0
  219. package/dist/tex/mathjax.d.ts +33 -0
  220. package/dist/tex/mathjax.d.ts.map +1 -0
  221. package/dist/tex/mathjax.js +74 -0
  222. package/dist/tex/mathjax.js.map +1 -0
  223. package/dist/tex/matrix.d.ts +101 -0
  224. package/dist/tex/matrix.d.ts.map +1 -0
  225. package/dist/tex/matrix.js +56 -0
  226. package/dist/tex/matrix.js.map +1 -0
  227. package/dist/tex/node.d.ts +98 -0
  228. package/dist/tex/node.d.ts.map +1 -0
  229. package/dist/tex/node.js +25 -0
  230. package/dist/tex/node.js.map +1 -0
  231. package/dist/tex/tween.d.ts +50 -0
  232. package/dist/tex/tween.d.ts.map +1 -0
  233. package/dist/tex/tween.js +253 -0
  234. package/dist/tex/tween.js.map +1 -0
  235. package/dist/tex/typeset.d.ts +133 -0
  236. package/dist/tex/typeset.d.ts.map +1 -0
  237. package/dist/tex/typeset.js +403 -0
  238. package/dist/tex/typeset.js.map +1 -0
  239. package/dist/three/axes3d.d.ts +247 -0
  240. package/dist/three/axes3d.d.ts.map +1 -0
  241. package/dist/three/axes3d.js +187 -0
  242. package/dist/three/axes3d.js.map +1 -0
  243. package/dist/three/curve-plot3d.d.ts +126 -0
  244. package/dist/three/curve-plot3d.d.ts.map +1 -0
  245. package/dist/three/curve-plot3d.js +109 -0
  246. package/dist/three/curve-plot3d.js.map +1 -0
  247. package/dist/three/entries.d.ts +17 -0
  248. package/dist/three/entries.d.ts.map +1 -0
  249. package/dist/three/entries.js +15 -0
  250. package/dist/three/entries.js.map +1 -0
  251. package/dist/three/label3d.d.ts +11 -0
  252. package/dist/three/label3d.d.ts.map +1 -0
  253. package/dist/three/label3d.js +42 -0
  254. package/dist/three/label3d.js.map +1 -0
  255. package/dist/three/plot-point3d.d.ts +99 -0
  256. package/dist/three/plot-point3d.d.ts.map +1 -0
  257. package/dist/three/plot-point3d.js +34 -0
  258. package/dist/three/plot-point3d.js.map +1 -0
  259. package/dist/three/space.d.ts +43 -0
  260. package/dist/three/space.d.ts.map +1 -0
  261. package/dist/three/space.js +58 -0
  262. package/dist/three/space.js.map +1 -0
  263. package/dist/three/surface-plot3d.d.ts +207 -0
  264. package/dist/three/surface-plot3d.d.ts.map +1 -0
  265. package/dist/three/surface-plot3d.js +261 -0
  266. package/dist/three/surface-plot3d.js.map +1 -0
  267. package/dist/three/vector-arrow3d.d.ts +96 -0
  268. package/dist/three/vector-arrow3d.d.ts.map +1 -0
  269. package/dist/three/vector-arrow3d.js +53 -0
  270. package/dist/three/vector-arrow3d.js.map +1 -0
  271. package/package.json +80 -3
  272. package/registry.json +251 -0
  273. package/src/annotate/angle-mark.ts +137 -0
  274. package/src/annotate/curly-brace.ts +148 -0
  275. package/src/annotate/emphasis-mark.ts +118 -0
  276. package/src/engine.ts +86 -0
  277. package/src/index.ts +29 -0
  278. package/src/kit/brace.ts +37 -0
  279. package/src/kit/cache.ts +61 -0
  280. package/src/kit/component.ts +57 -0
  281. package/src/kit/contour.ts +94 -0
  282. package/src/kit/coords.ts +278 -0
  283. package/src/kit/curve.ts +47 -0
  284. package/src/kit/equation.ts +181 -0
  285. package/src/kit/equation3d.ts +137 -0
  286. package/src/kit/expression.ts +159 -0
  287. package/src/kit/field-mark.ts +171 -0
  288. package/src/kit/field.ts +50 -0
  289. package/src/kit/follow.ts +229 -0
  290. package/src/kit/furniture.ts +113 -0
  291. package/src/kit/geometry.ts +49 -0
  292. package/src/kit/graph.ts +116 -0
  293. package/src/kit/mark.ts +152 -0
  294. package/src/kit/part-fills.ts +61 -0
  295. package/src/kit/place.ts +77 -0
  296. package/src/kit/sampler.ts +281 -0
  297. package/src/kit/scale.ts +39 -0
  298. package/src/kit/source.ts +57 -0
  299. package/src/kit/system.ts +105 -0
  300. package/src/kit/ticks.ts +85 -0
  301. package/src/kit/withdrawn.ts +8 -0
  302. package/src/marks/curve-area.ts +89 -0
  303. package/src/marks/drop-lines.ts +71 -0
  304. package/src/marks/plot-point.ts +102 -0
  305. package/src/marks/riemann-sum.ts +99 -0
  306. package/src/marks/tangent-line.ts +119 -0
  307. package/src/marks/vector-arrow.ts +98 -0
  308. package/src/nodes.ts +99 -0
  309. package/src/plots/function-plot.ts +220 -0
  310. package/src/plots/points-plot.ts +103 -0
  311. package/src/plots/stream-lines.ts +160 -0
  312. package/src/plots/traced-path.ts +70 -0
  313. package/src/plots/vector-field.ts +107 -0
  314. package/src/structures/graph-layout.ts +145 -0
  315. package/src/structures/network-graph.ts +291 -0
  316. package/src/structures/sample-space.ts +210 -0
  317. package/src/systems/axes2d.ts +226 -0
  318. package/src/systems/number-line.ts +130 -0
  319. package/src/systems/number-plane.ts +232 -0
  320. package/src/systems/polar-plane.ts +177 -0
  321. package/src/tex/geometry.ts +703 -0
  322. package/src/tex/index.ts +15 -0
  323. package/src/tex/mathjax.ts +82 -0
  324. package/src/tex/matrix.ts +97 -0
  325. package/src/tex/node.ts +74 -0
  326. package/src/tex/tween.ts +308 -0
  327. package/src/tex/typeset.ts +461 -0
  328. package/src/three/axes3d.ts +267 -0
  329. package/src/three/curve-plot3d.ts +146 -0
  330. package/src/three/entries.ts +42 -0
  331. package/src/three/label3d.ts +52 -0
  332. package/src/three/plot-point3d.ts +63 -0
  333. package/src/three/space.ts +92 -0
  334. package/src/three/surface-plot3d.ts +318 -0
  335. package/src/three/vector-arrow3d.ts +88 -0
@@ -0,0 +1,145 @@
1
+ import type { Vector2 } from "@motionscript/sdk";
2
+
3
+ /** Where a graph's vertices are placed, inside a square from -1 to 1 each way, y up. */
4
+
5
+ export type GraphLayout = "circular" | "spring" | "tree" | "grid";
6
+
7
+ export const GRAPH_LAYOUTS: readonly GraphLayout[] = ["circular", "spring", "tree", "grid"];
8
+
9
+ export interface GraphEdge {
10
+ from: string;
11
+ to: string;
12
+ }
13
+
14
+ /** Each vertex's place under `layout`, by name. */
15
+ export function layOut(layout: GraphLayout, vertices: readonly string[], edges: readonly GraphEdge[], root: string): Map<string, Vector2> {
16
+ const n = vertices.length;
17
+ if (n === 0) return new Map();
18
+ if (n === 1) return new Map([[vertices[0], { x: 0, y: 0 }]]);
19
+ switch (layout) {
20
+ case "grid":
21
+ return grid(vertices);
22
+ case "tree":
23
+ return fill(tree(vertices, edges, root));
24
+ case "spring":
25
+ return fill(spring(vertices, edges));
26
+ default:
27
+ return circular(vertices);
28
+ }
29
+ }
30
+
31
+ function circular(vertices: readonly string[]): Map<string, Vector2> {
32
+ const n = vertices.length;
33
+ // The first at the top, the rest clockwise, as a clock is read.
34
+ return new Map(vertices.map((name, i) => {
35
+ const angle = Math.PI / 2 - (2 * Math.PI * i) / n;
36
+ return [name, { x: Math.cos(angle), y: Math.sin(angle) }];
37
+ }));
38
+ }
39
+
40
+ function grid(vertices: readonly string[]): Map<string, Vector2> {
41
+ const columns = Math.ceil(Math.sqrt(vertices.length));
42
+ const rows = Math.ceil(vertices.length / columns);
43
+ const at = (i: number, count: number) => (count === 1 ? 0 : -1 + (2 * i) / (count - 1));
44
+ return new Map(vertices.map((name, i) => [name, { x: at(i % columns, columns), y: -at(Math.floor(i / columns), rows) }]));
45
+ }
46
+
47
+ function neighbours(vertices: readonly string[], edges: readonly GraphEdge[]): Map<string, string[]> {
48
+ const near = new Map(vertices.map((name) => [name, [] as string[]]));
49
+ for (const { from, to } of edges) {
50
+ if (from === to || !near.has(from) || !near.has(to)) continue;
51
+ near.get(from)!.push(to);
52
+ near.get(to)!.push(from);
53
+ }
54
+ return near;
55
+ }
56
+
57
+ /** Levels down from `root`, and across by the leaves under each, every component its own tree beside the last. */
58
+ function tree(vertices: readonly string[], edges: readonly GraphEdge[], root: string): Map<string, Vector2> {
59
+ const near = neighbours(vertices, edges);
60
+ const placed = new Map<string, Vector2>();
61
+ let column = 0;
62
+ const visit = (name: string, depth: number, seen: Set<string>): number => {
63
+ seen.add(name);
64
+ const children = near.get(name)!.filter((next) => !seen.has(next));
65
+ for (const child of children) seen.add(child);
66
+ if (children.length === 0) {
67
+ placed.set(name, { x: column++, y: -depth });
68
+ return placed.get(name)!.x;
69
+ }
70
+ const xs = children.map((child) => visit(child, depth + 1, seen));
71
+ const x = (xs[0] + xs[xs.length - 1]) / 2;
72
+ placed.set(name, { x, y: -depth });
73
+ return x;
74
+ };
75
+ const seen = new Set<string>();
76
+ const first = near.has(root) ? root : vertices[0];
77
+ for (const start of [first, ...vertices]) if (!seen.has(start)) visit(start, 0, seen);
78
+ return placed;
79
+ }
80
+
81
+ /** Edges pull and every pair pushes, from the circle, for a fixed number of cooling steps: the same answer every time. */
82
+ function spring(vertices: readonly string[], edges: readonly GraphEdge[]): Map<string, Vector2> {
83
+ const n = vertices.length;
84
+ const index = new Map(vertices.map((name, i) => [name, i]));
85
+ const start = circular(vertices);
86
+ const x = vertices.map((name) => start.get(name)!.x);
87
+ const y = vertices.map((name) => start.get(name)!.y);
88
+ const links = edges.flatMap(({ from, to }) => {
89
+ const a = index.get(from);
90
+ const b = index.get(to);
91
+ return a === undefined || b === undefined || a === b ? [] : [[a, b] as const];
92
+ });
93
+ const k = Math.sqrt(4 / n);
94
+ const steps = 160;
95
+ for (let step = 0; step < steps; step++) {
96
+ const dx = new Float64Array(n);
97
+ const dy = new Float64Array(n);
98
+ for (let i = 0; i < n; i++) {
99
+ for (let j = i + 1; j < n; j++) {
100
+ let ex = x[i] - x[j];
101
+ let ey = y[i] - y[j];
102
+ let d = Math.hypot(ex, ey);
103
+ // Two on one spot are parted along a fixed, if arbitrary, line.
104
+ if (d < 1e-6) [ex, ey, d] = [1e-3 * (i - j), 1e-3, 1e-3];
105
+ const push = (k * k) / d;
106
+ dx[i] += (ex / d) * push;
107
+ dy[i] += (ey / d) * push;
108
+ dx[j] -= (ex / d) * push;
109
+ dy[j] -= (ey / d) * push;
110
+ }
111
+ }
112
+ for (const [a, b] of links) {
113
+ const ex = x[a] - x[b];
114
+ const ey = y[a] - y[b];
115
+ const d = Math.max(Math.hypot(ex, ey), 1e-6);
116
+ const pull = (d * d) / k;
117
+ dx[a] -= (ex / d) * pull;
118
+ dy[a] -= (ey / d) * pull;
119
+ dx[b] += (ex / d) * pull;
120
+ dy[b] += (ey / d) * pull;
121
+ }
122
+ const limit = 0.12 * (1 - step / steps);
123
+ for (let i = 0; i < n; i++) {
124
+ const d = Math.hypot(dx[i], dy[i]);
125
+ if (d > 0) {
126
+ x[i] += (dx[i] / d) * Math.min(d, limit);
127
+ y[i] += (dy[i] / d) * Math.min(d, limit);
128
+ }
129
+ }
130
+ }
131
+ return new Map(vertices.map((name, i) => [name, { x: x[i], y: y[i] }]));
132
+ }
133
+
134
+ /** `placed` stretched to reach -1 and 1 on each axis it spreads along, and centred on the one it does not. */
135
+ function fill(placed: Map<string, Vector2>): Map<string, Vector2> {
136
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
137
+ for (const p of placed.values()) {
138
+ minX = Math.min(minX, p.x);
139
+ maxX = Math.max(maxX, p.x);
140
+ minY = Math.min(minY, p.y);
141
+ maxY = Math.max(maxY, p.y);
142
+ }
143
+ const scale = (v: number, lo: number, hi: number) => (hi - lo < 1e-9 ? 0 : -1 + (2 * (v - lo)) / (hi - lo));
144
+ return new Map([...placed].map(([name, p]) => [name, { x: scale(p.x, minX, maxX), y: scale(p.y, minY, maxY) }]));
145
+ }
@@ -0,0 +1,291 @@
1
+ import {
2
+ component2d,
3
+ Graphics2D,
4
+ Types,
5
+ type Color,
6
+ type Fill,
7
+ type FillResolved,
8
+ type NodeOf,
9
+ type NormalizedColor,
10
+ type PaintProps,
11
+ type RenderContext,
12
+ type ShadowResolved,
13
+ type Size2D,
14
+ type Stroke,
15
+ type StrokeResolved,
16
+ type Values,
17
+ type Vector2,
18
+ // Named so the emitted declaration reaches these through the sdk, not core.
19
+ type Node2D as _Node2D,
20
+ type Node2DProps as _Node2DProps,
21
+ type Shadow as _Shadow,
22
+ } from "@motionscript/sdk";
23
+ import { createBoundedCache } from "../kit/cache";
24
+ import { listed, PAINT, PAINT_COMMANDS, painted } from "../kit/component";
25
+ import { drawLabels, loadFormulas, type Label } from "../kit/furniture";
26
+ import { lerpPartFills, partPaint, readPartFills, withPartFill, type PartFill, type PartFillResolved } from "../kit/part-fills";
27
+ import { GRAPH_LAYOUTS, layOut, type GraphEdge, type GraphLayout } from "./graph-layout";
28
+
29
+ /** A vertex placed by hand, in the graph's box from -1 to 1 each way, y up. */
30
+ export interface GraphPosition {
31
+ vertex: string;
32
+ x: number;
33
+ y: number;
34
+ }
35
+
36
+ export interface NetworkGraphProps extends PaintProps {
37
+ vertices?: string[];
38
+ edges?: GraphEdge[];
39
+ directed?: boolean;
40
+ arrangement?: GraphLayout;
41
+ root?: string;
42
+ positions?: GraphPosition[];
43
+ vertexRadius?: number;
44
+ vertexStroke?: Stroke;
45
+ labels?: boolean;
46
+ labelSize?: number;
47
+ labelColor?: Color;
48
+ fontFamily?: string;
49
+ partFills?: PartFill[];
50
+ }
51
+
52
+ // Every list keeps each entry as it was written, a blank or a repeat included, so
53
+ // an editor showing the list shows the row it just added. What is drawn skips
54
+ // what is not complete yet (`names`, `links`).
55
+
56
+ function readVertices(value: readonly unknown[] | undefined): string[] {
57
+ return (Array.isArray(value) ? value : []).map((name) => String(name ?? ""));
58
+ }
59
+
60
+ // An edge reads from `{ from, to }` or a pair, so a list written by hand is as good as one from a table.
61
+ function readEdges(value: readonly unknown[] | undefined): GraphEdge[] {
62
+ return (Array.isArray(value) ? value : []).map((edge) => {
63
+ const [from, to] = Array.isArray(edge) ? edge : [(edge as GraphEdge)?.from, (edge as GraphEdge)?.to];
64
+ return { from: String(from ?? ""), to: String(to ?? "") };
65
+ });
66
+ }
67
+
68
+ function readPositions(value: readonly GraphPosition[] | undefined): GraphPosition[] {
69
+ const at = (n: unknown) => (typeof n === "number" && Number.isFinite(n) ? n : 0);
70
+ return (Array.isArray(value) ? value : []).map((entry) => ({ vertex: String(entry?.vertex ?? ""), x: at(entry?.x), y: at(entry?.y) }));
71
+ }
72
+
73
+ /** How far a directed edge and the one back between the same two vertices bow apart, as a share of their length. */
74
+ const BOW = 0.12;
75
+
76
+ const NUL = String.fromCharCode(0);
77
+
78
+ const state = {
79
+ ...PAINT,
80
+ vertices: Types.custom<string[]>([], { resolve: readVertices, animatable: false, kind: "vector" }),
81
+ edges: Types.custom<GraphEdge[]>([], { resolve: readEdges, animatable: false, kind: "vector" }),
82
+ /** Draw each edge as an arrow from its `from` to its `to`. */
83
+ directed: Types.boolean(false, { animatable: false }),
84
+ arrangement: listed(GRAPH_LAYOUTS, "circular", { animatable: false }),
85
+ /** The vertex a tree hangs from; left empty, the first. */
86
+ root: Types.text("", { animatable: false }),
87
+ /** Vertices placed by hand, whatever the layout says, in the box from -1 to 1 each way. */
88
+ positions: Types.custom<GraphPosition[]>([], { resolve: readPositions, animatable: false, kind: "vector" }),
89
+ vertexRadius: Types.number(18, { min: 0, unit: "px" }),
90
+ vertexStroke: Types.stroke([]),
91
+ labels: Types.boolean(true, { animatable: false }),
92
+ labelSize: Types.number(18, { min: 1, unit: "px" }),
93
+ labelColor: Types.color("#111827"),
94
+ fontFamily: Types.text("", { animatable: false }),
95
+ /** Paints for a vertex by its name, or an edge written `a-b`, over the graph's own. */
96
+ partFills: Types.custom<PartFill[], PartFillResolved[]>([], { resolve: readPartFills, lerp: lerpPartFills, kind: "vector" }),
97
+ /** The arrangement an `arrangeTo` is leaving, and how far it is towards the new one. */
98
+ layoutFrom: Types.text("", { private: true }),
99
+ layoutMix: Types.number(1, { private: true }),
100
+ };
101
+
102
+ /** What a graph is drawn from: its own entries, as its fields and its node both read them. */
103
+ export type GraphValues = Values<typeof state>;
104
+
105
+ /**
106
+ * Vertices and the edges between them, arranged by a rule: in a circle, by
107
+ * springs, as a tree from `root`, or in a grid. Its `fill` is the vertices and
108
+ * its `stroke` the edges, with an arrowhead each when `directed`. `arrangeTo`
109
+ * moves every vertex to where another rule places it; `partFillTo` paints a
110
+ * vertex, or an edge written `a-b`. (`layout` is every node's own box.)
111
+ */
112
+ export const NetworkGraph = component2d({
113
+ key: "networkGraph",
114
+ state,
115
+ defaults: {
116
+ fill: "#e5e7eb",
117
+ stroke: { weight: 3, fill: "#9ca3af", align: "center", cap: "round" },
118
+ },
119
+ load: (loader, s) => {
120
+ if (s.fontFamily !== "") loader.font(s.fontFamily);
121
+ if (s.labels) loadFormulas(loader, names(s));
122
+ },
123
+ commands: {
124
+ ...PAINT_COMMANDS,
125
+ /** Move every vertex to where another arrangement places it. */
126
+ arrangeTo: {
127
+ // No default: one left out keeps the arrangement the graph has.
128
+ args: { arrangement: listed(GRAPH_LAYOUTS, undefined) },
129
+ run: (timeline, s) => {
130
+ const from = s.arrangement;
131
+ const to = timeline.args.arrangement ?? from;
132
+ return timeline.animate((t) => ({ arrangement: to, layoutFrom: from, layoutMix: t }));
133
+ },
134
+ },
135
+ /** Paint one part of the graph: a vertex by its name, or an edge written `a-b`. */
136
+ partFillTo: {
137
+ args: { part: Types.text(""), fill: Types.custom<Fill>("#facc15", { kind: "fills" }) },
138
+ run: (timeline, s) => {
139
+ const { part, fill } = timeline.args;
140
+ if (!part || fill == null) return timeline.tween({});
141
+ return timeline.tween({ partFills: withPartFill(s.partFills, { part, fill }) });
142
+ },
143
+ },
144
+ },
145
+ render: (ctx, s) => painted(ctx, () => drawGraph(ctx, s)),
146
+ });
147
+
148
+ export type NetworkGraph = NodeOf<typeof NetworkGraph>;
149
+
150
+ /** Where each vertex is drawn in a graph of `size`, in pixels from its centre, y up. */
151
+ export function vertexPoints(graph: GraphValues, size: Size2D): Map<string, Vector2> {
152
+ const room = graph.vertexRadius + Math.max(2, graph.labelSize * 0.2);
153
+ const halfX = Math.max(0, size.width / 2 - room);
154
+ const halfY = Math.max(0, size.height / 2 - room);
155
+ const to = placed(graph, graph.arrangement);
156
+ const from = graph.layoutMix < 1 && graph.layoutFrom !== "" ? placed(graph, graph.layoutFrom as GraphLayout) : null;
157
+ const t = graph.layoutMix;
158
+ const out = new Map<string, Vector2>();
159
+ for (const [name, p] of to) {
160
+ const q = from?.get(name) ?? p;
161
+ out.set(name, { x: (q.x + (p.x - q.x) * t) * halfX, y: (q.y + (p.y - q.y) * t) * halfY });
162
+ }
163
+ return out;
164
+ }
165
+
166
+ function drawGraph(ctx: RenderContext, graph: GraphValues): void {
167
+ const points = vertexPoints(graph, ctx.size);
168
+ if (points.size === 0) return;
169
+ const parts = new Map((graph.partFills as PartFillResolved[]).map((entry) => [entry.part, entry]));
170
+ drawEdges(ctx, graph, points, parts);
171
+ drawVertices(ctx, graph, points, parts);
172
+ }
173
+
174
+ // Two layouts are held at once while one becomes the other, and a scene may hold several graphs.
175
+ const layouts = createBoundedCache<Map<string, Vector2>>(32);
176
+
177
+ /** Each vertex's place under `layout`, from -1 to 1, a hand-placed one where it is. */
178
+ function placed(graph: GraphValues, layout: GraphLayout): Map<string, Vector2> {
179
+ const vertices = names(graph);
180
+ const edges = links(graph);
181
+ const key = [layout, graph.root, vertices.join(NUL), JSON.stringify(edges), JSON.stringify(graph.positions)].join("|");
182
+ let at = layouts.get(key);
183
+ if (!at) {
184
+ at = layOut(layout, vertices, edges, graph.root.trim());
185
+ for (const { vertex, x, y } of graph.positions) {
186
+ const name = vertex.trim();
187
+ if (at.has(name)) at.set(name, { x, y });
188
+ }
189
+ layouts.set(key, at);
190
+ }
191
+ return at;
192
+ }
193
+
194
+ function drawEdges(ctx: RenderContext, graph: GraphValues, points: Map<string, Vector2>, parts: Map<string, PartFillResolved>): void {
195
+ const stroke = graph.stroke as StrokeResolved[];
196
+ if (stroke.length === 0) return;
197
+ const r = graph.vertexRadius;
198
+ const all = links(graph);
199
+ const pairs = new Set(all.map(({ from, to }) => `${from}${NUL}${to}`));
200
+ const plain = new Graphics2D();
201
+ let drawnPlain = false;
202
+ for (const { from, to } of all) {
203
+ const a = points.get(from);
204
+ const b = points.get(to);
205
+ if (!a || !b) continue;
206
+ const run = from === to ? loop(a, r) : edge(a, b, r, graph.directed && pairs.has(`${to}${NUL}${from}`) ? BOW : 0);
207
+ if (run.length < 2) continue;
208
+ const paint = parts.get(`${from}-${to}`) ?? (graph.directed ? undefined : parts.get(`${to}-${from}`));
209
+ const own = graph.directed || paint !== undefined;
210
+ const g = own ? new Graphics2D() : plain;
211
+ g.line({ points: run, radius: 0, start: graph.start, end: graph.end });
212
+ if (!own) {
213
+ drawnPlain = true;
214
+ continue;
215
+ }
216
+ let layers = stroke;
217
+ if (paint) layers = layers.map((layer) => ({ ...layer, fill: partPaint(layer.fill, paint) }));
218
+ if (graph.directed && from !== to) layers = layers.map((layer) => ({ ...layer, endCap: layer.endCap ?? "triangle" }));
219
+ ctx.draw(g.stroke(layers));
220
+ }
221
+ if (drawnPlain) ctx.draw(plain.stroke(stroke));
222
+ }
223
+
224
+ function drawVertices(ctx: RenderContext, graph: GraphValues, points: Map<string, Vector2>, parts: Map<string, PartFillResolved>): void {
225
+ const r = graph.vertexRadius;
226
+ const fill = graph.fill as FillResolved[];
227
+ const outline = graph.vertexStroke as StrokeResolved[];
228
+ const labels: Label[] = [];
229
+ for (const [name, p] of points) {
230
+ if (r > 0) {
231
+ const paint = partPaint(fill, parts.get(name));
232
+ const disc = new Graphics2D().ellipse({ x: p.x, y: p.y, width: r * 2, height: r * 2 });
233
+ ctx.draw(disc.shadow(graph.shadow as ShadowResolved[]).fill(paint));
234
+ if (outline.length > 0) ctx.draw(new Graphics2D().ellipse({ x: p.x, y: p.y, width: r * 2, height: r * 2 }).stroke(outline));
235
+ }
236
+ if (graph.labels) labels.push({ text: name, at: { x: p.x, y: p.y }, align: "center" });
237
+ }
238
+ for (const part of drawLabels(labels, { fontSize: graph.labelSize, fontFamily: graph.fontFamily, color: graph.labelColor as NormalizedColor })) {
239
+ ctx.draw(part);
240
+ }
241
+ }
242
+
243
+ /** The vertices drawn: each name once, trimmed, the blank ones left out. */
244
+ function names(graph: Pick<GraphValues, "vertices">): string[] {
245
+ return [...new Set(graph.vertices.map((name) => name.trim()).filter((name) => name !== ""))];
246
+ }
247
+
248
+ /** The edges drawn: both ends named. */
249
+ function links(graph: Pick<GraphValues, "edges">): GraphEdge[] {
250
+ return graph.edges.flatMap(({ from, to }) => {
251
+ const a = from.trim();
252
+ const b = to.trim();
253
+ return a === "" || b === "" ? [] : [{ from: a, to: b }];
254
+ });
255
+ }
256
+
257
+ /** An edge from one vertex's rim to the other's, straight or bowed to its left. */
258
+ function edge(a: Vector2, b: Vector2, r: number, bow: number): Vector2[] {
259
+ const dx = b.x - a.x;
260
+ const dy = b.y - a.y;
261
+ const length = Math.hypot(dx, dy);
262
+ if (!(length > 2 * r)) return [];
263
+ if (bow === 0) {
264
+ const ux = dx / length;
265
+ const uy = dy / length;
266
+ return [{ x: a.x + ux * r, y: a.y + uy * r }, { x: b.x - ux * r, y: b.y - uy * r }];
267
+ }
268
+ const mid = { x: (a.x + b.x) / 2 - (dy / length) * bow * length, y: (a.y + b.y) / 2 + (dx / length) * bow * length };
269
+ const run: Vector2[] = [];
270
+ for (let i = 0; i <= 16; i++) {
271
+ const t = i / 16;
272
+ const u = 1 - t;
273
+ run.push({ x: u * u * a.x + 2 * u * t * mid.x + t * t * b.x, y: u * u * a.y + 2 * u * t * mid.y + t * t * b.y });
274
+ }
275
+ // Trimmed back to the rims along the curve.
276
+ const outside = (p: Vector2, c: Vector2) => Math.hypot(p.x - c.x, p.y - c.y) >= r;
277
+ return run.filter((p) => outside(p, a) && outside(p, b));
278
+ }
279
+
280
+ /** An edge from a vertex to itself: a small loop above it. */
281
+ function loop(c: Vector2, r: number): Vector2[] {
282
+ const run: Vector2[] = [];
283
+ const radius = Math.max(r * 0.8, 6);
284
+ const cy = c.y + r + radius * 0.6;
285
+ for (let i = 0; i <= 24; i++) {
286
+ const angle = -Math.PI / 2 + (2 * Math.PI * i) / 24;
287
+ const p = { x: c.x + Math.cos(angle) * radius, y: cy + Math.sin(angle) * radius };
288
+ if (Math.hypot(p.x - c.x, p.y - c.y) >= r) run.push(p);
289
+ }
290
+ return run;
291
+ }
@@ -0,0 +1,210 @@
1
+ import {
2
+ component2d,
3
+ fillOps,
4
+ Graphics2D,
5
+ Types,
6
+ type Color,
7
+ type Fill,
8
+ type FillResolved,
9
+ type NodeOf,
10
+ type NormalizedColor,
11
+ type PaintProps,
12
+ type RenderContext,
13
+ type ShadowResolved,
14
+ type Size2D,
15
+ type StrokeResolved,
16
+ type Values,
17
+ type Vector2,
18
+ // Named so the emitted declaration reaches these through the sdk, not core.
19
+ type Node2D as _Node2D,
20
+ type Node2DProps as _Node2DProps,
21
+ type Shadow as _Shadow,
22
+ type Stroke as _Stroke,
23
+ } from "@motionscript/sdk";
24
+ import { braceOutline } from "../kit/brace";
25
+ import { omit, PAINT, PAINT_COMMANDS, painted } from "../kit/component";
26
+ import { drawLabels, loadFormulas, type Label } from "../kit/furniture";
27
+ import { lerpFillScale, readFillScale } from "../kit/scale";
28
+ import { formatTick } from "../kit/ticks";
29
+
30
+ export interface SampleSpaceProps extends PaintProps {
31
+ columnShares?: number[];
32
+ rowShares?: number[];
33
+ columnFills?: Fill[];
34
+ columnLabels?: string[];
35
+ rowLabels?: string[];
36
+ values?: boolean;
37
+ labelSize?: number;
38
+ labelColor?: Color;
39
+ fontFamily?: string;
40
+ }
41
+
42
+ /** The parts' paints until told otherwise, a column each, round again past the last. */
43
+ const PALETTE = ["#58a6ff", "#f59e0b", "#4ade80", "#f472b6", "#a78bfa", "#2dd4bf"];
44
+
45
+ /** How strongly the lower part of a split column shows its paint. */
46
+ const LOWER = 0.45;
47
+
48
+ function readShares(value: readonly number[] | undefined): number[] {
49
+ return (Array.isArray(value) ? value : []).map((share) => (Number.isFinite(share) && share > 0 ? share : 0));
50
+ }
51
+
52
+ // Shares tween one by one; a different count has nothing to pair with, and changes at the end.
53
+ function lerpShares(from: number[], to: number[], t: number): number[] {
54
+ if (from.length !== to.length) return t < 1 ? from : to;
55
+ return to.map((share, i) => from[i] + (share - from[i]) * t);
56
+ }
57
+
58
+ const state = {
59
+ // Its parts are painted from `columnFills`, and it trims no outline of its own.
60
+ ...omit(PAINT, "fill", "start", "end"),
61
+ /** How the whole is shared across, left to right; any numbers, read as shares of their sum. */
62
+ columnShares: Types.custom<number[]>([1], { resolve: readShares, lerp: lerpShares, kind: "vector" }),
63
+ /** Each column's upper share, 0 to 1; a column without one is not cut across. */
64
+ rowShares: Types.custom<number[]>([], { resolve: readShares, lerp: lerpShares, kind: "vector" }),
65
+ /** Each column's paint, left to right, round again past the last; its lower part shows it fainter. */
66
+ columnFills: Types.custom<Fill[], FillResolved[][]>([], { resolve: readFillScale, lerp: lerpFillScale, kind: "vector" }),
67
+ columnLabels: Types.custom<string[]>([], { animatable: false, kind: "vector" }),
68
+ /** The upper part's name and the lower's, written on the left. */
69
+ rowLabels: Types.custom<string[]>([], { animatable: false, kind: "vector" }),
70
+ /** Write each part's probability in it. */
71
+ values: Types.boolean(false, { animatable: false }),
72
+ labelSize: Types.number(20, { min: 1, unit: "px" }),
73
+ labelColor: Types.color("#e5e7eb"),
74
+ fontFamily: Types.text("", { animatable: false }),
75
+ };
76
+
77
+ /** What a sample space is drawn from: its own entries, as its fields and its node both read them. */
78
+ export type SampleSpaceValues = Values<typeof state>;
79
+
80
+ /** One part of a sample space: its box in pixels from the node's centre, y up, and its probability. */
81
+ export interface SamplePart {
82
+ x: number;
83
+ y: number;
84
+ width: number;
85
+ height: number;
86
+ probability: number;
87
+ column: number;
88
+ upper: boolean;
89
+ }
90
+
91
+ /**
92
+ * A probability's whole, as a box cut into columns by `columnShares` (shares of
93
+ * the whole, P(A) and P(not A)) and each column cut again by its `rowShares` entry
94
+ * (P(B | A) above, the rest below): each part's area is its probability.
95
+ * Braces name the columns below and the rows on the left; `divideTo` moves the
96
+ * cuts.
97
+ */
98
+ export const SampleSpace = component2d({
99
+ key: "sampleSpace",
100
+ state,
101
+ defaults: { stroke: { weight: 2, fill: "#0b0d12", align: "center" } },
102
+ load: (loader, s) => {
103
+ if (s.fontFamily !== "") loader.font(s.fontFamily);
104
+ loadFormulas(loader, [...s.columnLabels, ...s.rowLabels]);
105
+ },
106
+ commands: {
107
+ ...omit(PAINT_COMMANDS, "fillTo", "progressTo", "flash"),
108
+ /** Move the cuts: the columns' shares, each column's upper share, or both. */
109
+ divideTo: { args: ["columnShares", "rowShares"] },
110
+ },
111
+ render: (ctx, s) => painted(ctx, () => drawSpace(ctx, s)),
112
+ });
113
+
114
+ export type SampleSpace = NodeOf<typeof SampleSpace>;
115
+
116
+ /** Each part of a sample space of `size`: columns left to right, upper part first. */
117
+ export function sampleParts(space: SampleSpaceValues, size: Size2D): SamplePart[] {
118
+ const box = boxOf(space, size);
119
+ const shares = space.columnShares;
120
+ const total = shares.reduce((sum, share) => sum + share, 0);
121
+ if (!(total > 0) || box.width <= 0 || box.height <= 0) return [];
122
+ const out: SamplePart[] = [];
123
+ let left = box.x - box.width / 2;
124
+ shares.forEach((share, column) => {
125
+ const width = (box.width * share) / total;
126
+ const p = share / total;
127
+ const cut = space.rowShares[column];
128
+ const top = box.y + box.height / 2;
129
+ if (cut === undefined) {
130
+ out.push({ x: left + width / 2, y: box.y, width, height: box.height, probability: p, column, upper: true });
131
+ } else {
132
+ const upper = Math.min(1, Math.max(0, cut));
133
+ const h = box.height * upper;
134
+ out.push({ x: left + width / 2, y: top - h / 2, width, height: h, probability: p * upper, column, upper: true });
135
+ out.push({ x: left + width / 2, y: top - h - (box.height - h) / 2, width, height: box.height - h, probability: p * (1 - upper), column, upper: false });
136
+ }
137
+ left += width;
138
+ });
139
+ return out;
140
+ }
141
+
142
+ function drawSpace(ctx: RenderContext, space: SampleSpaceValues): void {
143
+ const parts = sampleParts(space, ctx.size);
144
+ if (parts.length === 0) return;
145
+ const fills = space.columnFills;
146
+ const stroke = space.stroke as StrokeResolved[];
147
+ const labels: Label[] = [];
148
+ for (const part of parts) {
149
+ if (!(part.width > 0) || !(part.height > 0)) continue;
150
+ const base = fills.length > 0 ? fills[part.column % fills.length] : fillOps.resolve(PALETTE[part.column % PALETTE.length]);
151
+ const paint = part.upper ? base : base.map((layer) => ({ ...layer, opacity: (layer.opacity ?? 1) * LOWER }));
152
+ const g = new Graphics2D().rect({ x: part.x, y: part.y, width: part.width, height: part.height });
153
+ ctx.draw(g.shadow(space.shadow as ShadowResolved[]).fill(paint));
154
+ if (stroke.length > 0) ctx.draw(new Graphics2D().rect({ x: part.x, y: part.y, width: part.width, height: part.height }).stroke(stroke));
155
+ if (space.values && part.height > space.labelSize && part.width > space.labelSize) {
156
+ labels.push({ text: formatTick(Math.round(part.probability * 1000) / 1000, 0.001), at: { x: part.x, y: part.y }, align: "center" });
157
+ }
158
+ }
159
+ labels.push(...braces(ctx, space, parts));
160
+ const style = { fontSize: space.labelSize, fontFamily: space.fontFamily, color: space.labelColor as NormalizedColor };
161
+ for (const part of drawLabels(labels, style)) ctx.draw(part);
162
+ }
163
+
164
+ /** Room for the braces and their names, below and on the left, taken from the box. */
165
+ function boxOf(space: SampleSpaceValues, size: Size2D): { x: number; y: number; width: number; height: number } {
166
+ const { width, height } = size;
167
+ const room = space.labelSize * 2.6;
168
+ const below = space.columnLabels.some((label) => label !== "") ? room : 0;
169
+ const left = space.rowLabels.some((label) => label !== "") ? room * 1.6 : 0;
170
+ return { x: left / 2, y: below / 2, width: Math.max(0, width - left), height: Math.max(0, height - below) };
171
+ }
172
+
173
+ /** Braces under each column and beside the first column's parts, and the labels that name them. */
174
+ function braces(ctx: RenderContext, space: SampleSpaceValues, parts: readonly SamplePart[]): Label[] {
175
+ const box = boxOf(space, ctx.size);
176
+ const reach = space.labelSize * 0.8;
177
+ const gap = 6;
178
+ const runs = new Graphics2D();
179
+ const labels: Label[] = [];
180
+ let drawn = false;
181
+ const brace = (from: Vector2, to: Vector2, out: Vector2, text: string, align: Label["align"]) => {
182
+ if (text === "") return;
183
+ // A frame centred on the node's own centre, so the path is drawn where it is and not moved onto it.
184
+ runs.path({ data: braceOutline(from, to, out, reach), centerBounds: [-1, -1, 1, 1] });
185
+ drawn = true;
186
+ const mid = { x: (from.x + to.x) / 2, y: (from.y + to.y) / 2 };
187
+ const far = reach + space.labelSize * 0.75;
188
+ labels.push({ text, at: { x: mid.x + out.x * far, y: mid.y + out.y * far }, align });
189
+ };
190
+ const bottom = box.y - box.height / 2 - gap;
191
+ for (const part of parts) {
192
+ if (!part.upper && space.rowShares[part.column] !== undefined) continue;
193
+ const text = space.columnLabels[part.column] ?? "";
194
+ // Left to right along the bottom, so the bulge, to the edge's right, points down.
195
+ brace({ x: part.x + part.width / 2, y: bottom }, { x: part.x - part.width / 2, y: bottom }, { x: 0, y: -1 }, text, "center");
196
+ }
197
+ const first = parts.filter((part) => part.column === 0);
198
+ const left = box.x - box.width / 2 - gap;
199
+ if (space.rowShares[0] !== undefined) {
200
+ first.forEach((part) => {
201
+ const text = space.rowLabels[part.upper ? 0 : 1] ?? "";
202
+ brace({ x: left, y: part.y - part.height / 2 }, { x: left, y: part.y + part.height / 2 }, { x: -1, y: 0 }, text, "right");
203
+ });
204
+ }
205
+ if (drawn) {
206
+ const fill = fillOps.resolve({ type: "solid", color: space.labelColor as NormalizedColor });
207
+ ctx.draw(runs.stroke({ weight: 2, fill, align: "center", cap: "round", join: "round" }));
208
+ }
209
+ return labels;
210
+ }