feat: add floating power cards for all powered furniture

This commit is contained in:
jhartworks committed 2026-11-11 16:24:52 +01:00
1 parent 6bd3598779
commit 4967dd7950
19 files changed
+1125 -810

No files matched your search

@@ -12,6 +12,7 @@ import type { EditorHost } from "../host.ts";
import { lightEffectFields } from "../light-effect-fields.ts";
import { lightEffectSource } from "../../../light-effects.ts";
import { renderDeviceValues } from "../device-values.ts";
import { isSymcon, isSymconVariable } from "../../../entities/symcon-values.ts";
import { calibrationFrom, calibrationFromRooms, gridPlaces, gridRooms, mapCamera, nudgeCalibration, type CalibrationNudge, type Place } from "../../../live/vacuum-map.ts";
/** What the forms of a piece of furniture make the editor do. */
@@ -266,11 +267,13 @@ export function furnitureLinks(host: EditorHost, item: Furniture, actions: Furni
const t = host.t;
const lamp = isLamp(item.type);
const main = mainEntity(item, hass);
const power = entityOptions(hass, (id) => isPowerSensor(hass, id));
const power = entityOptions(hass, (id) => isSymcon(hass) ? isSymconVariable(hass, id, [1, 2]) : isPowerSensor(hass, id));
const set = (key: keyof Furniture) => (v: string | null) => actions.update({ [key]: noneAsNull(v) });
const kindOptions = (accept: (id: string) => boolean) => entityOptions(hass, accept);
const strings = (host.doc.settings.roof.strings ?? []).filter((s) => s.inverter === item.id).map((s) => s.name);
const hasLink = !!item.entity && item.entity !== "none";
const autoPower = automaticLink(host, item, "power");
const powerRef = item.power === "none" ? null : item.power || autoPower;
const doors = item.type === "fridge_smart" ? kindOptions((id) => id.startsWith("binary_sensor.")) : [];
const hintKey: I18nKey = item.type === "ceiling_fan" ? "fan_hint" : lamp ? (item.type === "lamp_pendant" ? "lamp_hint_pendant" : "lamp_hint") : isMediaFurniture(item.type) ? "furn_links_hint_tv" : item.type === "robot_vacuum" ? "robot_hint" : "furn_links_hint";
return html`${linkBlock(
@@ -287,7 +290,8 @@ export function furnitureLinks(host: EditorHost, item: Furniture, actions: Furni
lamp ? lightEffectFields(host, item, lightEffectSource(hass, item, item.entity && item.entity !== "none" ? item.entity : automaticLink(host, item, "entity"))?.attributes.effect_list, actions.update) : nothing,
hasScreen(item.type) ? glowField(host, item.ambilight, (v) => actions.update({ ambilight: v }), { label: "ambilight", hint: "ambilight_hint", lowest: 0 }) : nothing,
(isMediaFurniture(item.type) || isSpeakerFurniture(item.type)) ? glowField(host, item.sound_rings, (v) => actions.update({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing,
item.type === "grid_point" ? nothing : entityField(host, t(meterParent(host.doc, item) ? "meter_sub_power" : powerLabel(item.type)), item.power ?? null, automaticLink(host, item, "power"), power, (v) => actions.update({ power: v })),
item.type === "grid_point" ? nothing : html`${entityField(host, t(meterParent(host.doc, item) ? "meter_sub_power" : powerLabel(item.type)), item.power ?? null, autoPower, power, (v) => actions.update({ power: v }))}
${checkField(host, t("furniture_power_card"), !!item.power_card, (on) => actions.update({ power_card: on || undefined }))}${hint(t("furniture_power_card_hint"), "nf-wide")}`,
)}
${isCooling(item.type) ? coolingLinks(host, item, actions) : lamp || item.type === "grid_point" ? nothing : deviceTempLink(host, item, actions)}
${item.type === "meter" ? subMeterLinks(host, item, actions) : nothing}
@@ -302,7 +306,7 @@ export function furnitureLinks(host: EditorHost, item: Furniture, actions: Furni
)
: nothing}
${item.type === "wallbox" ? linkBlock(entityField(host, t("furn_wallbox_status"), item.status ?? null, undefined, kindOptions((id) => isBinary(id) || isNumeric(id)), set("status"))) : nothing}
${!lamp || item.entity
${!lamp || hasLink || powerRef
? html`${checkField(host, t("device_confirm"), !!item.confirm, (on) => actions.update({ confirm: on }), { title: t("device_confirm_hint") })}
<div class="nf-form">${markerField(host, item.marker ?? null, (v) => actions.update({ marker: v }))}${iconField(host, item.icon, (v) => actions.update({ icon: v }))}${lamp ? nothing : pinShiftField(host, item.pin_offset, (v) => actions.update({ pin_offset: v }))}</div>`
: nothing}
+6 -2
View File
@@ -31,6 +31,7 @@ import { weatherEntity } from "../weather.ts";
import { chosenEffects, readSkyWeather, withDensity } from "../live/sky-weather.ts";
import { energyPicture, houseHub, type EnergyPicture } from "../live/energy-flow.ts";
import { roomClimateCards } from "../live/room-climate-card.ts";
import { furniturePowerCards } from "../live/furniture-power-card.ts";
import { loadWeek, type WeekBars } from "../live/week-bars.ts";
import { binsDue, loadToday, sortDay, type TodayItem } from "../live/today.ts";
import { forecastDays, loadForecast } from "../live/forecast.ts";
@@ -2659,7 +2660,10 @@ export class NfView3d extends LitElement {
for (const p of this.liveHeatPumps(b)) cards.push({ kind: "heatpump", at: p.at, name: p.name, pump: p.pump });
for (const m of media) cards.push({ kind: "media", at: { ...m.at, y: m.at.y + 0.5 }, media: m });
}
if (this.liveCardsOn && !this.dimmed) cards.push(...roomClimateCards(hass, b, this.floorId, this.roomId));
if (this.liveCardsOn && !this.dimmed) {
cards.push(...roomClimateCards(hass, b, this.floorId, this.roomId));
cards.push(...furniturePowerCards(hass, b, this.furnitureLinks ?? new Map(), this.floorId, this.roomId));
}
if (JSON.stringify(cards) !== JSON.stringify(this._liveCards)) this._liveCards = cards;
v.setLiveAnchors(
cards.map((c) => c.at),
@@ -2710,7 +2714,7 @@ export class NfView3d extends LitElement {
const own = this.ownSensors();
const e = this._liveEnergy?.summary;
const energy = !!e && !this.roomId && this.showEnergy && !!this.hass && !(e.consumption === null && e.grid === null && e.solar === null && e.battery === null);
const climate = this.building?.floors.some((f) => f.rooms.some((r) => r.climate_card));
const climate = this.building?.floors.some((f) => f.rooms.some((r) => r.climate_card) || f.furniture.some((m) => m.power_card));
const climateToggle = climate ? this.renderCardToggle() : nothing;
const roomNames = this.roomNamesButton ? html`<button class="nf-energy-item nf-flow-toggle nf-room-names-toggle" aria-pressed=${this.roomLabels} title=${translate(this.hass, "room_names_toggle_hint")} @click=${() => {
this.roomLabels = !this.roomLabels;
+4
View File
@@ -28,6 +28,8 @@ const DE = {
climate_card: "Raumklima als schwebende Karte",
climate_card_hint: "Zeigt Temperatur, Luftfeuchtigkeit und CO₂ über diesem Raum. In der 3D-Ansicht lassen sie sich über „Karten“ ein- und ausblenden.",
climate_card_missing: "Keine aktuellen Messwerte",
furniture_power_card: "Leistung als 3D-Kachel",
furniture_power_card_hint: "Zeigt den Leistungswert über diesem Möbelstück, auch ohne verknüpfte Schaltvariable. Die Kachel bleibt bei 0 W sichtbar. Bei archivierten Variablen öffnet das Trendsymbol den Verlauf. Der Schalter „Karten“ blendet die schwebenden Kacheln gemeinsam ein und aus.",
climate_illuminance: "Helligkeit",
device_values: "Zusätzliche Werte",
device_value: "Datenpunkt",
@@ -2071,6 +2073,8 @@ const EN: Record<Key, string> = {
climate_card: "Room climate as a floating card",
climate_card_hint: "Shows temperature, humidity and CO₂ over this room. Toggle them with “Cards” in the 3D view.",
climate_card_missing: "No current readings",
furniture_power_card: "Power as a floating 3D card",
furniture_power_card_hint: "Shows the power reading above this furniture, even without a linked switch. The card remains visible at 0 W. Logged variables offer a trend button. Use the Cards switch to show or hide floating cards together.",
climate_illuminance: "Illuminance",
device_values: "Additional values",
device_value: "Data point",
+15 -2
View File
@@ -22,6 +22,7 @@ import type { RoomClimateCard } from "./room-climate-card.ts";
import { fromCelsius, tempUnit } from "../devices.ts";
import { trendButton } from "../components/trend-button.ts";
import { loggedEntities } from "../trend-data.ts";
import type { FurniturePowerCard } from "./furniture-power-card.ts";
export interface HouseCard {
kind: "house";
@@ -64,7 +65,7 @@ export interface HeatPumpCard {
pump: HeatPumpInfo;
}
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard | RoomClimateCard;
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard | RoomClimateCard | FurniturePowerCard;
/** A button on a card was pressed: the 3D view calls the service (with extra data such as the volume). */
export type LiveCardAction = (domain: string, service: string, entity: string, data?: Record<string, unknown>) => void;
@@ -327,14 +328,26 @@ function roomClimateCard(hass: HomeAssistant | undefined, c: RoomClimateCard, i:
</div>`;
}
function furniturePowerCard(hass: HomeAssistant | undefined, c: FurniturePowerCard, i: number): TemplateResult {
const power = c.power === null ? "–" : `${c.power < 0 ? "−" : ""}${watts(hass, c.power)}`;
return html`<div class="live-card live-card-power" data-i=${i} data-furniture=${c.id} role="group" aria-label=${c.name}>
<div class="live-power-name">${c.name}</div><div class="live-row"><span aria-hidden="true">⚡</span><b>${power}</b>${trendButton(hass, [c.powerEntity], c.name)}</div>
</div>`;
}
export function renderLhCards(hass: HomeAssistant | undefined, cards: readonly LiveCard[], act: LiveCardAction, fold?: LiveCardFold, climateOnly = false): TemplateResult | typeof nothing {
if (!cards.length) return nothing;
return html`<div class="live-cards">
${cards.map((c, i) => (c.kind === "roomclimate" ? roomClimateCard(hass, c, i) : climateOnly ? nothing : c.kind === "house" ? houseCard(hass, c, i, fold) : c.kind === "car" ? carCard(hass, c, i, act) : c.kind === "printer" ? printerCard(hass, c, i) : c.kind === "heatpump" ? heatPumpCard(hass, c, i) : mediaCard(hass, c, i, act)))}
${cards.map((c, i) => (c.kind === "roomclimate" ? roomClimateCard(hass, c, i) : c.kind === "power" ? furniturePowerCard(hass, c, i) : climateOnly ? nothing : c.kind === "house" ? houseCard(hass, c, i, fold) : c.kind === "car" ? carCard(hass, c, i, act) : c.kind === "printer" ? printerCard(hass, c, i) : c.kind === "heatpump" ? heatPumpCard(hass, c, i) : mediaCard(hass, c, i, act)))}
</div>`;
}
export const liveCardStyles = css`
.live-card.live-card-power { display:grid; gap:4px; min-width:90px; max-width:220px; box-sizing:border-box; }
.live-power-name { font-size:11px; color:var(--nf-muted); overflow:hidden; text-overflow:ellipsis; }
.live-card-power .live-row { align-items:center; gap:6px; }
.live-card-power .live-row b { margin-left:auto; color:color-mix(in srgb,#ffca8a 80%,var(--nf-text)); font-variant-numeric:tabular-nums; }
.live-card-power nf-trend-button { margin-left:0; }
.live-cards {
position: absolute;
inset: 0;
@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf } from "../entities/fixtures.ts";
import { emptyBuilding, FURNITURE_TYPES, normalizeBuilding, type Furniture } from "../model.ts";
import { furnitureEntities } from "../entities/furniture-links.ts";
import { isElectric, setPacks } from "../packs.ts";
import { furniturePowerCards } from "./furniture-power-card.ts";
const item = (id: string, extra: Partial<Furniture> = {}): Furniture => ({ id, type: "wallbox", x: 2, z: 2, w: .3, d: .3, h: .4, rotation: 0, variant: null, power: "cover.knx", power_card: true, ...extra });
const native = (value: number, unit = "W") => entity("cover.knx", "open", { symcon_id: 123, symcon_variable_type: 2, symcon_numeric_value: value, unit_of_measurement: unit });
const plan = (...items: Furniture[]) => ({ ...emptyBuilding(), floors: [floorWith([box("garage", 0, 0, 5, 5)], { furniture: items })] });
test("power-only native links work for every electric built-in and a pack wallbox with a status light", () => {
setPacks([{ id: "test", name: "Test", publisher: "test", items: [{ id: "wallbox", name: { de: "Wallbox" }, size: [.3, .3, .4], light: "wall", parts: [] }] }]);
try {
const types = [...FURNITURE_TYPES.filter(isElectric), "pack:test:wallbox"];
const b = plan(...types.map((type, n) => item(String(n), { type, entity: null })));
const h = hassOf([native(11, "kW")]);
const cards = furniturePowerCards(h, b, furnitureEntities(h, b.floors), null, null);
assert.equal(cards.length, types.length);
assert.ok(cards.every((c) => c.power === 11000 && c.powerEntity === "cover.knx"));
assert.equal(cards.at(-1)?.name, "Wallbox");
} finally { setPacks([]); }
});
test("zero, export, unavailable and missing values retain their meaning and update live", () => {
const b = plan(item("wallbox")), h = hassOf([native(0)]);
const read = () => furniturePowerCards(h, b, new Map(), null, null)[0].power;
assert.equal(read(), 0);
h.states["cover.knx"] = native(-2.5, "kW");
assert.equal(read(), -2500);
h.states["cover.knx"] = entity("cover.knx", "unavailable", { symcon_id: 123, symcon_numeric_value: 1234 });
assert.equal(read(), null);
delete h.states["cover.knx"];
assert.equal(read(), null);
});
test("cards are opt-in, respect explicit none and use automatic links including the native source of aliases", () => {
const b = plan(item("default", { power_card: undefined }), item("none", { power: "none" }), item("unlinked", { power: null }), item("auto", { power: null }), item("explicit"));
const h = hassOf([native(250), entity("light.alias", "on", { symcon_source_entity: "cover.knx" })]);
const links = new Map([ ["none", { entity: null, power: "cover.knx" }], ["auto", { entity: null, power: "light.alias" }] ]);
assert.deepEqual(furniturePowerCards(h, b, links, null, null).map((c) => [c.id, c.powerEntity, c.power]), [["auto", "cover.knx", 250], ["explicit", "cover.knx", 250]]);
});
test("floor, room and furniture visibility filter cards while anchors follow mounting and pin offsets", () => {
const b = plan(item("garage", { name: "Meine Wallbox", mount_y: .9, pin_offset: { x: .1, y: .2, z: -.3 } }), item("outside", { x: 7 }), item("hidden", { show_when: { entity: "binary_sensor.visible" } }));
b.floors.push(floorWith([box("office", 0, 0, 5, 5)], { id: "upper", furniture: [item("upper")] }));
const h = hassOf([native(500), entity("binary_sensor.visible", "off")]);
const read = (floor: string | null, room: string | null) => furniturePowerCards(h, b, new Map(), floor, room);
assert.deepEqual(read(null, null).map((c) => c.id), ["garage", "outside", "upper"]);
assert.deepEqual(read("upper", null).map((c) => c.id), ["upper"]);
assert.deepEqual(read(null, "garage").map((c) => c.id), ["garage"]);
assert.deepEqual(read("upper", "garage"), []);
assert.equal(read(null, "garage")[0].name, "Meine Wallbox");
const at = read(null, "garage")[0].at;
assert.deepEqual([at.floorId, at.x, at.z], [b.floors[0].id, 2.1, 1.7]);
assert.ok(Math.abs(at.y - 1.85) < 1e-10);
});
test("the setting and links survive plan normalization and JSON persistence", () => {
const b = normalizeBuilding(JSON.parse(JSON.stringify(plan(item("wallbox")))));
assert.equal(b.floors[0].furniture[0].power_card, true);
assert.equal(furniturePowerCards(hassOf([native(100)]), b, new Map(), null, null)[0].power, 100);
});
+38
View File
@@ -0,0 +1,38 @@
import { mountBase } from "../packs.ts";
import { pointInPolygon, type Building } from "../model.ts";
import { furnitureName } from "../furniture-names.ts";
import { furnitureShown } from "../entities/visibility.ts";
import type { FurnitureLinks } from "../entities/furniture-links.ts";
import type { HomeAssistant } from "../types.ts";
import { readPower } from "../energy.ts";
import type { PlanPoint } from "../viewer/live-energy.ts";
export interface FurniturePowerCard {
kind: "power";
id: string;
name: string;
powerEntity: string;
power: number | null;
at: PlanPoint;
}
/** Power-only links are enough: never require a switch, a special furniture type, or a positive reading. */
export function furniturePowerCards(hass: HomeAssistant, building: Building, links: ReadonlyMap<string, FurnitureLinks>, floorId: string | null, roomId: string | null): FurniturePowerCard[] {
const cards: FurniturePowerCard[] = [];
for (const floor of building.floors) {
if (floorId && floor.id !== floorId) continue;
const room = roomId ? floor.rooms.find((r) => r.id === roomId) : null;
if (roomId && !room) continue;
for (const item of floor.furniture) {
if (!item.power_card || item.power === "none" || !furnitureShown(hass, item)) continue;
if (room && !pointInPolygon([item.x, item.z], room.points)) continue;
const source = item.power || links.get(item.id)?.power;
if (!source || source === "none") continue;
const powerEntity = String(hass.states[source]?.attributes.symcon_source_entity || source);
const offset = item.pin_offset;
cards.push({ kind: "power", id: item.id, name: item.name || furnitureName(hass, item.type), powerEntity,
power: readPower(hass.states[powerEntity]), at: { floorId: floor.id, x: item.x + (offset?.x ?? 0), z: item.z + (offset?.z ?? 0), y: mountBase(floor, item) + item.h + .35 + (offset?.y ?? 0) } });
}
}
return cards;
}
+2
View File
@@ -263,6 +263,8 @@ export interface Furniture extends LightEffectConfig {
entity?: EntityRef;
/** Power sensor (null = automatic: the linked entity's device or a matching name). */
power?: EntityRef;
/** Show this furniture's linked power reading as its own floating 3D card. */
power_card?: boolean;
/** Fridges and freezers: a temperature sensor of the fridge (temp_entity) and one of the freezer compartment; the marker shows them and warns when too warm. Any other device: its own thermometer, shown on its pin (#112). */
temp_entity?: string | null;
temp_entity2?: string | null;
+145
View File
@@ -0,0 +1,145 @@
// Native power-only furniture, the real object-tree picker and floating cards in the built UI.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { extname, join, relative, resolve } from "node:path";
import puppeteer from "puppeteer-core";
const root = resolve(import.meta.dirname, "..");
const server = createServer((req, res) => {
const file = resolve(root, `.${decodeURIComponent(new URL(req.url, "http://localhost").pathname)}`);
if (relative(root, file).startsWith("..") || !existsSync(file)) return res.writeHead(404).end();
res.writeHead(200, { "content-type": ({ ".html": "text/html", ".js": "text/javascript", ".json": "application/json" })[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file));
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
let browser;
try {
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
const page = await browser.newPage(), errors = [];
page.on("pageerror", (e) => errors.push(String(e)));
await page.setViewport({ width: 1440, height: 1000 });
await page.evaluateOnNewDocument(() => localStorage.setItem("nextfloor.cards", "0"));
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html?noshowcase`, { waitUntil: "networkidle0" });
await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length);
await page.evaluate(async () => {
const p = window.nfPanel, b = structuredClone(p.data.building), f = b.floors[0];
const room = f.rooms[0], [x, z] = room.points[0];
const piece = (id, type, dx, extra = {}) => ({ id, type, name: id, x: x + 1 + dx, z: z + 1, w: .3, d: .3, h: .4, rotation: 0, variant: null, entity: "none", power: "none", ...extra });
for (const floor of b.floors) {
floor.furniture = []; floor.power_entity = null; floor.utility_meters = null;
for (const r of floor.rooms) { r.area_id = null; r.climate_card = false; }
}
f.furniture = [piece("Wallbox", "pack:nextfloor.energie:wallbox", 0, { mount_y: .9 }), piece("Waschmaschine", "washer", 2, { power: "sensor.202", power_card: true }), piece("Standard-Wallbox", "wallbox", 4, { power: "sensor.202", power_card: true })];
b.floors[1].furniture = [piece("Oben", "lamp_table", 0, { power: "sensor.202", power_card: true })];
for (const key of Object.keys(b.energy)) b.energy[key] = null;
const states = {
"cover.201": { entity_id: "cover.201", state: "open", attributes: { symcon_id: 201, symcon_variable_type: 2, symcon_value: 11000, symcon_numeric_value: 11000, unit_of_measurement: "W", symcon_formatted: "11.000 W", friendly_name: "Wallbox Gesamtleistung", symcon_archive: { id: 999, counter: false } } },
"sensor.202": { entity_id: "sensor.202", state: "0", attributes: { symcon_id: 202, symcon_variable_type: 1, symcon_value: 0, symcon_numeric_value: 0, unit_of_measurement: "W", friendly_name: "Andere Leistung" } },
};
const node = (object_id, parent_id, name, object_type = 0, extra = {}) => ({ object_id, parent_id, name, object_type, path: `Haus / Garage / ${name}`, hidden: true, position: 0, icon: "", ...extra });
const objects = [node(100, 0, "Haus"), node(101, 100, "Garage"), node(201, 101, "Wallbox Gesamtleistung", 2, { entity_id: "cover.201" }), node(202, 101, "Andere Leistung", 2, { entity_id: "sensor.202" })];
window.powerFloor = f.id; window.powerRoom = room.id;
p.data.edit(b); p.hass = { ...p.hass, language: "de", states, symconObjects: objects };
await p.updateComplete;
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click();
});
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot);
await page.evaluate(async () => {
const e = window.nfPanel.shadowRoot.querySelector("nf-editor"); window.powerEditor = e;
e._floorId = window.powerFloor; e.selectItem("furniture", "Wallbox"); await e.updateComplete;
const field = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((l) => l.textContent.trim().startsWith(e.t("furn_power")));
if (!field) throw new Error("Pack wallbox power picker missing");
const picker = field.querySelector("nf-entity-picker"); await picker.updateComplete;
const native = picker.shadowRoot.querySelector("nf-symcon-object-picker"); await native.updateComplete;
native.shadowRoot.querySelector(".trigger").click(); await native.updateComplete;
const input = native.shadowRoot.querySelector(".search"); input.value = "Wallbox Gesamtleistung"; input.dispatchEvent(new Event("input", { bubbles: true })); await native.updateComplete;
const row = native.shadowRoot.querySelector("#object-201");
if (!row?.classList.contains("selectable")) throw new Error("Native float power must be selectable even with an inferred cover domain");
row.click(); await native.updateComplete; native.shadowRoot.querySelector(".apply").click();
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
const marker = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((l) => l.textContent.trim().startsWith(e.t("marker_show")));
if (!marker) throw new Error("A power-only pack light must offer the marker controls too");
const option = [...e.shadowRoot.querySelectorAll("label.nf-check")].find((l) => l.textContent.includes("Leistung als 3D-Kachel"));
if (!option) throw new Error("Power card setting missing");
option.querySelector("input").click();
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
option.scrollIntoView({ block: "center" });
});
assert.deepEqual(await page.evaluate(() => {
const f = window.nfPanel.data.building.floors[0].furniture[0]; return [f.power, f.power_card, f.entity];
}), ["cover.201", true, "none"], "selecting a power-only link and enabling the card edits the saved plan");
const out = join(root, "preview/screenshots"); mkdirSync(out, { recursive: true });
await page.screenshot({ path: join(out, "symcon-power-card-editor.png") });
await page.evaluate(() => [...window.nfPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "3D").click());
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-view3d")?.shadowRoot.querySelector(".nf-card-toggle"));
await page.evaluate(async () => {
const v = window.nfPanel.shadowRoot.querySelector("nf-view3d"); window.powerView = v;
window.nfPanel.openFloor(window.powerFloor); await window.nfPanel.updateComplete; await v.updateComplete;
const toggle = v.shadowRoot.querySelector(".nf-card-toggle");
if (toggle.getAttribute("aria-pressed") !== "false") throw new Error("Cards should begin disabled for this test");
toggle.click();
});
await page.waitForFunction(() => window.powerView.shadowRoot.querySelector('.live-card-power[data-furniture="Wallbox"]')?.style.visibility === "visible");
const values = () => page.evaluate(() => [...window.powerView.shadowRoot.querySelectorAll(".live-card-power")].map((c) => [c.dataset.furniture, c.querySelector("b").textContent]));
assert.deepEqual(await values(), [["Wallbox", "11 kW"], ["Waschmaschine", "0 W"], ["Standard-Wallbox", "0 W"]]);
assert.equal(await page.evaluate(() => window.powerView.shadowRoot.querySelector('.live-card-power[data-furniture="Wallbox"] nf-trend-button')?.ids[0]), "cover.201", "native logging enables the small trend trigger");
assert.equal(await page.evaluate(() => !!window.powerView.shadowRoot.querySelector('.live-card-power[data-furniture="Waschmaschine"] nf-trend-button')), false);
await page.screenshot({ path: join(out, "symcon-power-cards-desktop.png") });
const setValue = async (value, state = "open") => {
await page.evaluate(({ value, state }) => {
const p = window.nfPanel, old = p.hass.states["cover.201"];
p.hass = { ...p.hass, states: { ...p.hass.states, "cover.201": { ...old, state, attributes: { ...old.attributes, symcon_numeric_value: value, symcon_value: value } } } };
}, { value, state });
};
await setValue(0);
await page.waitForFunction(() => window.powerView.shadowRoot.querySelector('.live-card-power[data-furniture="Wallbox"] b')?.textContent === "0 W");
await setValue(-1500);
await page.waitForFunction(() => window.powerView.shadowRoot.querySelector('.live-card-power[data-furniture="Wallbox"] b')?.textContent === "−1,5 kW");
await setValue(1500, "unavailable");
await page.waitForFunction(() => window.powerView.shadowRoot.querySelector('.live-card-power[data-furniture="Wallbox"] b')?.textContent === "–");
await setValue(7400);
await page.evaluate(() => window.nfPanel.openFloor(null));
await page.waitForFunction(() => window.powerView.shadowRoot.querySelectorAll(".live-card-power").length === 4);
await page.evaluate(() => { window.nfPanel.openFloor(window.powerFloor); window.nfPanel._roomId = window.powerRoom; });
await page.waitForFunction(() => window.powerView.shadowRoot.querySelector('.live-card-power[data-furniture="Wallbox"]')?.style.visibility === "visible");
assert.ok((await values()).every(([name]) => name !== "Oben"), "selected rooms exclude furniture from other floors");
await page.evaluate(async () => { window.nfPanel._roomId = null; await window.nfPanel.updateComplete; });
await page.setViewport({ width: 390, height: 844 });
await page.evaluate(async () => { window.powerView.resetView(); await new Promise((done) => setTimeout(done, 900)); });
await page.waitForFunction(() => {
const cards = [...window.powerView.shadowRoot.querySelectorAll(".live-card-power")];
return cards.length === 3 && cards.every((c) => { const r = c.getBoundingClientRect(); return c.style.visibility === "visible" && r.left >= 0 && r.right <= innerWidth; });
}, { timeout: 5000 }).catch(async (error) => {
console.log(await page.evaluate(() => ({ floor: window.powerView.floorId, room: window.powerView.roomId, cards: [...window.powerView.shadowRoot.querySelectorAll(".live-card-power")].map((c) => ({ name: c.dataset.furniture, visibility: c.style.visibility, rect: c.getBoundingClientRect().toJSON(), parent: c.parentElement.getBoundingClientRect().toJSON(), transform: c.style.transform, x: c.dataset.x, y: c.dataset.y })) })));
await page.screenshot({ path: join(out, "symcon-power-cards-mobile-failure.png") });
throw error;
});
const mobileCards = await page.evaluate(() => [...window.powerView.shadowRoot.querySelectorAll(".live-card-power")].map((c) => {
const r = c.getBoundingClientRect(), stage = c.parentElement.getBoundingClientRect();
return { name: c.dataset.furniture, top: r.top, bottom: r.bottom, stageTop: stage.top, stageBottom: stage.bottom };
}));
assert.ok(mobileCards.every((c) => c.top >= c.stageTop && c.bottom <= c.stageBottom), JSON.stringify(mobileCards));
await page.screenshot({ path: join(out, "symcon-power-cards-mobile.png") });
await page.evaluate(() => window.powerView.shadowRoot.querySelector(".nf-card-toggle").click());
await page.waitForFunction(() => !window.powerView.shadowRoot.querySelector(".live-card-power"));
await page.evaluate(() => [...window.nfPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click());
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot);
await page.evaluate(async () => {
const e = window.nfPanel.shadowRoot.querySelector("nf-editor"); e._floorId = window.powerFloor; e.selectItem("furniture", "Wallbox"); await e.updateComplete;
const option = [...e.shadowRoot.querySelectorAll("label.nf-check")].find((l) => l.textContent.includes("Leistung als 3D-Kachel"));
if (!option.querySelector("input").checked) throw new Error("Power card flag did not survive reopening the editor");
option.querySelector("input").click();
await e.updateComplete; await window.nfPanel.updateComplete;
[...window.nfPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "3D").click();
});
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-view3d")?.shadowRoot.querySelector(".nf-card-toggle"));
await page.evaluate(async () => { const v = window.nfPanel.shadowRoot.querySelector("nf-view3d"); window.powerView = v; window.nfPanel.openFloor(window.powerFloor); await window.nfPanel.updateComplete; await v.updateComplete; v.shadowRoot.querySelector(".nf-card-toggle").click(); });
await page.waitForFunction(() => window.powerView.shadowRoot.querySelectorAll(".live-card-power").length === 2);
assert.ok((await values()).every(([name]) => name !== "Wallbox"), "disabling an individual card takes effect independently of the global Cards switch");
assert.deepEqual(errors, []);
console.log("Power-only wallbox and all electric furniture: picker, persistence, live/zero/offline values, trends, navigation and desktop/mobile cards passed.");
} finally {
await browser?.close();
await new Promise((done) => server.close(done));
}