-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBarChart.vue
More file actions
292 lines (264 loc) · 6.92 KB
/
BarChart.vue
File metadata and controls
292 lines (264 loc) · 6.92 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
<template>
<span>
<div
class="responsive-container"
>
<Bar
is="bar"
:data="localChartData"
:options="chartOptions"
/>
</div>
</span>
</template>
<script>
import { Chart, registerables } from 'chart.js';
import { Bar } from 'vue-chartjs'
import sassColorVariables from '../assets/sass/tokens/colors.module.scss';
import paleteBuilder from '../utils/methods/paleteBuilder.js';
// Registrar o elemento "point" no registro (Torna-se necessário para marcações de ponto)
Chart.register(...registerables);
export default {
name: 'CdsBarChart',
components: {
Bar,
},
props: {
/**
* Define o conjunto de dados a serem mostrados no gráfico.
* O objeto deve conter o parâmetro `name` (para identificar o conjunto de dados)
* e `datasets`, array de objetos que apresentará `label` (indicar o rótulo do dado) e
* `data` (array com os valores númericos).
*/
data: {
type: Array,
required: true,
},
/**
* A variante de cor. São 11 variantes:
* @values green, teal, blue, indigo, violet, pink, red, orange, amber, dark
*/
variant: {
type: String,
required: true,
default: 'green',
validator: (value) => {
return ['green', 'turquoise', 'blue', 'indigo', 'violet', 'pink', 'red', 'orange', 'amber', 'gray', 'dark'].includes(value);
}
},
/**
* Defina as labels do gráfico
*/
labels: {
type: Array,
required: true,
default: () => [],
},
/**
* Configura a porcentagem ocupada pela barra do gráfico. (0.1-1).
*/
barWidth: {
type: Number,
default: 5,
},
/**
* Prop para exibir as barras na direção do eixo x
*/
horizontalBar: {
type: Boolean,
default: true,
},
},
data() {
return {
sassColorVariables,
localChartData: {},
localLabels: [],
palletColors: [],
deleteFirstTwoColors: false, //NOTE: Responsável por garantir que as cores gray e dark da paleta não serão removidos os dois primeiros elementos
chartOptions: {
responsive: true,
maintainAspectRatio: false, // NOTE: Caso true manterá aspecto de proporção original, caso false, será dimensionado para preencher completamente o contêiner (Isso pode fazer com que o gráfico pareça distorcido se o container tiver proporção de aspecto diferente do gráfico original)
categoryPercentage: null, //NOTE: Configura a porcentagem ocupada pela barra do gráfico. (0-1)
indexAxis: this.horizontalBar ? 'y' : 'x',
scales: this.horizontalBar
? {
x: { beginAtZero: true },
}
: {
y: {
beginAtZero: true,
grace: '5%',
ticks: {
precision: 0
},
categoryPercentage: 0.6,
barPercentage: 0.8
},
},
plugins: {
tooltip: {
callbacks: {
beforeTitle: function (context) {
return `${context[0].dataset.name}`;
}
}
},
legend: {
display: true,
labels: {
usePointStyle: true,
pointStyle: 'rectRounded',
},
},
}
},
}
},
watch: {
labels: {
handler(newValue) {
this.localLabels = newValue;
this.mergeChartDataNoSelect(this.data);
},
immediate: true,
},
variant: {
handler(newValue) {
if (newValue === 'gray' || newValue === 'dark') {
this.deleteFirstTwoColors = true;
} else {
this.deleteFirstTwoColors = false;
}
this.mergeChartDataNoSelect(this.data);
},
immediate: true,
},
data: {
handler(newValue) {
this.mergeChartDataNoSelect(newValue);
},
immediate: true,
},
barWidth: {
handler(newValue) {
const categoryPercentage = (newValue >= 0.1 && newValue <= 1) ? newValue : 1;
this.chartOptions = {
...this.chartOptions,
categoryPercentage,
};
},
immediate: true,
},
horizontalBar: {
handler(newValue) {
this.chartOptions = {
...this.chartOptions,
indexAxis: newValue ? 'y' : 'x',
scales: {
...this.chartOptions.scales,
x: newValue
? { beginAtZero: true }
: { ...this.chartOptions.scales?.x },
y: !newValue
? {
beginAtZero: true,
grace: '5%',
ticks: {
precision: 0
},
categoryPercentage: 0.6,
barPercentage: 0.8
}
: { ...this.chartOptions.scales?.y },
},
};
},
immediate: true,
},
},
methods: {
paleteBuilder,
palete() {
this.palletColors = this.paleteBuilder(this.sassColorVariables.palete);
this.removeFirstTwoElements();
},
// NOTE: Função responsável por remover os dois primeiros elementos da paleta para quando não é gray ou Dark Neutrals
removeFirstTwoElements() {
for (let i = 0; i < this.palletColors.length; i++) {
const color = this.palletColors[i];
if (this.deleteFirstTwoColors === false) {
color.colorShades.splice(0, 2);
color.colorTokens.splice(0, 2);
color.colorData.splice(0, 2);
}
}
},
// NOTE: Adiciona campo dataset.name com o nome do objeto respectivo
addDataSetNames() {
this.data.forEach(item => {
item.datasets.forEach(dataset => {
dataset.name = item.name;
});
});
},
// NOTE: Função que recebe uma matriz de dados dos gráfico.
mergeChartDataNoSelect(data) {
// data.labels = this.localLabels;
const mergedData = { labels: this.localLabels, datasets: [] };
this.addDataSetNames();
data.forEach(obj => {
obj.datasets.forEach(state => {
const dataset = {
label: state.label,
data: state.data,
name: state.name,
borderRadius: 6,
};
mergedData.datasets.push(dataset);
});
});
this.palete();
const backgroundColor = this.generateBackgroundColor();
this.setColors(mergedData.datasets, backgroundColor);
this.localChartData = mergedData;
},
// NOTE: Função responsável por buscar a cor na paleta
generateBackgroundColor() {
const variantLowercase = this.variant.toLowerCase();
const palletColor = this.palletColors.find(color => color.variantName.toLowerCase().includes(variantLowercase));
if (palletColor) {
return palletColor.colorShades;
}
return [];
},
// NOTE: Função responsável por setar backgroundColor
// Ocorre essa verificação para garantir que o mesmo conjunto de dados para mais de um item selecionado tenha a mesma cor
setColors(datasets, backgroundColor) {
const colors = {};
this.chartOptions.plugins.legend.display = true;
datasets.forEach(dataset => {
const objectName = dataset.name;
let colorIndex;
if (datasets.length === 1) {
colorIndex = 2;
colors[objectName] = backgroundColor[colorIndex];
this.chartOptions.plugins.legend.display = false;
}
if (!colors[objectName]) {
colorIndex = Object.keys(colors).length % backgroundColor.length;
colors[objectName] = backgroundColor[colorIndex];
}
dataset.backgroundColor = colors[objectName];
dataset.borderRadius = 6;
});
},
}
}
</script>
<style lang="scss" scoped>
.responsive-container{
width: 100%;
height: 100%;
}
</style>