1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | import { assign } from "./utils";
|
8 | import * as easings from "./easings";
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | const ANIMATE_DEFAULTS = {
|
14 | easing: "quadraticInOut",
|
15 | duration: 150,
|
16 | };
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | export function animateNodes(graph, targets, options, callback) {
|
22 | options = assign({}, ANIMATE_DEFAULTS, options);
|
23 |
|
24 | const easing = typeof options.easing === "function" ? options.easing : easings[options.easing];
|
25 |
|
26 | const start = Date.now();
|
27 |
|
28 | const startPositions = {};
|
29 |
|
30 | for (const node in targets) {
|
31 | const attrs = targets[node];
|
32 | startPositions[node] = {};
|
33 |
|
34 | for (const k in attrs) startPositions[node][k] = graph.getNodeAttribute(node, k);
|
35 | }
|
36 |
|
37 | let frame = null;
|
38 |
|
39 | const step = () => {
|
40 | let p = (Date.now() - start) / options.duration;
|
41 |
|
42 | if (p >= 1) {
|
43 |
|
44 | for (const node in targets) {
|
45 | const attrs = targets[node];
|
46 |
|
47 | for (const k in attrs) graph.setNodeAttribute(node, k, attrs[k]);
|
48 | }
|
49 |
|
50 | if (typeof callback === "function") callback();
|
51 |
|
52 | return;
|
53 | }
|
54 |
|
55 | p = easing(p);
|
56 |
|
57 | for (const node in targets) {
|
58 | const attrs = targets[node];
|
59 | const s = startPositions[node];
|
60 |
|
61 | for (const k in attrs) graph.setNodeAttribute(node, k, attrs[k] * p + s[k] * (1 - p));
|
62 | }
|
63 |
|
64 | frame = requestAnimationFrame(step);
|
65 | };
|
66 |
|
67 | step();
|
68 |
|
69 | return () => {
|
70 | if (frame) cancelAnimationFrame(frame);
|
71 | };
|
72 | }
|