forked from juizi-com/volto-GraphBlock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathView.jsx
More file actions
180 lines (164 loc) · 4.74 KB
/
View.jsx
File metadata and controls
180 lines (164 loc) · 4.74 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
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
LineElement,
PointElement,
ArcElement,
Tooltip,
Legend,
BarController,
LineController,
PieController,
DoughnutController,
} from 'chart.js';
import React, { useEffect, useState, useRef } from 'react';
import { Chart } from 'react-chartjs-2';
import Papa from 'papaparse';
import './style.css';
import { GRAPH_COLOURS, PIE_COLOURS } from './index';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
LineElement,
PointElement,
ArcElement,
Tooltip,
Legend,
BarController,
LineController,
PieController,
DoughnutController
);
const View = ({ data, block }) => {
const [parsedData, setParsedData] = useState(null);
const [windowWidth, setWindowWidth] = useState(typeof window !== 'undefined' ? window.innerWidth : 1200);
const [figureNumber, setFigureNumber] = useState(null);
const containerRef = useRef(null);
useEffect(() => {
const handleResize = () => setWindowWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
useEffect(() => {
if (!data.independent) {
const blocks = Array.from(document.querySelectorAll('.graph-block'));
const index = blocks.findIndex((el) => el.contains(containerRef.current));
if (index !== -1) {
let count = 0;
for (let i = 0; i <= index; i++) {
if (!blocks[i].classList.contains('independent')) {
count++;
}
}
setFigureNumber(count);
}
}
}, [data.independent, windowWidth]);
useEffect(() => {
const file = Array.isArray(data.csvFile) ? data.csvFile[0] : data.csvFile;
if (!file || !file['@id']) return;
const url = file['@id'].includes('/@@download/file')
? file['@id']
: `${file['@id']}/@@download/file`;
fetch(url)
.then((res) => res.text())
.then((csvText) => {
const result = Papa.parse(csvText, { header: true });
console.log('GRAPH DEBUG:', {
block,
figureNumber,
file,
rows: result.data.length,
});
setParsedData(result.data);
})
.catch((err) => {
console.error('CSV load error:', err);
});
}, [data.csvFile]);
let chartData = null;
let chartOptions = null;
if (parsedData) {
const isPieChart = data.chartType === 'pie' || data.chartType === 'doughnut';
const cleanedData = parsedData.filter(
(row) => Object.values(row).join('').trim() !== ''
);
const columnKeys = Object.keys(cleanedData[0] || {});
const labelKey = columnKeys[0];
const datasetKeys = columnKeys.slice(1);
chartData = {
labels: cleanedData.map((row) => row[labelKey]),
datasets: datasetKeys.map((key, i) => ({
label: key,
data: cleanedData.map((row) => Number(row[key])),
backgroundColor: isPieChart ? PIE_COLOURS : GRAPH_COLOURS[i % GRAPH_COLOURS.length],
borderColor: isPieChart ? PIE_COLOURS : GRAPH_COLOURS[i % GRAPH_COLOURS.length],
borderWidth: 1,
})),
};
chartOptions = {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: {
display: isPieChart || datasetKeys.length > 1,
},
},
scales: isPieChart
? {}
: {
x: {
title: {
display: Boolean(data.xLabel),
text: data.xLabel || '',
},
},
y: {
title: {
display: Boolean(data.yLabel),
text: data.yLabel || '',
},
},
},
};
}
const wrapperClass = [
'block',
'graph-block',
data.independent ? 'independent' : '',
data.useNarrow ? 'narrow' : '',
].filter(Boolean).join(' ');
return (
<div className={wrapperClass} ref={containerRef}>
<div className="graph-inner">
{data.title && <h3>{data.title}</h3>}
{parsedData ? (
<>
<div className="chart-container">
<Chart
key={windowWidth}
type={data.chartType || 'bar'}
data={chartData}
options={chartOptions}
/>
</div>
{data.description && (
<figcaption className="graph-caption">
{!data.independent && typeof figureNumber === 'number' ? (
<strong>{`Figure ${figureNumber}: `}</strong>
) : null}
{data.description}
</figcaption>
)}
</>
) : (
<div style={{ color: 'red' }}>No graph data loaded</div>
)}
</div>
</div>
);
};
export default View;