Files
NextFloor/frontend/symcon-climate-smoke.mjs
T

357 lines
32 KiB
JavaScript

// Complete climate-card flow against the built UI and an invented Symcon object tree.
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 { build } from "esbuild";
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((done) => server.listen(0, "127.0.0.1", done));
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 = [];
let trendAssetRequests = 0;
page.on("request", (r) => { if (r.url().includes("/nextfloor-trend.js")) trendAssetRequests++; });
page.on("pageerror", (e) => errors.push(String(e)));
await page.evaluateOnNewDocument(() => localStorage.setItem("nextfloor.cards", "0"));
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);
const adapter = await build({ entryPoints: [join(root, "frontend/src/symcon-bridge.ts")], bundle: true, write: false, format: "iife", globalName: "SymconAdapter", logLevel: "silent" });
await page.addScriptTag({ content: adapter.outputFiles[0].text });
await page.evaluate(async () => {
window.humidityValue = 51.6;
window.bootstrapCalls = 0;
window.nativeCalls = [];
window.trendRequests = [];
window.presenceValue = true;
window.rainValue = false;
const raw = (id, name, type, value, unit, domain = "sensor") => ({ entity_id: `${domain}.${id}`, name, path: `Haus / DP KNX / OG Allgemein / Heizen Kühlen / RAT Teeküche / Weiterer Unterordner / Messwerte / ${name}`, state: domain === "cover" ? "open" : String(value), attributes: { symcon_id: id, symcon_variable_type: type, symcon_value: value, symcon_numeric_value: typeof value === "number" ? value : undefined, symcon_formatted: `${String(value).replace(".", ",")}${unit ? ` ${unit}` : ""}`, unit_of_measurement: unit } });
const originalFetch = window.fetch;
window.fetch = async (url, init) => {
if (!String(url).includes("/hook/climate-fixture/")) return originalFetch(url, init);
const request = JSON.parse(init.body);
if (request.action === "archive/trend") {
window.trendRequests.push(request);
if (window.trendReject) return new Response(JSON.stringify({ error: "fixture_archive_unavailable" }), { status: 404 });
const span = request.end - request.start;
const aggregation = request.aggregation === "auto" ? span <= 172800 ? "raw" : "hour" : request.aggregation;
const type = request.entity_id.endsWith("219") ? 3 : request.entity_id.endsWith("213") ? 0 : 2;
const points = window.trendEmpty ? [] : Array.from({ length: 6 }, (_, i) => ({ t: request.start + Math.floor(span * i / 6), d: span / 6, v: type === 3 ? i ? "Raum belegt" : "=1+2" : type === 0 ? i % 2 : 20 + i / 3, min: 19, max: 23 }));
return new Response(JSON.stringify({ entity_id: request.entity_id, start: request.start, end: request.end, aggregation, counter: false, type, truncated: !!window.trendTruncated, points }));
}
if (request.action === "variables/action") { window.nativeCalls.push(request); return new Response("[]"); }
window.bootstrapCalls++;
const variables = [raw(201, "Raumtemperatur", 2, 21.5, "°C"), raw(202, "Messwert Raumfeuchtigkeit", 2, window.humidityValue, "%", "cover"), raw(203, "CO₂", 1, 780, "ppm"), raw(204, "Raumhelligkeit", 2, 320.5, "lx"), raw(205, "Zusatztemperatur", 2, 21.5, "°C")];
const heating = raw(206, "Fußbodenheizung Wert", 1, 35, "%", "sensor");
Object.assign(heating.attributes, { symcon_has_action: true, symcon_min: 0, symcon_max: 100, symcon_step: 1 });
const reheat = raw(211, "Nachheizregister Wert", 0, true, "", "light");
reheat.attributes.symcon_has_action = true;
const status = raw(212, "Raumstatus Alias", 1, 2, "", "climate");
status.attributes.symcon_formatted = "Besprechung";
variables.push(heating, raw(207, "Zuluft Volumenstrom", 2, 120, "m³/h"), raw(208, "Abluft Volumenstrom", 2, 110, "m³/h"), raw(209, "Zuluft Temperatur", 2, 19.6, "°C"), raw(210, "Abluft Temperatur", 2, 22.3, "°C"), reheat, status,
raw(213, "Hannes anwesend", 0, window.presenceValue, "", "light"), raw(214, "Regenkontakt", 0, window.rainValue, "", "cover"), raw(215, "Windmessung", 2, 8, "m/s", "climate"), raw(216, "Wolkenmessung", 1, 65, "%"));
variables.push(raw(219, "Raumtext", 3, "Frei", ""));
for (const v of variables) if ([201, 203, 206, 213, 215, 219].includes(v.attributes.symcon_id)) v.attributes.symcon_archive = { id: 999, counter: false, first: 1, last: 1794384000 };
for (const id of [217, 218]) variables.push({ entity_id: `schedule.${id}`, name: id === 217 ? "Heizzeiten" : "Lüftungszeiten", path: `Haus / Schaltuhren / ${id === 217 ? "Heizzeiten" : "Lüftungszeiten"}`, state: "on", attributes: { symcon_id: id, symcon_schedule: true, next_run: 1794387600, next_action: 2, actions: [{ id: 1, name: "Nacht", color: 255 }, { id: 2, name: "Tag", color: 16711680 }], groups: [{ id: 0, days: 31, points: [{ hour: 6, minute: 30, second: 0, action: 2 }, { hour: 20, minute: 0, second: 0, action: 1 }] }] } });
const objects = [{ object_id: 100, parent_id: 0, name: "Technik", path: "Gebäude / OG / Technik", object_type: 0, position: 0, hidden: true, icon: "" },
...variables.map((v) => ({ object_id: v.attributes.symcon_id, parent_id: 100, entity_id: v.entity_id, name: v.name, path: v.path, object_type: v.attributes.symcon_schedule ? 4 : 2, position: 0, hidden: false, icon: "" }))];
return new Response(JSON.stringify({ state_revision: window.bootstrapCalls, building_revision: 1, variables, objects, areas: [{ area_id: "symcon-category-100", name: "Gebäude / OG / Technik" }] }));
};
window.__NEXTFLOOR_SYMCON__ = { endpoint: "/hook/climate-fixture", token: "fixture-only" };
const bridge = new window.SymconAdapter.SymconBridge();
await bridge.start();
bridge.stop();
const p = window.nfPanel;
const originalCallWS = p.hass.callWS;
const apply = () => {
const h = bridge.snapshot();
p.hass = { ...p.hass, language: "de", states: h.states, entities: h.entities, areas: h.areas, symconObjects: h.symconObjects, symconRefresh: h.symconRefresh, callService: h.callService, callWS: (message) => message.type === "nextfloor/archive/trend" ? h.callWS(message) : originalCallWS(message) };
};
apply();
bridge.onChange(apply);
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.climateEditor = e;
e._floorId = e._doc.floors[0].id;
window.climateRoomId = e._doc.floors[0].rooms[0].id;
window.climateFloorId = e._floorId;
e.selectItem("room", window.climateRoomId);
await e.updateComplete;
const name = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((el) => el.textContent.trim() === e.t("room_name")).querySelector("input");
name.value = "Raum 12"; name.dispatchEvent(new Event("change", { bubbles: true }));
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
const area = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((el) => el.textContent.trim().startsWith(e.t("area"))).querySelector("select");
area.value = "symcon-category-100"; area.dispatchEvent(new Event("change", { bubbles: true }));
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
if (e._doc.floors[0].rooms[0].name !== "Raum 12") throw new Error("Choosing an area must not rename a Symcon room");
e.shadowRoot.querySelector(".nf-take-area-name").click();
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
if (e._doc.floors[0].rooms[0].name !== "Technik") throw new Error("The explicit name button must copy only the native leaf category");
const section = [...e.shadowRoot.querySelectorAll("details.nf-points")].find((d) => d.querySelector("summary").textContent === "Raumklima");
section.open = true;
window.climateSection = section;
window.pickNative = async (scope, label, id, name) => {
const field = [...scope.querySelectorAll("label.nf-field")].find((el) => el.textContent.trim().startsWith(label));
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 = name;
input.dispatchEvent(new Event("input", { bubbles: true }));
await native.updateComplete;
const row = native.shadowRoot.querySelector(`#object-${id}`);
if (!row?.classList.contains("selectable")) throw new Error(`${name} must be selectable despite its inferred domain`);
row.click();
await native.updateComplete;
native.shadowRoot.querySelector(".apply").click();
await e.updateComplete;
await window.nfPanel.updateComplete;
await e.updateComplete;
};
window.pickClimate = (label, id, name) => window.pickNative(window.climateSection, label, id, name);
await window.pickClimate("Temperatur", 201, "Raumtemperatur");
await window.pickClimate("Luftfeuchte", 202, "Messwert Raumfeuchtigkeit");
await window.pickClimate("CO₂", 203, "CO₂");
await window.pickClimate("Helligkeit", 204, "Raumhelligkeit");
for (const [label, id, name] of [["Fußbodenheizung", 206, "Fußbodenheizung Wert"], ["Zuluft-VSR", 207, "Zuluft Volumenstrom"], ["Abluft-VSR", 208, "Abluft Volumenstrom"], ["Zulufttemperatur", 209, "Zuluft Temperatur"], ["Ablufttemperatur", 210, "Abluft Temperatur"], ["NHR", 211, "Nachheizregister Wert"], ["Raumstatus", 212, "Raumstatus Alias"], ["Schaltuhr hinzufügen", 217, "Heizzeiten"], ["Schaltuhr hinzufügen", 218, "Lüftungszeiten"]]) await window.pickClimate(label, id, name);
if (/Durchsagen|Ruhezeit für Durchsagen/.test(e.shadowRoot.textContent)) throw new Error("Announcement fields remain in the Symcon room form");
const panel = document.createElement("nf-room-panel");
Object.assign(panel, { hass: window.nfPanel.hass, building: e._doc, floor: e._doc.floors[0], room: e._doc.floors[0].rooms[0] });
panel.style = "position:fixed;right:0;top:0;width:390px;height:100vh;z-index:2000;background:#202020";
document.body.append(panel); await panel.updateComplete;
if (!panel.shadowRoot.querySelector(".nf-rp-facts").textContent.includes("Besprechung") || panel.shadowRoot.querySelector(".nf-rp-facts").textContent.includes("Komfort")) throw new Error("Native room status did not replace the calculated comfort score");
const hvac = panel.shadowRoot.querySelector("nf-room-hvac"); await hvac.updateComplete;
hvac.shadowRoot.querySelectorAll(".schedule").forEach((d) => d.open = true);
if (hvac.shadowRoot.querySelectorAll(".schedule").length !== 2 || !hvac.shadowRoot.textContent.includes("06:30") || !hvac.shadowRoot.textContent.includes("Zuluft-VSR")) throw new Error("Linked native HVAC values and schedules are missing in the room menu");
const input = hvac.shadowRoot.querySelector('input[type="number"]'); input.value = "25"; input.dispatchEvent(new Event("change", { bubbles: true }));
const clock = hvac.shadowRoot.querySelector('.schedule input[type="checkbox"]'); clock.click();
await hvac.updateComplete;
window.nativeRoomPanel = panel;
await window.pickClimate("… und noch ein Sensor", 205, "Zusatztemperatur");
window.unlinkTemperature = async () => {
const field = [...window.climateSection.querySelectorAll("label.nf-field")].find((el) => el.textContent.trim().startsWith("Temperatur"));
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(".clear").click();
await e.updateComplete;
await window.nfPanel.updateComplete;
await e.updateComplete;
};
await window.unlinkTemperature();
if (e._doc.floors[0].rooms[0].climate.temperature !== "sensor.205") throw new Error("Clearing the first averaged sensor removed its remaining link");
if (e._doc.floors[0].rooms[0].climate.humidity !== "cover.202") throw new Error("Unlinking temperature changed another metric");
await window.unlinkTemperature();
if (e._doc.floors[0].rooms[0].climate.temperature !== "none") throw new Error("The last temperature link must stay explicitly unlinked");
await window.pickClimate("Temperatur", 201, "Raumtemperatur");
const label = [...window.climateSection.querySelectorAll("label.nf-check")].find((el) => el.textContent.includes("schwebende Karte"));
label.querySelector("input").click();
await e.updateComplete;
const second = e._doc.floors[0].rooms[1];
second.climate = { temperature: "sensor.201", humidity: "none", co2: "none", illuminance: "none" };
window.compactRoomId = second.id;
e.selectItem("room", second.id);
await e.updateComplete;
const section2 = [...e.shadowRoot.querySelectorAll("details.nf-points")].find((d) => d.querySelector("summary").textContent === "Raumklima");
section2.open = true;
[...section2.querySelectorAll("label.nf-check")].find((el) => el.textContent.includes("schwebende Karte")).querySelector("input").click();
await e.updateComplete;
e.selectItem("room", null);
await e.updateComplete;
if (/Wetterentität|Bluetooth-Ortung|Durchsagen/.test(e.shadowRoot.textContent)) throw new Error("Home Assistant-only weather, Bluetooth or announcement fields remain in Symcon settings");
const weather = e.shadowRoot.querySelector(".nf-symcon-weather"); weather.open = true;
for (const [label, id, name] of [[e.t("rain_sensor"), 214, "Regenkontakt"], ["Windgeschwindigkeit", 215, "Windmessung"], ["Bewölkung", 216, "Wolkenmessung"]]) await window.pickNative(e.shadowRoot.querySelector(".nf-symcon-weather"), label, id, name);
const presence = e.shadowRoot.querySelector(".nf-symcon-presence"); presence.open = true;
await window.pickNative(presence, "Person hinzufügen", 213, "Hannes anwesend");
const currentPresence = e.shadowRoot.querySelector(".nf-symcon-presence");
const personRow = () => [...e.shadowRoot.querySelectorAll(".nf-symcon-presence .nf-form")].find((row) => row.querySelector("nf-entity-picker")?.value === "light.213");
const ownName = personRow().querySelector('input[type="text"]'); ownName.value = "Hannes"; ownName.dispatchEvent(new Event("change", { bubbles: true }));
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
const roomSelect = personRow().querySelector("select"); roomSelect.value = window.climateRoomId; roomSelect.dispatchEvent(new Event("change", { bubbles: true }));
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
[...window.nfPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "3D").click();
});
await page.waitForFunction(() => window.nativeCalls.length === 2);
assert.deepEqual(await page.evaluate(() => window.nativeCalls.map((r) => [r.domain, r.service, r.data])), [["symcon", "set_value", { entity_id: "sensor.206", value: 25 }], ["schedule", "set_active", { entity_id: "schedule.217", active: false }]]);
const out = join(root, "preview/screenshots");
mkdirSync(out, { recursive: true });
await page.screenshot({ path: join(out, "symcon-native-room-hvac.png") });
await page.evaluate(() => window.nativeRoomPanel.remove());
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-view3d")?.viewer);
await page.evaluate(() => { window.climateView = window.nfPanel.shadowRoot.querySelector("nf-view3d"); });
assert.equal(await page.evaluate(() => window.nfPanel.data.building.presence.some((p) => p.person === "light.213" && p.name === "Hannes")), true, "an arbitrary native Boolean is a person presence source");
assert.match(await page.evaluate(() => [...window.climateView.shadowRoot.querySelectorAll(".nf-presence-state")].find((el) => el.textContent.includes("Hannes")).textContent), /Hannes.*Anwesend/s);
assert.equal(await page.evaluate(() => window.climateView.hass.states["weather.nextfloor_symcon"].attributes.wind_speed), 28.8);
assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelectorAll(".nf-presence-state").length), 1, "only configured native Boolean sources appear in the presence bar");
await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-weather-values").click());
assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-weather-dialog").open), true);
assert.match(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-weather-dialog").textContent), /Windgeschwindigkeit.*8 m\/s/s);
await page.keyboard.press("Escape");
await page.waitForFunction(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle"));
assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").getAttribute("aria-pressed")), "false");
await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").click());
await page.evaluate(async () => {
const p = window.nfPanel;
p.shadowRoot.querySelector("nf-view3d").syncDevices(true);
await window.climateView.updateComplete;
if (window.climateView.shadowRoot.querySelector(".live-card-roomclimate")) throw new Error("All-floors overview must not show room climate cards");
const name = p.data.building.floors.find((f) => f.id === window.climateFloorId).name;
[...p.shadowRoot.querySelectorAll(".nf-nav button")].find((b) => b.textContent.trim() === name).click();
});
await page.waitForFunction(() => window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 2);
const text = () => page.evaluate(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"]`).textContent);
await page.evaluate(() => {
window.assertClimateLayout = () => {
for (const card of window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")) {
const rows = [...card.querySelectorAll(".live-row")], bounds = rows.map((r) => r.getBoundingClientRect());
const values = rows.map((r) => r.querySelector("b").getBoundingClientRect());
if (Math.max(...values.map((r) => r.right)) - Math.min(...values.map((r) => r.right)) > .5) throw new Error("Logged and unlogged values must share the same right edge");
if (Math.max(...bounds.map((r) => r.height)) > 18.5 || Math.max(...bounds.map((r) => r.height)) - Math.min(...bounds.map((r) => r.height)) > .5) throw new Error("A trend icon must not increase a climate row's height");
for (const row of rows) {
const value = row.querySelector("b").getBoundingClientRect(), metric = row.querySelector("span").getBoundingClientRect();
if (metric.right > value.left) throw new Error("The metric symbol must not overlap its value");
const trend = row.querySelector("nf-trend-button");
if (!trend) continue;
const button = trend.shadowRoot.querySelector("button").getBoundingClientRect(), glyph = trend.shadowRoot.querySelector("svg").getBoundingClientRect();
if (button.width > 18.5 || button.height > 18.5 || glyph.width > 12.5 || value.right > button.left) throw new Error("The compact trend symbol must occupy its own column");
}
}
};
});
await page.evaluate(async () => { for (const b of window.climateView.shadowRoot.querySelectorAll("nf-trend-button")) await b.updateComplete; window.assertClimateLayout(); });
assert.match(await text(), /21,5\s*°C/);
assert.match(await text(), /52\s*%/);
assert.match(await text(), /780\s*ppm/);
assert.match(await text(), /321\s*lx/);
assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".live-climate-co2 span").textContent), "☁", "CO2 uses a cloud symbol");
assert.equal(await page.evaluate(() => !!window.climateView.shadowRoot.querySelector(".live-card-house")), false, "climate cards do not require an energy meter");
assert.equal(await page.evaluate(() => window.nfPanel.data.building.floors[0].rooms[0].climate.humidity), "cover.202");
assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.compactRoomId}"]`).querySelectorAll(".live-row").length), 1, "unlinked humidity and CO2 do not get rows");
assert.equal(await page.evaluate(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].some((c) => /Wohnzimmer|Küche|Temperatur|Luftfeuchte/.test(c.textContent))), false, "cards show no repeated room name or metric labels");
await page.evaluate(() => {
const p = window.nfPanel;
[...p.shadowRoot.querySelectorAll(".nf-nav button")].find((b) => b.textContent.trim() === p.t("all_floors")).click();
});
await page.waitForFunction(() => window.climateView.floorId === null && !window.climateView.shadowRoot.querySelector(".live-card-roomclimate"));
await page.evaluate(() => {
const p = window.nfPanel;
const name = p.data.building.floors.find((f) => f.id === window.climateFloorId).name;
[...p.shadowRoot.querySelectorAll(".nf-nav button")].find((b) => b.textContent.trim() === name).click();
});
await page.waitForFunction(() => window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 2);
await page.evaluate(() => { window.humidityValue = 62.4; window.presenceValue = false; window.rainValue = true; window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").click(); });
await page.waitForFunction(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"]`).textContent.includes("62 %"));
assert.match(await page.evaluate(() => [...window.climateView.shadowRoot.querySelectorAll(".nf-presence-state")].find((el) => el.textContent.includes("Hannes")).textContent), /Abwesend/);
assert.equal(await page.evaluate(() => window.climateView.hass.states["weather.nextfloor_symcon"].state), "rainy");
await page.waitForFunction(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].every((c) => c.style.visibility === "visible"));
await page.screenshot({ path: join(out, "symcon-climate-desktop.png") });
assert.equal(trendAssetRequests, 0, "the chart bundle stays lazy until a trend is opened");
assert.equal(await page.evaluate(() => !!window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"] .live-climate-humidity nf-trend-button`)), false, "unlogged values have no trend icon");
await page.evaluate(async () => {
const b = window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"] .live-climate-temperature nf-trend-button`);
await b.updateComplete; b.shadowRoot.querySelector("button").click();
});
await page.waitForFunction(() => document.querySelector("nf-trend-dialog")?.shadowRoot.querySelector(".plot path"));
assert.equal(trendAssetRequests, 1);
await page.evaluate(() => { window.trendDialog = document.querySelector("nf-trend-dialog"); });
assert.equal(await page.evaluate(() => window.trendRequests.at(-1).entity_id), "sensor.201");
await page.evaluate(async () => {
const d = window.trendDialog;
if (!d.shadowRoot.querySelector("dialog").open) throw new Error("Trend must open as a modal");
[...d.shadowRoot.querySelectorAll(".presets button")].find((b) => b.textContent === "7 Tage").click();
});
await page.waitForFunction(() => window.trendDialog.series[0]?.aggregation === "hour");
assert.equal(await page.evaluate(() => { const r = window.trendRequests.at(-1); return r.end - r.start; }), 604800);
await page.evaluate(async () => {
const d = window.trendDialog; d.shadowRoot.querySelector(".settings").open = true;
const inputs = d.shadowRoot.querySelectorAll('input[type="number"]');
for (const [i, value] of [[0, "15"], [1, "30"]]) { inputs[i].value = value; inputs[i].dispatchEvent(new Event("input", { bubbles: true })); }
const selects = d.shadowRoot.querySelectorAll(".settings select"); selects[0].value = "bar"; selects[0].dispatchEvent(new Event("change", { bubbles: true }));
await d.updateComplete;
if (!d.shadowRoot.querySelector(".plot g rect")) throw new Error("Selectable bar chart is missing");
const resolution = d.shadowRoot.querySelector("form select"); resolution.value = "day"; resolution.dispatchEvent(new Event("change", { bubbles: true }));
});
await page.waitForFunction(() => window.trendDialog.series[0]?.aggregation === "day");
await page.evaluate(async () => {
const d = window.trendDialog, min = d.shadowRoot.querySelector('input[type="number"]'); min.value = "40"; min.dispatchEvent(new Event("input", { bubbles: true })); await d.updateComplete;
if (!d.shadowRoot.textContent.includes("kleiner")) throw new Error("Invalid manual value range must be explained");
min.value = "15"; min.dispatchEvent(new Event("input", { bubbles: true })); await d.updateComplete;
const from = d.shadowRoot.querySelectorAll('input[type="datetime-local"]')[0]; from.value = "2099-01-01T00:00"; from.dispatchEvent(new Event("change", { bubbles: true }));
d.shadowRoot.querySelector("form").dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })); await d.updateComplete;
if (!d.shadowRoot.textContent.includes("Ende muss nach")) throw new Error("Invalid time range must be explained");
d.shadowRoot.querySelector(".presets button").click();
});
await page.waitForFunction(() => window.trendDialog.series[0]?.points.length === 6);
await page.evaluate(async () => {
window.trendEmpty = true;
[...window.trendDialog.shadowRoot.querySelectorAll("button")].find((b) => b.textContent === "Aktualisieren").click();
});
await page.waitForFunction(() => window.trendDialog.shadowRoot.textContent.includes("Keine Archivwerte"));
await page.evaluate(() => { window.trendEmpty = false; window.trendReject = true; [...window.trendDialog.shadowRoot.querySelectorAll("button")].find((b) => b.textContent === "Aktualisieren").click(); });
await page.waitForFunction(() => window.trendDialog.shadowRoot.textContent.includes("fixture_archive_unavailable"));
await page.evaluate(() => { window.trendReject = false; window.trendTruncated = true; [...window.trendDialog.shadowRoot.querySelectorAll("button")].find((b) => b.textContent === "Aktualisieren").click(); });
await page.waitForFunction(() => window.trendDialog.shadowRoot.textContent.includes("10.000 Einträge"));
await page.evaluate(async () => {
const original = URL.createObjectURL.bind(URL), click = HTMLAnchorElement.prototype.click;
URL.createObjectURL = (blob) => { window.exportedTrendCsv = blob; return original(blob); };
HTMLAnchorElement.prototype.click = function() { if (this.download !== "Symcon-Trend.csv") return click.call(this); };
[...window.trendDialog.shadowRoot.querySelectorAll("button")].find((b) => b.textContent === "CSV").click();
URL.createObjectURL = original; HTMLAnchorElement.prototype.click = click;
if (!(await window.exportedTrendCsv.text()).includes("Zeit;Wert")) throw new Error("CSV export is missing");
window.trendTruncated = false;
[...window.trendDialog.shadowRoot.querySelectorAll("button")].find((b) => b.textContent === "Aktualisieren").click();
});
await page.waitForFunction(() => window.trendDialog.series[0]?.points.length === 6 && !window.trendDialog.loading);
await page.screenshot({ path: join(out, "symcon-trend-desktop.png") });
await page.setViewport({ width: 390, height: 844 });
await page.waitForFunction(() => window.trendDialog.width < 400);
assert.equal(await page.evaluate(() => { const r = window.trendDialog.shadowRoot.querySelector("dialog").getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth; }), true);
await page.screenshot({ path: join(out, "symcon-trend-mobile.png") });
await page.keyboard.press("Escape");
await page.waitForFunction(() => !document.querySelector("nf-trend-dialog"));
for (const [ids, table] of [[["sensor.219"], true], [["light.213"], false], [["sensor.201", "sensor.203"], false]]) {
await page.evaluate(async (ids) => {
const b = document.createElement("nf-trend-button"); Object.assign(b, { hass: window.nfPanel.hass, ids, label: "Raumwerte" }); document.body.append(b); await b.updateComplete; b.shadowRoot.querySelector("button").click(); window.testTrendButton = b;
}, ids);
await page.waitForFunction(() => document.querySelector("nf-trend-dialog")?.series.length);
assert.equal(await page.evaluate(() => !!document.querySelector("nf-trend-dialog").shadowRoot.querySelector("table")), table);
if (ids.length === 2) assert.equal(await page.evaluate(() => document.querySelector("nf-trend-dialog").shadowRoot.querySelectorAll(".chart-group").length), 2, "different units have separate axes");
await page.keyboard.press("Escape"); await page.waitForFunction(() => !document.querySelector("nf-trend-dialog"));
await page.evaluate(() => window.testTrendButton.remove());
}
await page.setViewport({ width: 390, height: 844 });
await page.evaluate(() => { window.nfPanel.narrow = true; });
await page.waitForFunction(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].every((c) => { const r = c.getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth; }));
await page.evaluate(() => window.assertClimateLayout());
await page.screenshot({ path: join(out, "symcon-climate-mobile.png") });
await page.evaluate(() => { const p = window.nfPanel; p._floorId = window.climateFloorId; p._roomId = window.climateRoomId; });
await page.waitForFunction(() => window.climateView.panelOpen && window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 1);
assert.match(await text(), /62\s*%/);
await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").click());
await page.waitForFunction(() => !window.climateView.shadowRoot.querySelector(".live-card-roomclimate"));
assert.deepEqual(errors, []);
console.log("OK: native climate/HVAC/schedules/weather/presence; explicit area leaf-name adoption; lazy archive trends with time/resolution/Y range, raw/Boolean/string data, CSV, error/empty/limit states, separate units and desktop/mobile dialogs");
} finally {
await browser?.close();
await new Promise((done) => server.close(done));
}