-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml-js-card.js
More file actions
executable file
·342 lines (308 loc) · 12.1 KB
/
html-js-card.js
File metadata and controls
executable file
·342 lines (308 loc) · 12.1 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
/**
* html-js-card
* Una custom card per Home Assistant che permette di usare
* HTML, CSS e JavaScript arbitrario direttamente dal YAML Lovelace.
*
* Autore: generata con Claude / Amira
* Repository: /config/www/html-js-card/
*
* Configurazione YAML esempio:
*
* type: custom:html-js-card
* title: La mia card # opzionale
* height: 400px # opzionale, default auto
* entities: # opzionale, lista entità da iniettare
* - sensor.temperatura
* - input_number.soglia
* scripts: # opzionale, CDN esterni da caricare
* - https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js
* content: |
* <div id="mia-card">...</div>
* <script>
* // Variabili disponibili automaticamente:
* // - hass → oggetto Home Assistant completo
* // - entities → { 'sensor.temperatura': { state, attributes, ... } }
* // - card → elemento DOM della card
* console.log(hass.states['sensor.temperatura'].state);
* </script>
*/
class HtmlJsCard extends HTMLElement {
constructor() {
super();
this._hass = null;
this._config = null;
this._initialized = false;
this._scriptsLoaded = false;
this._updateTimer = null;
this.attachShadow({ mode: 'open' });
}
// ── Configurazione dal YAML ──────────────────────────────────────────────
setConfig(config) {
if (!config.content) {
throw new Error('html-js-card: il campo "content" è obbligatorio.');
}
this._config = config;
this._initialized = false;
this._scriptsLoaded = false;
this._render();
}
// ── Ricezione stato HA ───────────────────────────────────────────────────
set hass(hass) {
this._hass = hass;
if (!this._initialized) {
this._render();
} else {
this._updateEntities();
}
}
// ── Altezza card (per il layout Lovelace) ────────────────────────────────
getCardSize() {
const h = parseInt(this._config?.height || '200');
return Math.ceil(h / 50);
}
// ── Render principale ────────────────────────────────────────────────────
async _render() {
if (!this._config || !this._hass) return;
const config = this._config;
const shadow = this.shadowRoot;
// Struttura base
shadow.innerHTML = `
<style>
:host {
display: block;
font-family: var(--primary-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif);
}
ha-card {
overflow: hidden;
height: ${config.height || 'auto'};
}
.card-header {
display: flex;
align-items: center;
padding: 12px 16px 0;
font-size: 14px;
font-weight: 500;
color: var(--primary-text-color);
letter-spacing: 0.01em;
}
.card-content {
padding: ${config.padding !== undefined ? config.padding : '12px 16px 16px'};
height: ${config.height ? 'calc(100% - ' + (config.title ? '44px' : '0px') + ')' : 'auto'};
box-sizing: border-box;
overflow: ${config.overflow || 'hidden'};
}
#hjc-loading {
display: flex;
align-items: center;
justify-content: center;
height: 60px;
color: var(--secondary-text-color);
font-size: 13px;
gap: 8px;
}
#hjc-loading::before {
content: '';
width: 14px; height: 14px;
border: 2px solid var(--divider-color);
border-top-color: var(--primary-color);
border-radius: 50%;
animation: hjc-spin 0.8s linear infinite;
}
@keyframes hjc-spin { to { transform: rotate(360deg); } }
#hjc-error {
background: var(--error-color, #a32d2d);
color: #fff;
border-radius: 8px;
padding: 10px 14px;
font-size: 12px;
line-height: 1.5;
display: none;
}
</style>
<ha-card>
${config.title ? `<div class="card-header">${config.title}</div>` : ''}
<div class="card-content">
<div id="hjc-loading">Caricamento...</div>
<div id="hjc-error"></div>
<div id="hjc-content" style="display:none; height:100%;"></div>
</div>
</ha-card>
`;
// Carica script esterni se presenti
if (config.scripts && config.scripts.length > 0 && !this._scriptsLoaded) {
try {
await this._loadScripts(config.scripts);
this._scriptsLoaded = true;
} catch(e) {
this._showError('Errore caricamento script: ' + e.message);
return;
}
} else {
this._scriptsLoaded = true;
}
this._injectContent();
}
// ── Carica script CDN esterni ────────────────────────────────────────────
_loadScripts(urls) {
return Promise.all(urls.map(url => new Promise((resolve, reject) => {
// Evita di ricaricare script già presenti nel documento principale
if (document.querySelector(`script[src="${url}"]`)) {
resolve(); return;
}
const s = document.createElement('script');
s.src = url;
s.onload = resolve;
s.onerror = () => reject(new Error(`Impossibile caricare: ${url}`));
// Aggiunge al documento principale (non al shadow) per renderlo globale
document.head.appendChild(s);
})));
}
// ── Inietta HTML e JavaScript del content ───────────────────────────────
_injectContent() {
const shadow = this.shadowRoot;
const loading = shadow.getElementById('hjc-loading');
const contentDiv = shadow.getElementById('hjc-content');
const config = this._config;
try {
// Separa HTML da script
const { html, scripts } = this._parseContent(config.content);
// Inietta HTML
contentDiv.innerHTML = html;
contentDiv.style.display = 'block';
loading.style.display = 'none';
// Costruisci oggetto entities
const entities = this._buildEntities();
// Esegui tutti gli script con il contesto HA iniettato
scripts.forEach(scriptCode => {
this._executeScript(scriptCode, entities, contentDiv);
});
// Supporto campo opzionale `js:` — eseguito dopo il content
if (config.js) {
this._executeScript(config.js, entities, contentDiv);
}
this._initialized = true;
// Imposta aggiornamento automatico se configurato
if (config.update_interval) {
this._startAutoUpdate(config.update_interval);
}
} catch(e) {
console.error('html-js-card error:', e);
this._showError(e.message);
}
}
// ── Separa HTML dagli script nel content ────────────────────────────────
_parseContent(content) {
const scripts = [];
const scriptRegex = /<script[^>]*>([\s\S]*?)<\/script>/gi;
let match;
while ((match = scriptRegex.exec(content)) !== null) {
scripts.push(match[1]);
}
const html = content.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
return { html, scripts };
}
// ── Costruisce oggetto entities dall'elenco in config ───────────────────
_buildEntities() {
const entities = {};
if (this._config.entities && this._hass) {
this._config.entities.forEach(entityId => {
if (this._hass.states[entityId]) {
entities[entityId] = this._hass.states[entityId];
}
});
}
return entities;
}
// ── moreInfo — spara dall'host element (fuori dal shadow DOM) ─────────────
_moreInfo(entityId) {
this.dispatchEvent(new CustomEvent('hass-more-info', {
bubbles: true,
composed: true,
detail: { entityId }
}));
}
// ── Esegue uno script con variabili HA iniettate ────────────────────────
_executeScript(code, entities, contentEl) {
try {
// Wrap in funzione con variabili disponibili:
// - hass → oggetto HA completo
// - entities → entità dichiarate in config
// - card → elemento DOM #hjc-content
// - config → configurazione YAML della card
// - shadow → shadowRoot
// - moreInfo → apre popup nativo HA (entityId: string)
const fn = new Function(
'hass', 'entities', 'card', 'config', 'shadow', 'moreInfo',
'"use strict";\n' + code
);
fn(
this._hass,
entities,
contentEl,
this._config,
this.shadowRoot,
this._moreInfo.bind(this)
);
} catch(e) {
console.error('html-js-card script error:', e);
this._showError('Errore script: ' + e.message);
}
}
// ── Aggiorna solo le entità senza re-renderizzare tutto ─────────────────
_updateEntities() {
// Emette un evento custom che gli script interni possono ascoltare
const contentEl = this.shadowRoot?.getElementById('hjc-content');
if (!contentEl) return;
const entities = this._buildEntities();
const event = new CustomEvent('hass-update', {
detail: { hass: this._hass, entities },
bubbles: false
});
contentEl.dispatchEvent(event);
}
// ── Aggiornamento automatico ─────────────────────────────────────────────
_startAutoUpdate(intervalSeconds) {
if (this._updateTimer) clearInterval(this._updateTimer);
this._updateTimer = setInterval(() => {
const contentEl = this.shadowRoot?.getElementById('hjc-content');
if (!contentEl) return;
const entities = this._buildEntities();
const event = new CustomEvent('hass-update', {
detail: { hass: this._hass, entities },
bubbles: false
});
contentEl.dispatchEvent(event);
}, intervalSeconds * 1000);
}
// ── Mostra errore ────────────────────────────────────────────────────────
_showError(msg) {
const shadow = this.shadowRoot;
const loading = shadow?.getElementById('hjc-loading');
const errorDiv = shadow?.getElementById('hjc-error');
if (loading) loading.style.display = 'none';
if (errorDiv) {
errorDiv.style.display = 'block';
errorDiv.textContent = '⚠ html-js-card: ' + msg;
}
}
// ── Pulizia ──────────────────────────────────────────────────────────────
disconnectedCallback() {
if (this._updateTimer) clearInterval(this._updateTimer);
}
}
// ── Registrazione elemento custom ────────────────────────────────────────────
customElements.define('html-js-card', HtmlJsCard);
// ── Info per il pannello custom cards di HA ──────────────────────────────────
window.customCards = window.customCards || [];
window.customCards.push({
type: 'html-js-card',
name: 'HTML + JS Card',
description: 'Card che permette HTML, CSS e JavaScript arbitrario direttamente dal YAML Lovelace. Supporta entità HA, script CDN esterni e aggiornamento automatico.',
preview: false,
documentationURL: 'https://github.com/tuousername/html-js-card',
});
console.info(
'%c HTML-JS-CARD %c v1.0.0 ',
'background:#1D9E75;color:#fff;padding:2px 6px;border-radius:4px 0 0 4px;font-weight:600;',
'background:#f0ede8;color:#1a1a18;padding:2px 6px;border-radius:0 4px 4px 0;'
);