// A custom card that actually looks like something // Not like something good, mind you, but *something* at least. class MyCustomCard2 extends HTMLElement { setConfig(config) { this._config = config; // Example configuration: // // type: custom:my-custom-card2 // entity: light.bed_light // if(!config.entity) { // If no entity was specified, this will display a red error card with the message below throw new Error('You need to define an entity'); } // Make sure this only runs once if(!this.setupComplete) { // A ha-card element should be the base of all cards // Best practice, and makes themes and stuff work const card = document.createElement("ha-card"); // At this point, we don't necessarily know anything about the current state // of anything, but we can set up the general structure of the card. this.nameDiv = document.createElement("div"); card.appendChild(this.nameDiv); this.button = document.createElement("button"); this.button.addEventListener("click", () => this.buttonClicked()); card.appendChild(this.button); this.appendChild(card); this.setupComplete = true; } } set hass(hass) { this._hass = hass; // Update the card in case anything has changed if(!this._config) return; // Can't assume setConfig is called before hass is set const stateObj = hass.states[this._config.entity]; if(!stateObj) return; // This could be handled more gracefully this.nameDiv.innerHTML = stateObj.attributes.friendly_name || stateObj.entity_id; this.button.innerHTML = stateObj.state === "on" ? "Turn off" : "Turn on"; } buttonClicked() { const stateObj = this._hass.states[this._config.entity]; // Sanity checking is left as an exercise for the reader const service = stateObj.state === "on" ? "turn_off" : "turn_on"; // Turn on or off the light // https://developers.home-assistant.io/docs/frontend_data#hasscallservicedomain-service-data this._hass.callService("light", service, {entity_id: this._config.entity}); } } customElements.define('my-custom-card2', MyCustomCard2);