fix: select native variables by datatype and explain rejected links

This commit is contained in:
jhartworks committed 2026-11-12 10:14:19 +01:00
1 parent 4967dd7950
commit 8c6b23bd22
29 files changed
+2031 -1790

No files matched your search

@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { entity, hassOf } from "../../entities/fixtures.ts";
import { entityOptions, isBinary, isNumeric, isPowerSensor, powerSensorOf } from "./entities.ts";
import { entityOptions, isBinary, isNumeric, isPowerSensor, nativeEntityOptions, powerSensorOf } from "./entities.ts";
import { symconControl } from "../../symcon-controls.ts";
test("numbers and switches are told apart by their domain", () => {
for (const id of ["sensor.a", "input_number.b", "number.c"]) assert.equal(isNumeric(id), true, id);
@@ -48,3 +49,15 @@ test("an energy device's own power sensor wins over the found one, and 'none' me
assert.equal(powerSensorOf({ id: "m1" }, found), "sensor.found");
assert.equal(powerSensorOf({ id: "m2" }, found), null);
});
test("native manual choices never depend on a variable's name, path, unit, profile or inferred domain", () => {
const names = ["Garage_EG_Allgemein_Li_Schalten", "Treppenhaus EG schalten", "Rolladen", "Schloss", "Irgendwas"];
const states = names.map((name, n) => entity(`${n % 2 ? "switch" : "cover"}.${100 + n}`, "off", { symcon_id: 100 + n, symcon_variable_type: 0, symcon_value: false, symcon_profile: `~${name}`, friendly_name: name, symcon_path: `Haus / ${name} / Value` }));
const h = hassOf([...states, ...states.map((s) => symconControl(s, "light")!), entity("climate.200", "heat", { symcon_id: 200, symcon_variable_type: 2, unit_of_measurement: "unbekannt" }), entity("sensor.300", "Text", { symcon_id: 300, symcon_variable_type: 3 })], {}, { symconObjects: [] });
assert.deepEqual(nativeEntityOptions(h, { types: [0], role: "light" }, null).map((o) => o.id).sort(), names.map((_, n) => `light.${100 + n}`));
assert.equal(nativeEntityOptions(h, { types: [1, 2] }, null)[0].id, "climate.200");
assert.equal(nativeEntityOptions(h, {}, null).length, 7, "all native datatypes are available for a general value field, without alias duplicates");
assert.deepEqual(nativeEntityOptions(h, { unsupported: "Eine Variable ist kein Kalender." }, null), [], "native variables cannot impersonate an unsupported calendar capability");
assert.equal(nativeEntityOptions(h, { types: [0], role: "light" }, "cover.100").find((o) => o.id === "cover.100")?.sourceEntity, undefined, "saved native references remain stable");
assert.equal(nativeEntityOptions(h, { types: [0], excluded: (id) => id === "cover.100" ? "Bereits verknüpft" : undefined }, null).length, 4);
});
@@ -2,6 +2,8 @@
import { entityName } from "../../devices.ts";
import type { HomeAssistant } from "../../types.ts";
import { isSymconVariable } from "../../entities/symcon-values.ts";
import type { PickerRequirement } from "../picker-rejection.ts";
export interface EntityOption {
id: string;
@@ -52,6 +54,20 @@ export function entityOptions(hass: HomeAssistant | undefined, accept: (id: stri
.sort((a, b) => a.label.localeCompare(b.label));
}
/** Native manual selection depends on the field's datatype, never on a guessed domain/name/profile. */
export function nativeEntityOptions(hass: HomeAssistant, requirement: PickerRequirement, value: string | null): EntityOption[] {
if (requirement.unsupported) return [];
return entityOptions(hass, (id) => isSymconVariable(hass, id, requirement.types) && !requirement.excluded?.(id)).map((option) => {
if (!requirement.role) return option;
const state = hass.states[option.id];
const role = `${requirement.role}.${state.attributes.symcon_id}`;
const current = value ? hass.states[value] : undefined;
// Keep saved native references stable; new choices use the field's explicit control role.
const id = value && (value === option.id || current?.attributes.symcon_source_entity === option.id) ? value : hass.states[role] ? role : option.id;
return id === option.id ? option : { ...option, id, sourceEntity: option.id };
});
}
/** The power sensor of an energy device: set by hand, or the one found on its Home Assistant device. */
export function powerSensorOf(item: { id: string; power?: string | null }, found: Map<string, { power: string | null }>): string | null {
return item.power && item.power !== "none" ? item.power : (found.get(item.id)?.power ?? null);
+6 -3
View File
@@ -6,8 +6,9 @@ import { unsafeHTML } from "lit/directives/unsafe-html.js";
import { entityName } from "../../devices.ts";
import type { I18nKey } from "../../i18n.ts";
import { MARKER_SHOWS, type MarkerShow, type PinOffset } from "../../model.ts";
import type { EntityOption } from "./entities.ts";
import { nativeEntityOptions, type EntityOption } from "./entities.ts";
import type { EditorHost } from "./host.ts";
import type { PickerRequirement } from "../picker-rejection.ts";
import { pluginMdiIcon } from "../../plugins/registry.ts";
import "../entity-picker.ts";
import "../help-popup.ts";
@@ -88,16 +89,18 @@ export function colorField(host: EditorHost, label: string, value: string | null
* A searchable picker for an entity. `auto` is what "automatic" would choose: a name, null for "nothing found", or undefined when
* there is no automatic choice. The stored value is null for automatic, "none" for none, and the entity id otherwise.
*/
export function entityField(host: EditorHost, label: string, value: string | null, auto: string | null | undefined, options: EntityOption[], onChange: (v: string | null) => void): TemplateResult {
export function entityField(host: EditorHost, label: string, value: string | null, auto: string | null | undefined, options: EntityOption[], onChange: (v: string | null) => void, requirement: PickerRequirement = {}): TemplateResult {
const autoText = auto === undefined ? null : auto ? host.t("entity_auto", { name: entityName(host.hass, auto) }) : host.t("entity_auto_none");
// the fixed choices (automatic, none) come first, then the entities filtered as one types
const fixed = [...(autoText !== null ? [{ id: "__auto", label: autoText }] : []), { id: "none", label: host.t("entity_none") }];
const current = value ?? (autoText !== null ? "__auto" : "none");
const choices = host.hass?.symconObjects !== undefined && !requirement.schedule ? nativeEntityOptions(host.hass, requirement, value) : options;
return html`<label class="nf-field nf-wide"
>${label}
<nf-entity-picker
.options=${options}
.options=${choices}
.objectTree=${host.hass?.symconObjects}
.context=${{ ...requirement, label, states: host.hass?.states }}
.fixed=${fixed}
.value=${current}
.placeholder=${host.t("entity_search")}
@@ -146,7 +146,7 @@ export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: P
};
const real = picked[0] && picked[0] !== "none";
const slots = real ? [...picked, null] : picked;
return slots.map((id, i) => entityField(host, i ? host.t("climate_more") : label, id, i ? undefined : (found[0] ?? null), options, (v) => save(slots.map((x, j) => (j === i ? v : x)))));
return slots.map((id, i) => entityField(host, i ? host.t("climate_more") : label, id, i ? undefined : (found[0] ?? null), options, (v) => save(slots.map((x, j) => (j === i ? v : x))), { types: [1, 2] }));
};
return html`<details class="nf-points" ?open=${chosen || !!room.climate_card}>
<summary>${host.t("climate")}</summary>
@@ -99,11 +99,11 @@ export function renderDeviceForm(host: EditorHost, placed: Placement, actions: D
${entityName(host.hass, placed.entity_id)}
</p>
<div class="nf-form">
${kind === "cover" ? entityField(host, t("cover_tilt_entity"), placed.cover_tilt ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => set({ cover_tilt: v && v !== "none" ? v : null })) : nothing}
${kind === "cover" ? entityField(host, t("cover_tilt_entity"), placed.cover_tilt ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => set({ cover_tilt: v && v !== "none" ? v : null }), { types: [1, 2], role: "cover" }) : nothing}
${kind === "cover" ? html`
${checkField(host, t("cover_direction_invert"), !!placed.cover_inverted, (on) => set({ cover_inverted: on || undefined }))}
${checkField(host, t("cover_tilt_direction_invert"), !!placed.cover_tilt_inverted, (on) => set({ cover_tilt_inverted: on || undefined }))}
${entityField(host, t("cover_position_entity"), placed.position ?? null, undefined, entityOptions(host.hass, (id) => isPositionVariable(host.hass, id)), (v) => set({ position: v && v !== "none" ? v : null }))}
${entityField(host, t("cover_position_entity"), placed.position ?? null, undefined, entityOptions(host.hass, (id) => isPositionVariable(host.hass, id)), (v) => set({ position: v && v !== "none" ? v : null }), { types: [1, 2] })}
${placed.position ? checkField(host, t("cover_position_invert"), !!placed.position_inverted, (on) => set({ position_inverted: on || undefined })) : nothing}
${hint(t("cover_direction_hint"), "nf-wide")}` : nothing}
${light ? html`${selectField(host, t("lamp_mount"), mount, lampMounts, mountChange, { wide: true })}${glowField(host, placed.glow_scale, (v) => set({ glow_scale: v }))}` : nothing}
@@ -102,6 +102,7 @@ function utilityMeters(host: EditorHost, floor: Floor): TemplateResult {
${hint("Ohne eigenen Stockwerkszähler werden die Bereichszähler der Räume summiert. In der verknüpften Bereichskategorie werden Kategorien oder Dummy-Module namens Elektro/Strom, Wasser, Gas, Heizen und Kühlen durchsucht. Darin werden Leistung bzw. Durchfluss und Verbrauch bzw. Energie erkannt. Ein eigener Stockwerkszähler ersetzt nur die zugehörige Raumsumme. × stellt die automatische Raumsumme wieder her. Einheiten und Verbrauchszeiträume werden getrennt ausgewertet.", "nf-wide")}
${UTILITY_KINDS.map((kind) => html`<b class="nf-wide">${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</b>${(["power", "energy"] as const).map((metric) => html`<label class="nf-field nf-wide">${metric === "power" ? "Leistung / Durchfluss" : "Energie / Verbrauch"}
<nf-entity-picker .options=${options} .objectTree=${host.hass?.symconObjects} .fixed=${[{ id: "__auto", label: "Raumsumme (automatisch)" }]} .value=${floorMeter(host.hass!, floor, kind, metric) ?? "__auto"} ?disabled=${!host.admin}
.context=${{ label: `${UTILITY_LABELS[kind]}: ${metric === "power" ? "Leistung / Durchfluss" : "Energie / Verbrauch"}`, types: [1, 2], states: host.hass?.states }}
@change=${(e: CustomEvent<{ value: string | null }>) => {
e.stopPropagation();
const value = e.detail.value;
@@ -195,7 +195,7 @@ export function careLink(host: EditorHost, item: Furniture, kind: "bin" | "mail"
export function coverLink(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult {
const t = host.t;
return html`<div class="nf-form nf-links">
${entityField(host, t("furn_cover_entity"), item.cover_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => actions.update({ cover_entity: noneAsNull(v) }))}
${entityField(host, t("furn_cover_entity"), item.cover_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => actions.update({ cover_entity: noneAsNull(v) }), { types: [1, 2], role: "cover" })}
${checkField(host, t("furn_cover_inverted"), !!item.cover_inverted, (on) => actions.update({ cover_inverted: on || undefined }), { title: t("furn_cover_inverted_hint") })}
${hint(t("furn_cover_hint"), "nf-wide")}
</div>`;
@@ -213,7 +213,7 @@ export function gangLinks(host: EditorHost, item: Furniture, gangs: number, acti
actions.update({ gang_entities: next });
};
return html`<div class="nf-form nf-links">
${Array.from({ length: gangs }, (_, i) => entityField(host, gangs === 1 ? t(socket ? "gang_socket_one" : "gang_switch_one") : t(socket ? "gang_socket" : "gang_switch", { n: i + 1 }), current[i] ?? null, undefined, options, set(i)))}
${Array.from({ length: gangs }, (_, i) => entityField(host, gangs === 1 ? t(socket ? "gang_socket_one" : "gang_switch_one") : t(socket ? "gang_socket" : "gang_switch", { n: i + 1 }), current[i] ?? null, undefined, options, set(i), { types: [0, 1, 2], role: "light" }))}
${hint(t(socket ? "gang_socket_hint" : "gang_switch_hint"), "nf-wide")}
</div>`;
}
@@ -227,8 +227,8 @@ function coolingLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkA
return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F");
});
return linkBlock(
entityField(host, t("fridge_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) })),
entityField(host, t("freezer_temp"), item.temp_entity2 ?? null, undefined, temps, (v) => actions.update({ temp_entity2: noneAsNull(v) })),
entityField(host, t("fridge_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) }), { types: [1, 2] }),
entityField(host, t("freezer_temp"), item.temp_entity2 ?? null, undefined, temps, (v) => actions.update({ temp_entity2: noneAsNull(v) }), { types: [1, 2] }),
hint(t("fridge_temp_hint"), "nf-wide"),
);
}
@@ -241,7 +241,7 @@ function deviceTempLink(host: EditorHost, item: Furniture, actions: FurnitureLin
return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F");
});
return linkBlock(
entityField(host, t("device_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) })),
entityField(host, t("device_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) }), { types: [1, 2] }),
hint(t("device_temp_hint"), "nf-wide"),
);
}
@@ -258,7 +258,7 @@ function extraLightFields(host: EditorHost, item: Furniture, actions: FurnitureL
actions.update({ extra_lights: next.filter(Boolean).length ? next.filter(Boolean) : undefined });
};
const rows = Math.min(4, current.length + 1);
return html`${Array.from({ length: rows }, (_, i) => entityField(host, t("lamp_extra_light", { n: i + 2 }), current[i] ?? null, undefined, options, set(i)))}${hint(t("lamp_extra_hint"), "nf-wide")}`;
return html`${Array.from({ length: rows }, (_, i) => entityField(host, t("lamp_extra_light", { n: i + 2 }), current[i] ?? null, undefined, options, set(i), { types: [0, 1, 2], role: "light" }))}${hint(t("lamp_extra_hint"), "nf-wide")}`;
}
export function furnitureLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult | typeof nothing {
@@ -277,31 +277,31 @@ export function furnitureLinks(host: EditorHost, item: Furniture, actions: Furni
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(
item.type === "grid_point" ? hint(t("grid_point_hint"), "nf-wide") : entityField(host, t(main.label), item.entity ?? null, automaticLink(host, item, "entity"), kindOptions(main.accept), (v) => actions.update({ entity: v })),
item.type === "grid_point" ? hint(t("grid_point_hint"), "nf-wide") : entityField(host, t(main.label), item.entity ?? null, automaticLink(host, item, "entity"), kindOptions(main.accept), (v) => actions.update({ entity: v }), lamp ? { types: [0, 1, 2], role: "light" } : {}),
item.type === "ceiling_fan"
? entityField(host, t("furn_fan_entity"), item.fan_entity ?? null, automaticLink(host, item, "fan"), kindOptions((id) => id.startsWith("fan.")), (v) => actions.update({ fan_entity: v }))
? entityField(host, t("furn_fan_entity"), item.fan_entity ?? null, automaticLink(host, item, "fan"), kindOptions((id) => id.startsWith("fan.")), (v) => actions.update({ fan_entity: v }), { types: [0, 1, 2] })
: nothing,
!lamp && !(ENERGY_DEVICES as readonly string[]).includes(item.type) && !hasScreen(item.type) ? stateLinks(host, item, actions) : nothing,
lamp && hasLink
? html`${entityField(host, t("furn_color_entity"), item.color_entity ?? null, undefined, kindOptions((id) => id.startsWith("light.") && id !== item.entity), set("color_entity"))}${hint(t("furn_color_entity_hint"), "nf-wide")}`
? html`${entityField(host, t("furn_color_entity"), item.color_entity ?? null, undefined, kindOptions((id) => id.startsWith("light.") && id !== item.entity), set("color_entity"), { types: [0, 1, 2], role: "light" })}${hint(t("furn_color_entity_hint"), "nf-wide")}`
: nothing,
lamp && hasLink ? extraLightFields(host, item, actions) : nothing,
lamp ? glowField(host, item.glow_scale, (v) => actions.update({ glow_scale: v })) : nothing,
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 : html`${entityField(host, t(meterParent(host.doc, item) ? "meter_sub_power" : powerLabel(item.type)), item.power ?? null, autoPower, 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 }), { types: [1, 2] })}
${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}
${item.type === "inverter" || item.type === "home_battery" ? deviceMeterLink(host, item, actions) : nothing}
${item.type === "meter" && !meterParent(host.doc, item) ? linkBlock(entityField(host, t("furn_export"), item.export ?? null, undefined, power, set("export")), hint(t("furn_export_hint"), "nf-wide")) : nothing}
${item.type === "meter" && !meterParent(host.doc, item) ? linkBlock(entityField(host, t("furn_export"), item.export ?? null, undefined, power, set("export"), { types: [1, 2] }), hint(t("furn_export_hint"), "nf-wide")) : nothing}
${item.type === "inverter" && (host.doc.settings.roof.solar ?? []).length > 0 ? hint(strings.length > 0 ? t("inverter_strings", { names: strings.join(", ") }) : t("inverter_strings_none"), "nf-wide") : nothing}
${item.type === "home_battery"
? linkBlock(
entityField(host, t("furn_soc"), item.soc ?? null, undefined, kindOptions((id) => isNumeric(id) && (hass.states[id]?.attributes.device_class === "battery" || hass.states[id]?.attributes.unit_of_measurement === "%")), set("soc")),
entityField(host, t("furn_charge"), item.charge ?? null, undefined, power, set("charge")),
entityField(host, t("furn_soc"), item.soc ?? null, undefined, kindOptions((id) => isNumeric(id) && (hass.states[id]?.attributes.device_class === "battery" || hass.states[id]?.attributes.unit_of_measurement === "%")), set("soc"), { types: [1, 2] }),
entityField(host, t("furn_charge"), item.charge ?? null, undefined, power, set("charge"), { types: [1, 2] }),
hint(t("furn_charge_hint"), "nf-wide"),
)
: nothing}
@@ -311,11 +311,11 @@ export function furnitureLinks(host: EditorHost, item: Furniture, actions: Furni
<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}
${item.type === "robot_vacuum"
? linkBlock(entityField(host, t("furn_robot_room"), item.room_sensor ?? null, robotRoomSensor(hass, furnitureEntities(hass, host.doc.floors).get(item.id)?.entity ?? null, null), kindOptions(isNumeric), (v) => actions.update({ room_sensor: v })))
? linkBlock(entityField(host, t("furn_robot_room"), item.room_sensor ?? null, robotRoomSensor(hass, furnitureEntities(hass, host.doc.floors).get(item.id)?.entity ?? null, null), kindOptions(isNumeric), (v) => actions.update({ room_sensor: v }), { types: [1, 2] }))
: nothing}
${item.type === "robot_vacuum" && hasLink ? robotMapBlock(host, item) : nothing}
${item.type === "fridge_smart"
? html`${linkBlock(entityField(host, t("furn_door_left"), item.door_left ?? null, undefined, doors, (v) => actions.update({ door_left: v })), entityField(host, t("furn_door_right"), item.door_right ?? null, undefined, doors, (v) => actions.update({ door_right: v })))}
? html`${linkBlock(entityField(host, t("furn_door_left"), item.door_left ?? null, undefined, doors, (v) => actions.update({ door_left: v }), { types: [0] }), entityField(host, t("furn_door_right"), item.door_right ?? null, undefined, doors, (v) => actions.update({ door_right: v }), { types: [0] }))}
${hint(t("fridge_hint"))}`
: nothing}
${renderDeviceValues(host, item.values, (values) => actions.update({ values }))}
@@ -51,7 +51,7 @@ function favorites(host: EditorHost): TemplateResult {
return html`<summary>${host.t("favorites")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</summary>
${hint(host.t("favorites_hint"))} ${list.map(row)}
${list.length < MAX_FAVORITES
? html`<div class="nf-form">${entityField(host, host.t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>`
? html`<div class="nf-form">${entityField(host, host.t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]), { excluded: (id) => list.includes(id) ? "Diese Variable ist bereits als Favorit verknüpft." : undefined })}</div>`
: nothing}`;
}
@@ -66,7 +66,7 @@ function outsideHidden(host: EditorHost, paneView?: () => StartView | null): Tem
<h4>${host.t("outside_hidden")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</h4>
${hint(host.t("outside_hidden_hint"))}
${list.map((id, i) => html`<div class="nf-row nf-dev-row"><span class="nf-dev-name"><span>${entityName(host.hass, id)}</span></span>${iconButton(host.t("delete"), "✕", () => store(removeAt(list, i)))}</div>`)}
<div class="nf-form">${entityField(host, host.t("outside_hidden_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>`;
<div class="nf-form">${entityField(host, host.t("outside_hidden_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]), { excluded: (id) => list.includes(id) ? "Diese Variable ist hier bereits eingetragen." : undefined })}</div>`;
}
/** The camera Outside opens with: the editor's 3D pane as it stands now (#83). */
@@ -134,7 +134,7 @@ function calendars(host: EditorHost): TemplateResult {
const days = host.doc.settings.today_days ?? 1;
return html`<h4>📅 ${t("today_calendars")}</h4>
${hint(t("today_calendars_hint"))} ${list.map(row)}
${list.length < 12 ? html`<div class="nf-form">${entityField(host, t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>` : nothing}
${list.length < 12 ? html`<div class="nf-form">${entityField(host, t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]), { unsupported: "Dieses Feld benötigt eine Kalenderquelle mit Terminen. Eine Symcon-Variable ist kein Kalender; Kalenderquellen werden vom Symcon-Modul derzeit nicht bereitgestellt." })}</div>` : nothing}
${list.length
? html`<div class="nf-form">
${selectField(host, t("today_days"), String(days), [1, 2, 3, 5, 7].map((n): [string, string] => [String(n), t(n === 1 ? "today_days_one" : "today_days_n", { n })]), (v) => host.change((d) => (d.settings.today_days = Number(v) > 1 ? Number(v) : undefined)))}
@@ -169,12 +169,12 @@ function blindFields(host: EditorHost, o: Opening, actions: OpeningActions, list
const automatic = automaticLink(host, o, "cover");
const hasBlind = o.cover !== "none" && (o.cover || automatic);
const symcon = host.hass?.symconObjects !== undefined;
return html`${entityField(host, t(symcon ? "symcon_cover_position" : window ? "cover_entity" : "door_cover"), o.cover, automatic, lists.covers, (v) => actions.update({ cover: v }))}
${symcon || (hasBlind && o.blind === "venetian") ? entityField(host, t("cover_tilt_entity"), o.cover_tilt ?? null, undefined, lists.covers, (v) => actions.update({ cover_tilt: noneAsNull(v) })) : nothing}
return html`${entityField(host, t(symcon ? "symcon_cover_position" : window ? "cover_entity" : "door_cover"), o.cover, automatic, lists.covers, (v) => actions.update({ cover: v }), { types: [1, 2], role: "cover" })}
${symcon || (hasBlind && o.blind === "venetian") ? entityField(host, t("cover_tilt_entity"), o.cover_tilt ?? null, undefined, lists.covers, (v) => actions.update({ cover_tilt: noneAsNull(v) }), { types: [1, 2], role: "cover" }) : nothing}
${hasBlind
? html`${checkField(host, t("cover_direction_invert"), !!o.cover_inverted, (on) => actions.update({ cover_inverted: on || undefined }))}
${o.cover_tilt || o.blind === "venetian" ? checkField(host, t("cover_tilt_direction_invert"), !!o.cover_tilt_inverted, (on) => actions.update({ cover_tilt_inverted: on || undefined })) : nothing}
${entityField(host, t("cover_position_entity"), o.position ?? null, undefined, lists.positions, (v) => actions.update({ position: noneAsNull(v) }))}
${entityField(host, t("cover_position_entity"), o.position ?? null, undefined, lists.positions, (v) => actions.update({ position: noneAsNull(v) }), { types: [1, 2] })}
${o.position ? checkField(host, t("cover_position_invert"), !!o.position_inverted, (on) => actions.update({ position_inverted: on })) : nothing}
${checkField(host, t("device_confirm"), !!o.confirm, (on) => actions.update({ confirm: on }), { title: t("cover_confirm_hint") })}
${window
+1 -1
View File
@@ -106,7 +106,7 @@ function windowForm(deps: RoofPanelDeps, win: RoofWindow): TemplateResult {
const covers = entityOptions(host.hass, (id) => id.startsWith("cover."));
const contacts = entityOptions(host.hass, (id) => isBinary(id) || isNumeric(id));
const link = (label: I18nKey, value: string | null | undefined, options: typeof covers, key: "cover" | "contact" | "tilt" | "window") =>
entityField(host, t(label), value ?? null, undefined, options, (v) => set({ [key]: v === "none" ? null : v }));
entityField(host, t(label), value ?? null, undefined, options, (v) => set({ [key]: v === "none" ? null : v }), key === "cover" || key === "window" ? { types: [1, 2], role: "cover" } : { types: [0, 1, 2] });
const moveToFace = (key: string) => {
const next = faces.find((f) => f.key === key);
if (next) set({ ...proposeWindow(next, win.id), w: win.w, h: win.h, cover: win.cover, contact: win.contact, tilt: win.tilt, window: win.window, name: win.name });
+1 -1
View File
@@ -65,7 +65,7 @@ function spotForm(host: EditorHost, state: SideState, room: Room, actions: RoomA
${selectField(host, host.t("spots_type"), draft.type, types, (type) => change({ type }), { wide: true })}
${numberField(host, host.t("spots_cols"), draft.cols, (v) => change({ cols: spotCount(v) }), 1, 1)}
${numberField(host, host.t("spots_rows"), draft.rows, (v) => change({ rows: spotCount(v) }), 1, 1)}
${entityField(host, host.t("furn_entity_light"), draft.entity, undefined, lights, (v) => change({ entity: v === "none" ? null : v }))}
${entityField(host, host.t("furn_entity_light"), draft.entity, undefined, lights, (v) => change({ entity: v === "none" ? null : v }), { types: [0, 1, 2], role: "light" })}
<div class="nf-actions nf-wide">
<button class="nf-btn nf-primary" ?disabled=${count === 0} @click=${() => actions.placeSpots()}>${host.t("spots_add", { n: count })}</button>
<button class="nf-btn" @click=${() => (state.spots = null)}>${host.t("cancel")}</button>
@@ -55,7 +55,7 @@ function statusFields(host: EditorHost, ids: string[], set: (ids: string[]) => v
)}
</div>`
: nothing}
${ids.length < 12 ? entityField(host, t("status_add"), null, undefined, options, (v) => v && v !== "none" && set([...ids, v])) : nothing}
${ids.length < 12 ? entityField(host, t("status_add"), null, undefined, options, (v) => v && v !== "none" && set([...ids, v]), { excluded: (id) => ids.includes(id) ? "Diese Variable ist in der Statusanzeige bereits verknüpft." : undefined }) : nothing}
${hint(t("status_entities_hint"), "nf-wide")}`;
}
@@ -13,19 +13,20 @@ export function renderSymconRoomHvac(host: EditorHost, room: Room, patch: (chang
const schedules = room.hvac?.schedules ?? [];
const plans = entityOptions(host.hass, (id) => !!host.hass?.states[id]?.attributes.symcon_schedule);
return html`
${entityField(host, host.t("floor_heating"), room.floor_heating ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [0, 1, 2])), (v) => patch({ floor_heating: v === "none" ? null : v }))}
${ROOM_HVAC_FIELDS.map((field) => entityField(host, field.label, room.hvac?.[field.key] ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, field.types)), (v) => set({ [field.key]: v === "none" ? null : v })))}
${entityField(host, host.t("floor_heating"), room.floor_heating ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [0, 1, 2])), (v) => patch({ floor_heating: v === "none" ? null : v }), { types: [0, 1, 2] })}
${ROOM_HVAC_FIELDS.map((field) => entityField(host, field.label, room.hvac?.[field.key] ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, field.types)), (v) => set({ [field.key]: v === "none" ? null : v }), { types: field.types }))}
${hint("Raumstatus zeigt den in Symcon hinterlegten Alias der Integer-Variable. Beschreibbare Heizungs- und Lüftungswerte können im Raummenü bedient werden.", "nf-wide")}
${schedules.map((id, i) => entityField(host, `Schaltuhr ${i + 1}`, id, undefined, plans.filter((p) => p.id === id || !schedules.includes(p.id)), (v) => set({ schedules: v && v !== "none" ? schedules.map((old, j) => i === j ? v : old) : schedules.filter((_, j) => i !== j) })))}
${entityField(host, "Schaltuhr hinzufügen", null, undefined, plans.filter((p) => !schedules.includes(p.id)), (v) => v && v !== "none" && set({ schedules: [...schedules, v] }))}`;
${schedules.map((id, i) => entityField(host, `Schaltuhr ${i + 1}`, id, undefined, plans.filter((p) => p.id === id || !schedules.includes(p.id)), (v) => set({ schedules: v && v !== "none" ? schedules.map((old, j) => i === j ? v : old) : schedules.filter((_, j) => i !== j) }), { schedule: true, excluded: (entity) => schedules.includes(entity) ? "Diese Schaltuhr ist in diesem Raum bereits verknüpft." : undefined }))}
${entityField(host, "Schaltuhr hinzufügen", null, undefined, plans.filter((p) => !schedules.includes(p.id)), (v) => v && v !== "none" && set({ schedules: [...schedules, v] }), { schedule: true, excluded: (entity) => schedules.includes(entity) ? "Diese Schaltuhr ist in diesem Raum bereits verknüpft." : undefined })}`;
}
export function renderSymconWeather(host: EditorHost, settings: BuildingSettings, set: (change: Partial<BuildingSettings>) => void) {
const types = (key: string) => key === "condition" ? [0, 1, 2, 3] : key === "wind_bearing" ? [1, 2, 3] : ["snow", "fog", "lightning"].includes(key) ? [0, 1, 2] : [1, 2];
return html`<details class="nf-wide nf-symcon-weather"><summary>Wettervariablen</summary><div class="nf-form">
${WEATHER_VARIABLE_KEYS.map((key) => entityField(host, WEATHER_VARIABLE_LABELS[key], settings.weather_variables?.[key] ?? null, undefined,
entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, key === "condition" ? [0, 1, 2, 3] : key === "wind_bearing" ? [1, 2, 3] : ["snow", "fog", "lightning"].includes(key) ? [0, 1, 2] : [1, 2])),
(v) => set({ weather_variables: { ...settings.weather_variables, [key]: v === "none" ? null : v } })))}
${entityField(host, host.t("rain_sensor"), settings.rain_sensor ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [0, 1, 2])), (v) => set({ rain_sensor: v === "none" ? null : v }))}
entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, types(key))),
(v) => set({ weather_variables: { ...settings.weather_variables, [key]: v === "none" ? null : v } }), { types: types(key) }))}
${entityField(host, host.t("rain_sensor"), settings.rain_sensor ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [0, 1, 2])), (v) => set({ rain_sensor: v === "none" ? null : v }), { types: [0, 1, 2] })}
${settings.rain_sensor ? checkField(host, host.t("rain_sensor_inverted"), !!settings.rain_sensor_inverted, (on) => set({ rain_sensor_inverted: on || undefined })) : nothing}
${hint("Wähle die Wetterwerte einzeln aus dem Symcon-Objektbaum. Einheiten werden aus den Variablen übernommen. Der Regensensor kann Boolean oder eine numerische Regenrate sein.", "nf-wide")}
</div></details>`;
@@ -40,11 +41,11 @@ export function renderSymconPresence(host: EditorHost) {
return html`<details class="nf-section nf-symcon-presence"><summary>${host.t("presence")}</summary>
${links.map((link, i) => html`<div class="nf-form">
${textField(host, "Person", link.name ?? entityName(host.hass, link.person), (name) => patch(i, { name }), { wide: true, maxlength: 100 })}
${entityField(host, "Anwesenheit (Boolean)", link.person, undefined, options.filter((o) => o.id === link.person || !links.some((l) => l.person === o.id)), (v) => v && v !== "none" ? patch(i, { person: v }) : replace(links.filter((_, j) => j !== i)))}
${entityField(host, "Anwesenheit (Boolean)", link.person, undefined, options.filter((o) => o.id === link.person || !links.some((l) => l.person === o.id)), (v) => v && v !== "none" ? patch(i, { person: v }) : replace(links.filter((_, j) => j !== i)), { types: [0], excluded: (entity) => links.some((l) => l.person === entity) ? "Diese Anwesenheitsvariable ist bereits mit einer Person verknüpft." : undefined })}
<label class="nf-field nf-wide">Raum für die 3D-Anzeige<select ?disabled=${!host.admin} .value=${link.room ?? ""} @change=${(e: Event) => patch(i, { room: (e.target as HTMLSelectElement).value || null })}><option value="">Kein Raum</option>${rooms.map((r) => html`<option value=${r.id}>${r.name}</option>`)}</select></label>
<button class="nf-link nf-wide" ?disabled=${!host.admin} @click=${() => replace(links.filter((_, j) => j !== i))}>× Person entfernen</button>
</div>`)}
<div class="nf-form">${entityField(host, "Person hinzufügen (Boolean)", null, undefined, options.filter((o) => !links.some((l) => l.person === o.id)), (v) => v && v !== "none" && replace([...links, { person: v, sensor: null }]))}</div>
<div class="nf-form">${entityField(host, "Person hinzufügen (Boolean)", null, undefined, options.filter((o) => !links.some((l) => l.person === o.id)), (v) => v && v !== "none" && replace([...links, { person: v, sensor: null }]), { types: [0], excluded: (entity) => links.some((l) => l.person === entity) ? "Diese Anwesenheitsvariable ist bereits mit einer Person verknüpft." : undefined })}</div>
${hint("Jede Person wird mit einer beliebigen Boolean-Variable verknüpft: true bedeutet anwesend, false abwesend. Ein Raum ist optional und bestimmt die Position der Person in 3D.")}
</details>`;
}
+4
View File
@@ -5,6 +5,7 @@
import { css, html, LitElement, nothing } from "lit";
import { tokens } from "../styles.ts";
import type { SymconObject } from "../types.ts";
import type { PickerContext } from "./picker-rejection.ts";
import "./symcon-object-picker.ts";
export interface PickerOption {
@@ -22,6 +23,7 @@ export class EntityPicker extends LitElement {
static properties = {
options: { attribute: false },
objectTree: { attribute: false },
context: { attribute: false },
fixed: { attribute: false },
value: { attribute: false },
disabled: { type: Boolean },
@@ -34,6 +36,7 @@ export class EntityPicker extends LitElement {
/** Entities to choose from. */
declare options: PickerOption[];
declare objectTree: readonly SymconObject[] | undefined;
declare context: PickerContext | undefined;
/** Choices shown before the entities (e.g. automatic, none); ids must not look like entity ids. */
declare fixed: PickerOption[];
/** The chosen id (an option's or a fixed choice's). */
@@ -114,6 +117,7 @@ export class EntityPicker extends LitElement {
protected render() {
if (this.objectTree !== undefined) return html`<nf-symcon-object-picker
.objects=${this.objectTree} .options=${this.options} .fixed=${this.fixed} .value=${this.value}
.context=${this.context}
.disabled=${this.disabled} .placeholder=${this.placeholder}
@change=${(event: CustomEvent<{ value: string | null }>) => { this.value = event.detail.value; }}
></nf-symcon-object-picker>`;
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { entity } from "../entities/fixtures.ts";
import type { SymconObject } from "../types.ts";
import { pickerRejection } from "./picker-rejection.ts";
const node = (object_type: number, entity_id?: string): SymconObject => ({ object_id: 123, parent_id: 0, name: "Value", path: "Haus / Garage / Value", object_type, entity_id, hidden: false, position: 0, icon: "" });
test("rejections distinguish a native datatype mismatch from an unavailable value", () => {
const states = { "cover.123": entity("cover.123", "unavailable", { symcon_variable_type: 0 }) };
const reason = pickerRejection(node(2, "cover.123"), { label: "Leistung", types: [1, 2], states });
assert.match(reason, /Datentyp Boolean/);
assert.match(reason, /Integer oder Float/);
assert.ok(!reason.includes("cover.123"));
assert.match(pickerRejection(node(2, "cover.123"), { states, excluded: () => "Bereits verknüpft." }), /Bereits verknüpft/);
});
test("missing data, instances, categories, broken links and unsupported schedules have distinct guidance", () => {
assert.match(pickerRejection(node(2), {}), /noch nicht geladen.*neu/);
assert.match(pickerRejection(node(2, "sensor.123"), { states: {} }), /nicht mehr vorhanden/);
assert.match(pickerRejection(node(2, "sensor.123"), { states: { "sensor.123": entity("sensor.123", "1") } }), /native Datentyp.*neu/);
assert.match(pickerRejection(node(1)), /Instanz.*Variable/);
assert.match(pickerRejection(node(0)), /Kategorie.*auf/);
assert.match(pickerRejection(node(6)), /Link.*direkt/);
assert.match(pickerRejection(node(4)), /keine unterstützte.*Schaltuhr/);
assert.match(pickerRejection(node(2, "sensor.123"), { schedule: true }), /Wochenplan-Ereignis.*keine Variable/);
assert.equal(pickerRejection(node(2, "sensor.123"), { unsupported: "Eine Variable ist kein Kalender." }), "Eine Variable ist kein Kalender.");
});
test("a remaining field exclusion reports native metadata without making up a restriction", () => {
const reason = pickerRejection(node(2, "cover.123"), { label: "Eigener Filter", states: { "cover.123": entity("cover.123", "open", { symcon_variable_type: 2, unit_of_measurement: "W" }) } });
assert.match(reason, /Eigener Filter/);
assert.match(reason, /Datentyp: Float/);
assert.match(reason, /Einheit: W/);
assert.match(reason, /erkannte Funktion: Jalousie/);
assert.ok(!reason.includes("Name") && !reason.includes("Schaltaktion"), "only known exclusion details are reported");
});
@@ -0,0 +1,49 @@
import type { HassEntity, SymconObject } from "../types.ts";
/** The field's native requirements, kept separate from the selectable options. */
export interface PickerRequirement {
label?: string;
types?: readonly number[];
/** Explicit purpose of a control; never inferred from the variable's name or path. */
role?: "light" | "cover";
schedule?: boolean;
/** A capability the native variable source cannot supply (e.g. a calendar). */
unsupported?: string;
/** A more specific exclusion, e.g. a variable already used by another entry. */
excluded?: (entity: string) => string | undefined;
}
export interface PickerContext extends PickerRequirement {
states?: Record<string, HassEntity>;
}
const DATA_TYPES = ["Boolean", "Integer", "Float", "String"];
const FUNCTIONS: Record<string, string> = { light: "Licht", cover: "Jalousie/Tor", switch: "Schalter", binary_sensor: "Binärsensor", sensor: "Sensor", climate: "Heizung", lock: "Schloss", script: "Skript", schedule: "Schaltuhr", media_player: "Mediengerät", fan: "Lüfter" };
/** Explain an actual rejected selection without guessing at missing metadata or exposing synthetic IDs. */
export function pickerRejection(node: SymconObject, context: PickerContext = {}): string {
if (node.virtual || node.object_type === 0) return "Das ist eine Kategorie. Klappe sie auf und wähle den Datenpunkt darunter aus.";
if (node.object_type === 1) return "Das ist eine Instanz. Klappe sie auf und wähle ihre Variable aus, zum Beispiel „Value“.";
if (context.schedule && node.object_type !== 4) return "Hier wird eine klassische Symcon-Schaltuhr (Wochenplan-Ereignis) erwartet, keine Variable.";
if (context.unsupported) return context.unsupported;
if (!node.entity_id) {
if (node.object_type === 2) return "Diese Variable wurde noch nicht geladen. Lade die Variablen oben in der Titelleiste neu und öffne die Auswahl erneut.";
if (node.object_type === 6) return "Dieser Link verweist auf keinen unterstützten Datenpunkt. Wähle die Variable direkt im Objektbaum aus.";
if (node.object_type === 4) return "Dieses Ereignis ist keine unterstützte klassische Symcon-Schaltuhr (Wochenplan).";
return "Dieser Objekttyp kann in diesem Feld nicht verknüpft werden. Wähle eine passende Variable aus.";
}
const state = context.states?.[node.entity_id];
if (context.states && !state) return "Diese Variable ist im aktuellen Datenbestand nicht mehr vorhanden. Lade die Variablen oben in der Titelleiste neu.";
const type = state?.attributes.symcon_variable_type;
const actual = type === undefined ? undefined : DATA_TYPES[Number(type)];
if (state && !state.attributes.symcon_schedule && !actual) return "Der native Datentyp dieser Variable ist nicht verfügbar. Lade die Variablen oben in der Titelleiste neu.";
if (actual && context.types && !context.types.includes(Number(type))) {
return `Datentyp ${actual} passt hier nicht. Für „${context.label || "dieses Feld"}“ wird ${context.types.map((t) => DATA_TYPES[t]).join(" oder ")} benötigt.`;
}
const excluded = context.excluded?.(node.entity_id);
if (excluded) return excluded;
const kind = FUNCTIONS[node.entity_id.split(".")[0]];
const unit = state?.attributes.unit_of_measurement;
const details = [actual && `Datentyp: ${actual}`, unit && `Einheit: ${unit}`, kind && `erkannte Funktion: ${kind}`].filter(Boolean).join(" · ");
return `Dieser Datenpunkt erfüllt den Filter${context.label ? ` für „${context.label}“` : " dieses Feldes"} nicht.${details ? ` ${details}.` : ""}`;
}
@@ -5,6 +5,7 @@ import { tokens } from "../styles.ts";
import type { SymconObject } from "../types.ts";
import type { PickerOption } from "./entity-picker.ts";
import { indexSymconTree, symconAncestors, symconTreeRows, type SymconTree, type SymconTreeRow } from "./symcon-tree.ts";
import { pickerRejection, type PickerContext } from "./picker-rejection.ts";
const TYPES = ["Kategorie", "Instanz", "Variable", "Skript", "Ereignis", "Medium", "Link"];
@@ -12,6 +13,7 @@ export class SymconObjectPicker extends LitElement {
static properties = {
objects: { attribute: false }, options: { attribute: false }, fixed: { attribute: false },
value: { attribute: false }, disabled: { type: Boolean }, placeholder: { attribute: false },
context: { attribute: false }, _notice: { state: true },
_query: { state: true }, _expanded: { state: true }, _pending: { state: true }, _active: { state: true }, _selected: { state: true },
};
@@ -21,6 +23,8 @@ export class SymconObjectPicker extends LitElement {
declare value: string | null;
declare disabled: boolean;
declare placeholder: string;
declare context: PickerContext | undefined;
private declare _notice: string;
private declare _query: string;
private declare _expanded: Set<number>;
private declare _pending: string | null;
@@ -38,6 +42,7 @@ export class SymconObjectPicker extends LitElement {
this.value = null;
this.disabled = false;
this.placeholder = "Datenpunkt auswählen";
this._notice = "";
this._query = "";
this._expanded = new Set();
this._pending = null;
@@ -65,6 +70,7 @@ export class SymconObjectPicker extends LitElement {
if (this.disabled) return;
this._pending = this.allowed.has(this.value ?? "") ? this.value : null;
this._query = "";
this._notice = "";
const selected = this.variableNode(this.value)
?? this.objects.find((node) => node.entity_id === this.value);
this._active = selected?.object_id ?? null;
@@ -112,6 +118,11 @@ export class SymconObjectPicker extends LitElement {
if (entity) {
this._pending = entity;
this._selected = node.object_id;
this._notice = "";
} else {
this._pending = null;
this._selected = null;
this._notice = pickerRejection(node, this.context);
}
}
@@ -167,7 +178,7 @@ export class SymconObjectPicker extends LitElement {
aria-level=${row.depth + 1} aria-posinset=${row.index} aria-setsize=${row.siblings}
aria-expanded=${row.hasChildren ? String(row.expanded) : nothing}
aria-selected=${selectable ? String(node.object_id === this._selected && entity === this._pending) : nothing}
aria-disabled=${node.entity_id && !selectable ? "true" : nothing}
aria-disabled=${!selectable && [2, 4, 6].includes(node.object_type) ? "true" : nothing}
class="node ${selectable ? "selectable" : ""} ${node.hidden ? "hidden-object" : ""} ${this._active === node.object_id ? "active" : ""}"
style=${`--depth:${row.depth}`} title=${node.path}
@click=${() => { this.select(node); this.renderRoot.querySelector<HTMLElement>(".tree")?.focus(); }}
@@ -202,19 +213,20 @@ export class SymconObjectPicker extends LitElement {
if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) this.close();
}
}} @keydown=${(event: KeyboardEvent) => event.stopPropagation()} @change=${(event: Event) => event.stopPropagation()}>
<header><div><h2 id="picker-title">Datenpunkt auswählen</h2><p>IP-Symcon · Objektbaum</p></div>
<header><div><h2 id="picker-title">Datenpunkt auswählen</h2><p>IP-Symcon · ${this.context?.label || "Objektbaum"}</p></div>
<button class="close" type="button" aria-label="Schließen" @click=${this.close}>×</button></header>
<div class="search-bar"><input class="search" type="search" placeholder="Im Objektbaum suchen …" aria-label="Objektbaum durchsuchen"
.value=${this._query} @input=${(event: Event) => { this._query = (event.target as HTMLInputElement).value; this._active = null; }}>
.value=${this._query} @input=${(event: Event) => { this._query = (event.target as HTMLInputElement).value; this._active = null; this._notice = ""; }}>
<button class="text-button" type="button" @click=${() => { this._query = ""; this._expanded = new Set(); this._active = null; }}>Alles zuklappen</button>
</div>
${this.fixed.length ? html`<div class="fixed" aria-label="Weitere Auswahlmöglichkeiten">${this.fixed.map((option) => html`
<button type="button" aria-pressed=${option.id === this._pending} @click=${() => { this._pending = option.id; this._active = null; this._selected = null; }}>${option.label}</button>`)}</div>` : nothing}
<button type="button" aria-pressed=${option.id === this._pending} @click=${() => { this._pending = option.id; this._active = null; this._selected = null; this._notice = ""; }}>${option.label}</button>`)}</div>` : nothing}
<div class="tree" role="tree" tabindex="0" aria-label="Symcon-Objektbaum" aria-activedescendant=${active ? `object-${active.node.object_id}` : nothing}
@keydown=${this.onTreeKey}>
${repeat(rows, (row) => row.node.object_id, (row) => this.renderRow(row))}
${!rows.length ? html`<p class="empty">${this.objects.length ? "Keine Objekte gefunden." : "Kein Objektbaum verfügbar. Bitte das Symcon-Modul aktualisieren und den Designer neu laden."}</p>` : nothing}
</div>
${this._notice ? html`<div class="rejection" role="status" aria-live="polite">${this._notice}</div>` : nothing}
<footer><div class="selection"><strong>${pendingNode?.name ?? pending?.label ?? "Noch kein Datenpunkt ausgewählt"}</strong>
<small>${pendingNode?.path ?? "Nur passende Datenpunkte können ausgewählt werden."}</small></div>
<div class="actions"><button type="button" @click=${this.close}>Abbrechen</button>
@@ -263,6 +275,7 @@ export class SymconObjectPicker extends LitElement {
.icon { flex:none; width:17px; height:17px; color:#8796a9; } .type-0 { color:#c69a42; } .type-1 { color:#8d9ac6; } .type-2 { color:#55a58c; }
.selected-mark { margin-left:8px; }
.empty { padding:20px; color:var(--nf-muted); }
.rejection { flex:none; margin:0 20px 12px; padding:8px 10px; border-left:2px solid #e5b56d; border-radius:4px; background:#e5b56d0c; color:var(--nf-text); font-size:12px; line-height:1.4; overflow-wrap:anywhere; }
footer { display:flex; align-items:center; justify-content:space-between; gap:16px; border-top:1px solid var(--nf-line); padding:15px 20px; }
.selection { min-width:0; } .selection small { margin-top:4px; overflow-wrap:anywhere; }
.actions { display:flex; gap:8px; flex-shrink:0; }
+15 -1
View File
@@ -14,5 +14,19 @@ test("integer dimmers, normalized floats and separate blind variables preserve t
assert.equal(symconControl(fraction, "light")!.attributes.brightness, 102);
assert.equal(symconControl(fraction, "cover")!.attributes.current_position, 40);
assert.equal(symconPercent(entity("sensor.low", "10", { symcon_numeric_value: 10, symcon_min: 10, symcon_max: 110 })), 0);
assert.equal(symconControl(entity("switch.8", "on", { symcon_id: 8, symcon_variable_type: 0 }), "light"), null, "a boolean switch cannot pretend to dim");
const toggle = symconControl(entity("switch.8", "on", { symcon_id: 8, symcon_variable_type: 0 }), "light")!;
assert.deepEqual(toggle.attributes.supported_color_modes, ["onoff"], "a boolean can switch a light but cannot pretend to dim");
assert.equal(toggle.attributes.brightness, undefined);
});
test("Boolean lights use their raw value even when names previously classified them as a garage door or lock", () => {
for (const domain of ["cover", "lock", "binary_sensor", "switch", "sensor"]) {
const st = entity(`${domain}.57755`, "locked", { symcon_id: 57755, symcon_variable_type: 0, symcon_value: false });
assert.equal(symconControl(st, "light")!.state, "off");
st.attributes.symcon_value = true;
assert.equal(symconControl(st, "light")!.state, "on");
st.state = "unavailable";
assert.equal(symconControl(st, "light")!.state, "unavailable");
assert.equal(symconControl(st, "cover"), null, "a boolean is not a numeric blind position");
}
});
+10 -2
View File
@@ -1,4 +1,4 @@
// A Symcon numeric variable can be explicitly used as a light or a blind, regardless of its inferred domain.
// Explicit control roles use native values and datatypes, regardless of the variable's inferred domain.
import type { HassEntity } from "./types.ts";
export function symconPercent(st: HassEntity): number | null {
@@ -10,8 +10,16 @@ export function symconPercent(st: HassEntity): number | null {
}
export function symconControl(st: HassEntity, role: "light" | "cover"): HassEntity | null {
const percent = symconPercent(st);
const id = st.attributes.symcon_id;
if (role === "light" && st.attributes.symcon_variable_type === 0 && typeof id === "number") {
const value = st.attributes.symcon_value;
return { ...st, entity_id: `light.${id}`,
state: st.state === "unavailable" || st.state === "unknown" ? st.state : (typeof value === "boolean" ? value : st.state === "on") ? "on" : "off",
attributes: { ...st.attributes, color_mode: "onoff", supported_color_modes: ["onoff"],
...(st.entity_id !== `light.${id}` ? { symcon_source_entity: st.entity_id } : {}) },
};
}
const percent = symconPercent(st);
if (percent === null || typeof id !== "number") return null;
return {
...st, entity_id: `${role}.${id}`,
+34
View File
@@ -158,6 +158,10 @@ try {
const raw = (id, name, max, value, entity = `sensor.${id}`) => ({ entity_id: entity, name, path: `Haus / KNX / ${name}`, state: String(value), attributes: { symcon_id: id, symcon_variable_type: 1, symcon_numeric_value: value, symcon_min: 0, symcon_max: max, symcon_step: 1, symcon_has_action: true } });
const variables = [raw(42, "Dimmerwert", 255, 128, "cover.42"), raw(101, "Behang Position", 100, 40), raw(102, "Lamellen Position", 255, 128), raw(103, "Positionsrückmeldung", 255, 51, "cover.103"), raw(104, "Temperatur innen", 100, 21.7), raw(105, "Temperatur außen", 100, 48.2), raw(106, "Leistung", 100, 7.3)];
for (const v of variables.filter((v) => v.attributes.symcon_id >= 104)) Object.assign(v.attributes, { symcon_variable_type: 2, unit_of_measurement: v.attributes.symcon_id === 106 ? "W" : "°C" });
variables.push(...[
[57755, "Garage_EG_Allgemein_Li_Schalten", "cover"], [22231, "Treppenhaus EG schalten", "switch"], [60001, "Rolladen Heizung Schloss", "sensor"],
].map(([id, name, domain]) => ({ entity_id: `${domain}.${id}`, name, path: `Haus / ${name} / Value`, state: "off", attributes: { symcon_id: id, symcon_variable_type: 0, symcon_value: false, symcon_has_action: true } })));
variables.push({ entity_id: "sensor.60888", name: "Status als Text", path: "Haus / Status als Text", state: "Bereit", attributes: { symcon_id: 60888, symcon_variable_type: 3, symcon_value: "Bereit" } });
const objects = [{ object_id: 100, parent_id: 0, name: "Haus", path: "Haus", object_type: 0, position: 0, hidden: true, icon: "" },
...variables.map((v) => ({ object_id: v.attributes.symcon_id, parent_id: 100, name: v.name, path: v.path, entity_id: v.entity_id, object_type: 2, position: 0, hidden: false, icon: "" }))];
const originalFetch = window.fetch;
@@ -384,6 +388,36 @@ try {
if (!view.roomLabels) throw new Error("Tile names could not be restored");
card.remove();
});
await page.evaluate(async () => {
document.querySelectorAll("nf-room-panel,nf-quick-menu").forEach((el) => el.remove());
const e = window.ed; e.selectItem("furniture", window.controlLamp); await e.updateComplete;
const picker = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((l) => l.textContent.trim().startsWith(e.t("furn_entity_light"))).querySelector("nf-entity-picker");
window.lightPicker = picker;
await window.chooseControl(picker, 57755, "Garage_EG_Allgemein_Li_Schalten");
await window.nfPanel.updateComplete; await e.updateComplete;
if (e._doc.floors[0].furniture.find((m) => m.id === window.controlLamp).entity !== "light.57755") throw new Error("The garage Boolean was not linked with an explicit light role");
const attributes = e.hass.states["light.57755"].attributes;
if (attributes.brightness !== undefined || attributes.supported_color_modes[0] !== "onoff") throw new Error("Boolean light must remain a switch without a fake dimmer");
await window.chooseControl(picker, 22231, "Treppenhaus EG schalten");
await window.chooseControl(picker, 60001, "Rolladen Heizung Schloss");
await window.chooseControl(picker, 57755, "Garage_EG_Allgemein_Li_Schalten");
const native = picker.shadowRoot.querySelector("nf-symcon-object-picker");
native.shadowRoot.querySelector(".trigger").click(); await native.updateComplete;
const input = native.shadowRoot.querySelector(".search"); input.value = "Status als Text"; input.dispatchEvent(new Event("input", { bubbles: true })); await native.updateComplete;
native.shadowRoot.querySelector("#object-60888").click(); await native.updateComplete;
if (!native.shadowRoot.querySelector(".apply").disabled || !/Datentyp String.*Boolean oder Integer oder Float/.test(native.shadowRoot.querySelector(".rejection").textContent)) throw new Error("An incompatible variable must explain its actual datatype");
if (e._doc.floors[0].furniture.find((m) => m.id === window.controlLamp).entity !== "light.57755") throw new Error("Rejected selection changed the saved link");
});
await page.screenshot({ path: join(out, "symcon-light-picker-rejection.png") });
await page.setViewport({ width: 390, height: 844 });
await page.screenshot({ path: join(out, "symcon-light-picker-rejection-mobile.png") });
assert.ok(await page.evaluate(() => {
const root = window.lightPicker.shadowRoot.querySelector("nf-symcon-object-picker").shadowRoot;
const r = root.querySelector(".rejection").getBoundingClientRect();
const actions = root.querySelector(".actions").getBoundingClientRect();
return r.top >= 0 && r.bottom <= innerHeight && r.left >= 0 && r.right <= innerWidth && actions.height > 0 && actions.bottom <= innerHeight;
}), "the message and actions remain available on mobile");
await page.evaluate(() => window.lightPicker.shadowRoot.querySelector("nf-symcon-object-picker").shadowRoot.querySelector(".close").click());
assert.deepEqual(errors, []);
console.log("OK: collapsible walls, variable reload, KNX temperature, numeric dimmer/position/slat tree bindings, off-state dimming and independent room/quick-menu commands");
} finally {
+19
View File
@@ -53,6 +53,13 @@ try {
picker.options = [{ id: "sensor.301", label: "Temperatur Küche EG" }, { id: "sensor.303", label: "Leistung Küche EG" }, { id: "sensor.430", label: "Temperatur Küche OG" }, { id: "sensor.601", label: "Betriebsstunden" }];
picker.fixed = [{ id: "none", label: "Keine Variable" }];
picker.value = "sensor.301";
picker.context = { label: "Temperatur", types: [1, 2], states: {
"sensor.301": { entity_id: "sensor.301", state: "21.5", attributes: { symcon_variable_type: 2 } },
"climate.302": { entity_id: "climate.302", state: "off", attributes: { symcon_variable_type: 0 } },
"sensor.303": { entity_id: "sensor.303", state: "10", attributes: { symcon_variable_type: 2 } },
"sensor.430": { entity_id: "sensor.430", state: "22", attributes: { symcon_variable_type: 2 } },
"sensor.601": { entity_id: "sensor.601", state: "40", attributes: { symcon_variable_type: 1 } },
} };
window.pickerChanges = [];
picker.addEventListener("change", (event) => window.pickerChanges.push(event.detail?.value ?? "NATIVE"));
const ha = document.querySelector("#ha");
@@ -82,6 +89,18 @@ try {
assert.ok(result.rows.some((row) => row.id === "object-302" && row.disabled === "true"), "incompatible variables remain visible");
assert.ok(result.rows.some((row) => row.name === "Leerer Ordner"), "empty categories must stay visible");
assert.ok(!result.text.includes("sensor.301"), "internal IDs must not appear in picker text");
await click("#object-302"); await settle();
assert.ok(await page.evaluate(() => {
const root = document.querySelector("#symcon").shadowRoot.querySelector("nf-symcon-object-picker").shadowRoot;
return /Datentyp Boolean.*Integer oder Float/.test(root.querySelector('[role=status]').textContent) && root.querySelector('.apply').disabled;
}), "an incompatible variable explains its actual type and disables confirmation instead of retaining an earlier pending choice");
assert.equal((await state()).value, "sensor.301", "a rejection does not clear the saved link");
await page.screenshot({ path: join(out, "symcon-picker-rejection.png") });
await click("#object-301"); await settle();
assert.equal(await page.evaluate(() => !!document.querySelector("#symcon").shadowRoot.querySelector("nf-symcon-object-picker").shadowRoot.querySelector('[role=status]')), false, "a valid selection removes the message");
await click("#object-200"); await settle();
assert.match((await state()).text, /Instanz.*Variable/);
await click("#object-301"); await settle();
await page.screenshot({ path: join(out, "symcon-picker-desktop.png") });
await page.keyboard.press("Escape");
assert.equal((await state()).open, false, "Escape closes the native modal");
+4
View File
@@ -106,6 +106,10 @@ try {
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.waitForFunction(() => {
const v = window.powerView, stage = v.shadowRoot.querySelector(".nf-stage");
return v.viewer?.size.w === innerWidth && v.viewer.size.h === stage.clientHeight;
});
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")];