-
-
Notifications
You must be signed in to change notification settings - Fork 325
/
Copy pathsuper-simple-chart.js
82 lines (71 loc) · 2.08 KB
/
super-simple-chart.js
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
import { h, render } from "https://unpkg.com/preact?module";
import htm from "https://unpkg.com/htm?module";
const html = htm.bind(h);
export function bind(node, config) {
return {
create: (component, props, children) => h(component, props, ...children),
render: (element) => render(element, node),
unmount: () => render(null, node),
};
}
export function SuperSimpleChart(props) {
const data = props.data;
const lastDataIndex = data.length - 1;
const options = {
height: props.height || 100,
width: props.width || 100,
color: props.color || "blue",
lineWidth: props.lineWidth || 2,
axisColor: props.axisColor || "black",
};
const xData = data.map((point) => point.x);
const yData = data.map((point) => point.y);
const domain = {
xMin: Math.min(...xData),
xMax: Math.max(...xData),
yMin: Math.min(...yData),
yMax: Math.max(...yData),
};
return html`<svg
width="${options.width}px"
height="${options.height}px"
viewBox="0 0 ${options.width} ${options.height}"
>
${makePath(props, domain, data, options)} ${makeAxis(props, options)}
</svg>`;
}
function makePath(props, domain, data, options) {
const { xMin, xMax, yMin, yMax } = domain;
const { width, height } = options;
const getSvgX = (x) => ((x - xMin) / (xMax - xMin)) * width;
const getSvgY = (y) => height - ((y - yMin) / (yMax - yMin)) * height;
let pathD =
`M ${getSvgX(data[0].x)} ${getSvgY(data[0].y)} ` +
data.map(({ x, y }, i) => `L ${getSvgX(x)} ${getSvgY(y)}`).join(" ");
return html`<path
d="${pathD}"
style=${{
stroke: options.color,
strokeWidth: options.lineWidth,
fill: "none",
}}
/>`;
}
function makeAxis(props, options) {
return html`<g>
<line
x1="0"
y1=${options.height}
x2=${options.width}
y2=${options.height}
style=${{ stroke: options.axisColor, strokeWidth: options.lineWidth * 2 }}
/>
<line
x1="0"
y1="0"
x2="0"
y2=${options.height}
style=${{ stroke: options.axisColor, strokeWidth: options.lineWidth * 2 }}
/>
</g>`;
}