-
Notifications
You must be signed in to change notification settings - Fork 1
/
LineChartInteractions.tsx
205 lines (179 loc) · 5.84 KB
/
LineChartInteractions.tsx
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import * as React from "react";
import * as d3 from "d3";
import Chart from "../components/Chart";
import Line from "../components/Line";
import Axis from "../components/Axis";
import type { BoundedDimensions } from "../utils/types";
import type { WeatherData } from "../hooks/useWeatherData";
import styles from "./styles/LineChartInteractions.module.css";
//* Step 1b. Access Data
const dateParser = d3.timeParse("%Y-%m-%d");
const xAccessor = (d: WeatherData) => dateParser(d.date) as Date;
const yAccessor = (d: WeatherData) => d.temperatureMax;
//* Step 2. Create chart dimensions
const dimensions: BoundedDimensions = {
width: window.innerWidth * 0.9,
height: 400,
margin: {
top: 15,
right: 15,
bottom: 40,
left: 60,
},
boundedWidth: 0,
boundedHeight: 0,
};
dimensions.boundedWidth =
dimensions.width - dimensions.margin.left - dimensions.margin.right;
dimensions.boundedHeight =
dimensions.height - dimensions.margin.top - dimensions.margin.bottom;
const formatTimelineDate = d3.timeFormat("%B");
type TooltipState = {
show: boolean;
coords: {
x: number;
y: number;
};
closestDataPoint: WeatherData;
formattedDate?: string;
temperature?: number;
};
type TooltipAction =
| {
type: "SHOW";
payload: Omit<TooltipState, "show">;
}
| { type: "HIDE" };
function tooltipReducer(state: TooltipState, action: TooltipAction) {
switch (action.type) {
case "HIDE":
return { ...state, show: false };
case "SHOW":
return { ...state, show: true, ...action.payload };
}
}
function LineChartInteractions({ dataset }: { dataset: WeatherData[] }) {
//* Step 4. Create scales
const xScale = d3
.scaleTime()
.domain(d3.extent(dataset, xAccessor) as [Date, Date])
.range([0, dimensions.boundedWidth]);
const yScale = d3
.scaleLinear()
.domain(d3.extent(dataset, yAccessor) as [number, number])
.range([dimensions.boundedHeight, 0]);
const xAccessorScaled = (d: WeatherData) => xScale(xAccessor(d));
const yAccessorScaled = (d: WeatherData) => yScale(yAccessor(d));
const freezingTemperaturePlacement = yScale(32);
//* Step 7a. Handle interactions
const [tooltip, dispatch] = React.useReducer(tooltipReducer, {
show: false,
coords: {
x: 0,
y: 0,
},
closestDataPoint: dataset[0],
});
function getDistanceFromHoveredDate(d: WeatherData, hoveredDate: Date) {
// return Math.abs(xAccessor(d) - hoveredDate);
//? Convert the Date values to Number so TypeScript doesn't complain
return Math.abs(Number(xAccessor(d)) - Number(hoveredDate));
}
function showTooltip(event: React.MouseEvent) {
const [mouseXPosition] = d3.pointer(event);
const hoveredDate = xScale.invert(mouseXPosition);
const closestIndex = d3.leastIndex(dataset, (current, next) => {
return (
getDistanceFromHoveredDate(current, hoveredDate) -
getDistanceFromHoveredDate(next, hoveredDate)
);
});
const closestDataPoint = dataset[closestIndex as number];
const formatDate = d3.timeFormat("%A, %B %-d, %Y");
const x = xAccessorScaled(closestDataPoint) + dimensions.margin.left;
const y = yAccessorScaled(closestDataPoint) + dimensions.margin.top - 8;
dispatch({
type: "SHOW",
payload: {
coords: {
x,
y,
},
closestDataPoint,
formattedDate: formatDate(xAccessor(closestDataPoint)),
temperature: yAccessor(closestDataPoint),
},
});
}
function hideTooltip() {
dispatch({ type: "HIDE" });
}
return (
<div className={styles.container}>
<div className={styles.wrapper}>
{/* Step 3. Draw canvas */}
<Chart dimensions={dimensions}>
<rect
className={styles.freezing}
x="0"
y={freezingTemperaturePlacement}
width={dimensions.boundedWidth}
height={dimensions.boundedHeight - freezingTemperaturePlacement}
/>
{/* Step 5. Draw data */}
<Line
data={dataset}
xAccessor={xAccessorScaled}
yAccessor={yAccessorScaled}
/>
{/* Step 6. Draw peripherals */}
<Axis dimension="x" scale={xScale} formatTick={formatTimelineDate} />
<Axis
dimension="y"
scale={yScale}
label="Maximum Temperature (°F)"
/>
{/* Step 7b. Set up interactions */}
<rect
className={styles.listenerRect}
width={dimensions.boundedWidth}
height={dimensions.boundedHeight}
onMouseMove={showTooltip}
onMouseLeave={() => hideTooltip()}
/>
<line
className={styles.tooltipLine}
style={{ opacity: tooltip.show ? 1 : 0 }}
x1={xAccessorScaled(tooltip.closestDataPoint)}
y1={dimensions.boundedHeight}
x2={xAccessorScaled(tooltip.closestDataPoint)}
y2={yAccessorScaled(tooltip.closestDataPoint)}
/>
<circle
className={styles.tooltipDot}
style={{ opacity: tooltip.show ? 1 : 0 }}
cx={xAccessorScaled(tooltip.closestDataPoint)}
cy={yAccessorScaled(tooltip.closestDataPoint)}
r={4}
/>
</Chart>
<div
className={styles.tooltip}
style={{
opacity: tooltip.show ? 1 : 0,
transform: `translate(calc(${tooltip.coords.x}px - 50%), calc(${tooltip.coords.y}px - 100%))`,
}}
>
<div className={styles.tooltipDate}>
<span id="date">{tooltip.formattedDate}</span>
</div>
<div className="tooltip-temperature">
Maximum Temperature:{" "}
<span id="temperature">{tooltip.temperature} °F</span>
</div>
</div>
</div>
</div>
);
}
export default LineChartInteractions;