ha-template
Version:
A tiny (<2kB) lit component for rendering templates in Home Assistant custom cards
2 lines (1 loc) • 2.24 kB
JavaScript
import{LitElement as e,nothing as t}from"lit";import{notEqual as s}from"@lit/reactive-element";import{property as r,state as i}from"lit/decorators.js";function o(e,t,s,r){var i,o=arguments.length,a=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,s):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,s,r);else for(var n=e.length-1;n>=0;n--)(i=e[n])&&(a=(o<3?i(a):o>3?i(t,s,a):i(t,s))||a);return o>3&&a&&Object.defineProperty(t,s,a),a}"function"==typeof SuppressedError&&SuppressedError;class a extends e{constructor(){super(...arguments),this.template="",this.variables={},this.value=null,this.renderedValue=null,this.unsubscribePromise=null,this.subscriptionTask=Promise.resolve()}connectedCallback(){super.connectedCallback(),this.queueSubscriptionRefresh()}updated(e){(e.has("hass")||e.has("template")||e.has("variables")||e.has("value"))&&this.queueSubscriptionRefresh()}disconnectedCallback(){this.queueSubscriptionRefresh(),super.disconnectedCallback()}render(){var e,s;return null!==(s=null!==(e=this.renderedValue)&&void 0!==e?e:this.value)&&void 0!==s?s:t}queueSubscriptionRefresh(){this.subscriptionTask=this.subscriptionTask.then((()=>this.refreshSubscription())).catch((e=>{console.error("ha-template: Failed to refresh subscription",e)}))}async refreshSubscription(){await this.unsubscribeTemplate(),this.renderedValue=null,this.isConnected&&(this.hass?this.template?this.unsubscribePromise=this.hass.connection.subscribeMessage((e=>{this.renderedValue=e.result}),{type:"render_template",template:this.template,variables:this.variables}):console.warn("ha-template: template is not provided"):console.warn("ha-template: hass object is not provided"))}async unsubscribeTemplate(){if(!this.unsubscribePromise)return;const e=this.unsubscribePromise;this.unsubscribePromise=null;try{const t=await e;await Promise.resolve(t())}catch(e){if("not_found"!==e.code)throw e}}}function n(e="ha-template"){customElements.get(e)||customElements.define(e,a)}o([r()],a.prototype,"hass",void 0),o([r()],a.prototype,"template",void 0),o([r({hasChanged:s})],a.prototype,"variables",void 0),o([r()],a.prototype,"value",void 0),o([i()],a.prototype,"renderedValue",void 0);export{a as HATemplate,n as default};