@motionscript/math 0.1.0-alpha.7 → 0.1.0-alpha.9

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 (181) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/LICENSE +201 -201
  3. package/NOTICE +49 -48
  4. package/README.md +390 -391
  5. package/dist/annotate/angle-mark.d.ts +6 -6
  6. package/dist/annotate/angle-mark.js.map +1 -1
  7. package/dist/annotate/curly-brace.d.ts +9 -9
  8. package/dist/annotate/curly-brace.js.map +1 -1
  9. package/dist/annotate/emphasis-mark.d.ts +9 -9
  10. package/dist/annotate/emphasis-mark.js.map +1 -1
  11. package/dist/browser/chunks/{chunk-ABYBW64J.js → chunk-IRZCG6PM.js} +2 -2
  12. package/dist/browser/chunks/chunk-IRZCG6PM.js.map +7 -0
  13. package/dist/browser/chunks/{chunk-K77KLQX4.js → chunk-WMVW6ZIV.js} +2 -2
  14. package/dist/browser/chunks/chunk-WMVW6ZIV.js.map +7 -0
  15. package/dist/browser/chunks/{mathjax-DNP3YRES.js → mathjax-WV55AC2P.js} +1 -1
  16. package/dist/browser/chunks/{mathjax-DNP3YRES.js.map → mathjax-WV55AC2P.js.map} +1 -1
  17. package/dist/browser/index.js +1 -1
  18. package/dist/browser/index.js.map +3 -3
  19. package/dist/browser/kit.js +1 -1
  20. package/dist/browser/manifest.json +1 -1
  21. package/dist/browser/tex.js +1 -1
  22. package/dist/browser/tex.js.map +1 -1
  23. package/dist/engine.d.ts +1 -1
  24. package/dist/engine.js +1 -1
  25. package/dist/engine.js.map +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/kit/brace.js.map +1 -1
  28. package/dist/kit/cache.js.map +1 -1
  29. package/dist/kit/component.d.ts.map +1 -1
  30. package/dist/kit/component.js.map +1 -1
  31. package/dist/kit/contour.js.map +1 -1
  32. package/dist/kit/coords.js.map +1 -1
  33. package/dist/kit/curve.js.map +1 -1
  34. package/dist/kit/equation.js.map +1 -1
  35. package/dist/kit/equation3d.js.map +1 -1
  36. package/dist/kit/expression.js.map +1 -1
  37. package/dist/kit/field-mark.d.ts.map +1 -1
  38. package/dist/kit/field-mark.js.map +1 -1
  39. package/dist/kit/field.js.map +1 -1
  40. package/dist/kit/follow.d.ts +2 -2
  41. package/dist/kit/follow.d.ts.map +1 -1
  42. package/dist/kit/follow.js.map +1 -1
  43. package/dist/kit/furniture.js.map +1 -1
  44. package/dist/kit/geometry.js.map +1 -1
  45. package/dist/kit/graph.js.map +1 -1
  46. package/dist/kit/mark.js.map +1 -1
  47. package/dist/kit/part-fills.js.map +1 -1
  48. package/dist/kit/place.js.map +1 -1
  49. package/dist/kit/sampler.js +1 -1
  50. package/dist/kit/sampler.js.map +1 -1
  51. package/dist/kit/scale.js.map +1 -1
  52. package/dist/kit/source.js.map +1 -1
  53. package/dist/kit/system.js.map +1 -1
  54. package/dist/kit/ticks.js.map +1 -1
  55. package/dist/kit/withdrawn.js.map +1 -1
  56. package/dist/marks/curve-area.js.map +1 -1
  57. package/dist/marks/drop-lines.d.ts +6 -6
  58. package/dist/marks/drop-lines.js.map +1 -1
  59. package/dist/marks/plot-point.d.ts +3 -3
  60. package/dist/marks/plot-point.js.map +1 -1
  61. package/dist/marks/riemann-sum.d.ts +3 -3
  62. package/dist/marks/riemann-sum.js.map +1 -1
  63. package/dist/marks/tangent-line.d.ts +6 -6
  64. package/dist/marks/tangent-line.js.map +1 -1
  65. package/dist/marks/vector-arrow.d.ts +6 -6
  66. package/dist/marks/vector-arrow.js.map +1 -1
  67. package/dist/nodes.js.map +1 -1
  68. package/dist/plots/function-plot.d.ts +8 -8
  69. package/dist/plots/function-plot.d.ts.map +1 -1
  70. package/dist/plots/function-plot.js.map +1 -1
  71. package/dist/plots/points-plot.js.map +1 -1
  72. package/dist/plots/stream-lines.js.map +1 -1
  73. package/dist/plots/traced-path.js.map +1 -1
  74. package/dist/plots/vector-field.js.map +1 -1
  75. package/dist/structures/graph-layout.js.map +1 -1
  76. package/dist/structures/network-graph.js.map +1 -1
  77. package/dist/structures/sample-space.js.map +1 -1
  78. package/dist/systems/axes2d.d.ts.map +1 -1
  79. package/dist/systems/axes2d.js.map +1 -1
  80. package/dist/systems/number-line.js.map +1 -1
  81. package/dist/systems/number-plane.js.map +1 -1
  82. package/dist/systems/polar-plane.js.map +1 -1
  83. package/dist/tex/geometry.js.map +1 -1
  84. package/dist/tex/index.js.map +1 -1
  85. package/dist/tex/mathjax.js.map +1 -1
  86. package/dist/tex/matrix.d.ts +2 -2
  87. package/dist/tex/matrix.js.map +1 -1
  88. package/dist/tex/node.d.ts +2 -2
  89. package/dist/tex/node.js.map +1 -1
  90. package/dist/tex/tween.js.map +1 -1
  91. package/dist/tex/typeset.d.ts +4 -4
  92. package/dist/tex/typeset.d.ts.map +1 -1
  93. package/dist/tex/typeset.js.map +1 -1
  94. package/dist/three/axes3d.js.map +1 -1
  95. package/dist/three/curve-plot3d.d.ts +27 -27
  96. package/dist/three/curve-plot3d.d.ts.map +1 -1
  97. package/dist/three/curve-plot3d.js +3 -2
  98. package/dist/three/curve-plot3d.js.map +1 -1
  99. package/dist/three/entries.js.map +1 -1
  100. package/dist/three/label3d.d.ts.map +1 -1
  101. package/dist/three/label3d.js +3 -1
  102. package/dist/three/label3d.js.map +1 -1
  103. package/dist/three/plot-point3d.d.ts +27 -27
  104. package/dist/three/plot-point3d.js.map +1 -1
  105. package/dist/three/space.js.map +1 -1
  106. package/dist/three/surface-plot3d.d.ts +36 -36
  107. package/dist/three/surface-plot3d.js +6 -1
  108. package/dist/three/surface-plot3d.js.map +1 -1
  109. package/dist/three/vector-arrow3d.d.ts +27 -27
  110. package/dist/three/vector-arrow3d.js.map +1 -1
  111. package/package.json +5 -4
  112. package/registry.json +251 -251
  113. package/src/annotate/angle-mark.ts +137 -137
  114. package/src/annotate/curly-brace.ts +148 -148
  115. package/src/annotate/emphasis-mark.ts +118 -118
  116. package/src/engine.ts +86 -86
  117. package/src/index.ts +29 -29
  118. package/src/kit/brace.ts +37 -37
  119. package/src/kit/cache.ts +61 -61
  120. package/src/kit/component.ts +57 -57
  121. package/src/kit/contour.ts +94 -94
  122. package/src/kit/coords.ts +278 -278
  123. package/src/kit/curve.ts +47 -47
  124. package/src/kit/equation.ts +181 -181
  125. package/src/kit/equation3d.ts +137 -137
  126. package/src/kit/expression.ts +159 -159
  127. package/src/kit/field-mark.ts +171 -171
  128. package/src/kit/field.ts +50 -50
  129. package/src/kit/follow.ts +229 -229
  130. package/src/kit/furniture.ts +113 -113
  131. package/src/kit/geometry.ts +49 -49
  132. package/src/kit/graph.ts +116 -116
  133. package/src/kit/mark.ts +152 -152
  134. package/src/kit/part-fills.ts +61 -61
  135. package/src/kit/place.ts +77 -77
  136. package/src/kit/sampler.ts +281 -281
  137. package/src/kit/scale.ts +39 -39
  138. package/src/kit/source.ts +57 -57
  139. package/src/kit/system.ts +105 -105
  140. package/src/kit/ticks.ts +85 -85
  141. package/src/kit/withdrawn.ts +8 -8
  142. package/src/marks/curve-area.ts +89 -89
  143. package/src/marks/drop-lines.ts +71 -71
  144. package/src/marks/plot-point.ts +102 -102
  145. package/src/marks/riemann-sum.ts +99 -99
  146. package/src/marks/tangent-line.ts +119 -119
  147. package/src/marks/vector-arrow.ts +98 -98
  148. package/src/nodes.ts +99 -99
  149. package/src/plots/function-plot.ts +220 -220
  150. package/src/plots/points-plot.ts +103 -103
  151. package/src/plots/stream-lines.ts +160 -160
  152. package/src/plots/traced-path.ts +70 -70
  153. package/src/plots/vector-field.ts +107 -107
  154. package/src/structures/graph-layout.ts +145 -145
  155. package/src/structures/network-graph.ts +291 -291
  156. package/src/structures/sample-space.ts +210 -210
  157. package/src/systems/axes2d.ts +226 -226
  158. package/src/systems/number-line.ts +130 -130
  159. package/src/systems/number-plane.ts +232 -232
  160. package/src/systems/polar-plane.ts +177 -177
  161. package/src/tex/geometry.ts +703 -703
  162. package/src/tex/index.ts +15 -15
  163. package/src/tex/mathjax.ts +82 -82
  164. package/src/tex/matrix.ts +97 -97
  165. package/src/tex/node.ts +74 -74
  166. package/src/tex/tween.ts +308 -308
  167. package/src/tex/typeset.ts +461 -461
  168. package/src/three/axes3d.ts +267 -267
  169. package/src/three/curve-plot3d.ts +146 -144
  170. package/src/three/entries.ts +42 -42
  171. package/src/three/label3d.ts +52 -50
  172. package/src/three/plot-point3d.ts +63 -63
  173. package/src/three/space.ts +92 -92
  174. package/src/three/surface-plot3d.ts +318 -312
  175. package/src/three/vector-arrow3d.ts +88 -88
  176. package/dist/browser/chunks/chunk-ABYBW64J.js.map +0 -7
  177. package/dist/browser/chunks/chunk-K77KLQX4.js.map +0 -7
  178. package/dist/kit/placement.d.ts +0 -8
  179. package/dist/kit/placement.d.ts.map +0 -1
  180. package/dist/kit/placement.js +0 -8
  181. package/dist/kit/placement.js.map +0 -1
@@ -1,291 +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
- }
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
+ }