Skip to content

Instantly share code, notes, and snippets.

@balloob
Last active May 19, 2022 20:57
Show Gist options
  • Save balloob/bf2715efba46420d6ba1a01586946308 to your computer and use it in GitHub Desktop.
Save balloob/bf2715efba46420d6ba1a01586946308 to your computer and use it in GitHub Desktop.
Demo Lovelace strategy for Home Assistant
/*
Demo strategy that shows each area as a tab. Each tab shows the area entities.
To use:
- store this file in `<config>/www/demo-strategy.js`
- Add lovelace resource: `/local/demo-strategy.js`, type JavaScript Module
- Create a new Lovelace dashboard and set as content:
strategy:
name: 'custom:balloob-demo'
views: []
*/
class StrategyDemo {
/*
info: {
config?: LovelaceConfig;
hass: HomeAssistant;
narrow: boolean | undefined;
}
*/
static async generateDashboard(info) {
// Query all data we need. We will make it available to views by storing it in strategy options.
const [areas, devices, entities] = await Promise.all([
info.hass.callWS({ type: "config/area_registry/list" }),
info.hass.callWS({ type: "config/device_registry/list" }),
info.hass.callWS({ type: "config/entity_registry/list" }),
]);
// Each view itself is based on a strategy so we can delay rendering until it's opened
return {
views: areas.map((area) => ({
strategy: {
name: "custom:balloob-demo",
options: { area, devices, entities },
},
title: area.name,
path: area.area_id,
})),
};
}
/*
info: {
view: LovelaceViewConfig;
config: LovelaceConfig;
hass: HomeAssistant;
narrow: boolean | undefined;
}
*/
static async generateView(info) {
const { area, devices, entities } = info.view.strategy.options;
const areaDevices = new Set();
// Find all devices linked to this area
for (const device of devices) {
if (device.area_id === area.area_id) {
areaDevices.add(device.id);
}
}
const cards = [];
// Find all entities directly linked to this area
// or linked to a device linked to this area.
for (const entity of entities) {
if (
entity.area_id
? entity.area_id === area.area_id
: areaDevices.has(entity.device_id)
) {
cards.push({
type: "button",
entity: entity.entity_id,
});
}
}
return {
cards: [
{
type: "grid",
cards,
},
],
};
}
}
customElements.define("ll-strategy-balloob-demo", StrategyDemo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment