fix: separate hierarchy management from selected building editing

This commit is contained in:
jhartworks committed 2026-11-19 09:46:31 +01:00
1 parent bffc4d0acc
commit 382d6e04f2
18 files changed
+2103 -1648

No files matched your search

+127 -26
View File
@@ -1,4 +1,6 @@
import { floorSelection, normalizeTopology, topologyFloors } from "../topology.ts";
import { editorFloors, editorScopeChoices, editorScopeFromKey, editorScopeKey, moveSelectedFloor, reconcileEditorContext, scopeForFloor, selectEditorScope, type EditorScope } from "./editor/editor-context.ts";
import "./editor/hierarchy-manager.ts";
import { floorSelection, floorTopologyPath, normalizeTopology, topologyFloors } from "../topology.ts";
// 2D editor: floors, rooms (rectangles and free shapes), snapping, undo, background template.
import { html, LitElement, nothing, svg, type PropertyValues, type TemplateResult } from "lit";
@@ -205,6 +207,8 @@ export class NfEditor extends LitElement {
_tour: { state: true },
_sideOpen: { state: true },
_floorId: { state: true },
_editorScope: { state: true },
_floorMove: { state: true },
_energyNote: { state: true },
_ctx: { state: true },
_fixedHint: { state: true },
@@ -261,6 +265,8 @@ export class NfEditor extends LitElement {
private tourChecked = false;
private declare _sideOpen: boolean;
private declare _floorId: string | null;
private declare _editorScope: EditorScope | null;
private declare _floorMove: {floorId:string;targetId:string} | null;
/** What the import from the energy dashboard did (shown under its button). */
private declare _energyNote: string | null;
/** Open context menu (right-click, long press) at a plan point, for one item. */
@@ -327,6 +333,7 @@ export class NfEditor extends LitElement {
this.narrow = false;
this.roomLabels = true;
this._floorId = null;
this._editorScope=null;this._floorMove=null;
this._arcEdit = null;
this._routeDraft = null;
this.roof.sectionId = null;
@@ -634,7 +641,7 @@ export class NfEditor extends LitElement {
const next = structuredClone(this._doc);
if (!moveFurnitureToFloor(next, from, id, floorId)) return;
this.setDoc(next);
this._floorId = floorId;
this.adoptFloor(floorId);
this.selectItem("furniture", id);
}
@@ -680,7 +687,7 @@ export class NfEditor extends LitElement {
return new RoofController({
host: this.host,
floorId: () => editor._floorId,
setFloorId: (id) => (editor._floorId = id),
setFloorId: (id) => editor.adoptFloor(id),
confirm: (text) => confirm(text),
refresh: () => editor.requestUpdate(),
});
@@ -704,7 +711,7 @@ export class NfEditor extends LitElement {
/** What the roof and solar forms need. */
private roofDeps(): RoofPanelDeps {
return { host: this.host, roof: this.roof, floorId: this._floorId, setFloorId: (id) => (this._floorId = id), toggleLockPlan: () => this.toggleLockPlan() };
return { host: this.host, roof: this.roof, floorId: this._floorId, setFloorId: (id) => this.adoptFloor(id), toggleLockPlan: () => this.toggleLockPlan() };
}
private makeBackup(): BackupService {
@@ -719,7 +726,7 @@ export class NfEditor extends LitElement {
t: (key, vars) => editor.t(key, vars),
adopt: (building) => {
editor.setDoc(building);
editor._floorId = building.floors[0]?.id ?? null;
editor._editorScope=null;editor.adoptFloor(building.floors[0]?.id??null);
editor.selectItem("room", null);
editor.fit();
},
@@ -783,9 +790,10 @@ export class NfEditor extends LitElement {
}
this._doc = this.building;
this._doc3d = this.building;
if (!this._doc.floors.some((f) => f.id === this._floorId)) this._floorId = this._doc.floors[0]?.id ?? null;
this.syncEditorContext();
if (!this.floor?.rooms.some((r) => r.id === this.sel.room)) this.sel.room = null;
}
if(changed.has("_doc"))this.syncEditorContext();
}
protected firstUpdated(): void {
@@ -1090,11 +1098,11 @@ export class NfEditor extends LitElement {
}}
@device-move=${this.onDeviceMoved3d}
@floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => {
if (e.detail.floorId) this._floorId = e.detail.floorId;
if (e.detail.floorId) this.adoptFloor(e.detail.floorId);
this._sideOpen = false;
}}
@room-tap=${(e: CustomEvent<{ floorId: string; roomId: string | null }>) => {
if (e.detail.floorId) this._floorId = e.detail.floorId;
if (e.detail.floorId) this.adoptFloor(e.detail.floorId);
if (e.detail.roomId) this.selectFrom3d("room", e.detail.roomId);
else this._sideOpen = false;
}}
@@ -1124,6 +1132,93 @@ export class NfEditor extends LitElement {
// ------------------------------------------------------------------ document helpers
private clearPlanSelection(): void {
this.cancelPick();
this.selectItem("room",null);
this._note=null;this._draft=[];this._cursor=null;this._ctx=null;this._wallView=null;this.drag=null;this._fixedHint=false;
this.side.floorCopy=null;this.side.floorMenu=false;
this.side.shiftX=0;this.side.shiftZ=0;
}
private syncEditorContext(): void {
const next=reconcileEditorContext(this._doc,{scope:this._editorScope,floorId:this._floorId});
if(next.floorId===this._floorId&&editorScopeKey(next.scope)===editorScopeKey(this._editorScope))return;
this._editorScope=next.scope;this._floorId=next.floorId;this.clearPlanSelection();
}
private adoptFloor(id:string|null):void {
const f=id?this._doc.floors.find((f)=>f.id===id):undefined;
if(id&&!f)return;
this._floorId=f?.id??null;
if(f)this._editorScope=this._doc.topology?scopeForFloor(f):null;
this.clearPlanSelection();
}
private selectBuilding(scope:EditorScope):void {
const valid=editorScopeFromKey(this._doc,editorScopeKey(scope));if(!valid)return;
const next=selectEditorScope(this._doc,valid);
this._editorScope=next.scope;this._floorId=next.floorId;
this.clearPlanSelection();this.fit();
}
private openHierarchy():void {
const dialog=this.renderRoot.querySelector<HTMLDialogElement>(".nf-hierarchy-dialog");
if(dialog&&!dialog.open)dialog.showModal();
}
private async openFloorMove():Promise<void> {
if(!this.isAdmin||!this.floor||this.floor.outdoor_location_id||!this._doc.topology)return;
this._floorMove={floorId:this.floor.id,targetId:""};await this.updateComplete;
const dialog=this.renderRoot.querySelector<HTMLDialogElement>(".nf-floor-move-dialog");
if(dialog&&!dialog.open)dialog.showModal();
}
private applyFloorMove():void {
if(!this.isAdmin||!this._floorMove)return;
const {floorId,targetId}=this._floorMove,next=structuredClone(this._doc);
if(!moveSelectedFloor(next,this.floor?.id??null,floorId,targetId))return;
this.setDoc(next);this.adoptFloor(floorId);this.fit();
this.renderRoot.querySelector<HTMLDialogElement>(".nf-floor-move-dialog")?.close();
}
private renderEditorNavigation():TemplateResult|typeof nothing {
if(!this._doc.topology)return isSymcon(this.hass)?html`<div class="nf-editor-context"><button class="nf-btn nf-hierarchy-open" @click=${()=>this.openHierarchy()}>Hierarchie</button></div>`:nothing;
const scope=this._editorScope,choices=editorScopeChoices(this._doc),floors=editorFloors(this._doc,scope);
const label=choices.find(([key])=>key===editorScopeKey(scope))?.[1]??"Gebäude auswählen";
return html`<div class="nf-editor-context">
<div class="nf-editor-building-row"><label>Gebäude<select class="nf-editor-building-select" aria-label="Gebäude" title=${label} @change=${(e:Event)=>{const s=editorScopeFromKey(this._doc,(e.target as HTMLSelectElement).value);if(s)this.selectBuilding(s);}}>
${!scope?html`<option value="">Gebäude auswählen</option>`:nothing}
${choices.map(([key,name])=>html`<option value=${key} .selected=${key===editorScopeKey(scope)}>${name}</option>`)}
</select></label><button class="nf-btn nf-hierarchy-open" @click=${()=>this.openHierarchy()}>Hierarchie</button></div>
<nav class="nf-editor-floor-nav" aria-label="Etagen des gewählten Gebäudes">
<span class="nf-muted">${scope?.kind==="outside"?"Außenplan":"Etagen"}</span>
${[...floors].reverse().map((f)=>html`<button class="nf-chip" data-editor-floor=${f.id} aria-pressed=${f.id===this._floorId} @click=${()=>{this.adoptFloor(f.id);this.fit();}}>${f.name}</button>`)}
${scope?.kind==="building"?html`<button class="nf-btn nf-editor-add-floor" ?disabled=${!this.isAdmin} @click=${()=>this.addFloor(null)}>+ Etage</button>`:nothing}
${this.floor&&!this.floor.outdoor_location_id?html`<button class="nf-link nf-editor-move-floor" ?disabled=${!this.isAdmin} @click=${()=>void this.openFloorMove()}>Ausgewählte Etage verschieben…</button>`:nothing}
</nav>
</div>`;
}
private renderHierarchyDialogs():TemplateResult {
const move=this._floorMove,source=move?this._doc.floors.find((f)=>f.id===move.floorId):undefined;
const targets=editorScopeChoices(this._doc).filter(([key])=>key.startsWith("building:")&&key!==`building:${source?.building_id}`);
return html`<dialog class="nf-hierarchy-dialog" aria-label="Hierarchie verwalten" @keydown=${(e:KeyboardEvent)=>e.stopPropagation()}>
<header><h2>Hierarchie verwalten</h2><button class="nf-btn" aria-label="Schließen" @click=${()=>this.renderRoot.querySelector<HTMLDialogElement>(".nf-hierarchy-dialog")?.close()}>×</button></header>
<nf-hierarchy-manager .doc=${this._doc} .admin=${this.isAdmin} .suggestedName=${this.hass?.symconTitle?.trim()||"Gebäude 1"}
@hierarchy-change=${(e:CustomEvent<{building:Building}>)=>{e.stopPropagation();if(this.isAdmin)this.setDoc(e.detail.building);}}
@hierarchy-open=${(e:CustomEvent<EditorScope>)=>{e.stopPropagation();this.selectBuilding(e.detail);this.renderRoot.querySelector<HTMLDialogElement>(".nf-hierarchy-dialog")?.close();}}></nf-hierarchy-manager>
</dialog>
<dialog class="nf-floor-move-dialog" aria-label="Ausgewählte Etage verschieben" @close=${()=>this._floorMove=null} @keydown=${(e:KeyboardEvent)=>e.stopPropagation()}>
<header><h2>Ausgewählte Etage verschieben</h2><button class="nf-btn" aria-label="Schließen" @click=${()=>this.renderRoot.querySelector<HTMLDialogElement>(".nf-floor-move-dialog")?.close()}>×</button></header>
${move&&source?html`<p class="nf-floor-move-source">${floorTopologyPath(this._doc,source)}</p>
<label class="nf-field">Zielgebäude<select class="nf-floor-move-target" @change=${(e:Event)=>this._floorMove={...move,targetId:(e.target as HTMLSelectElement).value}}>
<option value="" .selected=${!move.targetId}>Zielgebäude auswählen</option>
${targets.map(([key,name])=>html`<option value=${key.slice(9)} .selected=${move.targetId===key.slice(9)}>${name}</option>`)}
</select></label>
<button class="nf-btn nf-primary nf-floor-move-apply" ?disabled=${!this.isAdmin||!move.targetId||source.id!==this.floor?.id||!targets.some(([key])=>key===`building:${move.targetId}`)} @click=${()=>this.applyFloorMove()}>Etage „${source.name}“ verschieben</button>`:nothing}
</dialog>`;
}
private get floor(): Floor | undefined {
return this._doc?.floors.find((f) => f.id === this._floorId);
}
@@ -1141,6 +1236,7 @@ export class NfEditor extends LitElement {
if (base) this.history.record(base);
if(next.topology)normalizeTopology(next);
this._doc = next;
this.syncEditorContext();
this.syncHistoryButtons();
this.dispatchEvent(new CustomEvent("building-changed", { detail: { building: next }, bubbles: true, composed: true }));
}
@@ -1171,7 +1267,7 @@ export class NfEditor extends LitElement {
private restore(doc: Building): void {
this._doc = doc;
if (!doc.floors.some((f) => f.id === this._floorId)) this._floorId = doc.floors[0]?.id ?? null;
this.syncEditorContext();
if (!this.floor?.rooms.some((r) => r.id === this.sel.room)) this.sel.room = null;
this.sel.corner = null;
this.syncHistoryButtons();
@@ -2228,8 +2324,8 @@ export class NfEditor extends LitElement {
const next = structuredClone(this._doc);
next.floors = next.floors.filter((f) => f.id !== floor.id);
this.setDoc(next);
this._floorId = next.floors[0]?.id ?? null;
this.sel.room = null;
this.syncEditorContext();
this.clearPlanSelection();
}
// ------------------------------------------------------------------ roof sections
@@ -2324,12 +2420,14 @@ export class NfEditor extends LitElement {
// ------------------------------------------------------------------ floors and rooms
private addFloor(from: HassFloor | null = null, parent?: string): void {
const floor = newFloorFor(this._doc, from, { first: this.t("default_floor"), next: (n) => this.t("new_floor", { n }) }, parent ?? this.floor?.building_id);
if(!this.isAdmin)return;
const target=parent??(this._editorScope?.kind==="building"?this._editorScope.id:undefined);
if(this._doc.topology&&(!target||!this._doc.topology.buildings.some((g)=>g.id===target)))return;
const floor = newFloorFor(this._doc, from, { first: this.t("default_floor"), next: (n) => this.t("new_floor", { n }) }, target);
const next = structuredClone(this._doc);
next.floors = floorsWith(next.floors, floor);
this.setDoc(next);
this._floorId = floor.id;
this.sel.room = null;
this.adoptFloor(floor.id);
this.side.floorMenu = false;
this.fit();
}
@@ -2351,8 +2449,7 @@ export class NfEditor extends LitElement {
const next = structuredClone(this._doc);
next.floors = floorsWith(next.floors, copy);
this.setDoc(next);
this._floorId = copy.id;
this.sel.room = null;
this.adoptFloor(copy.id);
this.side.floorCopy = null;
this.fit();
}
@@ -2360,7 +2457,11 @@ export class NfEditor extends LitElement {
private moveFloor(direction: -1 | 1): void {
const id = this._floorId;
if (!id) return;
const order = floorsSwapped(this._doc.floors, id, direction);
const siblings = editorFloors(this._doc, this._editorScope);
const reordered = floorsSwapped(siblings, id, direction);
const ids = new Set(siblings.map((f) => f.id));
let at = 0;
const order = this._doc.floors.map((f) => ids.has(f.id) ? reordered[at++] : f);
if (order.every((f, i) => f.id === this._doc.floors[i].id)) return;
const next = structuredClone(this._doc);
next.floors = order.map((f) => next.floors.find((x) => x.id === f.id)!);
@@ -2370,15 +2471,11 @@ export class NfEditor extends LitElement {
private floorActions(): FloorActions {
return {
openFloor: (id) => {
this._floorId = id;
this.sel.room = null;
this.sel.corner = null;
this._draft = [];
this.adoptFloor(id);
this.fit();
},
print: () => this.printPlan(),
addFloor: (from) => this.addFloor(from),
addFloorIn: (id) => this.addFloor(null,id),
moveFloor: (direction) => this.moveFloor(direction),
deleteFloor: () => this.deleteFloor(),
duplicateFloor: (options) => this.duplicateFloor(options),
@@ -2393,8 +2490,8 @@ export class NfEditor extends LitElement {
private roomActions(room: Room): RoomActions {
return {
select: (id) => this.selectItem("room", id),
patch: (patch) => this.updateRoom(patch),
setArea: (id) => this.setArea(id),
patch: (patch) => { if(this.room?.id===room.id)this.updateRoom(patch); },
setArea: (id) => { if(this.room?.id===room.id)this.setArea(id); },
setRect: (field, value) => this.setRect(field, value),
setCorner: (index, axis, value) => this.setPoint(index, axis, value),
removeCorner: (index) => this.deleteVertex(index),
@@ -2725,7 +2822,7 @@ export class NfEditor extends LitElement {
}
private openEnergyDevice(floor: Floor, item: Furniture): void {
this._floorId = floor.id;
this.adoptFloor(floor.id);
this.roof.solarId = null;
this.selectItem("furniture", item.id);
this.showPoint(item.x, item.z);
@@ -3162,12 +3259,15 @@ export class NfEditor extends LitElement {
const floor = this.floor;
const walls = floor ? generateWalls(floor.rooms, { exterior: this._doc.settings.wall_exterior, interior: this._doc.settings.wall_interior }, floor.walls ?? []) : null;
return html`
${this.renderHierarchyDialogs()}
${renderPreview(this.host, this.lib.preview)}
${this._wallView
? html`<nf-wall-view .host=${this.host} .doc=${this._doc} .roomId=${this._wallView.roomId} .edge=${this._wallView.edge} @close=${() => (this._wallView = null)}></nf-wall-view>`
: nothing}
<div class="nf-editor ${this.narrow ? "nf-narrow" : ""}">
<div class="nf-main">
<div class="nf-editor-head">
${this.renderEditorNavigation()}
<div class="nf-toolbar">
${this.narrow
? html`<select class="nf-tool-select" aria-label=${this.t("tool_select")} ?disabled=${!floor} @change=${(e: Event) => {
@@ -3210,6 +3310,7 @@ export class NfEditor extends LitElement {
</div>
${walls?.warnings.length ? html`<span class="nf-warn">${this.t("overlap_warning")}</span>` : nothing}
</div>
</div>
<div class="nf-stage-pair ${this._split ? "nf-split" : ""}" style=${this._split && !this.narrow ? `--nf-split:${Math.round(this._splitRatio * 100)}%` : ""}>
<div class="nf-canvas-wrap">
${this.houseTool ? html`<div class="nf-tool-note">${this.t(this._tool === "energy" ? "energy_only_note" : "roof_only_note")}</div>` : nothing}
@@ -3228,7 +3329,7 @@ export class NfEditor extends LitElement {
${this.planLayers(floor, walls?.walls ?? null)}
</svg>
${this.renderContext()}
${this._pick || this._fixedHint ? html`<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : this.t("fixed_drag_hint")}</p>` : html`<div class="nf-hint">${hint(!floor ? this.t("hint_empty") : this.t(`hint_${this._tool}` as I18nKey))}</div>`}
${this._pick || this._fixedHint ? html`<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : this.t("fixed_drag_hint")}</p>` : html`<div class="nf-hint">${hint(!floor ? this._doc.topology ? "Wähle oben ein Gebäude und lege dort mit + Etage ein Stockwerk an. Ort, Niederlassung und Gebäude verwaltest du über Hierarchie." : this.t("hint_empty") : this.t(`hint_${this._tool}` as I18nKey))}</div>`}
<button class="nf-keys-open" title=${this.t("keys_title")} aria-label=${this.t("keys_title")} @click=${() => (this._keys = true)}>?</button>
${this.isAdmin
? renderTour((k, vars) => this.t(k, vars), this._tour, (step) => {
@@ -40,7 +40,8 @@ export function gridLayer(ctx: CanvasContext, size: { w: number; h: number }): L
/** The rooms of the floor below, faintly, as orientation; rooms below that rise through this floor are hatched – it stays open there. */
export function floorBelowLayer(ctx: CanvasContext): Layer {
const floors = ctx.host.doc.floors;
const current=ctx.host.doc.floors.find((f)=>f.id===ctx.floorId);
const floors = ctx.host.doc.topology?ctx.host.doc.floors.filter((f)=>current?.outdoor_location_id?f.outdoor_location_id===current.outdoor_location_id:!f.outdoor_location_id&&f.building_id===current?.building_id):ctx.host.doc.floors;
const at = floors.findIndex((f) => f.id === ctx.floorId);
const below = at > 0 ? floors[at - 1] : undefined;
if (!below) return nothing;
@@ -0,0 +1,44 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { emptyBuilding, newFloor } from "../../model.ts";
import { box } from "../../entities/fixtures.ts";
import { editorFloors, editorScopeChoices, editorScopeFromKey, moveSelectedFloor, reconcileEditorContext, selectEditorScope } from "./editor-context.ts";
import { newFloorFor } from "./ops/floors.ts";
function project(){
const b=emptyBuilding();b.topology={locations:[{id:"u",name:"Urbach"}],branches:[{id:"nl",name:"Zentrale",location_id:"u"}],buildings:[{id:"a",name:"RAS19",branch_id:"nl"},{id:"b",name:"RAS21",branch_id:"nl"},{id:"empty",name:"Neu",branch_id:"nl"}]};
b.floors=[{...newFloor("eg-a","EG",0),building_id:"a",rooms:[box("it",0,0,5,5,"symcon-category-100")]},{...newFloor("eg-b","EG",0),building_id:"b"}];return b;
}
test("choosing a building is pure navigation and exposes only its own storeys",()=>{
const b=project(),before=structuredClone(b),scope={kind:"building" as const,id:"b"};
assert.deepEqual(selectEditorScope(b,scope),{scope,floorId:"eg-b"});
assert.deepEqual(editorFloors(b,scope).map((f)=>f.id),["eg-b"]);assert.deepEqual(b,before);
});
test("an explicitly selected empty building stays empty across reloads, metadata edits and changes in another building",()=>{
const b=project(),context=selectEditorScope(b,{kind:"building",id:"empty"});
assert.equal(context.floorId,null);assert.deepEqual(reconcileEditorContext(b,context),context);
b.topology!.locations[0].name="Urbach neu";b.floors.push({...newFloor("og-a","OG",3),building_id:"a"});
assert.deepEqual(reconcileEditorContext(JSON.parse(JSON.stringify(b)),context),context);
assert.deepEqual(reconcileEditorContext(b,{...context,floorId:"eg-a"}),context,"a foreign floor never becomes the implicit edit target");
const added=newFloorFor(b,null,{first:"EG",next:(n)=>`Etage ${n}`},context.scope!.id);
assert.equal(added.building_id,"empty");assert.equal(added.elevation,0);
});
test("deleting the last storey keeps its building selected instead of jumping to another building",()=>{
const b=project(),context=selectEditorScope(b,{kind:"building",id:"b"});b.floors=b.floors.filter((f)=>f.id!=="eg-b");
assert.deepEqual(reconcileEditorContext(b,context),{scope:{kind:"building",id:"b"},floorId:null});
});
test("floor reparenting requires the exact captured floor to still be selected and preserves room/data IDs",()=>{
const b=project(),before=structuredClone(b);
assert.equal(moveSelectedFloor(b,"eg-b","eg-a","empty"),false);assert.deepEqual(b,before);
assert.equal(moveSelectedFloor(b,null,"eg-a","empty"),false);assert.deepEqual(b,before);
assert.equal(moveSelectedFloor(b,"eg-a","eg-a","missing"),false);assert.deepEqual(b,before);
assert.equal(moveSelectedFloor(b,"eg-a","eg-a","empty"),true);
assert.deepEqual(b.floors[0],{...before.floors[0],building_id:"empty"});assert.deepEqual(b.floors[1],before.floors[1]);
});
test("location outside plans are separate editor scopes and cannot be silently turned into storeys",()=>{
const b=project();b.floors.push({...newFloor("garden","Außen",0),outdoor_location_id:"u",building_id:null});
const scope={kind:"outside" as const,id:"u"};assert.deepEqual(editorFloors(b,scope).map((f)=>f.id),["garden"]);
assert.equal(moveSelectedFloor(b,"garden","garden","a"),false);
assert.deepEqual(editorScopeFromKey(b,"outside:u"),scope);assert.equal(editorScopeFromKey(b,"building:unknown"),null);
assert.deepEqual(editorScopeChoices(b),[["building:a","Urbach / Zentrale / RAS19"],["building:b","Urbach / Zentrale / RAS21"],["building:empty","Urbach / Zentrale / Neu"],["outside:u","Urbach / Außen"]]);
});
@@ -0,0 +1,48 @@
import type { Building, Floor } from "../../model.ts";
export interface EditorScope { kind: "building" | "outside"; id: string }
export interface EditorContext { scope: EditorScope | null; floorId: string | null }
export const editorScopeKey = (s: EditorScope | null): string => s ? `${s.kind}:${s.id}` : "";
export function scopeForFloor(f: Floor | undefined): EditorScope | null {
if(!f)return null;
return f.outdoor_location_id ? {kind:"outside",id:f.outdoor_location_id} : f.building_id ? {kind:"building",id:f.building_id} : null;
}
export function editorScopeExists(b: Building, s: EditorScope | null): boolean {
return !!s && !!b.topology && (s.kind === "building" ? b.topology.buildings.some((g)=>g.id===s.id) : b.topology.locations.some((l)=>l.id===s.id)&&b.floors.some((f)=>f.outdoor_location_id===s.id));
}
export function editorFloors(b: Building, s: EditorScope | null): Floor[] {
if (!b.topology) return b.floors;
if (!editorScopeExists(b,s)) return [];
return b.floors.filter((f)=>s!.kind==="outside"?f.outdoor_location_id===s!.id:!f.outdoor_location_id&&f.building_id===s!.id);
}
/** Navigation returns a context only: choosing a building never edits a floor's parent. */
export function selectEditorScope(b: Building, s: EditorScope): EditorContext {
return {scope:s,floorId:editorFloors(b,s)[0]?.id??null};
}
/** In particular an empty, explicitly selected building must never fall back to another building's first floor. */
export function reconcileEditorContext(b: Building, current: EditorContext): EditorContext {
if (!b.topology) return {scope:null,floorId:b.floors.some((f)=>f.id===current.floorId)?current.floorId:b.floors[0]?.id??null};
const scope = editorScopeExists(b,current.scope) ? current.scope : scopeForFloor(b.floors.find((f)=>f.id===current.floorId)??b.floors[0])
?? (b.topology.buildings[0]?{kind:"building" as const,id:b.topology.buildings[0].id}:null);
const floors=editorFloors(b,scope);
return {scope,floorId:floors.some((f)=>f.id===current.floorId)?current.floorId:floors[0]?.id??null};
}
export function editorScopeChoices(b: Building): [string,string][] {
const t=b.topology;if(!t)return [];
return [...t.buildings.map((g):[string,string]=>{
const branch=t.branches.find((n)=>n.id===g.branch_id),location=t.locations.find((l)=>l.id===branch?.location_id);
return [`building:${g.id}`,[location?.name,branch?.name,g.name].filter(Boolean).join(" / ")];
}),...t.locations.filter((l)=>b.floors.some((f)=>f.outdoor_location_id===l.id)).map((l):[string,string]=>[`outside:${l.id}`,`${l.name} / Außen`])];
}
export function editorScopeFromKey(b: Building, key: string): EditorScope | null {
const split=key.indexOf(":"),kind=key.slice(0,split),id=key.slice(split+1);
const s=kind==="building"||kind==="outside"?{kind,id} as EditorScope:null;
return editorScopeExists(b,s)?s:null;
}
/** Explicitly moves the captured, still-selected floor; stale dialogs cannot reassign another floor. */
export function moveSelectedFloor(b: Building, selectedFloorId: string|null, sourceFloorId: string, buildingId: string): boolean {
const f=b.floors.find((f)=>f.id===sourceFloorId);
if(selectedFloorId!==sourceFloorId||!f||f.outdoor_location_id||!b.topology?.buildings.some((g)=>g.id===buildingId)||f.building_id===buildingId)return false;
f.building_id=buildingId;return true;
}
@@ -13,13 +13,11 @@ import { formatArea } from "../../../units.ts";
import type { EditorHost } from "../host.ts";
import { freeHaFloors, linkableHaFloors, unplacedAreas } from "../ops/floors.ts";
import type { SideState } from "../side-state.ts";
import { renderFloorAssignment, renderTopologyForm } from "./topology.ts";
/** What the floor form makes the editor do. */
export interface FloorActions {
openFloor(id: string): void;
addFloor(from: HassFloor | null): void;
addFloorIn(buildingId: string): void;
moveFloor(direction: -1 | 1): void;
deleteFloor(): void;
/** Copies the open floor on top of the house, with what the choices take along. */
@@ -118,12 +116,11 @@ function utilityMeters(host: EditorHost, floor: Floor): TemplateResult {
function floorForm(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor): TemplateResult {
const t = host.t;
const update = (patch: Partial<Floor>) => host.change((_, f) => Object.assign(f, patch));
const update = (patch: Partial<Floor>) => { if(host.floor?.id===floor.id)host.change((_, f) => Object.assign(f, patch)); };
const links = linkableHaFloors(host.doc, floor, host.hass?.floors);
const lacking = unplacedAreas(host.doc, floor, host.hass?.areas);
const haChoices: [string, string][] = [["", t("no_ha_floor")], ...links.map((f): [string, string] => [f.floor_id, f.name])];
return html`<div class="nf-form">
${renderFloorAssignment(host)}
${textField(host, t("floor_name"), floor.name, (v) => update({ name: v }), { wide: true })}
${numberField(host, t("elevation"), floor.elevation, (v) => update({ elevation: v }))}
${host.admin ? shiftRow(host, state, floorActions, floor) : nothing}
@@ -153,8 +150,7 @@ function floorForm(host: EditorHost, state: SideState, floorActions: FloorAction
/** The "Floors" section of the side panel. */
export function renderFloors(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor | undefined, selectedId: string | null): TemplateResult {
return html`<section>
<h3>${host.t("floors")}</h3>
${isSymcon(host.hass)||host.doc.topology?renderTopologyForm(host,floorActions):nothing}
${floorChips(host, state, floorActions, selectedId)} ${floor ? floorForm(host, state, floorActions, floor) : nothing}
<h3>${host.doc.topology&&floor?`${host.t("floor")} · ${floor.name}`:host.t("floors")}</h3>
${host.doc.topology?nothing:floorChips(host, state, floorActions, selectedId)} ${floor ? floorForm(host, state, floorActions, floor) : nothing}
</section>`;
}
+8 -2
View File
@@ -16,6 +16,7 @@ import { countsAsLiving, roomArea } from "../../../geometry/living-area.ts";
import { roomSpeaker } from "../../../live/announce.ts";
import { isSymcon } from "../../../entities/symcon-values.ts";
import { renderSymconRoomMeters } from "../symcon-fields.ts";
import { floorTopologyPath } from "../../../topology.ts";
/** What the room form makes the editor do, and the parts of it that the editor still draws itself. */
export interface RoomActions {
@@ -46,7 +47,10 @@ export function renderRoomList(host: EditorHost, floor: Floor, actions: Pick<Roo
return html`<section>
<h3>${host.t("rooms")}</h3>
<div class="nf-room-list">
${floor.rooms.map(
${isSymcon(host.hass)?[...new Set(floor.rooms.map((r)=>r.area_id??""))].map((id)=>html`<div class="nf-room-area-group" data-area-id=${id}>
<h4>${id?areaLeafName(host.hass,id)||host.hass?.areas?.[id]?.name||"Verknüpfter Bereich":"Ohne verknüpften Bereich"}</h4>
${floor.rooms.filter((r)=>(r.area_id??"")===id).map((room)=>html`<button class="nf-row" @click=${()=>actions.select(room.id)}><span>${room.name}</span><span class="nf-muted">${formatArea(host.hass,polygonArea(room.points))}</span></button>`)}
</div>`):floor.rooms.map(
(room) => html`<button class="nf-row" @click=${() => actions.select(room.id)}>
<span>${room.name}</span><span class="nf-muted">${formatArea(host.hass, polygonArea(room.points))}</span>
</button>`,
@@ -159,9 +163,11 @@ export function renderRoomForm(host: EditorHost, state: SideState, room: Room, a
html`<button class="nf-btn" @click=${() => actions.applyPackage(pkg)}><b>${t(`pkg_${pkg}` as I18nKey)}</b><span>${t(`pkg_${pkg}_desc` as I18nKey)}</span></button>`;
return html`<section>
<div class="nf-h3row"><h3>${t("room")}</h3>${actions.lockButton}</div>
${host.doc.topology&&host.floor?html`<div class="nf-room-context" title=${floorTopologyPath(host.doc,host.floor)}>${floorTopologyPath(host.doc,host.floor)}</div>`:nothing}
<div class="nf-form">
${textField(host, t("room_name"), room.name, (v) => actions.patch({ name: v }), { wide: true })}
${selectField(host, t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })}
${selectField(host, isSymcon(host.hass)?"Bereich (Symcon)":t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })}
${isSymcon(host.hass)?hint("Der Raum gehört zur oben gewählten Etage und damit zu deren Gebäude. Hier verknüpfst du seine Symcon-Bereichskategorie. Mehrere Räume derselben Etage können dieselbe Kategorie verwenden. Der Objektbaum und der Raumname werden dadurch nicht verändert.","nf-wide"):nothing}
${isSymcon(host.hass) && room.area_id ? html`<button type="button" class="nf-btn nf-wide nf-take-area-name" ?disabled=${!host.admin || !areaLeafName(host.hass, room.area_id)} @click=${() => actions.patch({ name: areaLeafName(host.hass, room.area_id!) })}>Bereichsnamen übernehmen</button>` : nothing}
${(room.sub_areas ?? []).map((a) => html`<span class="nf-chip nf-wide">${host.hass?.areas?.[a]?.name ?? a} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} title=${t("delete")} @click=${() => actions.patch({ sub_areas: (room.sub_areas ?? []).filter((x) => x !== a).length ? (room.sub_areas ?? []).filter((x) => x !== a) : null })}>✕</button></span>`)}
${room.area_id
@@ -1,45 +0,0 @@
import { html, nothing } from "lit";
import { uid } from "../../../model.ts";
import { addLocationOutside, enableTopology, floorTopologyPath } from "../../../topology.ts";
import { hint, selectField, textField } from "../fields.ts";
import type { EditorHost } from "../host.ts";
import type { FloorActions } from "./floor.ts";
export function renderTopologyForm(host:EditorHost,actions:FloorActions) {
const t=host.doc.topology;
const edit=(fn:(next:NonNullable<typeof t>)=>void)=>{
const b=structuredClone(host.doc);fn(b.topology!);host.replace(b);
};
if(!t)return html`<button class="nf-btn nf-topology-enable" ?disabled=${!host.admin} @click=${()=>{const b=structuredClone(host.doc);enableTopology(b,host.hass?.symconTitle?.trim()||"Gebäude 1");host.replace(b);}}>Ort / Niederlassung / Gebäude einrichten</button>`;
return html`<details class="nf-topology-form"><summary>Orte, Niederlassungen und Gebäude</summary>
${hint("Die Topologie lautet Ort / Niederlassung / Gebäude / Stockwerk / Raum. Bestehende Stockwerke behalten beim Zuordnen ihre Geometrie, Datenpunkte und Freigaben. Unter jedem Ort kann ein eigener Außenplan angelegt werden. Leere Gruppen lassen sich entfernen. Stockwerke ordnest du im Feld Zuordnung zu.")}
${t.locations.map((l)=>html`<details class="nf-topology-location" data-location=${l.id}><summary>${l.name}</summary><div class="nf-form">
${textField(host,"Ort",l.name,(name)=>edit((n)=>{n.locations.find((s)=>s.id===l.id)!.name=name;}),{wide:true,maxlength:100})}
${t.branches.filter((n)=>n.location_id===l.id).map((n)=>html`<details class="nf-wide nf-topology-branch" data-branch=${n.id}><summary>${n.name}</summary><div class="nf-form">
${textField(host,"Niederlassung",n.name,(name)=>edit((p)=>{p.branches.find((s)=>s.id===n.id)!.name=name;}),{wide:true,maxlength:100})}
${selectField(host,"Ort der Niederlassung",n.location_id,t.locations.map((s)=>[s.id,s.name]),(location_id)=>edit((p)=>{p.branches.find((s)=>s.id===n.id)!.location_id=location_id;}),{wide:true})}
${t.buildings.filter((g)=>g.branch_id===n.id).map((g)=>html`<details class="nf-wide nf-topology-building" data-building=${g.id}><summary>${g.name}</summary><div class="nf-form">
${textField(host,"Gebäude",g.name,(name)=>edit((p)=>{p.buildings.find((s)=>s.id===g.id)!.name=name;}),{wide:true,maxlength:100})}
${selectField(host,"Niederlassung des Gebäudes",g.branch_id,t.branches.map((s)=>[s.id,`${t.locations.find((l)=>l.id===s.location_id)?.name??""} / ${s.name}`]),(branch_id)=>edit((p)=>{p.buildings.find((s)=>s.id===g.id)!.branch_id=branch_id;}),{wide:true})}
<button class="nf-btn nf-topology-open-building" @click=${()=>{const f=host.doc.floors.find((f)=>f.building_id===g.id&&!f.outdoor_location_id);if(f)actions.openFloor(f.id);else if(host.admin)actions.addFloorIn(g.id);}}>Stockwerke öffnen</button>
<button class="nf-btn nf-topology-add-floor" ?disabled=${!host.admin} @click=${()=>actions.addFloorIn(g.id)}>+ Stockwerk</button>
<button class="nf-link nf-wide" ?disabled=${!host.admin||host.doc.floors.some((f)=>f.building_id===g.id)} @click=${()=>edit((p)=>{p.buildings=p.buildings.filter((s)=>s.id!==g.id);})}>Gebäude entfernen</button>
</div></details>`)}
<button class="nf-btn nf-topology-add-building" ?disabled=${!host.admin} @click=${()=>edit((p)=>{p.buildings.push({id:uid("building"),name:`Gebäude ${p.buildings.length+1}`,branch_id:n.id});})}>+ Gebäude</button>
<button class="nf-link" ?disabled=${!host.admin||t.buildings.some((g)=>g.branch_id===n.id)} @click=${()=>edit((p)=>{p.branches=p.branches.filter((s)=>s.id!==n.id);})}>Niederlassung entfernen</button>
</div></details>`)}
<button class="nf-btn nf-topology-add-branch" ?disabled=${!host.admin} @click=${()=>edit((p)=>{p.branches.push({id:uid("branch"),name:`Niederlassung ${p.branches.length+1}`,location_id:l.id});})}>+ Niederlassung</button>
<button class="nf-btn nf-topology-outside" ?disabled=${!host.admin} @click=${()=>{const b=structuredClone(host.doc),f=addLocationOutside(b,l.id);host.replace(b);actions.openFloor(f.id);}}>🌳 ${host.doc.floors.some((f)=>f.outdoor_location_id===l.id)?"Außen bearbeiten":"Außen anlegen"}</button>
<button class="nf-link" ?disabled=${!host.admin||t.branches.some((n)=>n.location_id===l.id)||host.doc.floors.some((f)=>f.outdoor_location_id===l.id)} @click=${()=>edit((p)=>{p.locations=p.locations.filter((s)=>s.id!==l.id);})}>Ort entfernen</button>
</div></details>`)}
<button class="nf-btn nf-topology-add-location" ?disabled=${!host.admin} @click=${()=>edit((p)=>{p.locations.push({id:uid("location"),name:`Ort ${p.locations.length+1}`});})}>+ Ort</button>
</details>`;
}
export function renderFloorAssignment(host:EditorHost) {
const t=host.doc.topology,f=host.floor;if(!t||!f)return nothing;
const options:[string,string][]=[...t.buildings.map((g):[string,string]=>{const n=t.branches.find((n)=>n.id===g.branch_id);return [g.id,`${t.locations.find((l)=>l.id===n?.location_id)?.name??""} / ${n?.name??""} / ${g.name}`];}),...t.locations.map((l):[string,string]=>[`outside:${l.id}`,`${l.name} / Außen`])];
return html`${selectField(host,"Zuordnung",f.outdoor_location_id?`outside:${f.outdoor_location_id}`:f.building_id??"",options,(id)=>host.change((_,floor)=>{
floor.outdoor_location_id=id.startsWith("outside:")?id.slice(8):null;floor.building_id=floor.outdoor_location_id?null:id;
}),{wide:true})}<span class="nf-sub nf-wide nf-topology-path" title=${floorTopologyPath(host.doc,f)}>${floorTopologyPath(host.doc,f)}</span>`;
}
@@ -0,0 +1,75 @@
import { css, html, LitElement, nothing, type PropertyValues } from "lit";
import { uid, type Building, type PlanTopology } from "../../model.ts";
import { addLocationOutside, enableTopology } from "../../topology.ts";
import { tokens } from "../../styles.ts";
import { hint } from "./fields.ts";
import type { EditorScope } from "./editor-context.ts";
/** Metadata only. Picking a row never reassigns floors or creates a storey. */
class HierarchyManager extends LitElement {
static properties = { doc:{attribute:false}, admin:{type:Boolean}, suggestedName:{attribute:false},
locationId:{state:true}, branchId:{state:true}, buildingId:{state:true} };
declare doc: Building;
declare admin: boolean;
declare suggestedName: string;
private declare locationId: string;
private declare branchId: string;
private declare buildingId: string;
constructor(){super();this.admin=false;this.suggestedName="Gebäude 1";this.locationId="";this.branchId="";this.buildingId="";}
protected willUpdate(_changed:PropertyValues){
const t=this.doc?.topology;if(!t)return;
if(!t.locations.some((l)=>l.id===this.locationId))this.locationId=t.locations[0]?.id??"";
const branches=t.branches.filter((n)=>n.location_id===this.locationId);
if(!branches.some((n)=>n.id===this.branchId))this.branchId=branches[0]?.id??"";
const buildings=t.buildings.filter((g)=>g.branch_id===this.branchId);
if(!buildings.some((g)=>g.id===this.buildingId))this.buildingId=buildings[0]?.id??"";
}
private edit(change:(b:Building,t:PlanTopology)=>void){
if(!this.admin||!this.doc?.topology)return;
const next=structuredClone(this.doc);change(next,next.topology!);this.publish(next);
}
private publish(next:Building){this.doc=next;this.dispatchEvent(new CustomEvent("hierarchy-change",{detail:{building:next},bubbles:true,composed:true}));}
private open(scope:EditorScope){this.dispatchEvent(new CustomEvent("hierarchy-open",{detail:scope,bubbles:true,composed:true}));}
private name(label:string,value:string,save:(name:string)=>void){
return html`<label>${label}<input maxlength="100" .value=${value} ?disabled=${!this.admin} @change=${(e:Event)=>save((e.target as HTMLInputElement).value.trim())}/></label>`;
}
render(){
const t=this.doc?.topology;
if(!t)return html`<div class="setup">${hint("Vorhandene Etagen werden einem ersten Ort, einer Niederlassung und einem Gebäude zugeordnet. Geometrie, Raumverknüpfungen und Benutzerrechte bleiben erhalten.")}
<button class="setup-button" ?disabled=${!this.admin} @click=${()=>{const b=structuredClone(this.doc);enableTopology(b,this.suggestedName);this.publish(b);}}>Hierarchie einrichten</button></div>`;
const l=t.locations.find((l)=>l.id===this.locationId),n=t.branches.find((n)=>n.id===this.branchId),g=t.buildings.find((g)=>g.id===this.buildingId);
return html`<div class="help">${hint("Hier pflegst du Ort, Niederlassung und Gebäude. Die Listen wechseln nur die Auswahl. Etagen legst du anschließend oben im Editor im gewählten Gebäude an. Räume und ihre Symcon-Bereichskategorie bearbeitest du rechts auf der ausgewählten Etage.")}</div>
<div class="columns">
<section aria-label="Orte"><h3>Orte</h3><div class="items">${t.locations.map((s)=>html`<button class="pick" data-location=${s.id} aria-pressed=${s.id===this.locationId} @click=${()=>{this.locationId=s.id;this.branchId="";this.buildingId="";}}>${s.name}</button>`)}</div>
<button class="add-location" ?disabled=${!this.admin} @click=${()=>{const id=uid("location");this.edit((_,p)=>p.locations.push({id,name:`Ort ${p.locations.length+1}`}));this.locationId=id;this.branchId="";this.buildingId="";}}>+ Ort</button>
${l?html`<div class="details">${this.name("Name des Ortes",l.name,(name)=>{if(this.locationId===l.id)this.edit((_,p)=>{p.locations.find((s)=>s.id===l.id)!.name=name;});})}
<button class="outside" ?disabled=${!this.admin&&!this.doc.floors.some((f)=>f.outdoor_location_id===l.id)} @click=${()=>{
if(!this.doc.floors.some((f)=>f.outdoor_location_id===l.id))this.edit((b)=>{addLocationOutside(b,l.id);});
this.open({kind:"outside",id:l.id});
}}>🌳 ${this.doc.floors.some((f)=>f.outdoor_location_id===l.id)?"Außenplan öffnen":"Außenplan anlegen"}</button>
<button class="delete" ?disabled=${!this.admin||t.branches.some((s)=>s.location_id===l.id)||this.doc.floors.some((f)=>f.outdoor_location_id===l.id)} @click=${()=>this.edit((_,p)=>{p.locations=p.locations.filter((s)=>s.id!==l.id);})}>Ort entfernen</button>
</div>`:nothing}
</section>
<section aria-label="Niederlassungen"><h3>Niederlassungen</h3><div class="items">${t.branches.filter((s)=>s.location_id===this.locationId).map((s)=>html`<button class="pick" data-branch=${s.id} aria-pressed=${s.id===this.branchId} @click=${()=>{this.branchId=s.id;this.buildingId="";}}>${s.name}</button>`)}</div>
<button class="add-branch" ?disabled=${!this.admin||!l} @click=${()=>{if(!l)return;const id=uid("branch");this.edit((_,p)=>p.branches.push({id,name:`Niederlassung ${p.branches.length+1}`,location_id:l.id}));this.branchId=id;this.buildingId="";}}>+ Niederlassung</button>
${n?html`<div class="details">${this.name("Name der Niederlassung",n.name,(name)=>{if(this.branchId===n.id)this.edit((_,p)=>{p.branches.find((s)=>s.id===n.id)!.name=name;});})}
<label>Ort der Niederlassung<select ?disabled=${!this.admin} .value=${n.location_id} @change=${(e:Event)=>{const id=(e.target as HTMLSelectElement).value;if(this.branchId!==n.id||!t.locations.some((l)=>l.id===id))return;this.edit((_,p)=>{p.branches.find((s)=>s.id===n.id)!.location_id=id;});this.locationId=id;}}>${t.locations.map((l)=>html`<option value=${l.id} .selected=${l.id===n.location_id}>${l.name}</option>`)}</select></label>
<button class="delete" ?disabled=${!this.admin||t.buildings.some((s)=>s.branch_id===n.id)} @click=${()=>this.edit((_,p)=>{p.branches=p.branches.filter((s)=>s.id!==n.id);})}>Niederlassung entfernen</button>
</div>`:nothing}
</section>
<section aria-label="Gebäude"><h3>Gebäude</h3><div class="items">${t.buildings.filter((s)=>s.branch_id===this.branchId).map((s)=>html`<button class="pick" data-building=${s.id} aria-pressed=${s.id===this.buildingId} @click=${()=>this.buildingId=s.id}>${s.name}<small>${this.doc.floors.filter((f)=>!f.outdoor_location_id&&f.building_id===s.id).length} Etagen</small></button>`)}</div>
<button class="add-building" ?disabled=${!this.admin||!n} @click=${()=>{if(!n)return;const id=uid("building");this.edit((_,p)=>p.buildings.push({id,name:`Gebäude ${p.buildings.length+1}`,branch_id:n.id}));this.buildingId=id;}}>+ Gebäude</button>
${g?html`<div class="details">${this.name("Name des Gebäudes",g.name,(name)=>{if(this.buildingId===g.id)this.edit((_,p)=>{p.buildings.find((s)=>s.id===g.id)!.name=name;});})}
<label>Niederlassung des Gebäudes<select ?disabled=${!this.admin} .value=${g.branch_id} @change=${(e:Event)=>{const id=(e.target as HTMLSelectElement).value,branch=t.branches.find((s)=>s.id===id);if(this.buildingId!==g.id||!branch)return;this.edit((_,p)=>{p.buildings.find((s)=>s.id===g.id)!.branch_id=id;});this.branchId=id;this.locationId=branch.location_id;}}>${t.branches.map((s)=>html`<option value=${s.id} .selected=${s.id===g.branch_id}>${t.locations.find((l)=>l.id===s.location_id)?.name} / ${s.name}</option>`)}</select></label>
<button class="open-building primary" @click=${()=>this.open({kind:"building",id:g.id})}>Im Editor auswählen</button>
<button class="delete" ?disabled=${!this.admin||this.doc.floors.some((f)=>f.building_id===g.id)} @click=${()=>this.edit((_,p)=>{p.buildings=p.buildings.filter((s)=>s.id!==g.id);})}>Gebäude entfernen</button>
</div>`:nothing}
</section>
</div>`;
}
static styles=[tokens,css`
:host{display:block;font:13px/1.4 system-ui;color:var(--nf-text)}button,input,select{box-sizing:border-box;font:inherit;color:inherit;background:var(--nf-fill,#ffffff08);border:1px solid var(--nf-line);border-radius:8px;padding:8px 10px;min-width:0}button{cursor:pointer}button:disabled,input:disabled,select:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}.columns{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}.help{margin-bottom:8px}section{min-width:0;border:1px solid var(--nf-line);border-radius:12px;padding:12px}h3{font-size:14px;margin:0 0 10px}.items{display:grid;align-content:start;gap:5px;min-height:100px;max-height:240px;overflow:auto;margin-bottom:10px}.pick{text-align:left;display:flex;justify-content:space-between;gap:8px;overflow-wrap:anywhere}.pick[aria-pressed=true]{border-color:var(--nf-accent);background:color-mix(in srgb,var(--nf-accent) 15%,transparent)}small{white-space:nowrap;color:var(--nf-muted)}.details{display:grid;gap:10px;margin-top:18px;padding-top:12px;border-top:1px solid var(--nf-line)}label{display:grid;gap:5px;font-size:12px;color:var(--nf-muted)}input,select{width:100%;color:var(--nf-text)}.delete{color:var(--nf-muted)}.primary{border-color:var(--nf-accent)}.setup{display:flex;gap:10px;align-items:center}@media(max-width:720px){.columns{grid-template-columns:1fr}.items{min-height:0;max-height:140px}.details{margin-top:10px}section{padding:10px}}
`];
}
if(!customElements.get("nf-hierarchy-manager"))customElements.define("nf-hierarchy-manager",HierarchyManager);
+10
View File
@@ -2,6 +2,16 @@ import { css } from "lit";
/** The editor's own styles: the plan canvas, the side panel with its forms and libraries, the 3D pane and the phone layout. */
export const editorStyles = css`
.nf-editor-context{display:grid;gap:8px;padding:10px 12px;border-bottom:1px solid var(--nf-line)}
.nf-editor-building-row,.nf-editor-floor-nav{display:flex;gap:8px;align-items:center;flex-wrap:wrap;min-width:0}
.nf-editor-building-row>label{display:flex;gap:8px;align-items:center;font-size:12px;min-width:0;flex:1}
.nf-editor-building-select{font:inherit;color:var(--nf-text);background:var(--nf-chrome-solid);border:1px solid var(--nf-line);border-radius:8px;padding:7px 10px;min-width:0;width:min(100%,480px)}
.nf-editor-floor-nav{font-size:12px}.nf-editor-floor-nav .nf-editor-move-floor{margin-left:auto;font-size:11px}
.nf-hierarchy-dialog,.nf-floor-move-dialog{box-sizing:border-box;width:min(1050px,calc(100vw - 24px));max-height:calc(100dvh - 24px);overflow:auto;padding:18px;border:1px solid var(--nf-line);border-radius:14px;color:var(--nf-text);background:var(--nf-chrome-solid,#1c1c1c);box-shadow:0 20px 70px #0008;font:13px/1.4 system-ui}
.nf-hierarchy-dialog::backdrop,.nf-floor-move-dialog::backdrop{background:#050b16a6;backdrop-filter:blur(3px)}
.nf-hierarchy-dialog>header,.nf-floor-move-dialog>header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px}.nf-hierarchy-dialog h2,.nf-floor-move-dialog h2{font-size:17px;margin:0}
.nf-floor-move-dialog{width:min(650px,calc(100vw - 24px))}.nf-floor-move-source{overflow-wrap:anywhere}.nf-floor-move-dialog>.nf-btn{margin-top:16px}
.nf-room-area-group h4{font-size:11px;color:var(--nf-muted);margin:12px 0 4px}.nf-room-context{font-size:11px;color:var(--nf-muted);margin:4px 0 12px;overflow-wrap:anywhere}
.nf-value-links h4 { margin: 12px 0; }
.nf-value-add { min-width: 30px; font-size: 18px; padding: 3px 8px; }
.nf-value-link { padding: 8px 0; border-bottom: 1px solid var(--nf-line); }
+131
View File
@@ -0,0 +1,131 @@
// Regression coverage for the editor workflow: metadata separately, navigation without writes,
// storeys created inside the selected building, native category links and explicit storey moves.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { extname, join, relative, resolve } from "node:path";
import puppeteer from "puppeteer-core";
const root = resolve(import.meta.dirname, ".."), out = join(root, "preview/screenshots");
mkdirSync(out, { recursive: true });
const server = createServer((req, res) => {
const file = resolve(root, `.${decodeURIComponent(new URL(req.url, "http://localhost").pathname)}`);
if (relative(root, file).startsWith("..") || !existsSync(file)) return res.writeHead(404).end();
res.writeHead(200, { "content-type": ({ ".html": "text/html", ".js": "text/javascript", ".json": "application/json" })[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file));
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
let browser;
try {
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
const page = await browser.newPage(), errors = [];
page.on("pageerror", (e) => errors.push(String(e)));
await page.setViewport({ width: 1440, height: 1000 });
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html?noshowcase`, { waitUntil: "networkidle0" });
await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length);
await page.evaluate(async () => {
const p = window.nfPanel, b = structuredClone(p.data.building), base = b.floors[0];
const room = (id, name, area_id) => ({ id, name, area_id, points: [[0, 0], [6, 0], [6, 5], [0, 5]], floor_material: "wood" });
const floor = (id, building_id, rooms) => ({ ...structuredClone(base), id, name: "EG", building_id, rooms, elevation: 0, openings: [], furniture: [], placements: [], outdoor: [], walls: [], notes: [], background: null, utility_meters: null, power_entity: null, start_view: null });
b.topology = { locations: [{ id: "u", name: "Urbach" }], branches: [{ id: "nl", name: "Zentrale", location_id: "u" }], buildings: [{ id: "a", name: "RAS19", branch_id: "nl" }, { id: "b", name: "RAS21", branch_id: "nl" }, { id: "empty", name: "Neubau", branch_id: "nl" }] };
b.floors = [floor("eg-a", "a", [room("it-a", "IT", "symcon-category-100")]), floor("eg-b", "b", [room("it-b", "Büro", "symcon-category-200")])];
b.settings.roof.type = "none"; b.settings.lock_plan = false; b.settings.start_view = null;
window.editorProject = structuredClone(b);
p.data.edit(b);
p.hass = { ...p.hass, language: "de", symconObjects: [], symconTitle: "Standorte", floors: {}, areas: { "symcon-category-100": { area_id: "symcon-category-100", name: "Urbach / RAS19 / EG / IT" }, "symcon-category-200": { area_id: "symcon-category-200", name: "Urbach / RAS21 / EG / Technik" } }, states: {}, user: { ...p.hass.user, is_admin: true } };
await p.updateComplete;
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click();
});
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot.querySelector(".nf-editor-building-select"));
await page.evaluate(() => {
window.e = window.nfPanel.shadowRoot.querySelector("nf-editor");
window.settle = async () => { await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete; };
window.pickBuilding = async (id) => { const s = e.shadowRoot.querySelector(".nf-editor-building-select"); s.value = `building:${id}`; s.dispatchEvent(new Event("change", { bubbles: true })); await settle(); };
window.manager = () => e.shadowRoot.querySelector("nf-hierarchy-manager");
window.writes = 0; e.addEventListener("building-changed", () => window.writes++);
});
const initial = await page.evaluate(() => JSON.stringify(e._doc.floors));
await page.evaluate(async () => { await pickBuilding("b"); e.moveFloor(-1); await settle(); await pickBuilding("empty"); });
assert.deepEqual(await page.evaluate(() => ({ floor: e._floorId, scope: e._editorScope.id, chips: e.shadowRoot.querySelectorAll("[data-editor-floor]").length, writes })), { floor: null, scope: "empty", chips: 0, writes: 0 });
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), initial, "building selection must not change or save floor assignments");
await page.evaluate(async () => { const b = structuredClone(e._doc); b.topology.locations[0].name = "Urbach neu"; const p = window.nfPanel; p.data.building = b; p.requestUpdate(); await settle(); });
assert.equal(await page.evaluate(() => e._floorId), null, "empty selection must survive a data refresh");
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-editor-add-floor").click(); await settle(); window.addedFloor = e._floorId; });
assert.deepEqual(await page.evaluate(() => ({ parent: e.floor.building_id, elevation: e.floor.elevation })), { parent: "empty", elevation: 0 });
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors.filter((f) => f.id !== window.addedFloor))), initial);
// Native category selection remains a property of the selected room, never a building assignment.
await page.evaluate(async () => { await pickBuilding("a"); e.shadowRoot.querySelector(".nf-room-list .nf-row").click(); await settle(); window.oldRoomActions = e.roomActions(e.room); });
assert.match(await page.evaluate(() => e.shadowRoot.querySelector(".nf-room-context").textContent), /Urbach neu \/ Zentrale \/ RAS19 \/ EG/);
assert.equal(await page.evaluate(() => !!e.shadowRoot.querySelector("aside nf-hierarchy-manager, aside .nf-topology-form")), false);
await page.evaluate(async () => {
const label = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((l) => l.textContent.trim().startsWith("Bereich (Symcon)"));
const s = label.querySelector("select"); s.value = "symcon-category-200"; s.dispatchEvent(new Event("change", { bubbles: true })); await settle();
});
assert.deepEqual(await page.evaluate(() => [e.room.name, e.room.area_id, e.floor.building_id]), ["IT", "symcon-category-200", "a"]);
await page.screenshot({ path: join(out, "symcon-editor-building.png") });
await page.evaluate(async () => { await pickBuilding("b"); window.beforeStale = JSON.stringify(e._doc); oldRoomActions.setArea("symcon-category-100"); oldRoomActions.patch({ name: "WRONG ROOM" }); await settle(); });
assert.equal(await page.evaluate(() => JSON.stringify(e._doc)), await page.evaluate(() => window.beforeStale), "stale room form must not mutate a room in a different building");
assert.equal(await page.evaluate(() => e.sel.room), null);
// A separate move dialog names and captures the selected floor; picking a target has no side effects.
await page.evaluate(async () => { await pickBuilding("a"); e.shadowRoot.querySelector(".nf-editor-move-floor").click(); await settle(); });
await page.waitForFunction(() => e.shadowRoot.querySelector(".nf-floor-move-dialog").open);
const beforeMove = await page.evaluate(() => JSON.stringify(e._doc.floors));
await page.evaluate(async () => { const s = e.shadowRoot.querySelector(".nf-floor-move-target"); s.value = "b"; s.dispatchEvent(new Event("change", { bubbles: true })); await settle(); });
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMove);
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-floor-move-dialog header button").click(); await settle(); });
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMove);
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-editor-move-floor").click(); await settle(); const s = e.shadowRoot.querySelector(".nf-floor-move-target"); s.value = "b"; s.dispatchEvent(new Event("change", { bubbles: true })); await settle(); e.shadowRoot.querySelector(".nf-floor-move-apply").click(); await settle(); });
const expectedMove = JSON.parse(beforeMove); expectedMove.find((f) => f.id === "eg-a").building_id = "b";
assert.deepEqual(await page.evaluate(() => e._doc.floors), expectedMove);
assert.deepEqual(await page.evaluate(() => [e._editorScope.id, e._floorId]), ["b", "eg-a"]);
// Metadata creation is isolated from storey creation, even when opening a new empty building.
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); });
assert.equal(await page.evaluate(() => e.shadowRoot.querySelector(".nf-hierarchy-dialog").open), true);
const beforeMetadata = await page.evaluate(() => JSON.stringify(e._doc.floors));
await page.evaluate(async () => {
const click = async (sel) => { manager().shadowRoot.querySelector(sel).click(); await manager().updateComplete; await settle(); await manager().updateComplete; };
const rename = async (label, value) => { const input = [...manager().shadowRoot.querySelectorAll("label")].find((l) => l.textContent.startsWith(label)).querySelector("input"); input.value = value; input.dispatchEvent(new Event("change", { bubbles: true })); await settle(); await manager().updateComplete; };
window.beforePickWrites = writes;
await click('[data-building="empty"]'); await click('[data-building="b"]');
if (writes !== beforePickWrites) throw new Error("Metadata selection must not write the plan");
await click(".add-location"); await rename("Name des Ortes", "Stuttgart");
await click(".add-branch"); await rename("Name der Niederlassung", "Werk");
await click(".add-building"); await rename("Name des Gebäudes", "Halle 2");
window.newMetadataBuilding = manager().buildingId;
});
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMetadata);
await page.screenshot({ path: join(out, "symcon-editor-hierarchy.png") });
await page.evaluate(async () => { manager().shadowRoot.querySelector(".open-building").click(); await settle(); });
assert.deepEqual(await page.evaluate(() => [e._editorScope.id, e._floorId, e.shadowRoot.querySelector(".nf-hierarchy-dialog").open]), [await page.evaluate(() => window.newMetadataBuilding), null, false]);
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMetadata);
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-editor-add-floor").click(); await settle(); });
assert.equal(await page.evaluate(() => e.floor.building_id), await page.evaluate(() => window.newMetadataBuilding));
// Each location's outdoor plan is an explicit action, outside any building's storeys.
await page.evaluate(async () => {
const locations = e._doc.topology.locations.map((l) => l.id);
for (const id of locations) { e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); manager().shadowRoot.querySelector(`[data-location="${id}"]`).click(); await manager().updateComplete; manager().shadowRoot.querySelector(".outside").click(); await settle(); }
});
assert.equal(await page.evaluate(() => new Set(e._doc.floors.filter((f) => f.outdoor_location_id).map((f) => f.outdoor_location_id)).size), 2);
assert.equal(await page.evaluate(() => !!e.shadowRoot.querySelector(".nf-editor-add-floor")), false, "outdoor plans do not add indoor storeys");
await page.setViewport({ width: 390, height: 844 });
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); });
assert.ok(await page.evaluate(() => { const d = e.shadowRoot.querySelector(".nf-hierarchy-dialog"), r = d.getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth && r.height <= innerHeight && d.scrollWidth <= d.clientWidth; }), "hierarchy dialog must fit a phone without horizontal scrolling");
await page.screenshot({ path: join(out, "symcon-editor-hierarchy-mobile.png") });
// Legacy setup is explicit and preserves stable IDs, geometry and native category links.
await page.evaluate(async () => {
e.shadowRoot.querySelector(".nf-hierarchy-dialog").close(); const p = window.nfPanel, b = structuredClone(window.editorProject); delete b.topology; for (const f of b.floors) delete f.building_id; window.legacyFloors = structuredClone(b.floors); p.data.edit(b); await settle();
e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); manager().shadowRoot.querySelector(".setup-button").click(); await settle();
});
assert.deepEqual(await page.evaluate(() => e._doc.floors.map(({ building_id, ...f }) => f)), await page.evaluate(() => window.legacyFloors));
assert.equal(await page.evaluate(() => new Set(e._doc.floors.map((f) => f.building_id)).size), 1);
assert.deepEqual(errors, []);
console.log("OK: separate hierarchy dialog, pure building navigation and refresh, selected-building storeys, native room category links, stale form guards, explicit/cancelled floor moves, metadata without implicit storeys, per-location outdoors, legacy migration and mobile layout");
} finally {
await browser?.close(); await new Promise((done) => server.close(done));
}
+1 -22
View File
@@ -83,27 +83,6 @@ try{
assert.deepEqual(await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").outside),["sensor.903"],"legacy outdoor pins stay within their location even without a dedicated outdoor floor");
await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").dispatchEvent(new CustomEvent("close",{bubbles:true,composed:true})));
// Enable/rename/reparent/add through the actual editor form; legacy IDs and room links remain intact.
await page.evaluate(async()=>{const p=window.nfPanel,b=structuredClone(window.topologyProject);delete b.topology;b.floors=b.floors.slice(0,2);for(const f of b.floors){delete f.building_id;delete f.outdoor_location_id;}p.data.edit(b);await p.updateComplete;[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b)=>b.textContent.includes("Editor")).click();});
await page.waitForFunction(()=>window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot.querySelector(".nf-topology-enable"));
await page.evaluate(async()=>{
const p=window.nfPanel,e=p.shadowRoot.querySelector("nf-editor");window.topoEditor=e;
const settle=async()=>{await e.updateComplete;await p.updateComplete;await e.updateComplete;};
e.shadowRoot.querySelector(".nf-topology-enable").click();await settle();
if(e._doc.floors[0].id!=="eg"||e._doc.floors[0].rooms[0].id!=="it"||!e._doc.floors[0].building_id)throw new Error("Enabling topology changed legacy IDs");
e.shadowRoot.querySelector(".nf-topology-form").open=true;e.shadowRoot.querySelector(".nf-topology-location").open=true;
const setName=async(selector,value)=>{const f=e.shadowRoot.querySelector(selector);f.open=true;const input=f.querySelector("label.nf-field input");input.value=value;input.dispatchEvent(new Event("change",{bubbles:true}));await settle();};
await setName(".nf-topology-location","Urbach");await setName(".nf-topology-branch","Zentrale");await setName(".nf-topology-building","RAS19");
e.shadowRoot.querySelector(".nf-topology-add-location").click();await settle();
const loc=e.shadowRoot.querySelectorAll(".nf-topology-location")[1];loc.open=true;loc.querySelector(".nf-topology-add-branch").click();await settle();
const branch=e.shadowRoot.querySelectorAll(".nf-topology-branch")[1];branch.open=true;branch.querySelector(".nf-topology-add-building").click();await settle();
const group=e.shadowRoot.querySelectorAll(".nf-topology-building")[1];group.open=true;const id=group.dataset.building;group.querySelector(".nf-topology-add-floor").click();await settle();
if(e._doc.floors.find((f)=>f.id===e._floorId).building_id!==id||e._doc.floors.find((f)=>f.id===e._floorId).elevation!==0)throw new Error("New building must get its own ground floor");
for(const locId of e._doc.topology.locations.map((l)=>l.id)){const loc=e.shadowRoot.querySelector(`[data-location="${locId}"]`);loc.open=true;loc.querySelector(".nf-topology-outside").click();await settle();}
if(new Set(e._doc.floors.filter((f)=>f.outdoor_location_id).map((f)=>f.outdoor_location_id)).size!==2)throw new Error("Outdoor plans are not independent per location");
});
await page.screenshot({path:join(out,"symcon-topology-editor.png")});
// The HTML-SDK tile uses the same hierarchy and hides its own upper menu until a floor is selected.
await page.evaluate(async()=>{const p=window.nfPanel,card=document.createElement("nextfloor-card");card.setConfig({type:"custom:nextfloor-card",fill:true,room_buttons:true,controls:true});card.hass=p.hass;card.style.cssText="display:block;height:850px";document.body.append(card);await card.updateComplete;card.data.edit(structuredClone(window.topologyProject));p.style.display="none";window.topoHost=card;window.topoCard=card;await card.updateComplete;});
await page.waitForFunction(()=>window.topoView()?.viewer&&window.topoView().shadowRoot.querySelector('[data-topology-kind="location"]'));
@@ -114,5 +93,5 @@ try{
await page.waitForFunction(()=>window.topoView().shadowRoot.querySelectorAll('[data-topology-kind="location"] img').length===2);
assert.ok(await page.evaluate(()=>{const r=window.topoView().shadowRoot.querySelector('[data-topology-kind="location"]').getBoundingClientRect();return r.left>=0&&r.right<=innerWidth&&r.width>30;}));
await page.screenshot({path:join(out,"symcon-topology-tile-mobile.png")});
assert.deepEqual(errors,[]);console.log("OK: five-level designer/tile navigation, upper menu only at floor level, scene isolation by branch/location/building, separate location outdoors, clipped room previews and exact renderer restoration, legacy migration and native editor group CRUD, mobile navigation");
assert.deepEqual(errors,[]);console.log("OK: five-level designer/tile navigation, upper menu only at floor level, scene isolation by branch/location/building, separate location outdoors, clipped room previews and exact renderer restoration, mobile navigation");
}finally{await browser?.close();await new Promise((done)=>server.close(done));}