forked from sdelliot/pie-chart-card
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pie-chart-card.js
164 lines (147 loc) · 5.42 KB
/
pie-chart-card.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
/*
Added this attribute, PM13.12.2020
chart_type: doughnut / pie
display_legend: false /true
*/
import "https://unpkg.com/chart.js@v2.9.3/dist/Chart.bundle.min.js?module";
import "https://cdn.jsdelivr.net/npm/chartjs-plugin-colorschemes";
console.info(
`%cPIE-CHART-CARD\n%cVersion: 0.0.1`,
"color: white; background: black; font: font-weight: bold;",
"color: black; background: white; font: font-weight: bold;",
""
);
class PieChartCard extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: 'open'
});
}
setConfig(config) {
if (!config.entities) {
throw new Error('You need to define an entity');
}
const root = this.shadowRoot;
if (root.lastChild) root.removeChild(root.lastChild);
const card = document.createElement('ha-card');
const content = document.createElement('div');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const style = document.createElement('style');
card.id ='ha-card';
content.id = 'content';
canvas.id = 'cnv';
content.style.height = '150px';
canvas.height=150;
card.appendChild(content);
card.appendChild(style);
content.appendChild(canvas);
root.appendChild(card);
this._config = config;
}
set hass(hass) {
// MACscr dont update workaround. not pretty
if (this.ran) {
return;
}
this.ran = true;
const root = this.shadowRoot;
const config = this._config;
const card = root.getElementById("ha-card");
const content = root.getElementById("content");
const canvas = root.getElementById("cnv");
const ctx = canvas.getContext('2d');
const hassEntities = config.entities.map(x => hass.states[x.entity]);
var display_legend = true;
if (config.display_legend !== undefined) {
display_legend = config.display_legend;
}
// If a name is not provided, use the friendly_name for the entity. If the friendly_name
// does not exist, use the actual entity.
var entityNames = config.entities.map(x => x.name !== undefined ? x.name : hass.states[x.entity]["attributes"]["friendly_name"] !== undefined ? hass.states[x.entity]["attributes"]["friendly_name"] : x.entity);
// If the entity does not exist, default to 0
var entityData = hassEntities.map(x => x === undefined ? 0 : x.state);
card.header = config.title ? config.title : 'Pie Chart';
if (config.total_amount){
const totalEntity = hass.states[config.total_amount]
var total = 0;
if (totalEntity !== undefined) {
total = totalEntity.state;
} else if (typeof(Number(config.total_amount)) === 'number') {
total = Number(config.total_amount);
} else {
console.log("ERROR: config.total_amount must be either an entity or number.")
}
const measured = hassEntities.map(x => Number(x.state)).reduce(( accumulator, currentValue ) => accumulator + currentValue, 0);
entityData.push(total - measured)
entityNames.push(config.unknownText ? config.unknownText : 'Unknown');
}
const emptyIndexes = entityData.reduce((arr, e, i) => ((e == 0) && arr.push(i), arr), [])
entityData = entityData.filter((element, index, array) => !emptyIndexes.includes(index));
entityNames = entityNames.filter((element, index, array) => !emptyIndexes.includes(index));
const doughnutChart = new Chart(ctx, {
type: config.chart_type, //'pie',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
maintainAspectRatio: false, // https://stackoverflow.com/a/53233861,
animation: { duration: 0 },
legend: {
position: 'bottom',
display: display_legend
},
hover: { mode: 'index' },
//plugins: {colorschemes: { scheme: 'brewer.Accent8' } },
plugins: {
labels: [{
render: 'label',
position: 'inside',
fontColor: '#000',
textMargin: 6
}
// I don't need to display percentage
// },
// {
// render: 'percentage',
// fontColor: '#000',
// }
]
},
// https://stackoverflow.com/a/49717859
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var meta = dataset._meta[Object.keys(dataset._meta)[0]];
var total = meta.total;
var currentValue = dataset.data[tooltipItem.index];
var percentage = parseFloat((currentValue/total*100).toFixed(1));
return currentValue + ' (' + percentage + '%)';
},
title: function(tooltipItem, data) {
return data.labels[tooltipItem[0].index];
}
}
},
}
});
var getData = function() {
doughnutChart.data = { datasets: [{ data: entityData }], labels: entityNames };
doughnutChart.update();
};
getData();
}
getCardSize() {
return 3;
}
}
customElements.define('pie-chart-card', PieChartCard);