feat: release Symcon 0.2.2 with object tree selection and hook recovery

This commit is contained in:
jhartworks committed 2026-11-09 12:50:45 +01:00
1 parent 4a875aa8ea
commit eff9eb83d7
19 files changed
+2273 -1064

No files matched your search

+1
View File
@@ -96,6 +96,7 @@ export function entityField(host: EditorHost, label: string, value: string | nul
>${label}
<nf-entity-picker
.options=${options}
.objectTree=${host.hass?.symconObjects}
.fixed=${fixed}
.value=${current}
.placeholder=${host.t("entity_search")}
+10
View File
@@ -4,6 +4,8 @@
import { css, html, LitElement, nothing } from "lit";
import { tokens } from "../styles.ts";
import type { SymconObject } from "../types.ts";
import "./symcon-object-picker.ts";
export interface PickerOption {
id: string;
@@ -17,6 +19,7 @@ const MAX_SHOWN = 40;
export class EntityPicker extends LitElement {
static properties = {
options: { attribute: false },
objectTree: { attribute: false },
fixed: { attribute: false },
value: { attribute: false },
disabled: { type: Boolean },
@@ -28,6 +31,7 @@ export class EntityPicker extends LitElement {
/** Entities to choose from. */
declare options: PickerOption[];
declare objectTree: readonly SymconObject[] | 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). */
@@ -42,6 +46,7 @@ export class EntityPicker extends LitElement {
constructor() {
super();
this.options = [];
this.objectTree = undefined;
this.fixed = [];
this.value = null;
this.disabled = false;
@@ -105,6 +110,11 @@ 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}
.disabled=${this.disabled} .placeholder=${this.placeholder}
@change=${(event: CustomEvent<{ value: string }>) => { this.value = event.detail.value; }}
></nf-symcon-object-picker>`;
const current = this.current;
const hits = this._open ? this.hits : [];
return html`<div class="wrap">
@@ -0,0 +1,250 @@
// Native modal dialog with the actual Symcon object hierarchy. Numeric IDs never become input fields.
import { css, html, LitElement, nothing, svg, type PropertyValues } from "lit";
import { repeat } from "lit/directives/repeat.js";
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";
const TYPES = ["Kategorie", "Instanz", "Variable", "Skript", "Ereignis", "Medium", "Link"];
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 },
_query: { state: true }, _expanded: { state: true }, _pending: { state: true }, _active: { state: true }, _selected: { state: true },
};
declare objects: readonly SymconObject[];
declare options: PickerOption[];
declare fixed: PickerOption[];
declare value: string | null;
declare disabled: boolean;
declare placeholder: string;
private declare _query: string;
private declare _expanded: Set<number>;
private declare _pending: string | null;
private declare _active: number | null;
private declare _selected: number | null;
private tree: SymconTree = indexSymconTree([]);
private allowed = new Map<string, PickerOption>();
constructor() {
super();
this.objects = [];
this.options = [];
this.fixed = [];
this.value = null;
this.disabled = false;
this.placeholder = "Datenpunkt auswählen";
this._query = "";
this._expanded = new Set();
this._pending = null;
this._active = null;
this._selected = null;
}
protected willUpdate(changed: PropertyValues): void {
if (changed.has("objects")) this.tree = indexSymconTree(this.objects);
if (changed.has("options") || changed.has("fixed")) this.allowed = new Map([...this.fixed, ...this.options].map((option) => [option.id, option]));
}
private get dialog(): HTMLDialogElement | null { return this.renderRoot.querySelector("dialog"); }
private variableNode(entity: string | null): SymconObject | undefined {
const native = this.objects.find((node) => node.entity_id === entity && node.object_type === 2);
return native ? this.tree.nodes.get(native.object_id) : undefined;
}
private async open(): Promise<void> {
if (this.disabled) return;
this._pending = this.allowed.has(this.value ?? "") ? this.value : null;
this._query = "";
const selected = this.variableNode(this.value)
?? this.objects.find((node) => node.entity_id === this.value);
this._active = selected?.object_id ?? null;
this._selected = selected?.object_id ?? null;
const expanded = new Set(this._expanded);
if (selected) for (const id of symconAncestors(this.tree, selected.object_id)) expanded.add(id);
this._expanded = expanded;
await this.updateComplete;
if (!this.isConnected) return;
if (!this.dialog?.open) this.dialog?.showModal();
this.renderRoot.querySelector<HTMLInputElement>(".search")?.focus();
this.renderRoot.querySelector("[aria-selected=true]")?.scrollIntoView({ block: "nearest" });
}
private close(): void { this.dialog?.close(); }
private commit(): void {
if (this.disabled || !this._pending || !this.allowed.has(this._pending)) return;
this.value = this._pending;
this.close();
this.dispatchEvent(new CustomEvent("change", { detail: { value: this.value }, bubbles: true, composed: true }));
}
private toggle(id: number): void {
const expanded = new Set(this._expanded);
if (expanded.has(id)) expanded.delete(id); else expanded.add(id);
this._expanded = expanded;
}
private select(node: SymconObject): void {
this._active = node.object_id;
if (node.entity_id && this.allowed.has(node.entity_id)) {
this._pending = node.entity_id;
this._selected = node.object_id;
}
}
private async onTreeKey(event: KeyboardEvent): Promise<void> {
const rows = symconTreeRows(this.tree, this._expanded, this._query);
const i = Math.max(0, rows.findIndex((row) => row.node.object_id === this._active));
const row = rows[i];
if (!row) return;
let next = i;
if (event.key === "ArrowDown") next = Math.min(rows.length - 1, i + 1);
else if (event.key === "ArrowUp") next = Math.max(0, i - 1);
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = rows.length - 1;
else if (event.key === "ArrowRight") {
if (row.hasChildren && !row.expanded) this.toggle(row.node.object_id);
else if (row.hasChildren) next = Math.min(rows.length - 1, i + 1);
} else if (event.key === "ArrowLeft") {
if (row.expanded && !this._query) this.toggle(row.node.object_id);
else next = Math.max(0, rows.findIndex((item) => item.node.object_id === row.node.parent_id));
} else if (event.key === " " || event.key === "Enter") {
this.select(row.node);
if (event.key === "Enter" && row.node.entity_id && this.allowed.has(row.node.entity_id)) this.commit();
} else return;
event.preventDefault();
if (next !== i || this._active === null) this._active = rows[next].node.object_id;
await this.updateComplete;
this.renderRoot.querySelector(`#object-${this._active}`)?.scrollIntoView({ block: "nearest" });
}
private icon(type: number) {
const paths = [
svg`<path d="M3 6h7l2 2h9v12H3z"/>`,
svg`<path d="m12 3 9 5v9l-9 5-9-5V8zM3 8l9 5 9-5M12 13v9"/>`,
svg`<circle cx="12" cy="12" r="8"/><path d="m9 9 6 6m0-6-6 6"/>`,
svg`<path d="m8 7-5 5 5 5m8-10 5 5-5 5m-3-12-2 14"/>`,
svg`<circle cx="12" cy="12" r="9"/><path d="M12 6v6l4 2"/>`,
svg`<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m4 17 5-5 4 4 3-3 5 4"/>`,
svg`<path d="m10 14 4-4m-6 2-2 2a4 4 0 0 0 6 6l3-3m-6-9 3-3a4 4 0 0 1 6 6l-2 2"/>`,
];
return svg`<svg class="icon type-${type}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true">${paths[type] ?? paths[1]}</svg>`;
}
private renderRow(row: SymconTreeRow) {
const { node } = row;
const selectable = !!node.entity_id && this.allowed.has(node.entity_id);
return html`<div id="object-${node.object_id}" role="treeitem"
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 && node.entity_id === this._pending) : nothing}
aria-disabled=${node.entity_id && !selectable ? "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(); }}
@dblclick=${() => { if (selectable) { this.select(node); this.commit(); } else if (row.hasChildren) this.toggle(node.object_id); }}>
<button class="twisty" type="button" tabindex="-1" aria-label=${row.expanded ? "Zuklappen" : "Aufklappen"}
?disabled=${!row.hasChildren} @click=${(event: Event) => { event.stopPropagation(); this._active = node.object_id; this.toggle(node.object_id); }}>
${row.hasChildren ? (row.expanded ? "▾" : "▸") : nothing}
</button>
${this.icon(node.object_type)}<span class="node-name">${node.name || "(Ohne Namen)"}</span>
<small>${node.virtual ? "Systembereich" : (TYPES[node.object_type] ?? "Objekt")}${node.hidden ? " · ausgeblendet" : ""}</small>
${selectable && node.object_id === this._selected && node.entity_id === this._pending ? html`<span class="selected-mark" aria-hidden="true">✓</span>` : nothing}
</div>`;
}
protected render() {
const current = this.allowed.get(this.value ?? "");
const selectedNode = this.variableNode(this.value);
const pending = this.allowed.get(this._pending ?? "");
const selectedObject = this._selected === null ? undefined : this.tree.nodes.get(this._selected);
const pendingNode = (selectedObject?.entity_id === this._pending ? selectedObject : undefined) ?? this.variableNode(this._pending);
const rows = symconTreeRows(this.tree, this._expanded, this._query);
const active = rows.find((row) => row.node.object_id === this._active);
return html`<button type="button" class="trigger" ?disabled=${this.disabled} aria-haspopup="dialog" @click=${this.open}>
<span><strong>${selectedNode?.name ?? current?.label ?? "Datenpunkt auswählen"}</strong>
${selectedNode ? html`<small>${selectedNode.path}</small>` : nothing}</span><span aria-hidden="true">⌘</span>
</button>
<dialog aria-labelledby="picker-title" @click=${(event: MouseEvent) => {
event.stopPropagation();
if (event.target === this.dialog) {
const bounds = this.dialog!.getBoundingClientRect();
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>
<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; }}>
<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}
<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>
<footer><div class="selection"><strong>${pendingNode?.name ?? pending?.label ?? "Noch kein Datenpunkt ausgewählt"}</strong>
<small>${pendingNode?.path ?? "Nur passende Variablen können ausgewählt werden."}</small></div>
<div class="actions"><button type="button" @click=${this.close}>Abbrechen</button>
<button class="apply" type="button" ?disabled=${this.disabled || !pending} @click=${this.commit}>Übernehmen</button></div>
</footer>
</dialog>`;
}
static styles = [tokens, css`
:host { display:block; min-width:0; font:inherit; color:var(--nf-text); }
button,input { font:inherit; box-sizing:border-box; }
button { cursor:pointer; color:var(--nf-text); border:1px solid var(--nf-line); background:var(--nf-chrome-solid); border-radius:9px; padding:8px 12px; }
button:disabled { opacity:.45; cursor:default; }
button:focus-visible,input:focus-visible { outline:2px solid var(--nf-accent); outline-offset:2px; }
.trigger { width:100%; display:flex; align-items:center; justify-content:space-between; text-align:left; gap:12px; padding:9px 11px; }
.trigger>span:first-child { min-width:0; }
strong { font-weight:500; } small { display:block; color:var(--nf-muted); font-size:11px; }
.trigger small { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; margin-top:3px; }
dialog { width:min(780px,calc(100vw - 32px)); max-width:none; height:min(690px,calc(100dvh - 32px)); max-height:none; box-sizing:border-box; padding:0; border:1px solid var(--nf-line); border-radius:16px; color:var(--nf-text); background:var(--nf-chrome-solid); box-shadow:0 24px 80px #0008; font:14px system-ui,sans-serif; }
dialog[open] { display:flex; flex-direction:column; }
dialog::backdrop { background:#050b16a6; backdrop-filter:blur(3px); }
header { display:flex; align-items:center; justify-content:space-between; padding:20px 22px 16px; border-bottom:1px solid var(--nf-line); }
h2 { font-size:18px; font-weight:600; margin:0 0 4px; } header p { margin:0; color:var(--nf-muted); font-size:12px; }
.close { font-size:25px; padding:0; width:32px; height:32px; border-color:transparent; }
.search-bar { display:flex; align-items:center; gap:12px; padding:16px 20px 10px; }
.search { flex:1; min-width:0; border:1px solid var(--nf-line); border-radius:9px; padding:10px 12px; background:var(--nf-bg); color:var(--nf-text); }
.text-button { border:0; background:transparent; color:var(--nf-muted); font-size:12px; padding:6px 0; white-space:nowrap; }
.fixed { display:flex; flex-wrap:wrap; gap:6px; padding:0 20px 10px; }
.fixed button { padding:5px 10px; font-size:12px; }
.fixed [aria-pressed=true] { color:var(--nf-accent); border-color:var(--nf-accent); }
.tree { flex:1; min-height:80px; overflow:auto; overscroll-behavior:contain; margin:0 12px; padding:4px 0 12px; outline-offset:-2px; }
.node { display:flex; align-items:center; gap:8px; min-height:34px; border-radius:6px; padding:2px 10px 2px calc(4px + var(--depth)*22px); box-sizing:border-box; width:max-content; min-width:100%; }
.node:hover { background:color-mix(in srgb,var(--nf-accent) 8%,transparent); }
.node.active { outline:1px solid color-mix(in srgb,var(--nf-accent) 40%,transparent); outline-offset:-1px; }
.node[aria-selected=true] { background:color-mix(in srgb,var(--nf-accent) 16%,transparent); color:var(--nf-accent); }
.node.selectable { cursor:pointer; }
.node[aria-disabled=true] .node-name { color:var(--nf-muted); }
.node.hidden-object .node-name { font-style:italic; }
.node-name { flex:1; white-space:nowrap; }
.node small { margin-left:20px; white-space:nowrap; }
.twisty { border:0; background:transparent; border-radius:4px; padding:0; width:20px; height:26px; flex:none; font-size:18px; }
.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); }
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; }
.apply { color:white; background:var(--nf-accent); border-color:transparent; }
@media(max-width:580px) {
dialog { width:calc(100vw - 16px); height:calc(100dvh - 32px); border-radius:12px; }
header { padding:16px; } .search-bar { padding:12px; gap:8px; } .fixed { padding:0 12px 8px; }
.tree { margin:0 8px; } .node { gap:6px; padding-left:calc(2px + var(--depth)*18px); }
.node small { display:none; } footer { padding:12px; flex-direction:column; align-items:stretch; } .actions { justify-content:flex-end; }
}
`];
}
if (!customElements.get("nf-symcon-object-picker")) customElements.define("nf-symcon-object-picker", SymconObjectPicker);
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import type { SymconObject } from "../types.ts";
import { indexSymconTree, symconAncestors, symconTreeRows, SYMCON_SYSTEM_ROOT } from "./symcon-tree.ts";
const node = (object_id: number, parent_id: number, name: string, object_type = 0, position = 0): SymconObject =>
({ object_id, parent_id, name, object_type, position, path: name, hidden: false, icon: "" });
test("native position, type and name order are kept, including empty categories and non-variable objects", () => {
const tree = indexSymconTree([node(4, 0, "Variable", 2), node(2, 0, "Zentrale", 1), node(3, 0, "Zweiter Ordner"), node(1, 0, "Erster Ordner"), node(5, 0, "Skript", 3, -1)]);
assert.deepEqual(symconTreeRows(tree, new Set()).map((row) => row.node.object_id), [5, 1, 3, 2, 4]);
});
test("equal names and a slash inside a name remain distinct native branches", () => {
const tree = indexSymconTree([node(1, 0, "Haus / Altbau"), node(2, 1, "Heizung", 1), node(3, 0, "Heizung", 1), node(4, 2, "Temperatur", 2), node(5, 3, "Temperatur", 2)]);
assert.deepEqual(symconAncestors(tree, 4), [2, 1]);
assert.deepEqual(symconAncestors(tree, 5), [3]);
assert.deepEqual(symconTreeRows(tree, new Set([1, 2])).map((row) => [row.node.object_id, row.depth]), [[1, 0], [2, 1], [4, 2], [3, 0]]);
});
test("search opens the original ancestors and never searches internal IDs", () => {
const tree = indexSymconTree([node(1, 0, "Haus"), node(2, 1, "Küche", 1), node(3, 2, "Temperatur", 2), node(4, 1, "Garten")]);
const expanded = new Set<number>();
assert.deepEqual(symconTreeRows(tree, expanded, "temperatur").map((row) => row.node.object_id), [1, 2, 3]);
assert.equal(expanded.size, 0, "search must not change manual expansion state");
assert.deepEqual(symconTreeRows(tree, expanded, "3"), []);
});
test("hidden categories and their variables stay in the main category without a visibility filter", () => {
const objects = [{ ...node(1, 0, "Versteckt"), hidden: true }, { ...node(2, 1, "Technik"), hidden: true }, { ...node(3, 2, "Temperatur", 2), entity_id: "sensor.3" }];
const tree = indexSymconTree(objects);
const rows = symconTreeRows(tree, new Set([1, 2]));
assert.deepEqual(rows.map((row) => row.node.object_id), [1, 2, 3]);
assert.equal(rows[0].node.hidden, true);
assert.equal(rows[1].node.hidden, true);
assert.equal(rows[2].node.entity_id, "sensor.3");
});
test("all six system module types move into virtual groups while devices stay in the main category", () => {
const objects = [node(1, 0, "Haus"), { ...node(2, 1, "Heizung", 1), module_type: 3 }, node(3, 2, "Temperatur", 2)];
const types = [1, 2, 0, 4, 5, 6];
for (const type of types) {
objects.push({ ...node(20 + type, 0, `Modul ${type}`, 1), module_type: type });
objects.push({ ...node(40 + type, 20 + type, "Wert", 2), entity_id: `sensor.${40 + type}` });
}
const original = structuredClone(objects);
const tree = indexSymconTree(objects);
assert.deepEqual(symconTreeRows(tree, new Set()).map((row) => row.node.name), ["Haus", "System"]);
assert.deepEqual((tree.children.get(SYMCON_SYSTEM_ROOT) ?? []).map((entry) => entry.name), ["I/O", "Splitter", "Kerninstanzen", "Konfiguratoren", "Discovery", "Visualisierungen"]);
assert.equal(tree.nodes.get(2)?.parent_id, 1);
for (const type of types) {
assert.equal(tree.nodes.get(20 + type)?.parent_id, -10 - type);
assert.deepEqual(symconAncestors(tree, 40 + type), [20 + type, -10 - type, SYMCON_SYSTEM_ROOT]);
assert.equal(tree.nodes.get(40 + type)?.entity_id, `sensor.${40 + type}`);
}
assert.deepEqual(objects, original, "grouping must never mutate native parents or object data");
assert.ok([...tree.nodes.values()].filter((entry) => entry.virtual).every((entry) => !entry.entity_id && entry.object_id < 0));
});
test("system subtrees remain intact and searchable, including native folders already named System", () => {
const objects = [node(1, 0, "System"), { ...node(2, 1, "LAN", 1), module_type: 1 }, { ...node(3, 2, "Splitter", 1), module_type: 2 },
{ ...node(4, 3, "Betriebsstunden", 2), hidden: true, entity_id: "sensor.4" }];
const tree = indexSymconTree(objects);
assert.equal(tree.nodes.get(1)?.parent_id, 0, "an actual user category named System must not be merged or moved");
assert.equal(tree.nodes.get(3)?.parent_id, 2, "nested instances stay with their original parent");
assert.deepEqual(symconTreeRows(tree, new Set(), "System I/O Betriebsstunden").map((row) => row.node.object_id), [SYMCON_SYSTEM_ROOT, -11, 2, 3, 4]);
assert.equal(tree.nodes.get(4)?.hidden, true);
assert.equal(tree.nodes.get(4)?.path, "System / I/O / LAN / Splitter / Betriebsstunden");
});
+131
View File
@@ -0,0 +1,131 @@
import type { SymconObject } from "../types.ts";
export interface SymconTree {
nodes: Map<number, SymconObject>;
children: Map<number, SymconObject[]>;
}
export interface SymconTreeRow {
node: SymconObject;
depth: number;
hasChildren: boolean;
expanded: boolean;
index: number;
siblings: number;
}
// Symcon orders siblings by position, then object type, then name (IPS_SetPosition).
const collator = new Intl.Collator("de", { numeric: true, sensitivity: "base" });
export const SYMCON_SYSTEM_ROOT = -1;
const SYSTEM_GROUPS = [
{ type: 1, name: "I/O" },
{ type: 2, name: "Splitter" },
{ type: 0, name: "Kerninstanzen" },
{ type: 4, name: "Konfiguratoren" },
{ type: 5, name: "Discovery" },
{ type: 6, name: "Visualisierungen" },
] as const;
const isSystemInstance = (node: SymconObject): boolean => node.object_type === 1 && SYSTEM_GROUPS.some((group) => group.type === node.module_type);
/** Show the main category's objects first and tuck the logical console's system branches away.
* Hidden categories are never filtered; only this display copy is regrouped, never the native tree. */
function projectSymconObjects(objects: readonly SymconObject[]): readonly SymconObject[] {
const native = new Map(objects.map((node) => [node.object_id, node]));
const roots = objects.filter((node) => {
if (!isSystemInstance(node)) return false;
const seen = new Set([node.object_id]);
let parent = native.get(node.parent_id);
while (parent && !seen.has(parent.object_id)) {
if (isSystemInstance(parent)) return false; // Keep its entire native subtree together.
seen.add(parent.object_id);
parent = native.get(parent.parent_id);
}
return true;
});
if (!roots.length) return objects;
const projected = new Map(native);
const children = new Map<number, SymconObject[]>();
for (const node of objects) {
const siblings = children.get(node.parent_id) ?? [];
siblings.push(node);
children.set(node.parent_id, siblings);
}
const virtualCategory = (id: number, parent: number, name: string, path: string, position: number): SymconObject => ({
object_id: id, parent_id: parent, name, path, position, object_type: 0, hidden: false, icon: "", virtual: true,
});
projected.set(SYMCON_SYSTEM_ROOT, virtualCategory(SYMCON_SYSTEM_ROOT, 0, "System", "System", Number.MAX_SAFE_INTEGER));
const moved = new Set<number>();
const moveBranch = (node: SymconObject, parent: number, parentPath: string): void => {
if (moved.has(node.object_id)) return;
moved.add(node.object_id);
const copy = { ...node, parent_id: parent, path: `${parentPath} / ${node.name}` };
projected.set(node.object_id, copy);
for (const child of children.get(node.object_id) ?? []) moveBranch(child, node.object_id, copy.path);
};
SYSTEM_GROUPS.forEach((group, index) => {
const instances = roots.filter((node) => node.module_type === group.type);
if (!instances.length) return;
const id = -10 - group.type;
const path = `System / ${group.name}`;
projected.set(id, virtualCategory(id, SYMCON_SYSTEM_ROOT, group.name, path, index));
for (const instance of instances) moveBranch(instance, id, path);
});
return [...projected.values()];
}
export function indexSymconTree(objects: readonly SymconObject[]): SymconTree {
const projected = projectSymconObjects(objects);
const nodes = new Map(projected.map((node) => [node.object_id, node]));
const children = new Map<number, SymconObject[]>();
for (const node of projected) {
const parent = nodes.has(node.parent_id) ? node.parent_id : 0;
const siblings = children.get(parent) ?? [];
siblings.push(node);
children.set(parent, siblings);
}
for (const siblings of children.values()) siblings.sort((a, b) => a.position - b.position || a.object_type - b.object_type || collator.compare(a.name, b.name));
return { nodes, children };
}
/** Display ancestor IDs, including virtual system groups, without splitting names into paths. */
export function symconAncestors(tree: SymconTree, objectId: number): number[] {
const result: number[] = [];
const seen = new Set([objectId]);
let parent = tree.nodes.get(objectId)?.parent_id;
while (parent && !seen.has(parent) && tree.nodes.has(parent)) {
result.push(parent);
seen.add(parent);
parent = tree.nodes.get(parent)?.parent_id;
}
return result;
}
/** Search retains each match's displayed ancestors and opens that path without changing manual expansion. */
export function symconTreeRows(tree: SymconTree, expanded: ReadonlySet<number>, query = ""): SymconTreeRow[] {
const words = query.trim().toLocaleLowerCase("de").split(/\s+/).filter(Boolean);
const matches = words.length ? new Set<number>() : null;
if (matches) {
for (const node of tree.nodes.values()) {
if (words.every((word) => `${node.name} ${node.path}`.toLocaleLowerCase("de").includes(word))) {
matches.add(node.object_id);
for (const id of symconAncestors(tree, node.object_id)) matches.add(id);
}
}
}
const rows: SymconTreeRow[] = [];
const visited = new Set<number>();
const visit = (parent: number, depth: number) => {
const siblings = (tree.children.get(parent) ?? []).filter((node) => !matches || matches.has(node.object_id));
siblings.forEach((node, i) => {
if (visited.has(node.object_id)) return;
visited.add(node.object_id);
const hasChildren = (tree.children.get(node.object_id)?.length ?? 0) > 0;
const open = hasChildren && (!!matches || expanded.has(node.object_id));
rows.push({ node, depth, hasChildren, expanded: open, index: i + 1, siblings: siblings.length });
if (open) visit(node.object_id, depth + 1);
});
};
visit(0, 0);
return rows;
}
+14 -3
View File
@@ -4,7 +4,7 @@
// Symcon variables are exposed as named synthetic entities (for example `light.12345`), while the browser
// only ever shows and selects their object-tree path. The numeric object id stays an implementation detail.
import type { HassArea, HassEntity, HassEntityEntry, HomeAssistant } from "./types.ts";
import type { HassArea, HassEntity, HassEntityEntry, HomeAssistant, SymconObject } from "./types.ts";
interface SymconConfig {
endpoint: string;
@@ -28,6 +28,7 @@ interface Bootstrap {
building_revision: number;
variables: SymconVariable[];
areas: HassArea[];
objects?: SymconObject[];
}
interface VariableSnapshot {
@@ -35,6 +36,7 @@ interface VariableSnapshot {
building_revision: number;
variables?: SymconVariable[];
areas?: HassArea[];
objects?: SymconObject[];
}
type Listener = () => void;
@@ -80,6 +82,7 @@ export class SymconBridge {
private timer: ReturnType<typeof setInterval> | undefined;
private stateRevision = -1;
private buildingRevision = -1;
private objectsSignature = "";
private states: Record<string, HassEntity> = {};
private entities: Record<string, HassEntityEntry> = {};
private areas: Record<string, HassArea> = {};
@@ -90,6 +93,7 @@ export class SymconBridge {
states: this.states,
entities: this.entities,
areas: this.areas,
symconObjects: [],
config: { unit_system: { temperature: "°C" } },
themes: { darkMode: window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? true },
services: {},
@@ -140,7 +144,7 @@ export class SymconBridge {
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 });
this.apply({ variables: next.variables, areas: next.areas, objects: next.objects });
for (const listener of this.changeListeners) listener();
}
if (next.building_revision !== this.buildingRevision) {
@@ -152,7 +156,7 @@ export class SymconBridge {
}
}
private apply(data: { variables: SymconVariable[]; areas?: HassArea[] }): void {
private apply(data: { variables: SymconVariable[]; areas?: HassArea[]; objects?: SymconObject[] }): void {
this.states = Object.fromEntries(
data.variables.map((variable) => [
variable.entity_id,
@@ -178,6 +182,13 @@ export class SymconBridge {
this.facade.states = this.states;
this.facade.entities = this.entities;
this.facade.areas = this.areas;
if (data.objects) {
const signature = JSON.stringify(data.objects);
if (signature !== this.objectsSignature) {
this.facade.symconObjects = data.objects;
this.objectsSignature = signature;
}
}
}
private async callWS<T>(message: Record<string, unknown>): Promise<T> {
+20
View File
@@ -49,6 +49,24 @@ export interface HassConnection {
subscribeMessage<T>(callback: (msg: T) => void, msg: Record<string, unknown>): Promise<() => Promise<void>>;
}
/** An actual node of Symcon's object tree; names/paths are display text, IDs are internal keys. */
export interface SymconObject {
object_id: number;
parent_id: number;
name: string;
path: string;
object_type: number;
position: number;
hidden: boolean;
icon: string;
/** Native module type of an instance (0 core, 1 IO, 2 splitter, 3 device, 4–6 system). */
module_type?: number;
/** Display-only grouping node; never an actual Symcon object. */
virtual?: boolean;
/** Present on variables and links to variables. */
entity_id?: string;
}
export interface HomeAssistant {
language: string;
user?: { is_admin: boolean; name: string };
@@ -56,6 +74,8 @@ export interface HomeAssistant {
floors?: Record<string, HassFloor>;
entities?: Record<string, HassEntityEntry>;
devices?: Record<string, HassDevice>;
/** Present only in the Symcon host. The full native hierarchy, including non-variable nodes. */
symconObjects?: readonly SymconObject[];
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. */