-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
74 lines (61 loc) · 1.84 KB
/
index.ts
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
import { HomeAssistant } from 'custom-card-helpers';
import { LitElement, TemplateResult, nothing } from 'lit';
import { property, state } from 'lit/decorators.js';
type Template = TemplateResult | string | typeof nothing;
type UnsubscribePromise = Promise<() => Promise<void>>;
type UnsubscribeError = Error & { code: string };
export class HATemplate extends LitElement {
@property() public hass!: HomeAssistant;
@property() public template = '';
@property() public variables: Record<string, unknown> = {};
@property() public value: string | null = null;
@state() private unsubscribePromise: UnsubscribePromise | null = null;
public connectedCallback() {
super.connectedCallback();
if (!this.hass) {
console.warn('hass object is not provided');
return;
}
if (this.unsubscribePromise) {
return;
}
if (!this.template) {
return;
}
this.unsubscribePromise = this.hass.connection.subscribeMessage<{
result: string;
}>(
(msg) => {
this.value = msg.result;
},
{
type: 'render_template',
template: this.template,
variables: this.variables,
}
);
}
public async disconnectedCallback() {
super.disconnectedCallback();
if (this.unsubscribePromise) {
try {
const unsubscribe = await this.unsubscribePromise;
this.unsubscribePromise = null;
return unsubscribe();
} catch (err: unknown) {
// We don't care when connection is closed.
if ((err as UnsubscribeError).code !== 'not_found') {
throw err;
}
}
}
}
protected render(): Template {
return this.value ?? nothing;
}
}
export default function register(componentName = 'ha-template') {
if (!customElements.get(componentName)) {
customElements.define(componentName, HATemplate);
}
}