feat: improve Symcon designer controls and KNX temperature selection

This commit is contained in:
jhartworks committed 2026-11-09 15:01:54 +01:00
1 parent 804f2d0494
commit b934f78b9a
24 files changed
+908 -562

No files matched your search

@@ -1,10 +1,10 @@
// The device list of a room: the entities of its area to place, the rows with their pins, and the room's climate sensors.
import { html, nothing, type TemplateResult } from "lit";
import { CLIMATE_CLASSES, entityAreaId, entityKind, entityName, groupByDevice, isPlaceable, isRoomClimateSensor, kindOf, otherAreaEntities, roomClimateSensors, unassignedEntities, type ClimateKey, roomEntities } from "../../../devices.ts";
import { entityAreaId, entityKind, entityName, groupByDevice, isClimateValueSensor, isPlaceable, isRoomClimateSensor, kindOf, otherAreaEntities, roomClimateSensors, unassignedEntities, type ClimateKey, roomEntities } from "../../../devices.ts";
import { iconPath } from "../../../icons.ts";
import { pointInPolygon, type Room } from "../../../model.ts";
import { entityOptions, isNumeric } from "../entities.ts";
import { entityOptions } from "../entities.ts";
import { deviceIcon, entityField, hint } from "../fields.ts";
import type { EditorHost } from "../host.ts";
import { matchesQuery, placedElsewhere, placedInRoom, rankedBy, takeFirst, withToggled } from "../ops/device-list.ts";
@@ -133,7 +133,7 @@ export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: P
};
const field = (key: ClimateKey, label: string) => {
const found = roomClimateSensors(hass, host.floor ?? null, { ...room, climate: null }, key);
const wanted = entityOptions(hass, (id) => isNumeric(id) && hass.states[id]?.attributes.device_class === CLIMATE_CLASSES[key]);
const wanted = entityOptions(hass, (id) => isClimateValueSensor(hass, id, key));
// the room's own sensors first, then the others; device temperatures (a printer, a heat pump) come last
const options = rankedBy(wanted, (id) => (entityAreaId(hass, id) === room.area_id ? 0 : 1) + (isRoomClimateSensor(hass, id) ? 0 : 2));
const picked = [room.climate?.[key] ?? null].flat();
@@ -96,8 +96,8 @@ export function renderEdgeHeights(host: EditorHost, room: Room, actions: EdgeAct
</div>`;
});
};
return html`<div class="nf-edge-box">
<h4>${t("wall_heights")}</h4>
return html`<details class="nf-edge-box">
<summary>${t("wall_heights")}</summary>
${room.points.flatMap((_, edge) => rowsOf(edge))} ${hint(t("room_wall_hint"))}
</div>`;
</details>`;
}
+6 -2
View File
@@ -982,13 +982,17 @@ export const editorStyles = css`
border-radius: 12px;
background: color-mix(in srgb, var(--nf-accent) 6%, transparent);
}
.nf-edge-box h4 {
margin: 0 0 4px;
.nf-edge-box > summary {
cursor: pointer;
color: var(--nf-accent);
font-size: 13px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.nf-edge-box[open] > summary {
margin-bottom: 8px;
}
/* a wall row: name and length, the height, then the buttons (full height, no wall, cut) in one line;
a split point gets a line of its own below */
.nf-edge-height {
+3 -2
View File
@@ -192,8 +192,9 @@ export const tempUnit = (hass: HomeAssistant): "°C" | "°F" => (hass.config?.un
/** A reading in its unit (°F, K, anything else counts as °C) converted to °C. */
export function toCelsius(value: number, unit: unknown): number {
if (unit === "°F") return ((value - 32) * 5) / 9;
if (unit === "K") return value - 273.15;
const normalized = String(unit ?? "").replace(/\s/g, "").toLowerCase();
if (normalized === "°f" || normalized === "℉") return ((value - 32) * 5) / 9;
if (normalized === "k") return value - 273.15;
return value;
}
+18 -1
View File
@@ -2,7 +2,24 @@ import assert from "node:assert/strict";
import { test } from "node:test";
import { entity, floorWith, box, hassOf } from "./fixtures.ts";
import { registerPlugin, resetPlugins } from "../plugins/registry.ts";
import { areaEntities, entityAreaId, entityKind, groupByDevice, isHubDevice, isRelevant, isRoomClimateSensor, otherAreaEntities, powerSensorsOf, primaryEntities, roomClimateSensors, roomClimateValue, unassignedEntities } from "./registry.ts";
import { areaEntities, entityAreaId, entityKind, groupByDevice, isClimateValueSensor, isHubDevice, isRelevant, isRoomClimateSensor, otherAreaEntities, powerSensorsOf, primaryEntities, roomClimateSensors, roomClimateValue, unassignedEntities } from "./registry.ts";
test("a KNX numeric temperature remains selectable and readable even with an inferred actuator domain", () => {
const hass = hassOf([
entity("climate.12345", "heat", { symcon_id: 12345, symcon_variable_type: 2, symcon_numeric_value: 21.75, unit_of_measurement: "°C" }),
entity("sensor.23456", "22.5", { symcon_id: 23456, symcon_variable_type: 2, unit_of_measurement: " °C " }),
entity("sensor.power", "12", { device_class: "power", unit_of_measurement: "W" }),
entity("light.lamp", "on", { unit_of_measurement: "°C" }),
entity("sensor.fahrenheit", "68", { unit_of_measurement: "℉" }),
]);
assert.equal(isClimateValueSensor(hass, "climate.12345", "temperature"), true);
assert.equal(isClimateValueSensor(hass, "sensor.23456", "temperature"), true);
assert.equal(isClimateValueSensor(hass, "sensor.power", "temperature"), false);
assert.equal(isClimateValueSensor(hass, "light.lamp", "temperature"), false);
const room = { ...box("room", 0, 0, 4, 4), climate: { temperature: "climate.12345" } };
assert.equal(roomClimateValue(hass, null, room, "temperature"), 21.75);
assert.equal(roomClimateValue(hass, null, { ...room, climate: { temperature: "sensor.fahrenheit" } }, "temperature"), 20);
});
const lounge = hassOf(
[
+14 -2
View File
@@ -209,6 +209,17 @@ export const primaryEntities = (hass: HomeAssistant, ids: readonly string[]): st
export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity", co2: "carbon_dioxide" } as const;
export type ClimateKey = keyof typeof CLIMATE_CLASSES;
/** Numeric room values, including Symcon readings whose legacy domain was inferred from a parent name. */
export function isClimateValueSensor(hass: HomeAssistant, id: string, key: ClimateKey): boolean {
const a = hass.states[id]?.attributes;
if (!a) return false;
const symconNumber = (a.symcon_variable_type === 1 || a.symcon_variable_type === 2) && typeof a.symcon_id === "number";
if (!symconNumber && !/^(sensor|input_number|number)\./.test(id)) return false;
const unit = String(a.unit_of_measurement ?? "").replace(/\s/g, "").toLowerCase();
if (key === "temperature" && ["°c", "°f", "℃", "℉", "k"].includes(unit)) return true;
return a.device_class === CLIMATE_CLASSES[key];
}
/** A device with one of these domains is not a room sensor: a heat pump, a printer, a TV. */
const APPLIANCE_DOMAINS = new Set(["climate", "water_heater", "switch", "button", "camera", "media_player", "vacuum", "light", "fan", "lawn_mower"]);
/** Words in a name (English and German) that mark a temperature that is not the room's: pipes, printers, chips, outdoors, cold appliances. */
@@ -245,14 +256,15 @@ export function roomClimateSensors(hass: HomeAssistant, floor: Floor | null, roo
const inside = placedSensors.filter((p) => pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id);
const insideElsewhere = new Set(placedSensors.filter((p) => !pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id));
const candidates = new Set([...roomEntities(hass, room).filter((id) => !insideElsewhere.has(id)), ...inside]);
return [...candidates].filter((id) => id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === CLIMATE_CLASSES[key] && isRoomClimateSensor(hass, id));
return [...candidates].filter((id) => id.startsWith("sensor.") && isClimateValueSensor(hass, id, key) && isRoomClimateSensor(hass, id));
}
/** The average of the room's sensors, or null when none reports. Temperatures are always °C, whatever the sensor's unit. */
export function roomClimateValue(hass: HomeAssistant, floor: Floor | null, room: Room, key: ClimateKey): number | null {
const readings = roomClimateSensors(hass, floor, room, key)
.map((id) => {
const reading = Number(hass.states[id]?.state);
const state = hass.states[id];
const reading = Number(state?.attributes.symcon_numeric_value ?? state?.state);
return key === "temperature" ? toCelsius(reading, hass.states[id]?.attributes.unit_of_measurement) : reading;
})
.filter(Number.isFinite);
+8
View File
@@ -23,6 +23,10 @@ const DE = {
needs_restart: "Eine neue Version von NextFloor ({frontend}) ist installiert, aber Home Assistant läuft noch mit {version}. Bitte Home Assistant neu starten – bis dahin kann das Speichern fehlschlagen.",
needs_reload: "Diese Seite zeigt noch NextFloor {frontend}, Home Assistant hat schon {backend}. Bitte die Seite neu laden; in der Companion-App: Einstellungen → Companion-App → Frontend-Cache zurücksetzen.",
reload_page: "Neu laden",
symcon_variables_reload: "Variablen neu laden",
symcon_variables_loading: "Variablen werden geladen …",
symcon_variables_loaded: "Variablen und Objektbaum wurden neu geladen.",
symcon_variables_error: "Variablen konnten nicht neu geladen werden: {error}",
needs_restart_old: "Eine neue Version von NextFloor ist installiert, aber Home Assistant läuft noch mit einer älteren. Bitte Home Assistant neu starten – bis dahin schlägt das Speichern fehl.",
draft_found: "Nicht gespeicherte Änderungen vom {time} gefunden.",
draft_restore: "Übernehmen und speichern",
@@ -2042,6 +2046,10 @@ const EN: Record<Key, string> = {
needs_restart: "A new version of NextFloor ({frontend}) is installed, but Home Assistant still runs {version}. Please restart Home Assistant – until then saving may fail.",
needs_reload: "This page still shows NextFloor {frontend}, Home Assistant already has {backend}. Please reload the page; in the companion app: Settings → Companion app → Reset frontend cache.",
reload_page: "Reload",
symcon_variables_reload: "Reload variables",
symcon_variables_loading: "Loading variables …",
symcon_variables_loaded: "Variables and object tree reloaded.",
symcon_variables_error: "Could not reload variables: {error}",
needs_restart_old: "A new version of NextFloor is installed, but Home Assistant still runs an older one. Please restart Home Assistant – until then saving fails.",
draft_found: "Unsaved changes from {time} found.",
draft_restore: "Restore and save",
+27
View File
@@ -48,6 +48,9 @@ export class NextFloorPanel extends LitElement {
_outside: { state: true },
_timeDrag: { state: true },
_floorUndo: { state: true },
_variablesLoading: { state: true },
_variablesNotice: { state: true },
_variablesError: { state: true },
};
declare hass: HomeAssistant;
@@ -79,6 +82,9 @@ export class NextFloorPanel extends LitElement {
/** After "everything off" on a floor: the calls that bring it back, offered for a few seconds. */
private declare _floorUndo: ServiceCall[] | null;
private floorUndoTimer: ReturnType<typeof setTimeout> | undefined;
private declare _variablesLoading: boolean;
private declare _variablesNotice: string;
private declare _variablesError: boolean;
private readonly data = new BuildingController(this);
private readonly store = new PrefStore(browserStorage());
@@ -101,6 +107,9 @@ export class NextFloorPanel extends LitElement {
this._outside = false;
this._timeDrag = null;
this._floorUndo = null;
this._variablesLoading = false;
this._variablesNotice = "";
this._variablesError = false;
}
/** Shows or hides the time-of-day switch; hiding it goes back to the real sun. */
@@ -345,6 +354,22 @@ export class NextFloorPanel extends LitElement {
</div>`;
}
private async reloadVariables(): Promise<void> {
if (this._variablesLoading || !this.hass.symconRefresh) return;
this._variablesLoading = true;
this._variablesNotice = "";
this._variablesError = false;
try {
await this.hass.symconRefresh();
this._variablesNotice = this.t("symcon_variables_loaded");
} catch (error: unknown) {
this._variablesError = true;
this._variablesNotice = this.t("symcon_variables_error", { error: error instanceof Error ? error.message : String(error) });
} finally {
this._variablesLoading = false;
}
}
private renderHeader(building: Building | null) {
const saveState = this.data.saveState;
const tab = (mode: Mode, label: string, extra = "") =>
@@ -355,6 +380,7 @@ export class NextFloorPanel extends LitElement {
<h1>${NEXTFLOOR_MARK}NextFloor</h1>
${this.isAdmin ? html`<div class="nf-seg" role="tablist">${tab("view", this.t("view"))}${tab("editor", this.t("editor"))}${tab("extensions", `✦ ${this.t("ext_tab")}`, "nf-tab-ext")}</div>` : nothing}
<span class="nf-grow"></span>
${this.isAdmin && this.hass.symconRefresh ? html`<button class="nf-btn nf-reload-variables" ?disabled=${this._variablesLoading} aria-busy=${this._variablesLoading} @click=${() => void this.reloadVariables()}>↻ ${this.t(this._variablesLoading ? "symcon_variables_loading" : "symcon_variables_reload")}</button>` : nothing}
${this._mode === "view" && building?.floors.some((f) => f.rooms.length) ? this.renderViewOptions() : nothing}
${this._mode === "editor" && saveState !== "idle" ? html`<span class="nf-save nf-save-${saveState}">${this.t(saveLabel)}</span>` : nothing}
<span class="nf-version" title=${this.t("version_hint", { backend: this.data.backendVersion ?? "?" })}>v${this.data.frontendVersion}</span>
@@ -365,6 +391,7 @@ export class NextFloorPanel extends LitElement {
private renderNotices() {
const d = this.data;
const notices: TemplateResult[] = [];
if (this._variablesNotice) notices.push(html`<div class="nf-notice ${this._variablesError ? "nf-notice-error" : ""}" role=${this._variablesError ? "alert" : "status"}>${this._variablesNotice}</div>`);
if (d.needsRestart) {
// an old bundle in the browser or the companion app is cured by a reload, not by a restart
notices.push(
+69
View File
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import { test, type TestContext } from "node:test";
import { SymconBridge } from "./symcon-bridge.ts";
function mockWindow(context: TestContext): void {
const previous = Object.getOwnPropertyDescriptor(globalThis, "window");
Object.defineProperty(globalThis, "window", { configurable: true, value: { __NEXTFLOOR_SYMCON__: { endpoint: "/hook/test", token: "fixture" } } });
context.after(() => {
if (previous) Object.defineProperty(globalThis, "window", previous);
else Reflect.deleteProperty(globalThis, "window");
});
}
test("manual reload waits for polling, replaces removed variables and reloads the whole tree", async (context) => {
mockWindow(context);
const variable = (id: number) => ({ entity_id: `sensor.${id}`, name: "KNX Wert", path: "Haus / KNX / Wert", state: "21.75", attributes: { unit_of_measurement: "°C" } });
const actions: string[] = [];
let releasePoll!: () => void;
const pollGate = new Promise<void>((resolve) => { releasePoll = resolve; });
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
const { action } = JSON.parse(String(init.body));
actions.push(action);
if (action === "variables/snapshot") {
await pollGate;
return new Response(JSON.stringify({ state_revision: 1, building_revision: 1 }));
}
const reload = actions.filter((a) => a === "bootstrap").length > 1;
return new Response(JSON.stringify({ state_revision: 1, building_revision: 1, variables: [variable(reload ? 2 : 1)], areas: [], objects: [{ object_id: reload ? 2 : 1 }] }));
});
const bridge = new SymconBridge();
try {
const hass = await bridge.start();
bridge.stop();
let changes = 0;
bridge.onChange(() => { changes++; });
const poll = (bridge as unknown as { refresh(): Promise<void> }).refresh();
const reload = hass.symconRefresh!();
assert.deepEqual(actions, ["bootstrap", "variables/snapshot"], "manual bootstrap must not overlap the running poll");
releasePoll();
await Promise.all([poll, reload]);
assert.deepEqual(actions, ["bootstrap", "variables/snapshot", "bootstrap"]);
assert.deepEqual(Object.keys(bridge.snapshot().states), ["sensor.2"], "even an unchanged revision cannot suppress an explicit reload");
assert.equal(bridge.snapshot().symconObjects?.[0].object_id, 2);
assert.equal(changes, 1);
} finally {
releasePoll();
bridge.stop();
}
});
test("a failed manual reload reports the error and preserves existing values for a retry", async (context) => {
mockWindow(context);
let fail = false;
context.mock.method(globalThis, "fetch", async () => fail ? new Response("offline", { status: 503 })
: new Response(JSON.stringify({ state_revision: 1, building_revision: 1, variables: [{ entity_id: "sensor.1", name: "Temperatur", path: "Haus / Temperatur", state: "21.75", attributes: {} }], objects: [], areas: [] })));
const bridge = new SymconBridge();
try {
const hass = await bridge.start();
bridge.stop();
fail = true;
await assert.rejects(hass.symconRefresh!(), /503/);
assert.equal(bridge.snapshot().states["sensor.1"].state, "21.75");
fail = false;
await hass.symconRefresh!();
assert.equal(bridge.snapshot().states["sensor.1"].state, "21.75");
} finally {
bridge.stop();
}
});
+24 -20
View File
@@ -68,7 +68,7 @@ export class SymconBridge {
private stateRevision = -1;
private buildingRevision = -1;
private objectsSignature = "";
private refreshing = false;
private refreshTask: Promise<void> | undefined;
private states: Record<string, HassEntity> = {};
private entities: Record<string, HassEntityEntry> = {};
private areas: Record<string, HassArea> = {};
@@ -80,6 +80,7 @@ export class SymconBridge {
entities: this.entities,
areas: this.areas,
symconObjects: [],
symconRefresh: () => this.refresh(true),
config: { unit_system: { temperature: "°C" } },
themes: { darkMode: window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? true },
services: {},
@@ -106,7 +107,7 @@ export class SymconBridge {
this.apply(initial);
this.stateRevision = initial.state_revision;
this.buildingRevision = initial.building_revision;
this.timer = setInterval(() => void this.refresh(), 800);
this.timer = setInterval(() => void this.refresh().catch(() => undefined), 800);
return this.snapshot();
}
@@ -125,24 +126,27 @@ export class SymconBridge {
return { ...this.facade, states: { ...this.states }, entities: { ...this.entities }, areas: { ...this.areas } };
}
private async refresh(): Promise<void> {
if (this.refreshing) return;
this.refreshing = true;
try {
const next = await call<VariableSnapshot>(this.settings, "variables/snapshot", { revision: this.stateRevision });
if (next.state_revision !== this.stateRevision && next.variables) {
this.stateRevision = next.state_revision;
this.apply({ variables: next.variables, areas: next.areas, objects: next.objects });
for (const listener of this.changeListeners) listener();
}
if (next.building_revision !== this.buildingRevision) {
this.buildingRevision = next.building_revision;
for (const listener of this.buildingListeners) listener(next.building_revision);
}
} catch {
// A temporary unavailable WebHook must not blank a running visualization. The next poll retries.
} finally {
this.refreshing = false;
private refresh(force = false): Promise<void> {
// A manual reload waits for an in-flight poll, then requests a complete fresh tree.
if (this.refreshTask) return force ? this.refreshTask.catch(() => undefined).then(() => this.refresh(true)) : this.refreshTask;
const task = this.loadSnapshot(force).finally(() => {
if (this.refreshTask === task) this.refreshTask = undefined;
});
this.refreshTask = task;
return task;
}
private async loadSnapshot(force: boolean): Promise<void> {
const next = force ? await call<Bootstrap>(this.settings, "bootstrap")
: await call<VariableSnapshot>(this.settings, "variables/snapshot", { revision: this.stateRevision });
if ((force || next.state_revision !== this.stateRevision) && next.variables) {
this.stateRevision = next.state_revision;
this.apply({ variables: next.variables, areas: next.areas, objects: next.objects });
for (const listener of this.changeListeners) listener();
}
if (next.building_revision !== this.buildingRevision) {
this.buildingRevision = next.building_revision;
for (const listener of this.buildingListeners) listener(next.building_revision);
}
}
+2
View File
@@ -76,6 +76,8 @@ export interface HomeAssistant {
devices?: Record<string, HassDevice>;
/** Present only in the Symcon host. The full native hierarchy, including non-variable nodes. */
symconObjects?: readonly SymconObject[];
/** Reload variables, effective presentations and the native object tree without reloading the plan. */
symconRefresh?: () => Promise<void>;
states: Record<string, HassEntity>;
config?: { unit_system?: { temperature?: string }; latitude?: number; longitude?: number; time_zone?: string };
/** Home Assistant's theme state: `darkMode` is false in a light theme. */
+117
View File
@@ -0,0 +1,117 @@
// Browser regression checks against the built UI, using only the invented preview plan.
// Run from frontend/: node symcon-designer-smoke.mjs
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 types = { ".html": "text/html", ".js": "text/javascript", ".json": "application/json", ".png": "image/png" };
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": types[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
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));
let browser;
try {
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
const page = await browser.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(String(error)));
await page.setViewport({ width: 1440, height: 1000 });
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html`, { waitUntil: "networkidle0" });
await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length);
assert.equal(await page.evaluate(() => !!window.nfPanel.shadowRoot.querySelector(".nf-reload-variables")), false, "HA does not expose a Symcon-only button");
await page.evaluate(async () => {
const p = window.nfPanel;
const states = { ...p.hass.states, "climate.12345": { entity_id: "climate.12345", state: "heat", attributes: { friendly_name: "KNX Istwert", symcon_id: 12345, symcon_variable_type: 2, symcon_numeric_value: 21.75, unit_of_measurement: "°C" } } };
const objects = [
{ object_id: 100, parent_id: 0, name: "Haus", path: "Haus", object_type: 0, hidden: true, position: 0, icon: "" },
{ object_id: 101, parent_id: 100, name: "KNX Heizung", path: "Haus / KNX Heizung", object_type: 1, module_type: 3, hidden: false, position: 0, icon: "" },
{ object_id: 12345, parent_id: 101, name: "KNX Istwert", path: "Haus / KNX Heizung / KNX Istwert", object_type: 2, entity_id: "climate.12345", hidden: false, position: 0, icon: "" },
];
window.reloadCalls = 0;
p.hass = { ...p.hass, states, symconObjects: objects, symconRefresh: async () => {
window.reloadCalls++;
await new Promise((resolve) => { window.finishReload = resolve; });
if (window.failReload) throw new Error("Test: WebHook offline");
p.hass = { ...p.hass, symconObjects: [...p.hass.symconObjects, { object_id: 200, parent_id: 100, name: "Neue Kategorie", path: "Haus / Neue Kategorie", object_type: 0, hidden: false, position: 2, icon: "" }] };
} };
await p.updateComplete;
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((el) => /Editor/.test(el.textContent)).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 = e._doc.floors[0].id;
e.selectItem("room", e._doc.floors[0].rooms[0].id);
await e.updateComplete;
window.ed = e;
window.beforeReload = JSON.stringify(e._doc);
});
const wallState = () => page.evaluate(() => {
const d = window.ed.shadowRoot.querySelector(".nf-edge-box");
return { open: d.open, rowsVisible: [...d.querySelectorAll(".nf-edge-height")].some((r) => r.checkVisibility()) };
});
assert.deepEqual(await wallState(), { open: false, rowsVisible: false });
await page.evaluate(() => window.ed.shadowRoot.querySelector(".nf-edge-box summary").click());
assert.deepEqual(await wallState(), { open: true, rowsVisible: true });
await page.evaluate(() => window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").click());
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").disabled);
await page.evaluate(() => window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").click());
assert.equal(await page.evaluate(() => window.reloadCalls), 1, "busy button prevents duplicate reloads");
await page.evaluate(() => window.finishReload());
await page.waitForFunction(() => !window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").disabled);
assert.equal(await page.evaluate(() => JSON.stringify(window.ed._doc) === window.beforeReload), true, "refresh preserves the active plan");
assert.equal(await page.evaluate(() => window.ed.hass.symconObjects.some((o) => o.name === "Neue Kategorie")), true, "new native nodes propagate to editor pickers");
assert.deepEqual(await wallState(), { open: true, rowsVisible: true }, "hass updates preserve an expanded wall menu");
await page.evaluate(() => window.ed.shadowRoot.querySelector(".nf-edge-box summary").click());
assert.deepEqual(await wallState(), { open: false, rowsVisible: false });
await page.evaluate(async () => {
const e = window.ed;
const climate = [...e.shadowRoot.querySelectorAll("details.nf-points")].find((d) => d.querySelector("summary").textContent.includes("Raumklima"));
climate.open = true;
const picker = climate.querySelector("nf-entity-picker");
if (!picker.options.some((o) => o.id === "climate.12345")) throw new Error("KNX float missing from room temperature options");
window.tempPicker = picker.shadowRoot.querySelector("nf-symcon-object-picker");
window.tempPicker.shadowRoot.querySelector(".trigger").click();
await window.tempPicker.updateComplete;
const input = window.tempPicker.shadowRoot.querySelector(".search");
input.value = "KNX Istwert";
input.dispatchEvent(new Event("input", { bubbles: true }));
await window.tempPicker.updateComplete;
});
assert.equal(await page.evaluate(() => window.tempPicker.shadowRoot.querySelector("#object-12345").classList.contains("selectable")), true, "KNX temperature is enabled in the actual object-tree popup");
await page.evaluate(() => {
window.tempPicker.shadowRoot.querySelector("#object-12345").click();
window.tempPicker.shadowRoot.querySelector(".apply").click();
});
await page.waitForFunction(() => window.ed._doc.floors[0].rooms[0].climate?.temperature === "climate.12345");
await page.evaluate(() => { window.failReload = true; window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").click(); });
await page.waitForFunction(() => window.reloadCalls === 2);
await page.evaluate(() => window.finishReload());
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("[role=alert]")?.textContent.includes("WebHook offline"));
await page.evaluate(() => { window.failReload = false; window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").click(); });
await page.waitForFunction(() => window.reloadCalls === 3);
await page.evaluate(() => window.finishReload());
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("[role=status]")?.textContent.includes("wurden neu geladen"));
await page.evaluate(() => window.ed.shadowRoot.querySelector(".nf-edge-box").scrollIntoView({ block: "center" }));
const out = join(root, "preview/screenshots");
mkdirSync(out, { recursive: true });
await page.screenshot({ path: join(out, "symcon-designer-controls.png") });
await page.setViewport({ width: 390, height: 844 });
await page.evaluate(() => window.ed.shadowRoot.querySelector(".nf-edge-box").scrollIntoView({ block: "center" }));
await page.screenshot({ path: join(out, "symcon-designer-controls-mobile.png") });
assert.equal(await page.evaluate(() => {
const r = window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").getBoundingClientRect();
return r.left >= 0 && r.right <= innerWidth;
}), true, "reload button fits the mobile title bar");
assert.deepEqual(errors, []);
console.log("OK: collapsible walls, reload progress/error/duplicate protection, unchanged plan, updated object pickers, KNX temperature selection and mobile header");
} finally {
await browser?.close();
await new Promise((resolve) => server.close(resolve));
}