-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathWidgetIndex.js
More file actions
465 lines (438 loc) · 13.5 KB
/
Copy pathWidgetIndex.js
File metadata and controls
465 lines (438 loc) · 13.5 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
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import {createRoot} from 'react-dom/client';
import React, {useEffect, useState} from 'react';
import PropTypes from 'prop-types';
import Recruitment from './widgets/recruitment';
import StudyProgression from './widgets/studyprogression';
import AdminStats from './widgets/adminstats';
import {fetchData} from './Fetch';
import Modal from 'Modal';
import Loader from 'Loader';
import {useTranslation} from 'react-i18next';
import '../css/WidgetIndex.css';
import {setupCharts, unloadCharts} from './widgets/helpers/chartBuilder';
import jaStrings from '../locale/ja/LC_MESSAGES/statistics.json';
import hiStrings from '../locale/hi/LC_MESSAGES/statistics.json';
import frStrings from '../locale/fr/LC_MESSAGES/statistics.json';
import zhStrings from '../locale/zh/LC_MESSAGES/statistics.json';
/**
* WidgetIndex - the main window.
*
* @param {object} props
* @return {JSX.Element}
*/
const WidgetIndex = (props) => {
const [recruitmentData, setRecruitmentData] = useState({});
const [studyProgressionData, setStudyProgressionData] = useState({});
const [adminStatsData, setAdminStatsData] = useState({});
const [modalChart, setModalChart] = useState(null);
const {t, i18n} = useTranslation();
useEffect( () => {
i18n.addResourceBundle('ja', 'statistics', jaStrings);
i18n.addResourceBundle('hi', 'statistics', hiStrings);
i18n.addResourceBundle('fr', 'statistics', frStrings);
i18n.addResourceBundle('zh', 'statistics', zhStrings);
}, []);
// used by recruitment.js and studyprogression.js to display each chart.
const showChart = (section, chartID, chartDetails, setChartDetails) => {
let {title, chartType, options} = chartDetails[section][chartID];
return (
<div
className ="chart-card"
>
{/* Chart Title and Toggle */}
<div className ='chart-header'>
<h5 className ='chart-title'>{title}</h5>
{Object.keys(chartDetails[section][chartID].options).length > 1 && (
<div className ="chart-toggle-wrapper">
{Object.entries(options).map(([key, value]) => (
<button
key={key}
className={`chart-toggle-btn ${
chartType === value ? 'active' : ''
}`}
onClick={() => {
setChartDetails(
{
...chartDetails,
[section]: {
...chartDetails[section],
[chartID]: {
...chartDetails[section][chartID],
chartType: value,
},
},
}
);
setupCharts(
t,
false,
{
[section]: {
[chartID]: {
...chartDetails[section][chartID],
chartType: value,
},
},
},
t('Total', {ns: 'loris'}),
);
}}
>
{/* [Pie|Bar] toggle */}
{t(
key.charAt(0).toUpperCase() + key.slice(1),
{ns: 'statistics'},
)}
</button>
))}
</div>
)}
</div>
{/* Chart Canvas / Modal Trigger */}
<div className ="chart-visual-wrapper">
<a
onClick ={() => {
setModalChart(chartDetails[section][chartID]);
setupCharts(
t,
true,
{
[section]:
{[chartID]: chartDetails[section][chartID]},
},
t('Total', {ns: 'loris'}),
);
}}
id ={chartID}
>
<Loader />
</a>
</div>
</div>
);
};
const downloadAsCSV = (data, filename, dataType, labelsLabel) => {
const convertBarToCSV = (data) => {
const csvRows = [];
// Adding headers row
const headers = [labelsLabel, ...Object.keys(data.datasets)];
csvRows.push(headers.join(','));
// Adding data rows
const maxDatasetLength = Math.max(
...Object.values(data.datasets).map(
(arr) => arr.length
)
);
for (let i = 0; i < maxDatasetLength; i++) {
const values = [`"${data.labels[i]}"` || '']; // Label for this row
for (const datasetKey of Object.keys(data.datasets)) {
const value = data.datasets[datasetKey][i];
values.push(`"${value}"` || '');
}
csvRows.push(values.join(','));
}
return csvRows.join('\n');
};
const convertPieToCSV = (data) => {
const csvRows = [];
const headers = Object.keys(data[0]);
csvRows.push(headers.join(','));
for (const row of data) {
const values = headers.map(
(header) => {
const escapedValue = row[header].toString().replace(/"/g, '\\"');
return `"${escapedValue}"`;
}
);
csvRows.push(values.join(','));
}
return csvRows.join('\n');
};
const convertLineToCSV = (data) => {
const csvRows = [];
// Adding headers row
const headers = [
t('Labels', {ns: 'statistics'}),
...data.datasets.map((dataset) => dataset.name),
];
csvRows.push(headers.join(','));
// Adding data rows
for (let i = 0; i < data.labels.length; i++) {
const values = [data.labels[i]]; // Label for this row
for (const dataset of data.datasets) {
values.push(dataset.data[i] || '');
}
csvRows.push(values.join(','));
}
return csvRows.join('\n');
};
let csvData = '';
if (dataType == 'pie') {
csvData = convertPieToCSV(data);
} else if (dataType == 'bar') {
csvData = convertBarToCSV(data);
} else if (dataType == 'line') {
csvData = convertLineToCSV(data);
}
const blob = new Blob([csvData], {type: 'text/csv'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
// used by recruitment.js and studyprogression.js to update the filters for each chart.
const updateFilters = (
formDataObj,
section,
chartDetails,
setChartDetails
) => {
// Unload all charts in the section first
unloadCharts(t, chartDetails, section);
// Clear cached data from chartDetails to prevent old data from showing
let clearedChartDetails = {...chartDetails};
Object.keys(chartDetails[section]).forEach((chartID) => {
clearedChartDetails[section][chartID] = {
...chartDetails[section][chartID],
data: null,
chartObject: null,
};
});
setChartDetails(clearedChartDetails);
let formObject = new FormData();
for (const key in formDataObj) {
if (formDataObj[key] &&
typeof formDataObj[key] === 'object' &&
!Array.isArray(formDataObj[key])
) {
Object.entries(formDataObj[key]).forEach(([rangeKey, value]) => {
if (value !== '') {
const parameterName = `${key}${
rangeKey.charAt(0).toUpperCase()
}${rangeKey.slice(1)}`;
formObject.append(parameterName, value);
}
});
} else if (formDataObj[key] != '' && formDataObj[key] != ['']) {
formObject.append(key, formDataObj[key]);
}
}
const queryString = '?' + new URLSearchParams(formObject).toString();
let newChartDetails = {...clearedChartDetails};
const chartPromises = [];
Object.keys(chartDetails[section]).forEach(
(chart) => {
// update filters
let newChart = {
...clearedChartDetails[section][chart],
filters: queryString,
};
const chartPromise = setupCharts(
t,
false,
{[section]: {[chart]: newChart}},
t('Total', {ns: 'loris'}),
).then(
(data) => {
// update chart data
newChartDetails[section][chart] = data[section][chart];
}
);
chartPromises.push(chartPromise);
}
);
Promise.all(chartPromises).then(() => {
setChartDetails(newChartDetails);
});
};
/**
* Similar to componentDidMount and componentDidUpdate.
*/
useEffect(
() => {
/**
* setup - fetch recruitment and study progression data.
*
* @return {Promise<void>}
*/
const setup = async () => {
const data = await fetchData(
`${props.baseURL}/Widgets`
);
setRecruitmentData(data);
setStudyProgressionData(data);
setAdminStatsData(data);
};
setup().catch(
(error) => {
console.error(error);
}
);
},
[]
);
/**
* Renders the React component.
*
* @return {JSX.Element} - React markup for component.
*/
return (
<>
<Modal
show ={modalChart}
onClose ={() => setModalChart(null)}
width ={'1200px'}
title ={modalChart && modalChart.title}
throwWarning ={false}
>
<div
style ={{
margin: 'auto',
display: 'flex',
}}
>
<div
style ={{
margin: 'auto',
display: 'flex',
}}
id ='dashboardModal'
>
<Loader />
</div>
</div>
{modalChart && modalChart.chartType &&
<a
style ={{
position: 'absolute',
bottom: '10px',
left: '10px',
}}
onClick ={() => {
downloadAsCSV(
modalChart.data,
modalChart.title,
modalChart.dataType,
t('Labels', {ns: 'statistics'}),
);
}}
className ='btn btn-info'>
<span
className ='glyphicon glyphicon-download'
aria-hidden='true'/>
{' '}{t('Download Data as CSV', {ns: 'loris'})}
</a>
}
{modalChart
&& modalChart.chartType
&& modalChart.chartType !== 'line'
&& <a
style ={{
position: 'absolute',
bottom: '10px',
right: '10px',
}}
onClick ={() => {
exportChartAsImage('dashboardModal');
}}
className ='btn btn-info'>
<span
className ='glyphicon glyphicon-download'
aria-hidden ='true'
/>
{' '}{t('Download as PNG', {ns: 'statistics'})}
</a>
}
</Modal>
<Recruitment
data ={recruitmentData}
baseURL ={props.baseURL}
showChart ={showChart}
updateFilters ={updateFilters}
/>
<StudyProgression
data ={studyProgressionData}
baseURL ={props.baseURL}
showChart ={showChart}
updateFilters ={updateFilters}
/>
{loris.userHasPermission('user_account_multisite') && <AdminStats
data ={adminStatsData}
baseURL ={props.baseURL}
showChart ={showChart}
/>}
</>
);
};
WidgetIndex.propTypes = {
baseURL: PropTypes.string,
};
/**
* Render StatisticsIndex on page load.
*/
window.addEventListener(
'load',
() => {
createRoot(
document.getElementById('statistics_widgets')
).render(
<WidgetIndex
baseURL ={`${loris.BaseURL}/statistics`}
/>
);
}
);
/**
* Helper function to export a chart as an image
*
* @param {string} chartId
*/
const exportChartAsImage = (chartId) => {
const chartContainer = document.getElementById(chartId);
if (!chartContainer) {
console.error(`Chart with ID '${chartId}' not found.`);
return;
}
// Get the SVG element that represents the chart
const svgNode = chartContainer.querySelector('svg');
// Clone the SVG node to avoid modifying the original chart
const clonedSvgNode = svgNode.cloneNode(true);
// Modify the font properties of the text elements
const textElements = clonedSvgNode.querySelectorAll('text');
textElements.forEach(
(textElement) => {
textElement.style.fontFamily = 'Arial, sans-serif';
textElement.style.fontSize = '12px';
}
);
// Create a canvas element
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Get the SVG as XML data
const svgData = new XMLSerializer().serializeToString(clonedSvgNode);
// Create an image that can be used as the source for the canvas
const img = new Image();
img.onload = () => {
// Set the canvas size to match the chart's size
canvas.width = img.width;
canvas.height = img.height;
// Draw the image on the canvas
ctx.drawImage(img, 0, 0);
// Export the canvas to a data URL
const dataURL = canvas.toDataURL('image/png');
// Create a link and trigger a download
const link = document.createElement('a');
link.href = dataURL;
link.download = 'chart.png';
link.click();
// Clean up
canvas.remove();
};
img.src =
'data:image/svg+xml;base64,'
+ btoa(unescape(encodeURIComponent(svgData)));
};