// The sidebar page of Home Assistant: the 3D view, the editor, and the extensions page. import { html, LitElement, nothing, type PropertyValues, type TemplateResult } from "lit"; import { sunPosition, todayAt } from "./sun-position.ts"; import { loadCardEditor } from "./load-card-editor.ts"; import { BuildingController } from "./building-controller.ts"; import type { PluginRef } from "./plugins/api.ts"; import type { MarkerMode } from "./components/view3d.ts"; import "./components/room-panel.ts"; import "./components/view3d.ts"; import { confirmEntities, outsideEntities } from "./devices.ts"; import type { HeatMode } from "./heatmap.ts"; import { awaitingLanguage, translate, type I18nKey } from "./i18n.ts"; import { loadEditor } from "./load-editor.ts"; import type { Building, Floor, LightMood } from "./model.ts"; import { changeFurniture, changePlacement, dragDevice, dragFurniture, turned, withoutFurniture, withoutPlacement } from "./panel/edits.ts"; import { furnishBar, type FurnishHost } from "./panel/furnish-bar.ts"; import { NEXTFLOOR_MARK } from "./panel/mark.ts"; import { browserStorage, PrefStore, type DevicePrefs } from "./panel/prefs.ts"; import { panelStyles } from "./panel/styles.ts"; import { colorSchemeOf, controls, readableStyles, tokens } from "./styles.ts"; import { LOOKS, lookNow, type Look } from "./themes.ts"; import type { HomeAssistant } from "./types.ts"; import { withCoverControls } from "./entities/cover-controls.ts"; import { withSymconWeather } from "./symcon-weather.ts"; import { isSymcon } from "./entities/symcon-values.ts"; import { ALL_TOPOLOGY, floorSelection, topologyOutsideFloors, topologyParent, topologyPath, type TopologySelection } from "./topology.ts"; import { allOffPlan, floorSwitchables, type ServiceCall } from "./live/all-off.ts"; import type { FloorStack, Quality, WallMode } from "./viewer/viewer3d.ts"; type Mode = "view" | "editor" | "extensions"; type Key = I18nKey; export class NextFloorPanel extends LitElement { static properties = { hass: { attribute: false }, narrow: { type: Boolean }, route: { attribute: false }, panel: { attribute: false }, _mode: { state: true }, _editorReady: { state: true }, _topologyGroup: { state: true }, _floorId: { state: true }, _roomId: { state: true }, _wallMode: { state: true }, _prefs: { state: true }, _furnish: { state: true }, _selFurniture: { state: true }, _selDevice: { state: true }, _optsOpen: { state: true }, _switchesOpen: { state: true }, _timeOfDay: { state: true }, _outside: { state: true }, _timeDrag: { state: true }, _floorUndo: { state: true }, _variablesLoading: { state: true }, _variablesNotice: { state: true }, _variablesError: { state: true }, }; declare hass: HomeAssistant; declare narrow: boolean; declare route: unknown; declare panel: unknown; private declare _mode: Mode; /** The editor bundle has been loaded (it is fetched when the editor or the extensions page opens first). */ private declare _editorReady: boolean; private declare _topologyGroup: TopologySelection; private declare _floorId: string | null; private declare _roomId: string | null; private declare _wallMode: WallMode; /** The view settings that are remembered on this device. */ private declare _prefs: DevicePrefs; private declare _furnish: boolean; private declare _selFurniture: string | null; private declare _selDevice: string | null; /** Phones fold the view options behind a gear button. */ private declare _optsOpen: boolean; /** The menu of view switches above the stage is open. */ private declare _switchesOpen: boolean; /** The time-of-day slider: hours shown instead of now (null: the slider is closed and the view shows the real sun). */ private declare _timeOfDay: number | null; /** The Outside panel is open (the house view with the garden's and the roof's devices). */ private declare _outside: boolean; private outsideMemo: { building: Building; entities: unknown; ids: string[] } | null = null; /** The hour under the finger while the slider is dragged: the view follows only when it is let go (old tablets). */ private declare _timeDrag: number | null; /** After "everything off" on a floor: the calls that bring it back, offered for a few seconds. */ private declare _floorUndo: ServiceCall[] | null; private floorUndoTimer: ReturnType | undefined; private declare _variablesLoading: boolean; private declare _variablesNotice: string; private declare _variablesError: boolean; private readonly data = new BuildingController(this); private readonly store = new PrefStore(browserStorage()); constructor() { super(); this.narrow = false; this._mode = "view"; this._editorReady = !!customElements.get("nf-editor"); this._floorId = null; this._topologyGroup=ALL_TOPOLOGY; this._roomId = null; this._wallMode = "auto"; this._prefs = this.store.load(location.search); this._furnish = false; this._selFurniture = null; this._selDevice = null; this._optsOpen = false; this._switchesOpen = false; this._timeOfDay = null; this._outside = false; this._timeDrag = null; this._floorUndo = null; this._variablesLoading = false; this._variablesNotice = ""; this._variablesError = false; } /** Shows or hides the time-of-day switch; hiding it goes back to the real sun. */ private toggleTimeSlider(on: boolean): void { this.setPref("timeSlider", on); if (!on) [this._timeOfDay, this._timeDrag] = [null, null]; } /** The sun state the look follows: the real one, or the one of the hour on the time-of-day slider. */ private sunState(): string | undefined { const config = this.hass?.config; if (this._timeOfDay === null || config?.latitude === undefined || config.longitude === undefined) return this.hass?.states["sun.sun"]?.state; return sunPosition(todayAt(this._timeOfDay, config.time_zone), config.latitude, config.longitude).elevation > 0 ? "above_horizon" : "below_horizon"; } /** The time-of-day chip, and while it is on the slider over the hours of today with a button back to now. */ private renderTimeOfDay() { const t = this.t; if (this.hass?.config?.latitude === undefined) return nothing; const hours = this._timeDrag ?? this._timeOfDay; const label = (h: number) => `${String(Math.floor(h)).padStart(2, "0")}:${String(Math.round((h % 1) * 60)).padStart(2, "0")}`; const now = () => { const d = new Date(); return Math.round((d.getHours() + d.getMinutes() / 60) * 4) / 4; }; return html` ${hours !== null ? html`` : nothing}`; } private readonly t = (key: Key, vars?: Record): string => translate(this.hass, key, vars); /** Changes one remembered setting and keeps it on this device. */ private setPref(key: K, value: DevicePrefs[K]): void { this._prefs = { ...this._prefs, [key]: value }; this.store.save(key, value); } protected willUpdate(changed: PropertyValues): void { this.toggleAttribute("readable", !!this._prefs?.readable); if (changed.has("hass") && this.hass) { this.style.colorScheme = colorSchemeOf(this.hass); this.data.setHass(this.hass); } // a floor that no longer exists (the plan was edited elsewhere) closes const building = this.data.building; if (building && this._floorId && !building.floors.some((f) => f.id === this._floorId)) { this._floorId = null; this._topologyGroup=ALL_TOPOLOGY; this._roomId = null; } } private get isAdmin(): boolean { return this.hass?.user?.is_admin ?? false; } private setMode(mode: Mode): void { if (mode !== "view" && !this.isAdmin) return; if (mode === this._mode) return; if (mode === "view") void this.data.flush(); this._mode = mode; } private topologySelection(building: Building): TopologySelection { return this._floorId ? floorSelection(building,this._floorId,this._roomId) : this._topologyGroup; } private openTopology(selection: TopologySelection): void { const b=this.data.building;if(!b)return; this._roomId=selection.kind==="room"?selection.id??null:null; this._floorId=selection.kind==="room"?selection.floorId??null:selection.kind==="floor"?selection.id??null:selection.kind==="outside"?b.floors.find((f)=>f.outdoor_location_id===selection.id)?.id??null:null; this._topologyGroup=selection;this._outside=false; } private openFloor(floorId: string | null): void { this._topologyGroup=ALL_TOPOLOGY; this._floorId = floorId; this._roomId = null; this._outside = false; } /** The devices of Outside, worked out again only when the plan or the registry changes. */ private outsideIds(building: Building): string[] { if(building.topology)return outsideEntities(this.hass,topologyOutsideFloors(building,this.topologySelection(building)),building.settings.outside_hidden); const m = this.outsideMemo; if (m && m.building === building && m.entities === this.hass.entities) return m.ids; const ids = outsideEntities(this.hass, building.floors, building.settings.outside_hidden); this.outsideMemo = { building, entities: this.hass.entities, ids }; return ids; } /** Opens Outside over the house view (or closes it again). */ private openOutside(floorId?: string): void { const b=this.data.building; if(b?.topology){ const location=topologyPath(b,floorId?floorSelection(b,floorId):this.topologySelection(b)).find((n)=>n.selection.kind==="location"); if(!location)return; const f=b.floors.find((f)=>f.outdoor_location_id===location?.selection.id); if(f){const open=!this._outside;this.openTopology({kind:"outside",id:f.outdoor_location_id!});this._outside=open;return;} const open=!this._outside;this.openTopology(location.selection);this._outside=open;return; } const open = !this._outside; this.openFloor(null); this._outside = open; } private onRoomTap(e: CustomEvent<{ floorId: string; roomId: string | null }>): void { const { floorId, roomId } = e.detail; // an outdoor area's pin opens Outside if (roomId === "nf-outside") return this.openOutside(floorId); // in the house view, or on another floor, a tap opens the whole floor first and the rooms come next if ((this.data.building?.floors.length ?? 0) > 1 && floorId && this._floorId !== floorId) return this.openFloor(floorId); if (roomId) { this._roomId = roomId === this._roomId ? null : roomId; this._outside = false; } } // furnishing in 3D: every change builds a changed copy of the plan and saves it private readonly furnishHost: FurnishHost = { hass: undefined as unknown as HomeAssistant, building: undefined as unknown as Building, t: this.t, editFurniture: (id, change) => this.applyEdit((b) => changeFurniture(b, id, change)), editDevice: (entityId, change) => this.applyEdit((b) => changePlacement(b, entityId, change)), turnFurniture: (id, delta) => this.applyEdit((b) => changeFurniture(b, id, (f) => (f.rotation = turned(f.rotation, delta)))), turnDevice: (entityId, delta) => this.applyEdit((b) => changePlacement(b, entityId, (p) => (p.rotation = turned(p.rotation ?? 0, delta)))), removeFurniture: (id) => { this.applyEdit((b) => withoutFurniture(b, id)); this._selFurniture = null; }, removeDevice: (entityId) => { this.applyEdit((b) => withoutPlacement(b, entityId)); this._selDevice = null; }, finish: () => { this._furnish = false; this._selFurniture = null; this._selDevice = null; }, }; /** The light designer's moods of a room, saved with the plan. */ private saveMoods(roomId: string, moods: LightMood[]): void { this.applyEdit((b) => ({ ...b, floors: b.floors.map((f) => ({ ...f, rooms: f.rooms.map((r) => (r.id === roomId ? { ...r, moods: moods.length ? moods : undefined } : r)) })) })); } private applyEdit(edit: (building: Building) => Building): void { const building = this.data.building; if (building) this.data.edit(edit(building)); } private view3d() { return this.renderRoot.querySelector("nf-view3d") as (HTMLElement & { resetView(): void; lookThrough(entityId: string): void }) | null; } /** Escape and the back button: close the room, then the floor, and finally reset the camera. */ private back(): void { if (this._outside) this._outside = false; else if (this._roomId) this._roomId = null; else if(this.data.building?.topology && this.topologySelection(this.data.building).kind!=="all")this.openTopology(topologyParent(this.data.building,this.topologySelection(this.data.building))); else if (this._floorId && (this.data.building?.floors.length ?? 0) > 1) this._floorId = null; else this.view3d()?.resetView(); } private readonly onKey = (e: KeyboardEvent) => { if (e.key !== "Escape" || this._mode !== "view") return; if (this._prefs.clean) this.setPref("clean", false); else this.back(); }; connectedCallback(): void { super.connectedCallback(); window.addEventListener("keydown", this.onKey); } disconnectedCallback(): void { super.disconnectedCallback(); window.removeEventListener("keydown", this.onKey); } protected render() { // a language beyond German and English: its texts are fetched first, and then everything renders if (this.hass && awaitingLanguage(this.hass, this)) return nothing; const building = this.data.building; const cleanView = this._prefs.clean && this._mode === "view"; let body: TemplateResult | typeof nothing = nothing; if (building) { if (this._mode === "editor" && this.isAdmin) body = this.renderEditor(building); else if (this._mode === "extensions" && this.isAdmin) body = this.renderExtensions(); else body = this.renderView(building); } return html`
${cleanView ? nothing : html`${this.renderHeader(building)}${this.renderNotices()}`} ${this.data.error && !building ? html`

${this.t("load_error")}: ${this.data.error}

` : nothing} ${!building && !this.data.error ? html`

${this.t("loading")}

` : nothing} ${body}
`; } /** A row of buttons of which exactly one is pressed. */ private choiceRow(label: Key | null, options: readonly T[], current: T, text: (option: T) => string, pick: (option: T) => void, extra: TemplateResult | typeof nothing = nothing) { return html`
${options.map((o) => html``)}${extra}
`; } /** The accent colour well beside the looks, with a reset arrow once a colour is chosen. */ private accentPicker() { const accent = this._prefs.accent; return html``; } /** Quality, look, markers and the performance display; phones fold them behind the gear. */ private renderViewOptions() { const p = this._prefs; return html`
${this.choiceRow("quality", ["auto", "low", "high"] as Quality[], p.quality, (q) => this.t(`quality_${q}`), (q) => this.setPref("quality", q))} ${this.choiceRow("theme", LOOKS as readonly Look[], p.theme, (th) => this.t(`theme_${th}`), (th) => this.setPref("theme", th), this.accentPicker())} ${this.choiceRow("markers", ["none", "important", "all"] as MarkerMode[], p.markers, (m) => this.t(`markers_${m}`), (m) => this.setPref("markers", m))} ${isSymcon(this.hass) ? nothing : html`
${p.announceMuted ? "🔇" : "📢"}

${this.t("screen_name_hint")}

`}
`; } private async reloadVariables(): Promise { if (this._variablesLoading || !this.hass.symconRefresh) return; this._variablesLoading = true; this._variablesNotice = ""; this._variablesError = false; try { await this.hass.symconRefresh(); this._variablesNotice = this.t("symcon_variables_loaded"); } catch (error: unknown) { this._variablesError = true; this._variablesNotice = this.t("symcon_variables_error", { error: error instanceof Error ? error.message : String(error) }); } finally { this._variablesLoading = false; } } private renderHeader(building: Building | null) { const title = this.hass?.symconTitle?.trim() || "NextFloor"; const saveState = this.data.saveState; const tab = (mode: Mode, label: string, extra = "") => html``; const saveLabel: Key = saveState === "saving" ? "saving" : saveState === "saved" ? "saved" : "save_error"; return html`

${NEXTFLOOR_MARK}${title}

${this.isAdmin ? html`
${tab("view", this.t("view"))}${tab("editor", this.t("editor"))}${tab("extensions", `✦ ${this.t("ext_tab")}`, "nf-tab-ext")}
` : nothing} ${this._mode === "view" && building?.floors.some((f) => f.rooms.length) ? html`` : nothing} ${this.isAdmin && this.hass.symconRefresh ? html`` : nothing} ${this._mode === "view" && building?.floors.some((f) => f.rooms.length) ? this.renderViewOptions() : nothing} ${this._mode === "editor" && saveState !== "idle" ? html`${this.t(saveLabel)}` : nothing} v${this.data.frontendVersion}
`; } /** Restart hint, save errors and unsaved edits left from an earlier session. */ private renderNotices() { const d = this.data; const notices: TemplateResult[] = []; if (this._variablesNotice) notices.push(html`
${this._variablesNotice}
`); if (!isSymcon(this.hass) && d.needsRestart) { // an old bundle in the browser or the companion app is cured by a reload, not by a restart notices.push( d.versionGap === "frontend" ? html`
${this.t("needs_reload", { frontend: d.frontendVersion, backend: d.backendVersion ?? "?" })}
` : html`
${d.backendVersion ? this.t("needs_restart", { version: d.backendVersion, frontend: d.frontendVersion }) : this.t("needs_restart_old")}
`, ); } if (d.saveState === "error" && d.saveError) notices.push(html`
${this.t("save_failed_detail", { error: d.saveError })}
`); if (d.draft && this.isAdmin) { const time = new Date(d.draft.savedAt).toLocaleString(this.hass?.language); notices.push(html`
${this.t("draft_found", { time })}
`); } return notices.length > 0 ? html`
${notices}
` : nothing; } /** The editor and the extensions page come in one bundle that is loaded when one of them is first opened. */ private whenEditorLoaded(show: () => TemplateResult): TemplateResult { if (this._editorReady) return show(); loadEditor().then( () => (this._editorReady = true), (err: unknown) => (this.data.error = String(err)), ); return html`

${this.t("loading")}

`; } private renderExtensions() { return this.whenEditorLoaded(() => html` void this.data.reloadPacks()} @plugins-changed=${(e: CustomEvent) => this.applyEdit((b) => ({ ...b, settings: { ...b.settings, plugins: e.detail } }))}>`); } private renderEditor(building: Building) { return this.whenEditorLoaded( () => html`) => this.setPref("roomNames", e.detail.value)} .packs=${this.data.packs} .loadCardEditor=${loadCardEditor} @packs-changed=${() => void this.data.reloadPacks()} @building-changed=${(e: CustomEvent<{ building: Building }>) => this.data.edit(e.detail.building)} >`, ); } /** A single-row bar scrolls sideways with the mouse wheel, as a desktop has no swipe. */ private readonly onNavWheel = (e: WheelEvent) => { if (this._prefs.navWrap || !e.deltaY || e.deltaX) return; const nav = e.currentTarget as HTMLElement; if (nav.scrollWidth <= nav.clientWidth) return; nav.scrollLeft += e.deltaY; e.preventDefault(); }; /** Everything off on the open floor (the house when it has one floor), then its undo for ten seconds. */ private allOffChip(building: Building) { const floor = this._floorId ? building.floors.find((f) => f.id === this._floorId) : building.floors.length === 1 ? building.floors[0] : undefined; if (!floor || !this.hass) return nothing; if (this._floorUndo) { const undo = this._floorUndo; return html``; } const plan = allOffPlan(floorSwitchables(floor).map((id) => this.hass.states[id])); if (plan.count < 2) return nothing; return html``; } /** The bar of floors and rooms above the stage. */ private renderNav(building: Building) { if(building.topology){ const floor=building.floors.find((f)=>f.id===this._floorId); if(!floor||floor.outdoor_location_id)return nothing; return html``; } const shown: Floor[] = building.floors.filter((f) => !this._floorId || f.id === this._floorId); const several = building.floors.length > 1; const wrap = this._prefs.navWrap; // Outside: its own chip next to the floors as soon as a device stands outside the rooms or belongs to it const outside = this.outsideIds(building).length ? html`` : nothing; const floorChips = several ? html` ${[...building.floors].reverse().map((f) => html``)} ${outside} ${this.allOffChip(building)} ` : html`${outside} ${this.allOffChip(building)}`; const roomChips = shown.flatMap((floor) => [ // in the house view a small floor label comes before the rooms of each floor shown.length > 1 && floor.rooms.length ? html`${floor.name}` : nothing, ...floor.rooms.map( (room) => html``, ), ]); const wrapLabel = this.t(wrap ? "nav_row" : "nav_wrap"); return html``; } /** A chip that toggles one remembered setting. */ private toggleChip(key: "roomNames" | "weather", label: Key, hint?: Key) { return html``; } /** The switches at the bottom of the stage: walls, floors, roof, floor stacking, heat map, and the chips. */ private renderOverlay(building: Building) { const p = this._prefs; const t = this.t; const pair = (a: [boolean, () => void, string], b: [boolean, () => void, string]) => html`
${[a, b].map(([on, act, text]) => html``)}
`; const heats: HeatMode[] = ["none", "temperature", "humidity", "co2", "mould", "comfort", "power", "sun", "values", "wifi"]; const stacks: FloorStack[] = ["dim", "stacked", "single"]; const several = building.floors.length > 1; const back = this._roomId || (this._floorId && several) ? html`` : nothing; // one button for all switches, opening a menu upwards: the stage keeps the house in view, on a phone above all const toggle = html``; if (!this._switchesOpen) return html`
${toggle}${back}
`; return html`
(this._switchesOpen = false)}>
e.key === "Escape" && (this._switchesOpen = false)}>
${(["auto", "cut", "slope"] as const).map( (m) => html``, )}
${several && !this._floorId ? pair([p.explode, () => this.setPref("explode", true), t("floors_apart")], [!p.explode, () => this.setPref("explode", false), t("floors_stacked")]) : nothing} ${!this._floorId && building.settings.roof.type !== "none" ? html`
` : nothing} ${several && this._floorId ? html`
${stacks.map((m) => html``)}
` : nothing}
${heats.map((m) => html``)}
${this.toggleChip("roomNames", "room_names_short")} ${this.toggleChip("weather", "weather_short", "weather_hint")} ${p.timeSlider ? this.renderTimeOfDay() : nothing}
${toggle}${back}
`; } private renderView(building: Building) { if (!building.floors.some((f) => f.rooms.length || f.outdoor.length || f.furniture.length)) { return html`

${this.t(this.isAdmin ? (building.floors.length ? "no_rooms_admin" : "no_building_admin") : "no_building")}

${this.isAdmin ? html`` : nothing}
`; } const p = this._prefs; const room = building.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null; this.furnishHost.hass = this.hass; this.furnishHost.building = building; return html` ${p.clean ? nothing : this.renderNav(building)}
this.setPref("clean", !p.clean)} ?weather=${p.weather} .panelOpen=${!!this._roomId || this._outside} .floorId=${building.topology || building.floors.length > 1 ? this._floorId : (building.floors[0]?.id ?? null)} .roomId=${this._roomId} .outsideOpen=${this._outside} .wallMode=${this._wallMode} .solidWalls=${p.solidWalls} .explode=${p.explode} .keepRoof=${p.keepRoof} .markerMode=${p.markers} .heatMode=${p.heat} .theme=${lookNow(p.theme, this.sunState())} .timeOfDay=${this._timeOfDay} .clock=${p.clock === "none" ? null : p.clock} .announcements=${!isSymcon(this.hass) && !p.announceMuted} .glassWalls=${p.glassWalls} .screenName=${p.screenName || null} .lockButton=${true} .walkButton=${true} .travelButton=${true} .accent=${p.accent} .centralOpen=${p.menuOpen} .keepCamera=${p.keepCamera} .plain=${p.plain} .rightBack=${p.rightBack} .readable=${p.readable} .zoom=${p.zoom / 100} ?furnish=${this._furnish} .selectedFurniture=${this._selFurniture} @furniture-select=${(e: CustomEvent<{ id: string | null }>) => (this._selFurniture = e.detail.id)} @furniture-move=${(e: CustomEvent<{ id: string; x: number; z: number }>) => this.applyEdit((b) => dragFurniture(b, e.detail.id, e.detail.x, e.detail.z))} @device-select=${(e: CustomEvent<{ id: string | null }>) => (this._selDevice = e.detail.id)} @device-move=${(e: CustomEvent<{ id: string; x: number; z: number }>) => this.applyEdit((b) => dragDevice(b, e.detail.id, e.detail.x, e.detail.z))} .quality=${p.quality} ?showStats=${p.stats} @room-tap=${this.onRoomTap} @topology-tap=${(e: CustomEvent) => this.openTopology(e.detail)} @floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => this.openFloor(e.detail.floorId)} @back=${() => this.back()} > ${room ? html` f.rooms.some((r) => r.id === this._roomId)) ?? null} .confirmEntities=${confirmEntities(this.hass, building.floors)} .phrases=${building.settings.announce_phrases ?? null} .rooms=${building.floors.flatMap((f) => f.rooms)} @mood-change=${(e: CustomEvent<{ roomId: string; moods: LightMood[] }>) => this.saveMoods(e.detail.roomId, e.detail.moods)} @close=${() => (this._roomId = null)} >` : this._outside ? html` (this._outside = false)} >` : nothing} ${p.clean ? nothing : this.renderOverlay(building)} ${this._furnish ? furnishBar(this.furnishHost, this._selFurniture, this._selDevice) : nothing}
`; } static styles = [tokens, controls, panelStyles, readableStyles]; } if (!customElements.get("nextfloor-panel")) customElements.define("nextfloor-panel", NextFloorPanel);