-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathCharts.js
291 lines (274 loc) · 8.45 KB
/
Charts.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import React, { useEffect, useState } from 'react';
import {
LineChart,
Line,
BarChart,
Bar,
CartesianGrid,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
Label,
Legend,
} from 'recharts';
import { useSelector, useDispatch } from 'react-redux';
import Spinner from '@/components/Spinner';
import { setRefreshChart } from '@/lib/store/services/charts/ChartSlice';
import { fetchAnalyticsData } from '@/lib/store/services/charts/ChartData';
import {
renderCustomizedLegend,
CustomDot,
CustomizedAxisTick,
CustomTooltipLineGraph,
CustomTooltipBarGraph,
colors,
} from './components';
/**
* @description Custom hook to fetch analytics data
* @returns {Object} analyticsData, isLoading, error, loadingTime
*/
const useAnalytics = () => {
const dispatch = useDispatch();
const chartData = useSelector((state) => state.chart);
const refreshChart = useSelector((state) => state.chart.refreshChart);
const preferencesLoading = useSelector((state) => state.userDefaults.status === 'loading');
const isLoading = useSelector((state) => state.analytics.status === 'loading');
const analyticsData = useSelector((state) => state.analytics.data);
const [error, setError] = useState(null);
const [loadingTime, setLoadingTime] = useState(0);
useEffect(() => {
if (preferencesLoading) return;
const body = {
sites: chartData.chartSites,
startDate: chartData.chartDataRange.startDate,
endDate: chartData.chartDataRange.endDate,
chartType: chartData.chartType,
frequency: chartData.timeFrame,
pollutant: chartData.pollutionType,
organisation_name: chartData.organizationName,
};
const allPropertiesSet = Object.values(body).every(
(property) => property !== undefined && property !== null,
);
if (allPropertiesSet) {
const fetchData = async () => {
try {
setError(null);
setLoadingTime(Date.now());
await dispatch(fetchAnalyticsData(body));
dispatch(setRefreshChart(false));
} catch (err) {
setError(err.message);
} finally {
setLoadingTime(Date.now() - loadingTime);
}
};
fetchData();
}
}, [chartData, refreshChart]);
return { analyticsData, isLoading, error, loadingTime };
};
/**
* @description Charts component
* @param {String} chartType - Type of chart to render
* @param {String} width - Width of the chart
* @param {String} height - Height of the chart
* @returns {React.Component} Charts
*/
const Charts = ({ chartType = 'line', width = '100%', height = '100%' }) => {
const chartData = useSelector((state) => state.chart);
const { analyticsData, isLoading, error, loadingTime } = useAnalytics();
const [showLoadingMessage, setShowLoadingMessage] = useState(false);
const [hasLoaded, setHasLoaded] = useState(false);
useEffect(() => {
let timeoutId;
if (isLoading && loadingTime > 5000) {
timeoutId = setTimeout(() => setShowLoadingMessage(true), 5000);
} else if (!isLoading) {
setShowLoadingMessage(false);
setHasLoaded(true);
}
return () => clearTimeout(timeoutId);
}, [isLoading, loadingTime]);
// Error state
if (error) {
return (
<div className='ml-10 flex justify-center text-center items-center w-full h-full'>
<p className='text-red-500'>
An error has occurred. Please try again later or reach out to our support team for
assistance.
</p>
</div>
);
}
// Loading state
if (isLoading || !hasLoaded) {
return (
<div className='ml-10 flex justify-center text-center items-center w-full h-full'>
<div className='text-blue-500'>
<Spinner />
{showLoadingMessage && (
<span className='text-yellow-500 mt-2'>
The data is currently being processed. We appreciate your patience.
</span>
)}
</div>
</div>
);
}
// No data for this time range
if (hasLoaded && (analyticsData === null || analyticsData.length === 0)) {
return (
<div className='ml-10 flex justify-center items-center w-full h-full'>
There is no data available for the selected time range.
</div>
);
}
const transformedData = analyticsData.reduce((acc, curr) => {
if (!acc[curr.time]) {
acc[curr.time] = {
time: curr.time,
};
}
acc[curr.time][curr.name] = curr.value;
return acc;
}, {});
const dataForChart = Object.values(transformedData);
let allKeys = new Set();
if (dataForChart.length > 0) {
allKeys = new Set(Object.keys(dataForChart[0]));
}
// Render the chart
const renderChart = () => {
if (chartType === 'line') {
return (
<LineChart
data={dataForChart}
style={{ cursor: 'pointer' }}
margin={{
top: 38,
right: 10,
}}>
{Array.from(allKeys)
.filter((key) => key !== 'time')
.map((key, index) => (
<Line
key={key}
dataKey={key}
type='monotone'
stroke={colors[index % colors.length]}
strokeWidth={2}
dot={<CustomDot />}
activeDot={{ r: 6 }}
/>
))}
<CartesianGrid stroke='#ccc' strokeDasharray='5 5' vertical={false} />
<XAxis
dataKey='time'
tick={<CustomizedAxisTick />}
tickLine={true}
axisLine={false}
padding={{ left: 30, right: 30 }}
interval={0}
/>
<YAxis
axisLine={false}
fontSize={12}
tickLine={false}
tickFormatter={(tick) => {
if (tick >= 1000 && tick < 1000000) {
return tick / 1000 + 'K';
} else if (tick >= 1000000) {
return tick / 1000000 + 'M';
} else {
return tick;
}
}}>
<Label
value={chartData.pollutionType === 'pm2_5' ? 'PM2.5 (µg/m³)' : 'PM10 (µg/m³)'}
position='insideTopRight'
offset={0}
fontSize={12}
dy={-35}
dx={60}
/>
</YAxis>
<Legend
content={renderCustomizedLegend}
wrapperStyle={{ bottom: 0, right: 0, position: 'absolute' }}
/>
<Tooltip
content={<CustomTooltipLineGraph />}
cursor={{
stroke: '#aaa',
strokeOpacity: 0.3,
strokeWidth: 2,
strokeDasharray: '3 3',
}}
/>
</LineChart>
);
} else if (chartType === 'bar') {
return (
<BarChart
data={dataForChart}
style={{ cursor: 'pointer' }}
margin={{
top: 38,
right: 10,
}}>
{Array.from(allKeys)
.filter((key) => key !== 'time')
.map((key, index) => (
<Bar key={key} dataKey={key} fill={colors[index % colors.length]} barSize={15} />
))}
<CartesianGrid stroke='#ccc' strokeDasharray='5 5' vertical={false} />
<XAxis
dataKey='time'
tickLine={true}
interval={0}
tick={<CustomizedAxisTick />}
axisLine={false}
/>
<YAxis
axisLine={false}
fontSize={12}
tickLine={false}
tickFormatter={(tick) => {
if (tick >= 1000 && tick < 1000000) {
return tick / 1000 + 'K';
} else if (tick >= 1000000) {
return tick / 1000000 + 'M';
} else {
return tick;
}
}}>
<Label
value={chartData.pollutionType === 'pm2_5' ? 'PM2.5 (µg/m³)' : 'PM10 (µg/m³)'}
position='insideTopRight'
offset={0}
fontSize={12}
dy={-35}
dx={60}
/>
</YAxis>
<Legend
content={renderCustomizedLegend}
wrapperStyle={{ bottom: 0, right: 0, position: 'absolute' }}
/>
<Tooltip
content={<CustomTooltipLineGraph />}
cursor={{ fill: '#eee', fillOpacity: 0.3 }}
/>
</BarChart>
);
}
};
return (
<ResponsiveContainer width={width} height={height}>
{renderChart()}
</ResponsiveContainer>
);
};
export default Charts;