-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
chart-on-brush-highlight-tooltip.ts
99 lines (84 loc) · 2.42 KB
/
chart-on-brush-highlight-tooltip.ts
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
89
90
91
92
93
94
95
96
97
98
99
import { Chart, MASK_CLASS_NAME } from '../../../src';
function useTip({ container, onRemove = () => {}, offsetX = 20, offsetY = 0 }) {
let div;
const render = (data, [x, y]) => {
if (div) remove();
div = document.createElement('div');
div.innerHTML = `
Select a node:
<ul>${data.map((d) => `<li>${d.date}</li>`).join('')}</ul>
`;
div.style.position = 'absolute';
div.style.background = '#eee';
div.style.padding = '0.5em';
div.style.left = x + offsetX + 'px';
div.style.top = y + offsetY + 'px';
div.onclick = () => {
remove();
onRemove();
};
container.append(div);
};
const remove = () => {
if (div) div.remove();
div = null;
};
return [render, remove] as const;
}
export function chartOnBrushHighlightTooltip(context) {
const { container, canvas } = context;
const chart = new Chart({
container,
canvas,
});
const data = [
{ date: '2007-04-23', close: 93.24 },
{ date: '2007-04-24', close: 95.35 },
{ date: '2007-04-25', close: 98.84 },
{ date: '2007-04-26', close: 99.92 },
{ date: '2007-04-29', close: 99.8 },
{ date: '2007-05-01', close: 99.47 },
{ date: '2007-05-02', close: 100.39 },
{ date: '2007-05-03', close: 100.4 },
{ date: '2007-05-04', close: 100.81 },
{ date: '2007-05-07', close: 103.92 },
];
chart
.line()
.data(data)
.encode('x', (d) => new Date(d.date))
.encode('y', 'close')
.scale('y', { nice: true })
.interaction('brushXHighlight', true);
const [render, remove] = useTip({
container,
onRemove: () => chart.emit('brush:remove', {}),
});
chart.on('brush:start', onStart);
chart.on('brush:end', onUpdate);
chart.on('brush:remove', onRemove);
const finished = chart.render();
function onStart() {
chart.emit('tooltip:disable');
remove();
}
function onUpdate(e) {
const { canvas } = chart.getContext();
// @ts-ignore
const [mask] = canvas.document.getElementsByClassName(MASK_CLASS_NAME);
const bounds = mask.getBounds();
const x = bounds.max[0];
const y = bounds.center[1];
const [X] = e.data.selection;
const filtered = data.filter(
({ date }) => new Date(date) >= X[0] && new Date(date) <= X[1],
);
render(filtered, [x, y]);
}
function onRemove(e) {
const { nativeEvent } = e;
if (nativeEvent) remove();
chart.emit('tooltip:enable');
}
return { chart, finished };
}