forked from observablehq/plot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.js
More file actions
88 lines (83 loc) · 2.73 KB
/
vector.js
File metadata and controls
88 lines (83 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import {create} from "../context.js";
import {radians} from "../math.js";
import {maybeFrameAnchor, maybeNumberChannel, maybeTuple, keyword, identity} from "../options.js";
import {Mark} from "../plot.js";
import {
applyChannelStyles,
applyDirectStyles,
applyFrameAnchor,
applyIndirectStyles,
applyTransform
} from "../style.js";
const defaults = {
ariaLabel: "vector",
fill: null,
stroke: "currentColor",
strokeWidth: 1.5,
strokeLinecap: "round"
};
export class Vector extends Mark {
constructor(data, options = {}) {
const {x, y, length, rotate, anchor = "middle", frameAnchor} = options;
const [vl, cl] = maybeNumberChannel(length, 12);
const [vr, cr] = maybeNumberChannel(rotate, 0);
super(
data,
{
x: {value: x, scale: "x", optional: true},
y: {value: y, scale: "y", optional: true},
length: {value: vl, scale: "length", optional: true},
rotate: {value: vr, optional: true}
},
options,
defaults
);
this.length = cl;
this.rotate = cr;
this.anchor = keyword(anchor, "anchor", ["start", "middle", "end"]);
this.frameAnchor = maybeFrameAnchor(frameAnchor);
}
render(index, scales, channels, dimensions, context) {
const {x: X, y: Y, length: L, rotate: R} = channels;
const {length, rotate, anchor} = this;
const [cx, cy] = applyFrameAnchor(this, dimensions);
const fl = L ? (i) => L[i] : () => length;
const fr = R ? (i) => R[i] : () => rotate;
const fx = X ? (i) => X[i] : () => cx;
const fy = Y ? (i) => Y[i] : () => cy;
const k = anchor === "start" ? 0 : anchor === "end" ? 1 : 0.5;
return create("svg:g", context)
.attr("fill", "none")
.call(applyIndirectStyles, this, scales, dimensions)
.call(applyTransform, this, scales)
.call((g) =>
g
.selectAll()
.data(index)
.enter()
.append("path")
.call(applyDirectStyles, this)
.attr("d", (i) => {
const l = fl(i),
a = fr(i) * radians;
const x = Math.sin(a) * l,
y = -Math.cos(a) * l;
const d = (x + y) / 5,
e = (x - y) / 5;
return `M${fx(i) - x * k},${fy(i) - y * k}l${x},${y}m${-e},${-d}l${e},${d}l${-d},${e}`;
})
.call(applyChannelStyles, this, channels)
)
.node();
}
}
export function vector(data, {x, y, ...options} = {}) {
if (options.frameAnchor === undefined) [x, y] = maybeTuple(x, y);
return new Vector(data, {...options, x, y});
}
export function vectorX(data, {x = identity, ...options} = {}) {
return new Vector(data, {...options, x});
}
export function vectorY(data, {y = identity, ...options} = {}) {
return new Vector(data, {...options, y});
}