From a226f609d4c93fdcc059c05db67d8253b50d36e6 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:57:26 +0100 Subject: [PATCH 01/17] feat(overview): add the device_map card type to the layout settings Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/settings/cardcatalog.go | 3 ++ .../internal/settings/layout.schema.json | 13 ++++- dashboard/internal/settings/settings.go | 45 ++++++++++++++++ dashboard/internal/settings/settings_test.go | 54 +++++++++++++++++++ 4 files changed, 113 insertions(+), 2 deletions(-) diff --git a/dashboard/internal/settings/cardcatalog.go b/dashboard/internal/settings/cardcatalog.go index befb98a52..5a90bce9d 100644 --- a/dashboard/internal/settings/cardcatalog.go +++ b/dashboard/internal/settings/cardcatalog.go @@ -51,6 +51,9 @@ var cardCatalog = map[string]CardType{ // Ein ApexCharts-Liniendiagramm. Unter 16rem werden die Achsenbeschriftungen // unleserlich, und es nutzt jede zusaetzliche Hoehe. "history_view": {MinSpan: 1, MinWidth: "16rem", MinHeight: "14rem", FillsHeight: true, DefaultSpan: "2"}, + // Die Map nutzt jede Hoehe, die Breite folgt der Spalte. 18rem traegt + // Glas-Label, Pille und eine lesbare Anlage. + "device_map": {MinSpan: 1, MinWidth: "18rem", MinHeight: "18rem", FillsHeight: true, DefaultSpan: "full"}, } // fallbackCardType haelt jeden Aufrufer beantwortbar, auch wenn ein Typ ohne diff --git a/dashboard/internal/settings/layout.schema.json b/dashboard/internal/settings/layout.schema.json index 43efbe420..5483248ae 100644 --- a/dashboard/internal/settings/layout.schema.json +++ b/dashboard/internal/settings/layout.schema.json @@ -31,7 +31,7 @@ "required": ["id", "type", "span", "visible"], "properties": { "id": {"type": "string", "minLength": 1}, - "type": {"type": "string", "enum": ["device", "entity_value", "entity_group", "energy_flow", "energy_summary", "diagnostics", "energy_band", "energy_ring", "energy_board", "energy_day", "energy_schema", "energy_status", "energy_stats", "battery_status", "history_view"]}, + "type": {"type": "string", "enum": ["device", "entity_value", "entity_group", "energy_flow", "energy_summary", "diagnostics", "energy_band", "energy_ring", "energy_board", "energy_day", "energy_schema", "energy_status", "energy_stats", "battery_status", "history_view", "device_map"]}, "ref": {"type": "string"}, "entity_refs": { "type": "array", @@ -76,7 +76,16 @@ "stats_chart": {"type": "string", "enum": ["on", "off"]}, "history_series": {"type": "array", "items": {"type": "string", "minLength": 1}}, "history_range_hours": {"type": "string", "enum": ["1", "6", "24", "168", "720", "2160"]}, - "history_aggregate": {"type": "string", "enum": ["avg", "min", "max"]} + "history_aggregate": {"type": "string", "enum": ["avg", "min", "max"]}, + "map_wiring": {"type": "string", "enum": ["on", "off"]}, + "map_energy": {"type": "string", "enum": ["on", "off"]}, + "map_balance": {"type": "string", "enum": ["on", "off"]}, + "map_data": {"type": "string", "enum": ["on", "off"]}, + "map_role_edges": {"type": "string", "enum": ["on", "off"]}, + "map_automation_links": {"type": "string", "enum": ["on", "off"]}, + "map_edge_style": {"type": "string", "enum": ["curved", "straight"]}, + "map_width": {"type": "string", "enum": ["on", "off"]}, + "map_tap": {"type": "string", "enum": ["none", "highlight", "modal"]} } } } diff --git a/dashboard/internal/settings/settings.go b/dashboard/internal/settings/settings.go index d74cb1791..06aa35886 100644 --- a/dashboard/internal/settings/settings.go +++ b/dashboard/internal/settings/settings.go @@ -337,6 +337,20 @@ type Item struct { StatsKPIs []string `json:"stats_kpis,omitempty"` StatsChart string `json:"stats_chart,omitempty"` // "on" | "off" + // device_map: die Karte zeigt die Device-Map im Uebersichtsraster. Die + // Schalter und Stile wirken nur auf diese Kachel, andere Typen tragen + // keinen dieser Werte. Leer bei MapEdgeStyle und MapWidth heisst "wie in + // der Device-Map". MapTap legt fest, was ein Klick auf ein Geraet tut. + MapWiring string `json:"map_wiring,omitempty"` // "on" | "off" + MapEnergy string `json:"map_energy,omitempty"` // "on" | "off" + MapBalance string `json:"map_balance,omitempty"` // "on" | "off" + MapData string `json:"map_data,omitempty"` // "on" | "off" + MapRoleEdges string `json:"map_role_edges,omitempty"` // "on" | "off" + MapAutomationLinks string `json:"map_automation_links,omitempty"` // "on" | "off" + MapEdgeStyle string `json:"map_edge_style,omitempty"` // "" | "curved" | "straight" + MapWidth string `json:"map_width,omitempty"` // "" | "on" | "off" + MapTap string `json:"map_tap,omitempty"` // "none" | "highlight" | "modal" + // entity_group, history_view: frei zusammengestellte Liste an Entitaeten - anders als // Ref (ein einzelner Bezug) braucht dieser Typ mehrere. Title ist der // einzige Item-Typ mit freiem Anzeigetext statt eines vom Ref @@ -1080,6 +1094,15 @@ func cloneLayout(value Layout) Layout { StatsPeriod: item.StatsPeriod, StatsKPIs: append([]string(nil), item.StatsKPIs...), StatsChart: item.StatsChart, + MapWiring: item.MapWiring, + MapEnergy: item.MapEnergy, + MapBalance: item.MapBalance, + MapData: item.MapData, + MapRoleEdges: item.MapRoleEdges, + MapAutomationLinks: item.MapAutomationLinks, + MapEdgeStyle: item.MapEdgeStyle, + MapWidth: item.MapWidth, + MapTap: item.MapTap, EntityRefs: append([]string(nil), item.EntityRefs...), Title: item.Title, Display: item.Display, @@ -2843,6 +2866,28 @@ func normalizeEnergyGraphicOptions(item *Item) { item.StatsPeriod, item.StatsKPIs, item.StatsChart = "", nil, "" } + // device_map: jeder Schalter faellt auf seine Vorgabe, Stil und Breite + // bleiben leer, wenn sie leer sind ("wie in der Device-Map"). Andere + // Typen tragen keine Map-Felder. + if item.Type == "device_map" { + defaultString(&item.MapWiring, []string{"on", "off"}, "off") + defaultString(&item.MapEnergy, []string{"on", "off"}, "on") + defaultString(&item.MapBalance, []string{"on", "off"}, "on") + defaultString(&item.MapData, []string{"on", "off"}, "off") + defaultString(&item.MapRoleEdges, []string{"on", "off"}, "off") + defaultString(&item.MapAutomationLinks, []string{"on", "off"}, "off") + if item.MapEdgeStyle != "" { + defaultString(&item.MapEdgeStyle, []string{"curved", "straight"}, "") + } + if item.MapWidth != "" { + defaultString(&item.MapWidth, []string{"on", "off"}, "") + } + defaultString(&item.MapTap, []string{"none", "highlight", "modal"}, "highlight") + } else { + item.MapWiring, item.MapEnergy, item.MapBalance, item.MapData = "", "", "", "" + item.MapRoleEdges, item.MapAutomationLinks, item.MapEdgeStyle, item.MapWidth, item.MapTap = "", "", "", "", "" + } + // history_view: gebunden (Ref gesetzt) liefert die Sicht Serien, Zeitraum, // Kennwert und Namen - die Kachel traegt nichts davon selbst. Ohne Ref // fuellt defaultString die beiden Enums, die Serienliste bleibt wie sie diff --git a/dashboard/internal/settings/settings_test.go b/dashboard/internal/settings/settings_test.go index dc02af8c1..c8c5c1c18 100644 --- a/dashboard/internal/settings/settings_test.go +++ b/dashboard/internal/settings/settings_test.go @@ -3319,3 +3319,57 @@ func TestLearningMinutesPauseModeIsAccepted(t *testing.T) { t.Fatal("learning_ha_reconcile_disabled defaults to true, want false") } } + +// device_map: Vorgaben, unbekannte Werte und Klon der Map-Felder. +func TestNormalizeDeviceMapDefaults(t *testing.T) { + layout := normalizeLayout(Layout{Version: 3, Pages: []Page{{ID: "p", Name: "P", Groups: []Group{{ + ID: "g", Name: "G", Items: []Item{{ID: "m", Type: "device_map", Span: "full", Visible: true}}, + }}}}}) + item := layout.Pages[0].Groups[0].Items[0] + want := [9]string{"off", "on", "on", "off", "off", "off", "", "", "highlight"} + got := [9]string{item.MapWiring, item.MapEnergy, item.MapBalance, item.MapData, item.MapRoleEdges, item.MapAutomationLinks, item.MapEdgeStyle, item.MapWidth, item.MapTap} + if got != want { + t.Fatalf("device_map defaults = %q, want %q", got, want) + } +} + +func TestNormalizeDeviceMapUnknownValues(t *testing.T) { + layout := normalizeLayout(Layout{Version: 3, Pages: []Page{{ID: "p", Name: "P", Groups: []Group{{ + ID: "g", Name: "G", Items: []Item{{ID: "m", Type: "device_map", Span: "full", Visible: true, + MapTap: "zoom", MapEdgeStyle: "wavy", MapWidth: "maybe", MapData: "yes"}}, + }}}}}) + item := layout.Pages[0].Groups[0].Items[0] + if item.MapTap != "highlight" || item.MapEdgeStyle != "" || item.MapWidth != "" || item.MapData != "off" { + t.Fatalf("unknown values = tap %q, edge %q, width %q, data %q; want highlight, \"\", \"\", off", + item.MapTap, item.MapEdgeStyle, item.MapWidth, item.MapData) + } +} + +func TestNormalizeClearsMapFieldsOnOtherTypes(t *testing.T) { + layout := normalizeLayout(Layout{Version: 3, Pages: []Page{{ID: "p", Name: "P", Groups: []Group{{ + ID: "g", Name: "G", Items: []Item{{ID: "s", Type: "energy_stats", Span: "1", Visible: true, MapTap: "modal", MapWiring: "on", MapEdgeStyle: "curved", MapWidth: "on"}}, + }}}}}) + item := layout.Pages[0].Groups[0].Items[0] + if item.MapWiring != "" || item.MapEnergy != "" || item.MapBalance != "" || item.MapData != "" || item.MapRoleEdges != "" || item.MapAutomationLinks != "" || item.MapEdgeStyle != "" || item.MapWidth != "" || item.MapTap != "" { + t.Fatalf("fremder Typ traegt Map-Felder: %+v", item) + } +} + +func TestDeviceMapLayoutValidates(t *testing.T) { + layout := Layout{Version: 3, Pages: []Page{{ID: "p", Name: "P", Groups: []Group{{ + ID: "g", Name: "G", Items: []Item{{ID: "m", Type: "device_map", Span: "full", Visible: true, + MapWiring: "on", MapEnergy: "off", MapBalance: "off", MapData: "on", MapRoleEdges: "on", + MapAutomationLinks: "on", MapEdgeStyle: "straight", MapWidth: "off", MapTap: "modal"}}, + }}}}} + if err := validateLayout(layout); err != nil { + t.Fatalf("validateLayout: %v", err) + } + before := cloneLayout(layout) + after := cloneLayout(normalizeLayout(layout)) + if !reflect.DeepEqual(before, after) { + t.Fatalf("Klon veraendert device_map: before %+v, after %+v", before, after) + } + if !reflect.DeepEqual(layout, cloneLayout(layout)) { + t.Fatal("cloneLayout verliert device_map-Felder") + } +} From 99e8dbd56e709beb27fc4fe96d23a9a549b957cc Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:01:16 +0100 Subject: [PATCH 02/17] refactor(energy): move the plant renderer into a shared devicemap-live core The renderer of the energy plant moves to devicemap-live.js, which exposes window.DeviceMapLive.create(config). energy-plant.js keeps only the plant configuration (fixed energy and balance layers, role edges switch, node tap) plus the role edge switch and the row focus listener. The data flow layer is loaded and drawn by the core when its layer is on. Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/devicemap-live.js | 424 ++++++++++++++++++ .../internal/webui/static/js/energy-plant.js | 403 +++-------------- dashboard/internal/webui/templates/base.html | 2 +- dashboard/internal/webui/webui_test.go | 2 +- dashboard/test/devicemap-live.test.mjs | 160 +++++++ dashboard/test/energy-plant.test.mjs | 2 +- 6 files changed, 637 insertions(+), 356 deletions(-) create mode 100644 dashboard/internal/webui/static/js/devicemap-live.js create mode 100644 dashboard/test/devicemap-live.test.mjs diff --git a/dashboard/internal/webui/static/js/devicemap-live.js b/dashboard/internal/webui/static/js/devicemap-live.js new file mode 100644 index 000000000..0f08ca948 --- /dev/null +++ b/dashboard/internal/webui/static/js/devicemap-live.js @@ -0,0 +1,424 @@ +// Shared renderer core of the read-only device map arrangement. Used by the +// energy tab's plant view (energy-plant.js) and the device map card on the +// dashboard overview. window.DeviceMapLive.create(config) returns the state +// and methods of an Alpine.data component. The config decides what is drawn: +// layers, role edges, automation links, edge style, width by power. It also +// decides whether the component is active and what a node tap does. Every +// config function gets the component as its first argument. Spec section +// "Energie-Tab". +(() => { + const t = (key, params) => (window.I18n ? window.I18n.t(key, params) : key); + const requestJSON = async url => { + const response = await fetch(`${window.__DASHBOARD_BASE_PATH__ || ''}${url}`); + const body = await response.json().catch(() => ({})); + if (!response.ok) throw new Error((body && body.message) || 'request failed'); + return body; + }; + const REFRESH_MS = 1000; + + const create = config => { + let cy = null; + let labels = null; + return { + devices: [], + deviceMap: {version: 2, nodes: [], edges: []}, + energy: null, + groups: {}, + categories: {}, + iconMarkup: {}, + flows: null, + focusId: null, + empty: false, + loading: false, + _timer: null, + _pending: false, + _animator: null, + _setTimeout: (fn, ms) => setTimeout(fn, ms), + _offs: [], + + get view() { + const stored = this.deviceMap.view || {}; + const view = {edge_style: 'curved', width_by_power: false, ...stored, layers: config.layers(this)}; + const edgeStyle = config.edgeStyle(this); + if (edgeStyle) view.edge_style = edgeStyle; + const widthByPower = config.widthByPower(this); + if (widthByPower) view.width_by_power = widthByPower === 'on'; + const automation = config.automationLinks(this); + if (automation !== undefined) view.hide_automation_links = !automation; + return view; + }, + + async load() { + if (!this._offs.length) { + const on = (target, name, fn) => { target.addEventListener(name, fn); this._offs.push(() => target.removeEventListener(name, fn)); }; + on(window, 'registry-updated', () => this.onRegistryUpdated()); + on(window, 'energy-roles-changed', () => this.load()); + on(window, 'device-map-changed', () => this.load()); + const wake = () => setTimeout(() => this.flowAnimator().start(), 0); + on(document, 'visibilitychange', wake); + on(window, 'dashboard-panel-changed', wake); + } + this.loading = true; + try { + const withFlows = Boolean(config.layers(this).data); + const [devices, deviceMap, energy, roles, icons, flows] = await Promise.all([ + requestJSON('/api/v1/devices'), + requestJSON('/api/v1/device/map').catch(() => null), + requestJSON('/api/v1/energy').catch(() => null), + requestJSON('/api/v1/energy/roles').catch(() => null), + requestJSON('/api/v1/device/icons').catch(() => []), + withFlows ? requestJSON('/api/v1/device/map/flows').catch(() => null) : null, + ]); + this.devices = devices || []; + this.deviceMap = deviceMap || {version: 2, nodes: [], edges: []}; + this.energy = energy; + this.groups = (roles && roles.groups) || {}; + this.categories = (roles && roles.categories) || {}; + this.iconMarkup = Object.fromEntries((Array.isArray(icons) ? icons : []).map(icon => [icon.name, icon.markup])); + this.flows = flows; + this.empty = this.devices.every(device => device.id === window.DeviceMapModel.OWN_ENERGY_DEVICE_ID); + this.render(); + } finally { + this.loading = false; + } + }, + + destroy() { + this._offs.forEach(off => off()); + this._offs = []; + this.flowAnimator().stop(); + if (labels) { labels.destroy(); labels = null; } + if (cy) { cy.destroy(); cy = null; } + }, + + isActive() { + return config.isActive(this); + }, + + onRegistryUpdated() { + if (!this.isActive()) return; + if (this._timer) { this._pending = true; return; } + this.refreshEnergy(); + this._timer = this._setTimeout(() => { + this._timer = null; + if (this._pending) { this._pending = false; this.onRegistryUpdated(); } + }, REFRESH_MS); + }, + + async refreshEnergy() { + this.energy = await requestJSON('/api/v1/energy').catch(() => null); + this.applyEnergy(); + }, + + groupIds() { + return Object.keys(this.groups).map(id => window.DeviceMapModel.GROUP_PREFIX + id); + }, + + balanceId() { + return window.DeviceMapDataflow.balanceNodeId(new Set(this.devices.map(device => device.id))); + }, + + subDevices() { + return window.DeviceMapSubDevices.list(this.deviceMap); + }, + + // Role edges from the devices (and sub-devices) to the balance node. + roleEdgeList() { + return window.DeviceMapDataflow.roleEdges(this.energy, this.balanceId(), this.deviceMap); + }, + + subIsOrphan(sub) { + return window.DeviceMapSubDevices.isOrphan(sub, this.devices); + }, + + nodeIds() { + return new Set([...this.devices.map(device => device.id), ...this.subDevices().map(sub => sub.id), ...this.groupIds(), this.balanceId()]); + }, + + // Also the nodes of the data flow layer (rules, services, stubs are + // not in nodeIds, the flow edges end on them). + baseNodeIds() { + return new Set([...this.nodeIds(), ...this.flowNodes().map(node => node.id)]); + }, + + flowNodes() { + return ((this.flows && this.flows.nodes) || []).map(node => ({ + id: node.virtual_id, + kind: node.kind, + name: node.label_key ? t(node.label_key) : node.label, + node, + })); + }, + + stubInfo() { + return window.DeviceMapDataflow.stubs(this.flows, this.baseNodeIds()); + }, + + // Entities with a sub-device are measured under the sub-device's ID, so + // the meter keeps the ring of its other entities (as on the map page). + energyByDevice() { + return window.DeviceMapModel.deviceEnergy(window.DeviceMapSubDevices.remapSnapshot(this.energy, this.deviceMap)); + }, + + // Value of a sub-device node: its entity's reading, or the hint when + // the meter or the entity is gone. + subValueText(sub, energy) { + if (this.subIsOrphan(sub)) return t('devicemap.sub.missing'); + const device = this.devices.find(item => item.id === sub.device_id); + const entities = ((device && device.entities) || []).filter(entity => entity && entity.unique_id === sub.entity_id); + return window.DeviceMapModel.nodeValueText({entities}, energy.get(sub.id)); + }, + + // Dashed ring in the colour of the first role, the sub-device icon, no + // health dot (same spec as the map page). + subSpec(sub, energy) { + const entry = energy.get(sub.id); + const role = entry && entry.primaryRole; + return { + segments: entry ? entry.roles.map(item => entry.meta[item].color) : [], + icon: sub.icon ? `cat:${sub.icon}` : 'box', + iconColor: role ? entry.meta[role].color : 'text-muted', + health: 'unknown', + subDevice: true, + iconMarkup: this.iconMarkup[sub.icon] || '', + }; + }, + + wiringEdges() { + const wiring = window.DeviceMapGraph.wiringElements({devices: this.devices, deviceMap: this.deviceMap, groups: this.groups, nodeIds: this.nodeIds(), energy: this.energyByDevice()}); + if (!this.view.hide_automation_links) return wiring; + return wiring.filter(element => !window.DeviceMapDataflow.isAutomationLink({from: element.data.source, to: element.data.target})); + }, + + positions() { + const model = window.DeviceMapModel; + const df = window.DeviceMapDataflow; + const snap = value => value; + const positions = new Map((this.deviceMap.nodes || []).map(node => [node.device_id || node.virtual_id, {x: node.x, y: node.y}])); + const all = () => [...positions.values()]; + // Same spots the device map would pick, so a device that is not yet + // saved there does not land on the origin on top of another one. + const anchors = this.devices.map(device => positions.get(device.id)).filter(Boolean); + const balanceId = this.balanceId(); + const missing = this.devices.filter(device => !positions.has(device.id) && device.id !== balanceId).map(device => device.id); + if (balanceId !== df.BALANCE_ID && !(this.deviceMap.nodes || []).some(node => node.device_id === balanceId) && positions.has(df.BALANCE_ID)) { + positions.set(balanceId, positions.get(df.BALANCE_ID)); + } + if (!positions.has(balanceId)) { + const roleDevices = this.roleEdgeList().map(edge => positions.get(edge.from)).filter(Boolean); + positions.set(balanceId, df.placeBalance({rolePositions: roleDevices, allPositions: all(), snap})); + } + for (const spot of model.placeDevices({ids: missing, allPositions: anchors, snap})) positions.set(spot.id, {x: spot.x, y: spot.y}); + // Sub-devices without a saved spot go right of their meter, or one step + // right of the origin when the meter is gone (same rule as the map page). + for (const sub of this.subDevices()) { + if (positions.has(sub.id)) continue; + const anchor = positions.get(sub.device_id) || {x: 0, y: 0}; + positions.set(sub.id, window.DeviceMapSubDevices.placeNew({anchor, taken: all(), snap: null})); + } + for (const [id, group] of Object.entries(this.groups)) { + const nodeId = model.GROUP_PREFIX + id; + if (positions.has(nodeId)) continue; + const members = [...(group.members.devices || []), ...(group.members.groups || []).map(child => model.GROUP_PREFIX + child)]; + positions.set(nodeId, model.placeGroup({memberPositions: members.map(member => positions.get(member)).filter(Boolean), allPositions: all(), snap})); + } + // Data flow nodes and stubs, only while the data layer is on. Rules + // hang under the automation device when it has a position. + if (config.layers(this).data) { + const edges = df.flowEdges(this.flows, this.baseNodeIds(), balanceId); + const automation = positions.get('automation'); + const missing = this.flowNodes().filter(node => !positions.has(node.id)).map(node => ({ + id: node.id, + inputXs: edges.filter(edge => edge.to === node.id).map(edge => positions.get(edge.from)).filter(Boolean).map(position => position.x), + anchor: node.kind === 'rule' && automation ? {x: automation.x, y: automation.y} : undefined, + })); + for (const spot of df.placeFlowNodes({nodes: missing, allPositions: all(), snap})) positions.set(spot.id, {x: spot.x, y: spot.y}); + for (const stub of this.stubInfo().nodes) { + const anchor = positions.get(stub.anchor); + if (anchor) positions.set(stub.id, df.stubPosition(anchor, stub.unresolved.direction, stub.index)); + } + } + return positions; + }, + + // The note under a node on a substitute value, nothing for all others. + substituteLabel(entry) { + const nameOf = id => (this.devices.find(device => device.id === id) || {}).name || id; + const note = window.DeviceMapModel.substituteNote(entry, nameOf); + return note ? {note} : {}; + }, + + colorOf() { + const cache = {}; + return token => { + if (!(token in cache)) cache[token] = window.DashboardTheme.color(token); + return cache[token]; + }; + }, + + // Data flow edges of the visible layers: role edges (switch on, see + // the config), flow edges and stubs. Automation links follow the view. + dataEdges() { + const df = window.DeviceMapDataflow; + const layers = config.layers(this); + const nodeIds = this.nodeIds(); + const roles = config.roleEdges(this) ? this.roleEdgeList().filter(edge => nodeIds.has(edge.from)) : []; + const flows = layers.data ? df.flowEdges(this.flows, this.baseNodeIds(), this.balanceId()) : []; + const stubEdges = layers.data ? this.stubInfo().edges : []; + const edges = [...roles, ...flows, ...stubEdges].filter(edge => df.edgeVisible(edge, layers)); + return this.view.hide_automation_links ? edges.filter(edge => !df.isAutomationLink(edge)) : edges; + }, + + elements() { + const model = window.DeviceMapModel; + const graph = window.DeviceMapGraph; + const df = window.DeviceMapDataflow; + const layers = config.layers(this); + const energy = this.energyByDevice(); + const colorOf = this.colorOf(); + const positions = this.positions(); + const withPosition = (element, id) => (positions.get(id) ? {...element, position: positions.get(id)} : element); + const balanceId = this.balanceId(); + const devices = this.devices.map(device => withPosition({ + data: {id: device.id, name: device.name || device.id, + svg: device.id === balanceId + ? window.DeviceMapNodeSvg.virtualDataUri('balance', colorOf) + : window.DeviceMapNodeSvg.dataUri(model.ringSpec(energy.get(device.id), model.deviceHealth(device), (device.entities || []).length > 0, this.iconMarkup), colorOf)}, + }, device.id)); + const subs = this.subDevices().map(sub => withPosition({ + data: {id: sub.id, name: sub.label || sub.id, svg: window.DeviceMapNodeSvg.dataUri(this.subSpec(sub, energy), colorOf)}, + classes: this.subIsOrphan(sub) ? 'devicemap-sub devicemap-sub-orphan' : 'devicemap-sub', + }, sub.id)); + const groups = Object.entries(this.groups).map(([id, group]) => withPosition({ + data: {id: model.GROUP_PREFIX + id, name: group.label, svg: window.DeviceMapNodeSvg.groupDataUri(colorOf)}, classes: 'devicemap-group', + }, model.GROUP_PREFIX + id)); + const virtualKinds = [ + ...(balanceId === df.BALANCE_ID && (layers.balance || layers.data) ? [{id: df.BALANCE_ID, kind: 'balance', name: t('devicemap.balance.name')}] : []), + ...(layers.data ? this.flowNodes().map(node => ({id: node.id, kind: node.kind, name: node.name})) : []), + ...(layers.data ? this.stubInfo().nodes.map(stub => ({id: stub.id, kind: 'stub', name: t('devicemap.stub.name')})) : []), + ]; + const virtual = graph.virtualElements({kinds: virtualKinds, positions, colorOf}); + const wiring = this.wiringEdges(); + const flows = layers.energy ? graph.flowElements({pairs: graph.pairsOf(wiring), energy, view: this.view, edgeProps: this.deviceMap.edge_props}) : []; + return [...devices, ...subs, ...groups, ...virtual, ...wiring, ...flows, ...graph.dataEdgeElements(this.dataEdges())]; + }, + + labelItems() { + const model = window.DeviceMapModel; + const energy = this.energyByDevice(); + const {children, dirOf} = window.DeviceMapWiring.flowContext(window.DeviceMapGraph.pairsOf(this.wiringEdges()), this.deviceMap.edge_props, energy); + const df = window.DeviceMapDataflow; + const balanceId = this.balanceId(); + const balanceText = model.balanceValueText(this.energy && this.energy.balance); + return [ + ...this.devices.map(device => ({id: device.id, name: device.name || device.id, + value: device.id === balanceId ? balanceText : model.nodeValueText(device, energy.get(device.id)), + ...this.substituteLabel(energy.get(device.id))})), + ...this.subDevices().map(sub => ({id: sub.id, name: sub.label || sub.id, value: this.subValueText(sub, energy)})), + ...Object.entries(this.groups).map(([id, group]) => ({id: model.GROUP_PREFIX + id, name: group.label, value: model.groupValueText(model.edgeFlow(model.GROUP_PREFIX + id, energy, children, {dirOf}))})), + ...(balanceId === df.BALANCE_ID ? [{id: df.BALANCE_ID, name: t('devicemap.balance.name'), value: balanceText}] : []), + ]; + }, + + reducedMotion() { + return Boolean(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches); + }, + + graphStyle() { + const theme = window.DashboardTheme.colors({line: 'border', accent: 'accent', labelStrong: 'text-strong', panel: 'panel', info: 'info-line', faint: 'text-faint', warn: 'warn-line', subtle: 'text-subtle'}); + const colorOf = this.colorOf(); + const style = window.DeviceMapGraph.style({view: this.view, theme, color: token => colorOf(token), reducedMotion: this.reducedMotion()}); + return config.extraStyle ? [...style, ...config.extraStyle(this, theme)] : style; + }, + + flowAnimator() { + if (!this._animator) { + this._animator = window.DeviceMapGraph.createFlowAnimator({ + getCy: () => cy, + shouldAnimate: () => this.isActive() && !this.reducedMotion(), + requestFrame: fn => (window.requestAnimationFrame ? window.requestAnimationFrame(fn) : null), + cancelFrame: id => { if (window.cancelAnimationFrame) window.cancelAnimationFrame(id); }, + }); + } + return this._animator; + }, + + render() { + if (!this.$refs.canvas || typeof window.cytoscape !== 'function') return; + if (cy) cy.destroy(); + const hasPositions = (this.deviceMap.nodes || []).length > 0; + cy = window.cytoscape({ + container: this.$refs.canvas, + elements: this.elements(), + style: this.graphStyle(), + layout: hasPositions ? {name: 'preset', fit: true, padding: 24} : {name: 'breadthfirst', directed: true, padding: 24}, + autoungrabify: true, + userZoomingEnabled: false, + userPanningEnabled: false, + boxSelectionEnabled: false, + }); + cy.on('tap', 'node', event => this.onNodeTap(event.target.id())); + cy.on('tap', event => { if (event.target === cy) this.setFocus(null); }); + if (this.$refs.labels && !labels) labels = window.DeviceMapLabels.create(this.$refs.labels); + if (labels) { + labels.update(this.labelItems()); + cy.on('render', () => labels.sync(cy)); + labels.sync(cy); + } + this.flowAnimator().start(); + if (config.onRendered) config.onRendered(this, cy); + }, + + applyEnergy() { + if (!cy) return; + // A value change rebuilds the elements but keeps the instance, like + // the device map's applyEnergy(): nodes get new images, flows and + // role edges are replaced. + const fresh = new Map(this.elements().map(element => [element.data.id, element])); + cy.batch(() => { + cy.nodes().forEach(node => { const next = fresh.get(node.id()); if (next && next.data.svg) node.data('svg', next.data.svg); }); + cy.edges('.devicemap-flow, .devicemap-data').remove(); + for (const element of fresh.values()) { + if (element.classes && /devicemap-(flow|data)/.test(element.classes)) cy.add({group: 'edges', ...element}); + } + }); + if (labels) { labels.update(this.labelItems()); labels.sync(cy); } + if (this.focusId) this.setFocus(this.focusId); + this.flowAnimator().start(); + }, + + setFocus(id) { + this.focusId = id; + const df = window.DeviceMapDataflow; + const related = id ? df.relatedFocus(id, {wiringPairs: window.DeviceMapGraph.pairsOf(this.wiringEdges()), dataEdges: this.dataEdges(), layers: config.layers(this)}) : null; + if (labels) labels.setDimmed(related ? related.nodes : null); + if (!cy) return; + cy.batch(() => { + cy.elements().removeClass('devicemap-dimmed devicemap-focused'); + if (!related) return; + cy.nodes().forEach(node => { if (!related.nodes.has(node.id())) node.addClass('devicemap-dimmed'); }); + cy.edges().forEach(edge => { + if (!(related.nodes.has(edge.data('source')) && related.nodes.has(edge.data('target')))) edge.addClass('devicemap-dimmed'); + }); + cy.getElementById(id).addClass('devicemap-focused'); + }); + }, + + onNodeTap(id) { + config.onNodeTap(this, id); + }, + + // The rendered Cytoscape instance and the label overlay, null before + // the first render and after destroy(). + cy() { + return cy; + }, + + labels() { + return labels; + }, + }; + }; + + window.DeviceMapLive = {create}; +})(); diff --git a/dashboard/internal/webui/static/js/energy-plant.js b/dashboard/internal/webui/static/js/energy-plant.js index 7a2b8845a..10e2761e7 100644 --- a/dashboard/internal/webui/static/js/energy-plant.js +++ b/dashboard/internal/webui/static/js/energy-plant.js @@ -1,17 +1,10 @@ // Read-only plant view on the energy tab: the device map arrangement with // the energy and balance layers fixed on, no dragging, no panel. Clicking a // device flashes its rows in the role table, clicking a row highlights the -// device. Spec section "Energie-Tab". +// device. Spec section "Energie-Tab". The renderer lives in devicemap-live.js, +// this file only configures it. (() => { - const t = (key, params) => (window.I18n ? window.I18n.t(key, params) : key); - const requestJSON = async url => { - const response = await fetch(`${window.__DASHBOARD_BASE_PATH__ || ''}${url}`); - const body = await response.json().catch(() => ({})); - if (!response.ok) throw new Error((body && body.message) || 'request failed'); - return body; - }; const LAYERS = Object.freeze({wiring: false, energy: true, balance: true, data: false}); - const REFRESH_MS = 1000; // Role edges are opt-in on the plant view, remembered per browser. const ROLE_EDGES_KEY = 'energy-plant-role-edges'; const readRoleEdges = () => { @@ -21,361 +14,65 @@ try { window.localStorage.setItem(ROLE_EDGES_KEY, on ? '1' : '0'); } catch (error) { /* the choice lasts for this page only */ } }; - const energyPlantView = () => { - let cy = null; - let labels = null; - return { - devices: [], - deviceMap: {version: 2, nodes: [], edges: []}, - energy: null, - groups: {}, - categories: {}, - iconMarkup: {}, - focusId: null, - roleEdgesOn: false, - empty: false, - loading: false, - _timer: null, - _pending: false, - _animator: null, - _setTimeout: (fn, ms) => setTimeout(fn, ms), - _offs: [], + const PLANT_CONFIG = { + layers: () => LAYERS, + roleEdges: c => c.roleEdgesOn, + automationLinks: () => undefined, + edgeStyle: () => '', + widthByPower: () => '', + isActive: () => { + const panel = document.getElementById('energy-panel'); + return Boolean(panel && panel.classList.contains('active')) && document.visibilityState === 'visible'; + }, + onNodeTap: (c, id) => { + c.setFocus(id); + const model = window.DeviceMapModel; + if (model.isGroupId(id)) { + window.dispatchEvent(new CustomEvent('energy-focus-group', {detail: {id: id.slice(model.GROUP_PREFIX.length)}})); + return; + } + const device = c.devices.find(candidate => candidate.id === id); + if (!device) return; + const ids = (device.entities || []).filter(entity => model.isEligibleUnit(entity.unit_of_measurement)).map(entity => entity.unique_id); + if (ids.length) window.dispatchEvent(new CustomEvent('energy-focus-rows', {detail: {ids}})); + }, + }; - get view() { - const stored = this.deviceMap.view || {}; - return {edge_style: 'curved', width_by_power: false, ...stored, layers: LAYERS}; - }, + const method = fn => ({value: fn, writable: true, enumerable: true, configurable: true}); - async load() { - if (!this._offs.length) { - const on = (target, name, fn) => { target.addEventListener(name, fn); this._offs.push(() => target.removeEventListener(name, fn)); }; - on(window, 'registry-updated', () => this.onRegistryUpdated()); - on(window, 'energy-roles-changed', () => this.load()); - on(window, 'device-map-changed', () => this.load()); - on(window, 'energy-plant-focus', event => this.focusEntity((event.detail || {}).entityId)); - const wake = () => setTimeout(() => this.flowAnimator().start(), 0); - on(document, 'visibilitychange', wake); - on(window, 'dashboard-panel-changed', wake); + const energyPlantView = () => { + const core = window.DeviceMapLive.create(PLANT_CONFIG); + const coreLoad = core.load; + const coreDestroy = core.destroy; + let offFocus = null; + return Object.defineProperties({}, { + ...Object.getOwnPropertyDescriptors(core), + roleEdgesOn: {value: false, writable: true, enumerable: true, configurable: true}, + load: method(function load() { + if (!offFocus) { + const onFocus = event => this.focusEntity((event.detail || {}).entityId); + window.addEventListener('energy-plant-focus', onFocus); + offFocus = () => window.removeEventListener('energy-plant-focus', onFocus); this.roleEdgesOn = readRoleEdges(); } - this.loading = true; - try { - const [devices, deviceMap, energy, roles, icons] = await Promise.all([ - requestJSON('/api/v1/devices'), - requestJSON('/api/v1/device/map').catch(() => null), - requestJSON('/api/v1/energy').catch(() => null), - requestJSON('/api/v1/energy/roles').catch(() => null), - requestJSON('/api/v1/device/icons').catch(() => []), - ]); - this.devices = devices || []; - this.deviceMap = deviceMap || {version: 2, nodes: [], edges: []}; - this.energy = energy; - this.groups = (roles && roles.groups) || {}; - this.categories = (roles && roles.categories) || {}; - this.iconMarkup = Object.fromEntries((Array.isArray(icons) ? icons : []).map(icon => [icon.name, icon.markup])); - this.empty = this.devices.every(device => device.id === window.DeviceMapModel.OWN_ENERGY_DEVICE_ID); - this.render(); - } finally { - this.loading = false; - } - }, - - destroy() { - this._offs.forEach(off => off()); - this._offs = []; - this.flowAnimator().stop(); - if (labels) { labels.destroy(); labels = null; } - if (cy) { cy.destroy(); cy = null; } - }, - - isActive() { - const panel = document.getElementById('energy-panel'); - return Boolean(panel && panel.classList.contains('active')) && document.visibilityState === 'visible'; - }, - - onRegistryUpdated() { - if (!this.isActive()) return; - if (this._timer) { this._pending = true; return; } - this.refreshEnergy(); - this._timer = this._setTimeout(() => { - this._timer = null; - if (this._pending) { this._pending = false; this.onRegistryUpdated(); } - }, REFRESH_MS); - }, - - async refreshEnergy() { - this.energy = await requestJSON('/api/v1/energy').catch(() => null); - this.applyEnergy(); - }, - - groupIds() { - return Object.keys(this.groups).map(id => window.DeviceMapModel.GROUP_PREFIX + id); - }, - - balanceId() { - return window.DeviceMapDataflow.balanceNodeId(new Set(this.devices.map(device => device.id))); - }, - - subDevices() { - return window.DeviceMapSubDevices.list(this.deviceMap); - }, - - // Role edges from the devices (and sub-devices) to the balance node. - roleEdgeList() { - return window.DeviceMapDataflow.roleEdges(this.energy, this.balanceId(), this.deviceMap); - }, - + return coreLoad.call(this); + }), + destroy: method(function destroy() { + if (offFocus) { offFocus(); offFocus = null; } + coreDestroy.call(this); + }), // Switch in the plant head. The edges are rebuilt in place, the // arrangement and the flows stay as they are. - toggleRoleEdges(on) { + toggleRoleEdges: method(function toggleRoleEdges(on) { this.roleEdgesOn = Boolean(on); writeRoleEdges(this.roleEdgesOn); this.applyEnergy(); - }, - - subIsOrphan(sub) { - return window.DeviceMapSubDevices.isOrphan(sub, this.devices); - }, - - nodeIds() { - return new Set([...this.devices.map(device => device.id), ...this.subDevices().map(sub => sub.id), ...this.groupIds(), this.balanceId()]); - }, - - // Entities with a sub-device are measured under the sub-device's ID, so - // the meter keeps the ring of its other entities (as on the map page). - energyByDevice() { - return window.DeviceMapModel.deviceEnergy(window.DeviceMapSubDevices.remapSnapshot(this.energy, this.deviceMap)); - }, - - // Value of a sub-device node: its entity's reading, or the hint when - // the meter or the entity is gone. - subValueText(sub, energy) { - if (this.subIsOrphan(sub)) return t('devicemap.sub.missing'); - const device = this.devices.find(item => item.id === sub.device_id); - const entities = ((device && device.entities) || []).filter(entity => entity && entity.unique_id === sub.entity_id); - return window.DeviceMapModel.nodeValueText({entities}, energy.get(sub.id)); - }, - - // Dashed ring in the colour of the first role, the sub-device icon, no - // health dot (same spec as the map page). - subSpec(sub, energy) { - const entry = energy.get(sub.id); - const role = entry && entry.primaryRole; - return { - segments: entry ? entry.roles.map(item => entry.meta[item].color) : [], - icon: sub.icon ? `cat:${sub.icon}` : 'box', - iconColor: role ? entry.meta[role].color : 'text-muted', - health: 'unknown', - subDevice: true, - iconMarkup: this.iconMarkup[sub.icon] || '', - }; - }, - - wiringEdges() { - const wiring = window.DeviceMapGraph.wiringElements({devices: this.devices, deviceMap: this.deviceMap, groups: this.groups, nodeIds: this.nodeIds(), energy: this.energyByDevice()}); - if (!this.view.hide_automation_links) return wiring; - return wiring.filter(element => !window.DeviceMapDataflow.isAutomationLink({from: element.data.source, to: element.data.target})); - }, - - positions() { - const model = window.DeviceMapModel; - const df = window.DeviceMapDataflow; - const snap = value => value; - const positions = new Map((this.deviceMap.nodes || []).map(node => [node.device_id || node.virtual_id, {x: node.x, y: node.y}])); - const all = () => [...positions.values()]; - // Same spots the device map would pick, so a device that is not yet - // saved there does not land on the origin on top of another one. - const anchors = this.devices.map(device => positions.get(device.id)).filter(Boolean); - const balanceId = this.balanceId(); - const missing = this.devices.filter(device => !positions.has(device.id) && device.id !== balanceId).map(device => device.id); - if (balanceId !== df.BALANCE_ID && !(this.deviceMap.nodes || []).some(node => node.device_id === balanceId) && positions.has(df.BALANCE_ID)) { - positions.set(balanceId, positions.get(df.BALANCE_ID)); - } - if (!positions.has(balanceId)) { - const roleDevices = this.roleEdgeList().map(edge => positions.get(edge.from)).filter(Boolean); - positions.set(balanceId, df.placeBalance({rolePositions: roleDevices, allPositions: all(), snap})); - } - for (const spot of model.placeDevices({ids: missing, allPositions: anchors, snap})) positions.set(spot.id, {x: spot.x, y: spot.y}); - // Sub-devices without a saved spot go right of their meter, or one step - // right of the origin when the meter is gone (same rule as the map page). - for (const sub of this.subDevices()) { - if (positions.has(sub.id)) continue; - const anchor = positions.get(sub.device_id) || {x: 0, y: 0}; - positions.set(sub.id, window.DeviceMapSubDevices.placeNew({anchor, taken: all(), snap: null})); - } - for (const [id, group] of Object.entries(this.groups)) { - const nodeId = model.GROUP_PREFIX + id; - if (positions.has(nodeId)) continue; - const members = [...(group.members.devices || []), ...(group.members.groups || []).map(child => model.GROUP_PREFIX + child)]; - positions.set(nodeId, model.placeGroup({memberPositions: members.map(member => positions.get(member)).filter(Boolean), allPositions: all(), snap})); - } - return positions; - }, - - // The note under a node on a substitute value, nothing for all others. - substituteLabel(entry) { - const nameOf = id => (this.devices.find(device => device.id === id) || {}).name || id; - const note = window.DeviceMapModel.substituteNote(entry, nameOf); - return note ? {note} : {}; - }, - - colorOf() { - const cache = {}; - return token => { - if (!(token in cache)) cache[token] = window.DashboardTheme.color(token); - return cache[token]; - }; - }, - - elements() { - const model = window.DeviceMapModel; - const graph = window.DeviceMapGraph; - const df = window.DeviceMapDataflow; - const energy = this.energyByDevice(); - const colorOf = this.colorOf(); - const positions = this.positions(); - const withPosition = (element, id) => (positions.get(id) ? {...element, position: positions.get(id)} : element); - const balanceId = this.balanceId(); - const devices = this.devices.map(device => withPosition({ - data: {id: device.id, name: device.name || device.id, - svg: device.id === balanceId - ? window.DeviceMapNodeSvg.virtualDataUri('balance', colorOf) - : window.DeviceMapNodeSvg.dataUri(model.ringSpec(energy.get(device.id), model.deviceHealth(device), (device.entities || []).length > 0, this.iconMarkup), colorOf)}, - }, device.id)); - const subs = this.subDevices().map(sub => withPosition({ - data: {id: sub.id, name: sub.label || sub.id, svg: window.DeviceMapNodeSvg.dataUri(this.subSpec(sub, energy), colorOf)}, - classes: this.subIsOrphan(sub) ? 'devicemap-sub devicemap-sub-orphan' : 'devicemap-sub', - }, sub.id)); - const groups = Object.entries(this.groups).map(([id, group]) => withPosition({ - data: {id: model.GROUP_PREFIX + id, name: group.label, svg: window.DeviceMapNodeSvg.groupDataUri(colorOf)}, classes: 'devicemap-group', - }, model.GROUP_PREFIX + id)); - const balance = balanceId === df.BALANCE_ID - ? graph.virtualElements({kinds: [{id: df.BALANCE_ID, kind: 'balance', name: t('devicemap.balance.name')}], positions, colorOf}) - : []; - const wiring = this.wiringEdges(); - const flows = graph.flowElements({pairs: graph.pairsOf(wiring), energy, view: this.view, edgeProps: this.deviceMap.edge_props}); - const roles = this.roleEdgesOn ? graph.dataEdgeElements(this.roleEdgeList().filter(edge => this.nodeIds().has(edge.from))) : []; - return [...devices, ...subs, ...groups, ...balance, ...wiring, ...flows, ...roles]; - }, - - labelItems() { - const model = window.DeviceMapModel; - const energy = this.energyByDevice(); - const {children, dirOf} = window.DeviceMapWiring.flowContext(window.DeviceMapGraph.pairsOf(this.wiringEdges()), this.deviceMap.edge_props, energy); - const df = window.DeviceMapDataflow; - const balanceId = this.balanceId(); - const balanceText = model.balanceValueText(this.energy && this.energy.balance); - return [ - ...this.devices.map(device => ({id: device.id, name: device.name || device.id, - value: device.id === balanceId ? balanceText : model.nodeValueText(device, energy.get(device.id)), - ...this.substituteLabel(energy.get(device.id))})), - ...this.subDevices().map(sub => ({id: sub.id, name: sub.label || sub.id, value: this.subValueText(sub, energy)})), - ...Object.entries(this.groups).map(([id, group]) => ({id: model.GROUP_PREFIX + id, name: group.label, value: model.groupValueText(model.edgeFlow(model.GROUP_PREFIX + id, energy, children, {dirOf}))})), - ...(balanceId === df.BALANCE_ID ? [{id: df.BALANCE_ID, name: t('devicemap.balance.name'), value: balanceText}] : []), - ]; - }, - - reducedMotion() { - return Boolean(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches); - }, - - graphStyle() { - const theme = window.DashboardTheme.colors({line: 'border', accent: 'accent', labelStrong: 'text-strong', panel: 'panel', info: 'info-line', faint: 'text-faint', warn: 'warn-line', subtle: 'text-subtle'}); - const colorOf = this.colorOf(); - return window.DeviceMapGraph.style({view: this.view, theme, color: token => colorOf(token), reducedMotion: this.reducedMotion()}); - }, - - flowAnimator() { - if (!this._animator) { - this._animator = window.DeviceMapGraph.createFlowAnimator({ - getCy: () => cy, - shouldAnimate: () => this.isActive() && !this.reducedMotion(), - requestFrame: fn => (window.requestAnimationFrame ? window.requestAnimationFrame(fn) : null), - cancelFrame: id => { if (window.cancelAnimationFrame) window.cancelAnimationFrame(id); }, - }); - } - return this._animator; - }, - - render() { - if (!this.$refs.canvas || typeof window.cytoscape !== 'function') return; - if (cy) cy.destroy(); - const hasPositions = (this.deviceMap.nodes || []).length > 0; - cy = window.cytoscape({ - container: this.$refs.canvas, - elements: this.elements(), - style: this.graphStyle(), - layout: hasPositions ? {name: 'preset', fit: true, padding: 24} : {name: 'breadthfirst', directed: true, padding: 24}, - autoungrabify: true, - userZoomingEnabled: false, - userPanningEnabled: false, - boxSelectionEnabled: false, - }); - cy.on('tap', 'node', event => this.onNodeTap(event.target.id())); - cy.on('tap', event => { if (event.target === cy) this.setFocus(null); }); - if (this.$refs.labels && !labels) labels = window.DeviceMapLabels.create(this.$refs.labels); - if (labels) { - labels.update(this.labelItems()); - cy.on('render', () => labels.sync(cy)); - labels.sync(cy); - } - this.flowAnimator().start(); - }, - - applyEnergy() { - if (!cy) return; - // A value change rebuilds the elements but keeps the instance, like - // the device map's applyEnergy(): nodes get new images, flows and - // role edges are replaced. - const fresh = new Map(this.elements().map(element => [element.data.id, element])); - cy.batch(() => { - cy.nodes().forEach(node => { const next = fresh.get(node.id()); if (next && next.data.svg) node.data('svg', next.data.svg); }); - cy.edges('.devicemap-flow, .devicemap-data').remove(); - for (const element of fresh.values()) { - if (element.classes && /devicemap-(flow|data)/.test(element.classes)) cy.add({group: 'edges', ...element}); - } - }); - if (labels) { labels.update(this.labelItems()); labels.sync(cy); } - if (this.focusId) this.setFocus(this.focusId); - this.flowAnimator().start(); - }, - - setFocus(id) { - this.focusId = id; - const df = window.DeviceMapDataflow; - const dataEdges = this.roleEdgesOn ? this.roleEdgeList() : []; - const related = id ? df.relatedFocus(id, {wiringPairs: window.DeviceMapGraph.pairsOf(this.wiringEdges()), dataEdges, layers: LAYERS}) : null; - if (labels) labels.setDimmed(related ? related.nodes : null); - if (!cy) return; - cy.batch(() => { - cy.elements().removeClass('devicemap-dimmed devicemap-focused'); - if (!related) return; - cy.nodes().forEach(node => { if (!related.nodes.has(node.id())) node.addClass('devicemap-dimmed'); }); - cy.edges().forEach(edge => { - if (!(related.nodes.has(edge.data('source')) && related.nodes.has(edge.data('target')))) edge.addClass('devicemap-dimmed'); - }); - cy.getElementById(id).addClass('devicemap-focused'); - }); - }, - - onNodeTap(id) { - this.setFocus(id); - const model = window.DeviceMapModel; - if (model.isGroupId(id)) { - window.dispatchEvent(new CustomEvent('energy-focus-group', {detail: {id: id.slice(model.GROUP_PREFIX.length)}})); - return; - } - const device = this.devices.find(candidate => candidate.id === id); - if (!device) return; - const ids = (device.entities || []).filter(entity => model.isEligibleUnit(entity.unit_of_measurement)).map(entity => entity.unique_id); - if (ids.length) window.dispatchEvent(new CustomEvent('energy-focus-rows', {detail: {ids}})); - }, - - focusEntity(entityId) { + }), + focusEntity: method(function focusEntity(entityId) { const device = this.devices.find(candidate => (candidate.entities || []).some(entity => entity.unique_id === entityId)); if (device) this.setFocus(device.id); - }, - }; + }), + }); }; const register = () => { diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 970131984..619c1fb63 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -242,7 +242,7 @@

{{t "no_access.title"}}

{{if .Manager}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} -{{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} +{{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} {{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}}

{{t "panel.settings_loading"}}

{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index 53b0458a7..c985ff563 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -62,7 +62,7 @@ func TestOverviewRendersManagerControls(t *testing.T) { "id=\"devices-live\"", "hx-get=\"/?fragment=devices-live\"", "id=\"runtime-status\"", "runtimeStatusPanel", "data-runtime-status-enabled=\"true\"", "class=\"masthead-tools\"", "status-chip", "device-detail", "device-modal-warning", "discovery-diagnostics", "discovery_errors", "duplicateIDs", "discovery-error", - "Konfiguration", "Einstellungen", "Diagnose", "license-footer", "(0BSD)", "(MIT, Copyright Caleb Porzio)", "ApexCharts 4.7.0", "(MIT, Copyright ApexCharts)", "ApexCharts-Lizenz", "v2.0.6/LICENSE", "v3.14.9/README.md", "configPanel", "x-model=\"selectedName\"", "reloadService()", "show-runtime-status", "showRuntimeStatus", "role=\"switch\"", "settings-toggle-track", "id=\"config-panel\"", "id=\"energy-panel\"", "data-panel-script=\"/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/config-status.js?v=4,/static/js/config.page.js?v=11\"", "data-panel-script=\"/static/js-deps/cytoscape.min.js,/static/js/revisions.js?v=4,/static/js/devicemap-model.js?v=16,/static/js/devicemap-subdevices.js?v=1,/static/js/energy-chains.js?v=2,/static/js/energy-chain-suggest.js?v=2,/static/js/devicemap-graph.js?v=12,/static/js/devicemap-wiring.js?v=3,/static/js/devicemap-dataflow.js?v=5,/static/js/devicemap-node-svg.js?v=7,/static/js/devicemap-labels.js?v=6,/static/js/energy-plant.js?v=7,/static/js/device-picker.js?v=2,/static/js/devicemap-switch.js?v=2,/static/js/energy.page.js?v=19\"", "data-panel-css=\"/static/css/manager.css?v=54\"", + "Konfiguration", "Einstellungen", "Diagnose", "license-footer", "(0BSD)", "(MIT, Copyright Caleb Porzio)", "ApexCharts 4.7.0", "(MIT, Copyright ApexCharts)", "ApexCharts-Lizenz", "v2.0.6/LICENSE", "v3.14.9/README.md", "configPanel", "x-model=\"selectedName\"", "reloadService()", "show-runtime-status", "showRuntimeStatus", "role=\"switch\"", "settings-toggle-track", "id=\"config-panel\"", "id=\"energy-panel\"", "data-panel-script=\"/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/config-status.js?v=4,/static/js/config.page.js?v=11\"", "data-panel-script=\"/static/js-deps/cytoscape.min.js,/static/js/revisions.js?v=4,/static/js/devicemap-model.js?v=16,/static/js/devicemap-subdevices.js?v=1,/static/js/energy-chains.js?v=2,/static/js/energy-chain-suggest.js?v=2,/static/js/devicemap-graph.js?v=12,/static/js/devicemap-wiring.js?v=3,/static/js/devicemap-dataflow.js?v=5,/static/js/devicemap-node-svg.js?v=7,/static/js/devicemap-labels.js?v=6,/static/js/devicemap-live.js?v=1,/static/js/energy-plant.js?v=7,/static/js/device-picker.js?v=2,/static/js/devicemap-switch.js?v=2,/static/js/energy.page.js?v=19\"", "data-panel-css=\"/static/css/manager.css?v=54\"", "schema-form", "revision-preview", "config-presets-error", "config-actionbar-dock", "initActionBar()", "actionStatusText", "expandActions()", "id=\"config-form-save\"", "x-on:input=\"formDirty = true\"", "config-json", "resetEditor()", "id=\"config-save\"", "config-meta", "revision-diff", "revisionPanel(revisionConfig())", "setRevisionView('diff')", diff --git a/dashboard/test/devicemap-live.test.mjs b/dashboard/test/devicemap-live.test.mjs new file mode 100644 index 000000000..14e12d6d1 --- /dev/null +++ b/dashboard/test/devicemap-live.test.mjs @@ -0,0 +1,160 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JSDOM } from 'jsdom'; +import { installI18n } from './helpers/i18n.mjs'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const jsDir = path.join(here, '..', 'internal', 'webui', 'static', 'js'); +const files = ['theme.js', 'devicemap-model.js', 'devicemap-graph.js', 'devicemap-wiring.js', 'devicemap-subdevices.js', 'devicemap-dataflow.js', 'devicemap-node-svg.js', 'devicemap-labels.js', 'devicemap-live.js']; + +function routes(table) { + return async url => { + const key = Object.keys(table).find(prefix => String(url).endsWith(prefix)); + if (!key) return { ok: false, status: 404, json: async () => ({}) }; + return { ok: true, status: 200, json: async () => JSON.parse(JSON.stringify(table[key])) }; + }; +} + +// Builds the shared core with its own config, the way a card or the plant +// view does. The component is not wrapped in Alpine here. +function createLive(table, config) { + const dom = new JSDOM('', { runScripts: 'outside-only', pretendToBeVisual: true, url: 'http://localhost/' }); + dom.window.fetch = routes(table); + installI18n(dom.window); + const context = dom.getInternalVMContext(); + for (const name of files) vm.runInContext(fs.readFileSync(path.join(jsDir, name), 'utf8'), context); + const component = dom.window.DeviceMapLive.create({ ...CONFIG, ...config }); + component.$refs = {}; + return { component, window: dom.window }; +} + +// Inactive by default, so no animation loop runs during the tests. +const CONFIG = { + layers: () => ({ wiring: false, energy: true, balance: true, data: false }), + roleEdges: () => false, + automationLinks: () => undefined, + edgeStyle: () => '', + widthByPower: () => '', + isActive: () => false, + onNodeTap: () => {}, +}; + +const DEVICES = [ + { id: 'pv', name: 'PV', entities: [{ unique_id: 'pv1', unit_of_measurement: 'W', value: '500' }] }, + { id: 'wb', name: 'Wallbox', entities: [{ unique_id: 'wb1', unit_of_measurement: 'W', value: '300' }] }, +]; + +const TABLE = { + '/api/v1/devices': DEVICES, + '/api/v1/device/map': { version: 2, nodes: [{ device_id: 'pv', x: 100, y: 100 }, { device_id: 'wb', x: 300, y: 100 }], edges: [] }, + '/api/v1/energy': { entities: [ + { device_id: 'pv', entity_id: 'pv1', value: 500, unit: 'W', role: { role: 'pv', source: 'override' } }, + { device_id: 'wb', entity_id: 'wb1', value: 300, unit: 'W', role: { role: 'wallbox', source: 'override' } }, + ], balance: { grid_import: 0, grid_export: 200 } }, + '/api/v1/energy/roles': { assignments: {}, groups: {}, categories: {} }, + '/api/v1/device/icons': [], +}; + +const FLOWS = { + nodes: [{ virtual_id: 'rule:r1', kind: 'rule', label: 'R1' }], + edges: [{ id: 'e1', cat: 'trigger', from: { device_id: 'pv' }, to: { virtual_id: 'rule:r1' } }], + unresolved: [{ id: 'u1', target: { device_id: 'wb' }, direction: 'output' }], +}; + +const ids = component => component.elements().map(element => element.data.id); + +test('layers come from the config', async () => { + const { component } = createLive(TABLE, { layers: () => ({ wiring: false, energy: false, balance: false, data: false }) }); + await component.load(); + const elements = component.elements(); + assert.ok(!elements.some(element => element.classes && element.classes.includes('devicemap-flow')), 'no energy flow without the energy layer'); + assert.ok(!ids(component).includes('balance'), 'no balance node'); + assert.ok(!ids(component).some(id => id.startsWith('data-')), 'no data edge'); +}); + +test('data layer loads flows and adds rule nodes, data edges and stubs', async () => { + const calls = []; + const { component, window } = createLive({ ...TABLE, '/api/v1/device/map/flows': FLOWS }, { layers: () => ({ wiring: false, energy: true, balance: false, data: true }) }); + window.fetch = async url => { calls.push(String(url)); return routes({ ...TABLE, '/api/v1/device/map/flows': FLOWS })(url); }; + await component.load(); + assert.ok(calls.some(url => url.endsWith('/api/v1/device/map/flows')), 'flows are fetched'); + const list = ids(component); + assert.ok(list.includes('rule:r1')); + assert.ok(list.includes('data-e1')); + assert.ok(list.some(id => id.startsWith(window.DeviceMapDataflow.STUB_PREFIX)), 'a stub node'); +}); + +test('without the data layer the flows are not fetched and nothing data related is drawn', async () => { + const calls = []; + const { component, window } = createLive({ ...TABLE, '/api/v1/device/map/flows': FLOWS }, { layers: () => ({ wiring: false, energy: true, balance: true, data: false }) }); + window.fetch = async url => { calls.push(String(url)); return routes({ ...TABLE, '/api/v1/device/map/flows': FLOWS })(url); }; + await component.load(); + assert.ok(!calls.some(url => url.endsWith('/api/v1/device/map/flows'))); + const list = ids(component); + assert.ok(!list.includes('rule:r1')); + assert.ok(!list.includes('data-e1')); + assert.ok(!list.some(id => id.startsWith(window.DeviceMapDataflow.STUB_PREFIX))); +}); + +test('role edges need the balance or data layer', async () => { + const off = createLive(TABLE, { roleEdges: () => true, layers: () => ({ wiring: false, energy: true, balance: false, data: false }) }); + await off.component.load(); + assert.ok(!ids(off.component).some(id => id.startsWith('data-role:')), 'energy alone shows no role edge'); + + const on = createLive(TABLE, { roleEdges: () => true, layers: () => ({ wiring: false, energy: true, balance: true, data: false }) }); + await on.component.load(); + assert.ok(ids(on.component).includes('data-role:pv'), 'the balance layer shows the role edge'); +}); + +test('automation links follow the config', async () => { + const map = { ...TABLE['/api/v1/device/map'], edges: [{ id: 'relation-1', parent_id: 'automation', child_id: 'pv', kind: 'via_device', created_at: '' }] }; + const table = { ...TABLE, '/api/v1/devices': [...DEVICES, { id: 'automation', name: 'Automation', entities: [] }], '/api/v1/device/map': map }; + const hidden = createLive(table, { automationLinks: () => false }); + await hidden.component.load(); + const touches = element => element.data.source === 'automation' || element.data.target === 'automation'; + assert.ok(!hidden.component.elements().some(touches), 'hidden when the config says so'); + + const shown = createLive(table, { automationLinks: () => true }); + await shown.component.load(); + assert.ok(shown.component.elements().some(touches), 'shown when the config says so'); +}); + +test('edge style and width fall back to the map view', async () => { + const table = { ...TABLE, '/api/v1/device/map': { ...TABLE['/api/v1/device/map'], view: { edge_style: 'straight', width_by_power: true } } }; + const stored = createLive(table, { edgeStyle: () => '', widthByPower: () => '' }); + await stored.component.load(); + assert.equal(stored.component.view.edge_style, 'straight'); + assert.equal(stored.component.view.width_by_power, true); + + const forced = createLive(table, { edgeStyle: () => 'curved', widthByPower: () => 'off' }); + await forced.component.load(); + assert.equal(forced.component.view.edge_style, 'curved'); + assert.equal(forced.component.view.width_by_power, false); +}); + +test('an empty map shows the empty state and renders without a canvas', async () => { + const { component, window } = createLive({ ...TABLE, '/api/v1/devices': [] }); + const own = window.DeviceMapModel.OWN_ENERGY_DEVICE_ID; + const { component: ownOnly } = createLive({ ...TABLE, '/api/v1/devices': [{ id: own, name: 'Energy Node', entities: [] }] }); + await ownOnly.load(); + assert.equal(ownOnly.empty, true); + assert.doesNotThrow(() => ownOnly.render()); + await component.load(); + assert.equal(component.empty, true); +}); + +test('setFocus keeps a data edge of the focused device undimmed', async () => { + const { component, window } = createLive({ ...TABLE, '/api/v1/device/map/flows': FLOWS }, { layers: () => ({ wiring: false, energy: true, balance: false, data: true }) }); + window.fetch = routes({ ...TABLE, '/api/v1/device/map/flows': FLOWS }); + await component.load(); + const data = component.dataEdges(); + const related = window.DeviceMapDataflow.relatedFocus('pv', { wiringPairs: [], dataEdges: data, layers: component.view.layers }); + assert.ok(related.edges.has('e1'), 'the trigger edge belongs to the focus'); + assert.ok(related.nodes.has('rule:r1')); + assert.doesNotThrow(() => component.setFocus('pv')); + assert.equal(component.focusId, 'pv'); +}); diff --git a/dashboard/test/energy-plant.test.mjs b/dashboard/test/energy-plant.test.mjs index 0839d0568..febecf734 100644 --- a/dashboard/test/energy-plant.test.mjs +++ b/dashboard/test/energy-plant.test.mjs @@ -9,7 +9,7 @@ import { installI18n } from './helpers/i18n.mjs'; const here = path.dirname(fileURLToPath(import.meta.url)); const jsDir = path.join(here, '..', 'internal', 'webui', 'static', 'js'); -const files = ['theme.js', 'devicemap-model.js', 'devicemap-graph.js', 'devicemap-wiring.js', 'devicemap-subdevices.js', 'devicemap-dataflow.js', 'devicemap-node-svg.js', 'devicemap-labels.js', 'energy-plant.js']; +const files = ['theme.js', 'devicemap-model.js', 'devicemap-graph.js', 'devicemap-wiring.js', 'devicemap-subdevices.js', 'devicemap-dataflow.js', 'devicemap-node-svg.js', 'devicemap-labels.js', 'devicemap-live.js', 'energy-plant.js']; function routes(table) { return async url => { From 62c94569f1577609d3456e3ba18074c32e97b311 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:04:51 +0100 Subject: [PATCH 03/17] feat(overview): add viewport gestures and fit spring for map cards Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/devicemap-viewport.js | 270 ++++++++++++++++++ dashboard/test/devicemap-viewport.test.mjs | 270 ++++++++++++++++++ 2 files changed, 540 insertions(+) create mode 100644 dashboard/internal/webui/static/js/devicemap-viewport.js create mode 100644 dashboard/test/devicemap-viewport.test.mjs diff --git a/dashboard/internal/webui/static/js/devicemap-viewport.js b/dashboard/internal/webui/static/js/devicemap-viewport.js new file mode 100644 index 000000000..49d499616 --- /dev/null +++ b/dashboard/internal/webui/static/js/devicemap-viewport.js @@ -0,0 +1,270 @@ +// Zoom, Pan und Einpassen der Geraetekarte. Kein Alpine, kein DOM-Bau: die +// Karte reicht die Cytoscape-Instanz (getCy), den Reduced-Motion-Schalter und +// zwei Rueckrufe hinein. Die Rechenfunktionen oben sind einzeln testbar, +// create() bindet Gesten, Feder und Groessenaenderungen. +(() => { + const FIT_PADDING = 24; // px Rand beim Einpassen + const RESPONSE = 0.4; // s, Feder ohne Ueberschwingen (Daempfung 1.0) + const THRESHOLD = 0.02; // 2 % Abweichung von Zoom oder Pan + const HINT_MS = 1500; // Anzeigedauer des Hinweises, der Aufrufer setzt den Timer + const SWIPE_MIN = 24; // px, ab hier gilt ein Wisch als Wisch + const SWIPE_RATIO = 2.5; // fast waagerecht: |dx| > 2,5 * |dy| + const MIN_ZOOM = 0.1; + const MAX_ZOOM = 3; + const MAX_STEP = 1 / 120; // s, groesster Teilschritt der Feder + const OMEGA = (2 * Math.PI) / RESPONSE; + + // Mausrad-Hinweis zeigt sich einmal pro Seitenaufruf, nicht pro Karte. + let wheelHintShown = false; + + const clampZoom = zoom => Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom)); + const coarsePointer = () => Boolean(window.matchMedia && window.matchMedia('(pointer: coarse)').matches); + const midOf = (a, b) => ({x: (a.x + b.x) / 2, y: (a.y + b.y) / 2}); + + // Zoom und Pan, die alles Sichtbare mit 24 px Rand einpassen. null, wenn es + // nichts zu zeigen gibt oder die Karte keine Groesse hat. + const fitTarget = ({bb, width, height}) => { + if (!bb || !bb.w || !bb.h || !width || !height) return null; + const zoom = clampZoom(Math.min((width - 2 * FIT_PADDING) / bb.w, (height - 2 * FIT_PADDING) / bb.h)); + return {zoom, pan: {x: (width - zoom * (bb.x1 + bb.x2)) / 2, y: (height - zoom * (bb.y1 + bb.y2)) / 2}}; + }; + + // Groesste Abweichung vom Einpass-Ziel, Zoom relativ, Pan in Anteilen der kleineren Seite. + const deviation = ({zoom, pan}, target, {width, height}) => { + const zoomOff = Math.abs(zoom / target.zoom - 1); + const panOff = Math.hypot(pan.x - target.pan.x, pan.y - target.pan.y) / Math.min(width, height); + return Math.max(zoomOff, panOff); + }; + + // Ein Kanal der kritisch gedaempften Feder, semi-implizit in Teilschritten. + const springStep = (channel, target, omega, dt) => { + let left = dt; + while (left > 0) { + const h = Math.min(left, MAX_STEP); + channel.v += (-omega * omega * (channel.p - target) - 2 * omega * channel.v) * h; + channel.p += channel.v * h; + left -= h; + } + }; + + // Fast waagerecht und mindestens 24 px weit. + const isHorizontalSwipe = (dx, dy) => Math.abs(dx) > SWIPE_MIN && Math.abs(dx) > SWIPE_RATIO * Math.abs(dy); + + const create = ({container, getCy, reducedMotion, onFitShown, onHint}) => { + let destroyed = false; + let attachedCy = null; + let bbCache = null; + let spring = null; // {frame} solange die Feder laeuft + let pinch = null; + let swipe = null; + let fitShown = false; + const offs = []; + + const cy = () => (destroyed ? null : getCy()); + + const boundingBox = c => { + if (!bbCache) bbCache = c.elements(':visible').boundingBox(); + return bbCache; + }; + const targetOf = c => fitTarget({bb: boundingBox(c), width: c.width(), height: c.height()}); + + const setFitShown = value => { + if (value === fitShown) return; + fitShown = value; + onFitShown(value); + }; + + const updatePill = () => { + const c = cy(); + if (!c || spring) return; + const target = targetOf(c); + if (!target) return; + setFitShown(deviation({zoom: c.zoom(), pan: c.pan()}, target, {width: c.width(), height: c.height()}) > THRESHOLD); + }; + + // Die Feder bricht ab, ohne Ueberschwingen bleibt die Ansicht stehen. + const cancel = () => { + if (!spring) return; + cancelAnimationFrame(spring.frame); + spring = null; + updatePill(); + }; + + // Einpassen als Feder ohne Ueberschwingen, vom aktuellen Wert aus. Drei + // unabhaengige Kanaele: Mittelpunkt x/y in Kartenkoordinaten und der + // Zoom logarithmisch, damit Rein- und Rauszoomen gleich schnell wirken. + const fitAnimated = () => { + const c = cy(); + if (!c) return; + const target = targetOf(c); + if (!target) return; + cancel(); + setFitShown(false); + if (reducedMotion()) { c.viewport(target); return; } + const width = c.width(); + const height = c.height(); + const centerOf = ({zoom, pan}) => ({x: (width / 2 - pan.x) / zoom, y: (height / 2 - pan.y) / zoom}); + const from = centerOf({zoom: c.zoom(), pan: c.pan()}); + const to = centerOf(target); + const channels = [{p: from.x, v: 0}, {p: from.y, v: 0}, {p: Math.log(c.zoom()), v: 0}]; + const goal = [to.x, to.y, Math.log(target.zoom)]; + const eps = [0.25 / target.zoom, 0.25 / target.zoom, 0.001]; + let last = null; + const apply = () => { + const zoom = Math.exp(channels[2].p); + c.viewport({zoom, pan: {x: width / 2 - channels[0].p * zoom, y: height / 2 - channels[1].p * zoom}}); + }; + const step = now => { + if (!spring) return; + const dt = last === null ? 1 / 60 : Math.min(0.064, (now - last) / 1000); + last = now; + channels.forEach((channel, i) => springStep(channel, goal[i], OMEGA, dt)); + const settled = channels.every((channel, i) => Math.abs(channel.p - goal[i]) < eps[i] && Math.abs(channel.v) < eps[i] * 10); + if (settled) { + spring = null; + c.viewport(target); + updatePill(); + return; + } + apply(); + spring.frame = requestAnimationFrame(step); + }; + spring = {frame: requestAnimationFrame(step)}; + }; + + // --- Gesten am Container ------------------------------------------------- + const on = (target, name, fn, options) => { + target.addEventListener(name, fn, options); + offs.push(() => target.removeEventListener(name, fn, options)); + }; + + const onWheel = event => { + const c = cy(); + if (!c) return; + if (!(event.ctrlKey || event.metaKey)) { + // Normales Mausrad scrollt die Seite. Einmal sagen, wie Zoomen geht. + if (!wheelHintShown && Math.abs(event.deltaY) > Math.abs(event.deltaX)) { + wheelHintShown = true; + onHint('wheel'); + } + return; + } + // Strg/Cmd + Rad (und Trackpad-Pinch, das Chrome so meldet) zoomt um den Zeiger. + event.preventDefault(); + cancel(); + const unit = event.deltaMode === 1 ? 0.05 : 0.002; + const box = container.getBoundingClientRect(); + const level = clampZoom(c.zoom() * Math.exp(-event.deltaY * unit)); + c.zoom({level, renderedPosition: {x: event.clientX - box.left, y: event.clientY - box.top}}); + }; + + const touchPoint = touch => { + const box = container.getBoundingClientRect(); + return {x: touch.clientX - box.left, y: touch.clientY - box.top}; + }; + + const onTouchStart = event => { + cancel(); + const c = cy(); + if (!c) return; + if (event.touches.length === 2) { + const a = touchPoint(event.touches[0]); + const b = touchPoint(event.touches[1]); + const mid = midOf(a, b); + const zoom = c.zoom(); + const pan = c.pan(); + // Der Kartenpunkt unter der Fingermitte bleibt unter der Fingermitte. + pinch = {dist: Math.hypot(a.x - b.x, a.y - b.y) || 1, zoom, model: {x: (mid.x - pan.x) / zoom, y: (mid.y - pan.y) / zoom}}; + swipe = null; + } else if (event.touches.length === 1) { + pinch = null; + swipe = {start: touchPoint(event.touches[0]), hinted: false}; + } + }; + + const onTouchMove = event => { + const c = cy(); + if (!c) return; + if (pinch && event.touches.length === 2) { + event.preventDefault(); + const a = touchPoint(event.touches[0]); + const b = touchPoint(event.touches[1]); + const mid = midOf(a, b); + const zoom = clampZoom(pinch.zoom * Math.hypot(a.x - b.x, a.y - b.y) / pinch.dist); + c.viewport({zoom, pan: {x: mid.x - pinch.model.x * zoom, y: mid.y - pinch.model.y * zoom}}); + return; + } + // Ein Finger gehoert der Seite. Waagerecht wischen zeigt den Hinweis. + if (swipe && !swipe.hinted && event.touches.length === 1) { + const now = touchPoint(event.touches[0]); + if (isHorizontalSwipe(now.x - swipe.start.x, now.y - swipe.start.y)) { + swipe.hinted = true; + onHint('two_fingers'); + } + } + }; + + const onTouchEnd = event => { + if (event.touches.length < 2) pinch = null; + if (!event.touches.length) swipe = null; + }; + + on(container, 'pointerdown', () => cancel()); + on(container, 'wheel', onWheel, {passive: false}); + on(container, 'touchstart', onTouchStart, {passive: true}); + on(container, 'touchmove', onTouchMove, {passive: false}); + on(container, 'touchend', onTouchEnd, {passive: true}); + on(container, 'touchcancel', onTouchEnd, {passive: true}); + + // Neue Groesse: war die Karte eingepasst, bleibt sie eingepasst. Gemessen + // wird vor cy.resize(), solange Cytoscape noch die alte Groesse kennt. + const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => { + const c = cy(); + if (!c) return; + const before = targetOf(c); + const wasFitted = Boolean(before) && !spring + && deviation({zoom: c.zoom(), pan: c.pan()}, before, {width: c.width(), height: c.height()}) < THRESHOLD; + c.resize(); + bbCache = null; + const next = targetOf(c); + if (wasFitted && next) c.viewport(next); + updatePill(); + }) : null; + if (ro) ro.observe(container); + + // Bindet eine Cytoscape-Instanz: Zoom- und Pan-Grenzen, Pill und Doppeltipp. + const attach = c => { + attachedCy = c; + bbCache = null; + c.minZoom(MIN_ZOOM); + c.maxZoom(MAX_ZOOM); + // Maus: Ziehen verschiebt. Touch: ein Finger gehoert der Seite. + c.userPanningEnabled(!coarsePointer()); + c.userZoomingEnabled(false); + const target = targetOf(c); + if (target) c.viewport(target); + c.on('viewport', updatePill); + c.on('dbltap', fitAnimated); + updatePill(); + }; + + const destroy = () => { + if (destroyed) return; + if (spring) { cancelAnimationFrame(spring.frame); spring = null; } + destroyed = true; + if (attachedCy) { + attachedCy.off('viewport', updatePill); + attachedCy.off('dbltap', fitAnimated); + } + offs.forEach(off => off()); + if (ro) ro.disconnect(); + }; + + return {attach, fitAnimated, cancel, destroy}; + }; + + window.DeviceMapViewport = { + FIT_PADDING, RESPONSE, THRESHOLD, HINT_MS, SWIPE_MIN, SWIPE_RATIO, MIN_ZOOM, MAX_ZOOM, + fitTarget, deviation, springStep, isHorizontalSwipe, create, + }; +})(); diff --git a/dashboard/test/devicemap-viewport.test.mjs b/dashboard/test/devicemap-viewport.test.mjs new file mode 100644 index 000000000..82761c72c --- /dev/null +++ b/dashboard/test/devicemap-viewport.test.mjs @@ -0,0 +1,270 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JSDOM } from 'jsdom'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const source = fs.readFileSync(path.join(here, '..', 'internal', 'webui', 'static', 'js', 'devicemap-viewport.js'), 'utf8'); + +// Objekte aus dem vm-Kontext haben einen anderen Prototyp, daher per JSON vergleichen. +const plain = value => JSON.parse(JSON.stringify(value)); + +const BB = { x1: 0, x2: 1000, y1: 0, y2: 500, w: 1000, h: 500 }; + +// Fake-cy: measured ist die von Cytoscape gecachte Groesse und aendert sich +// erst bei resize(), box ist die echte DOM-Groesse. +function fakeCy() { + const cy = { + box: { w: 548, h: 298 }, + measured: { w: 548, h: 298 }, + zoomValue: 1, + panValue: { x: 0, y: 0 }, + handlers: {}, + viewportCalls: [], + zoomCalls: [], + bb: BB, + width: () => cy.measured.w, + height: () => cy.measured.h, + resize() { cy.measured = { ...cy.box }; }, + zoom(arg) { + if (arg === undefined) return cy.zoomValue; + cy.zoomCalls.push(arg); + cy.zoomValue = arg.level; + cy.emit('viewport'); + return cy; + }, + pan: () => ({ ...cy.panValue }), + viewport(arg) { + if (arg === undefined) return { zoom: cy.zoomValue, pan: { ...cy.panValue } }; + cy.viewportCalls.push(arg); + cy.zoomValue = arg.zoom; + cy.panValue = { ...arg.pan }; + cy.emit('viewport'); + return cy; + }, + elements: () => ({ boundingBox: () => cy.bb }), + on(name, fn) { (cy.handlers[name] ||= []).push(fn); return cy; }, + off(name, fn) { cy.handlers[name] = (cy.handlers[name] || []).filter(f => f !== fn); return cy; }, + emit(name) { (cy.handlers[name] || []).forEach(fn => fn()); }, + minZoom: () => cy, + maxZoom: () => cy, + userPanningEnabled: () => cy, + userZoomingEnabled: () => cy, + }; + return cy; +} + +function setup({ reducedMotion = false, onFitShown = () => {}, onHint = () => {} } = {}) { + const dom = new JSDOM('
', { runScripts: 'outside-only' }); + const win = dom.window; + // Manuell getaktete rAF-Schleife + const queue = new Map(); + let nextId = 1; + win.requestAnimationFrame = fn => { const id = nextId++; queue.set(id, fn); return id; }; + win.cancelAnimationFrame = id => { queue.delete(id); }; + const raf = { + tick(ms) { const pending = [...queue.values()]; queue.clear(); pending.forEach(fn => fn(ms)); }, + count: () => queue.size, + }; + const roCallbacks = []; + win.ResizeObserver = class { constructor(cb) { roCallbacks.push(cb); } observe() {} disconnect() {} }; + vm.runInContext(source, dom.getInternalVMContext()); + const container = win.document.getElementById('c'); + const api = win.DeviceMapViewport; + const cy = fakeCy(); + const vp = api.create({ + container, + getCy: () => cy, + reducedMotion: () => reducedMotion, + onFitShown, + onHint, + }); + const resize = () => roCallbacks.forEach(cb => cb([])); + return { win, container, cy, api, vp, raf, resize }; +} + +function touchSeq(win, container, type, points) { + const event = new win.Event(type, { bubbles: true, cancelable: true }); + event.touches = points.map(([clientX, clientY]) => ({ clientX, clientY })); + container.dispatchEvent(event); + return event; +} + +function wheel(win, container, init) { + const event = new win.WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 0, clientY: 0, deltaY: 0, ...init }); + container.dispatchEvent(event); + return event; +} + +test('fitTarget pads by 24 and centres', () => { + const { api } = setup(); + const t = api.fitTarget({ bb: BB, width: 548, height: 298 }); + assert.equal(t.zoom, 0.5); + assert.deepEqual(plain(t.pan), { x: 24, y: 24 }); +}); + +test('fitTarget clamps to 0.1 and 3 and gives null without content or size', () => { + const { api } = setup(); + const tiny = { x1: 0, x2: 1, y1: 0, y2: 1, w: 1, h: 1 }; + const huge = { x1: 0, x2: 1e6, y1: 0, y2: 1e6, w: 1e6, h: 1e6 }; + assert.equal(api.fitTarget({ bb: tiny, width: 548, height: 298 }).zoom, 3); + assert.equal(api.fitTarget({ bb: huge, width: 548, height: 298 }).zoom, 0.1); + assert.equal(api.fitTarget({ bb: { w: 0, h: 0 }, width: 548, height: 298 }), null); + assert.equal(api.fitTarget({ bb: BB, width: 0, height: 298 }), null); +}); + +test('deviation threshold', () => { + const { api } = setup(); + const target = { zoom: 0.5, pan: { x: 24, y: 24 } }; + const size = { width: 548, height: 298 }; + const low = api.deviation({ zoom: 0.5 * 1.019, pan: { x: 24, y: 24 } }, target, size); + const high = api.deviation({ zoom: 0.5 * 1.021, pan: { x: 24, y: 24 } }, target, size); + assert.ok(low < api.THRESHOLD); + assert.ok(high > api.THRESHOLD); +}); + +test('spring settles without overshoot', () => { + const { api } = setup(); + const omega = (2 * Math.PI) / 0.4; + const channel = { p: 2, v: 0 }; + const positions = []; + for (let i = 1; i <= 60; i++) { + api.springStep(channel, 1, omega, 1 / 60); + positions.push(channel.p); + } + assert.ok(positions.every(p => p >= 1 - 1e-9), 'never below the target'); + assert.ok(Math.abs(positions[17] - 1) < 0.1, 'after 0.3 s closer than 0.1'); + assert.ok(Math.abs(positions[47] - 1) < 0.001, 'after 0.8 s closer than 0.001'); +}); + +test('isHorizontalSwipe needs 24 px and a ratio of 2.5', () => { + const { api } = setup(); + assert.equal(api.isHorizontalSwipe(30, 10), true); + assert.equal(api.isHorizontalSwipe(30, 13), false); + assert.equal(api.isHorizontalSwipe(20, 2), false); + assert.equal(api.isHorizontalSwipe(-30, 10), true); +}); + +test('ctrl wheel zooms around the pointer, plain wheel hints once', () => { + const hints = []; + const { win, container, cy, vp } = setup({ onHint: kind => hints.push(kind) }); + vp.attach(cy); + const plain1 = wheel(win, container, { deltaY: 100 }); + const plain2 = wheel(win, container, { deltaY: 100 }); + assert.deepEqual(hints, ['wheel']); + assert.equal(plain1.defaultPrevented, false); + assert.equal(plain2.defaultPrevented, false); + assert.equal(cy.zoomCalls.length, 0); + const ctrl = wheel(win, container, { deltaY: -100, ctrlKey: true, clientX: 30, clientY: 40 }); + assert.equal(ctrl.defaultPrevented, true); + assert.equal(cy.zoomCalls.length, 1); + assert.deepEqual(plain(cy.zoomCalls[0].renderedPosition), { x: 30, y: 40 }); + assert.ok(cy.zoomCalls[0].level > 0.5, 'zoom in on a negative deltaY'); +}); + +test('two-finger pinch doubles the zoom and keeps the point under the fingers', () => { + const { win, container, cy, vp } = setup(); + vp.attach(cy); + cy.viewport({ zoom: 1, pan: { x: 0, y: 0 } }); + touchSeq(win, container, 'touchstart', [[100, 100], [200, 100]]); + touchSeq(win, container, 'touchmove', [[50, 100], [250, 100]]); + assert.ok(Math.abs(cy.zoom() / 2 - 1) < 0.05, `zoom ${cy.zoom()} is about 2`); + const pan = cy.pan(); + assert.ok(Math.abs((150 - pan.x) / cy.zoom() - 150) < 1e-6, 'model point x under the midpoint'); + assert.ok(Math.abs((100 - pan.y) / cy.zoom() - 100) < 1e-6, 'model point y under the midpoint'); +}); + +test('one-finger horizontal swipe hints once, vertical never, no preventDefault', () => { + const hints = []; + const { win, container, cy, vp } = setup({ onHint: kind => hints.push(kind) }); + vp.attach(cy); + const h1 = touchSeq(win, container, 'touchstart', [[100, 100]]); + const m1 = touchSeq(win, container, 'touchmove', [[140, 105]]); + const m2 = touchSeq(win, container, 'touchmove', [[170, 106]]); + touchSeq(win, container, 'touchend', []); + assert.deepEqual(hints, ['two_fingers']); + assert.equal(m1.defaultPrevented, false); + assert.equal(m2.defaultPrevented, false); + assert.equal(h1.defaultPrevented, false); + touchSeq(win, container, 'touchstart', [[100, 100]]); + touchSeq(win, container, 'touchmove', [[105, 160]]); + touchSeq(win, container, 'touchmove', [[106, 220]]); + touchSeq(win, container, 'touchend', []); + assert.deepEqual(hints, ['two_fingers'], 'vertical swipe gives no hint'); +}); + +test('a new gesture cancels the spring', () => { + const { win, container, cy, vp, raf } = setup(); + vp.attach(cy); + cy.viewport({ zoom: 1, pan: { x: 0, y: 0 } }); + vp.fitAnimated(); + raf.tick(1000 / 60); + assert.equal(raf.count(), 1, 'spring is running'); + container.dispatchEvent(new win.Event('pointerdown', { bubbles: true })); + assert.equal(raf.count(), 0, 'frame cancelled'); + const frozen = JSON.stringify(cy.viewport()); + for (let i = 2; i <= 30; i++) raf.tick((i * 1000) / 60); + assert.equal(JSON.stringify(cy.viewport()), frozen); +}); + +test('reduced motion jumps to the fit target', () => { + const { cy, vp, raf } = setup({ reducedMotion: true }); + vp.attach(cy); + cy.viewport({ zoom: 1, pan: { x: 0, y: 0 } }); + vp.fitAnimated(); + assert.equal(cy.zoom(), 0.5); + assert.deepEqual(plain(cy.pan()), { x: 24, y: 24 }); + assert.equal(raf.count(), 0); +}); + +test('fitAnimated moves over frames and settles on the target', () => { + const { cy, vp, raf } = setup(); + vp.attach(cy); + cy.viewport({ zoom: 1, pan: { x: 0, y: 0 } }); + vp.fitAnimated(); + raf.tick(1000 / 60); + assert.ok(cy.zoom() > 0.5 && cy.zoom() < 1, 'moving after one frame'); + for (let i = 2; i <= 120; i++) raf.tick((i * 1000) / 60); + assert.equal(cy.zoom(), 0.5); + assert.deepEqual(plain(cy.pan()), { x: 24, y: 24 }); +}); + +test('the fit pill follows the deviation from the fitted view', () => { + const shown = []; + const { cy, vp, raf } = setup({ onFitShown: value => shown.push(value) }); + vp.attach(cy); + assert.deepEqual(shown, []); + cy.viewport({ zoom: 1, pan: { x: 0, y: 0 } }); + assert.deepEqual(shown, [true]); + vp.fitAnimated(); + for (let i = 1; i <= 120; i++) raf.tick((i * 1000) / 60); + assert.deepEqual(shown, [true, false]); +}); + +test('resize keeps a fitted map fitted and a zoomed map zoomed', () => { + const { api, cy, vp, resize } = setup(); + vp.attach(cy); + cy.box = { w: 600, h: 320 }; + const before = cy.viewportCalls.length; + resize(); + assert.equal(cy.viewportCalls.length, before + 1, 'fitted map is refitted'); + const expected = api.fitTarget({ bb: BB, width: 600, height: 320 }); + assert.ok(Math.abs(cy.zoom() - expected.zoom) < 1e-9); + + cy.viewport({ zoom: 2, pan: { x: 0, y: 0 } }); + cy.box = { w: 500, h: 300 }; + const zoomedBefore = cy.viewportCalls.length; + resize(); + assert.equal(cy.viewportCalls.length, zoomedBefore, 'zoomed map is left alone'); +}); + +test('destroy stops listening on the container', () => { + const { win, container, cy, vp } = setup(); + vp.attach(cy); + vp.destroy(); + wheel(win, container, { deltaY: -100, ctrlKey: true }); + assert.equal(cy.zoomCalls.length, 0); +}); From 124761fbc66e3bfe6687fe3521cca87574d61bad Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:06:00 +0100 Subject: [PATCH 04/17] fix(energy): show role edges with the data layer on the live core Role edges end at the balance node, so they show with the balance or the data layer. The shared edgeVisible() rule stays unchanged. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/webui/static/js/devicemap-live.js | 14 ++++++++++---- dashboard/test/devicemap-live.test.mjs | 8 +++++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/dashboard/internal/webui/static/js/devicemap-live.js b/dashboard/internal/webui/static/js/devicemap-live.js index 0f08ca948..efbc5b50a 100644 --- a/dashboard/internal/webui/static/js/devicemap-live.js +++ b/dashboard/internal/webui/static/js/devicemap-live.js @@ -227,12 +227,12 @@ if (config.layers(this).data) { const edges = df.flowEdges(this.flows, this.baseNodeIds(), balanceId); const automation = positions.get('automation'); - const missing = this.flowNodes().filter(node => !positions.has(node.id)).map(node => ({ + const missingFlow = this.flowNodes().filter(node => !positions.has(node.id)).map(node => ({ id: node.id, inputXs: edges.filter(edge => edge.to === node.id).map(edge => positions.get(edge.from)).filter(Boolean).map(position => position.x), anchor: node.kind === 'rule' && automation ? {x: automation.x, y: automation.y} : undefined, })); - for (const spot of df.placeFlowNodes({nodes: missing, allPositions: all(), snap})) positions.set(spot.id, {x: spot.x, y: spot.y}); + for (const spot of df.placeFlowNodes({nodes: missingFlow, allPositions: all(), snap})) positions.set(spot.id, {x: spot.x, y: spot.y}); for (const stub of this.stubInfo().nodes) { const anchor = positions.get(stub.anchor); if (anchor) positions.set(stub.id, df.stubPosition(anchor, stub.unresolved.direction, stub.index)); @@ -265,7 +265,10 @@ const roles = config.roleEdges(this) ? this.roleEdgeList().filter(edge => nodeIds.has(edge.from)) : []; const flows = layers.data ? df.flowEdges(this.flows, this.baseNodeIds(), this.balanceId()) : []; const stubEdges = layers.data ? this.stubInfo().edges : []; - const edges = [...roles, ...flows, ...stubEdges].filter(edge => df.edgeVisible(edge, layers)); + // Role edges end at the balance node, so they show with the balance + // or the data layer (the shared edgeVisible() rule covers balance only). + const roleVisible = Boolean(layers.balance || layers.data); + const edges = [...roles, ...flows, ...stubEdges].filter(edge => (edge.cat === 'role' ? roleVisible : df.edgeVisible(edge, layers))); return this.view.hide_automation_links ? edges.filter(edge => !df.isAutomationLink(edge)) : edges; }, @@ -390,7 +393,10 @@ setFocus(id) { this.focusId = id; const df = window.DeviceMapDataflow; - const related = id ? df.relatedFocus(id, {wiringPairs: window.DeviceMapGraph.pairsOf(this.wiringEdges()), dataEdges: this.dataEdges(), layers: config.layers(this)}) : null; + const layers = config.layers(this); + // Same role edge rule as dataEdges(): balance or data shows them. + const focusLayers = {...layers, balance: Boolean(layers.balance || layers.data)}; + const related = id ? df.relatedFocus(id, {wiringPairs: window.DeviceMapGraph.pairsOf(this.wiringEdges()), dataEdges: this.dataEdges(), layers: focusLayers}) : null; if (labels) labels.setDimmed(related ? related.nodes : null); if (!cy) return; cy.batch(() => { diff --git a/dashboard/test/devicemap-live.test.mjs b/dashboard/test/devicemap-live.test.mjs index 14e12d6d1..7012a3971 100644 --- a/dashboard/test/devicemap-live.test.mjs +++ b/dashboard/test/devicemap-live.test.mjs @@ -110,6 +110,12 @@ test('role edges need the balance or data layer', async () => { assert.ok(ids(on.component).includes('data-role:pv'), 'the balance layer shows the role edge'); }); +test('role edges also show with the data layer on, not only with balance', async () => { + const { component } = createLive(TABLE, { roleEdges: () => true, layers: () => ({ wiring: false, energy: true, balance: false, data: true }) }); + await component.load(); + assert.ok(ids(component).some(id => id.startsWith('data-role:')), 'the role edge ends at the balance node, which the data layer shows'); +}); + test('automation links follow the config', async () => { const map = { ...TABLE['/api/v1/device/map'], edges: [{ id: 'relation-1', parent_id: 'automation', child_id: 'pv', kind: 'via_device', created_at: '' }] }; const table = { ...TABLE, '/api/v1/devices': [...DEVICES, { id: 'automation', name: 'Automation', entities: [] }], '/api/v1/device/map': map }; @@ -147,7 +153,7 @@ test('an empty map shows the empty state and renders without a canvas', async () assert.equal(component.empty, true); }); -test('setFocus keeps a data edge of the focused device undimmed', async () => { +test('the focus set of a device holds its trigger edge, so dimming leaves it', async () => { const { component, window } = createLive({ ...TABLE, '/api/v1/device/map/flows': FLOWS }, { layers: () => ({ wiring: false, energy: true, balance: false, data: true }) }); window.fetch = routes({ ...TABLE, '/api/v1/device/map/flows': FLOWS }); await component.load(); From 7d40301c14d9cd0152a7cb2d6928d706f86ced9e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:06:51 +0100 Subject: [PATCH 05/17] fix(overview): make viewport attach idempotent Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/devicemap-viewport.js | 7 ++++++- dashboard/test/devicemap-viewport.test.mjs | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/webui/static/js/devicemap-viewport.js b/dashboard/internal/webui/static/js/devicemap-viewport.js index 49d499616..8bad563fc 100644 --- a/dashboard/internal/webui/static/js/devicemap-viewport.js +++ b/dashboard/internal/webui/static/js/devicemap-viewport.js @@ -32,7 +32,7 @@ // Groesste Abweichung vom Einpass-Ziel, Zoom relativ, Pan in Anteilen der kleineren Seite. const deviation = ({zoom, pan}, target, {width, height}) => { const zoomOff = Math.abs(zoom / target.zoom - 1); - const panOff = Math.hypot(pan.x - target.pan.x, pan.y - target.pan.y) / Math.min(width, height); + const panOff = Math.hypot(pan.x - target.pan.x, pan.y - target.pan.y) / Math.max(1, Math.min(width, height)); return Math.max(zoomOff, panOff); }; @@ -234,6 +234,11 @@ // Bindet eine Cytoscape-Instanz: Zoom- und Pan-Grenzen, Pill und Doppeltipp. const attach = c => { + // Mehrfach-Aufruf sicher: alte Bindungen abbauen, bevor neu gebunden wird. + if (attachedCy) { + attachedCy.off('viewport', updatePill); + attachedCy.off('dbltap', fitAnimated); + } attachedCy = c; bbCache = null; c.minZoom(MIN_ZOOM); diff --git a/dashboard/test/devicemap-viewport.test.mjs b/dashboard/test/devicemap-viewport.test.mjs index 82761c72c..e885f0b42 100644 --- a/dashboard/test/devicemap-viewport.test.mjs +++ b/dashboard/test/devicemap-viewport.test.mjs @@ -140,6 +140,24 @@ test('spring settles without overshoot', () => { assert.ok(Math.abs(positions[47] - 1) < 0.001, 'after 0.8 s closer than 0.001'); }); +test('deviation stays finite for a zero-sized map', () => { + const { api } = setup(); + const target = { zoom: 0.5, pan: { x: 24, y: 24 } }; + const value = api.deviation({ zoom: 0.5, pan: { x: 30, y: 24 } }, target, { width: 0, height: 0 }); + assert.ok(Number.isFinite(value)); +}); + +test('attaching the same cy twice keeps one viewport handler', () => { + const shown = []; + const { cy, vp } = setup({ onFitShown: value => shown.push(value) }); + vp.attach(cy); + vp.attach(cy); + assert.equal(cy.handlers.viewport.length, 1, 'one viewport listener after two attaches'); + assert.equal(cy.handlers.dbltap.length, 1, 'one dbltap listener after two attaches'); + cy.viewport({ zoom: 1, pan: { x: 0, y: 0 } }); + assert.deepEqual(shown, [true], 'one viewport event gives one pill update'); +}); + test('isHorizontalSwipe needs 24 px and a ratio of 2.5', () => { const { api } = setup(); assert.equal(api.isHorizontalSwipe(30, 10), true); From a99435a23b5606fde8b73b78da19bb2ce6870395 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:09:33 +0100 Subject: [PATCH 06/17] feat(overview): add the device map card component Alpine component deviceMapCard reads its options from the data-map-* attributes of the card section and builds the shared renderer core with a per-instance config. Zoom, pan and fit come from the viewport controller, attached after every render. Modal taps open only real devices, the dimmed opacity is 25 percent. Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/devicemap-card.js | 141 ++++++++++++++++ dashboard/test/devicemap-card.test.mjs | 154 ++++++++++++++++++ 2 files changed, 295 insertions(+) create mode 100644 dashboard/internal/webui/static/js/devicemap-card.js create mode 100644 dashboard/test/devicemap-card.test.mjs diff --git a/dashboard/internal/webui/static/js/devicemap-card.js b/dashboard/internal/webui/static/js/devicemap-card.js new file mode 100644 index 000000000..6e69c28ab --- /dev/null +++ b/dashboard/internal/webui/static/js/devicemap-card.js @@ -0,0 +1,141 @@ +// Geraetekarte auf der Uebersicht. Alpine-Komponente deviceMapCard: sie +// liest ihre Optionen aus den data-map-*-Attributen ihres
, baut +// den gemeinsamen Renderer (devicemap-live.js) und legt Zoom, Pan und das +// Einpassen (devicemap-viewport.js) darueber. Jede Karte hat eigene Optionen +// und eigenen Zustand, die Konfiguration entsteht pro Instanz. +(() => { + const t = (key, params) => (window.I18n ? window.I18n.t(key, params) : key); + const HINT_MS = 1500; // Anzeigedauer des Hinweises + const DIMMED_OPACITY = 0.25; // Abgedunkelte Knoten neben dem Fokus + + // "on" ist an, alles andere aus. Fehlt ein Attribut, bleibt die Ebene aus. + const optionsOf = c => { + const data = (c.$el && c.$el.dataset) || {}; + const on = value => value === 'on'; + return { + layers: {wiring: on(data.mapWiring), energy: on(data.mapEnergy), balance: on(data.mapBalance), data: on(data.mapData)}, + roleEdges: on(data.mapRoleEdges), + automationLinks: on(data.mapAutomationLinks), + edgeStyle: data.mapEdgeStyle || '', + width: data.mapWidth || '', + tap: data.mapTap || 'none', + }; + }; + + // Antippbar: im Hervorheben jeder Knoten, im Modal nur echte Geraete. Keine + // Gruppen, keine Bilanz, keine Unter-Geraete und keine Regel- oder Stub-Knoten. + const tappable = (c, id) => { + const {tap} = optionsOf(c); + if (tap === 'highlight') return true; + if (tap !== 'modal') return false; + const isBalance = id === c.balanceId() || id === window.DeviceMapDataflow.BALANCE_ID; + return !isBalance + && !window.DeviceMapModel.isGroupId(id) + && !window.DeviceMapSubDevices.isSubId(id) + && c.devices.some(device => device.id === id); + }; + + const onNodeTap = (c, id) => { + const {tap} = optionsOf(c); + if (tap === 'highlight') { c.setFocus(c.focusId === id ? null : id); return; } + if (tap !== 'modal' || !tappable(c, id)) return; + const panel = document.getElementById('overview-panel'); + const scope = panel && window.Alpine.$data(panel); + if (scope && typeof scope.selectDevice === 'function') scope.selectDevice(id); + }; + + // Druck-Rueckmeldung und Handzeiger nur bei antippbaren Knoten. + const bindPointer = (c, cy) => { + cy.on('tapstart', 'node', event => { + if (tappable(c, event.target.id())) event.target.addClass('devicemap-pressed'); + }); + cy.on('tapend tapdragout', 'node', event => event.target.removeClass('devicemap-pressed')); + cy.on('mouseover', 'node', event => { if (tappable(c, event.target.id())) cy.container().style.cursor = 'pointer'; }); + cy.on('mouseout', 'node', () => { cy.container().style.cursor = ''; }); + }; + + const wheelKey = () => (/Mac|iPhone|iPad/.test((window.navigator && window.navigator.platform) || '') ? 'device_map.hint.wheel_mac' : 'device_map.hint.wheel'); + + const method = fn => ({value: fn, writable: true, enumerable: true, configurable: true}); + + const deviceMapCard = () => { + // Pro Karte: Viewport-Controller, Sichtbarkeitsbeobachter, Hinweis-Timer. + let viewport = null; + let io = null; + let hintTimer = null; + + const core = window.DeviceMapLive.create({ + layers: c => optionsOf(c).layers, + roleEdges: c => optionsOf(c).roleEdges, + automationLinks: c => optionsOf(c).automationLinks, + edgeStyle: c => optionsOf(c).edgeStyle, + widthByPower: c => optionsOf(c).width, + isActive: c => { + const panel = document.getElementById('overview-panel'); + return Boolean(panel && panel.classList.contains('active')) && document.visibilityState === 'visible' && c.inView; + }, + onNodeTap, + extraStyle: (c, theme) => [ + {selector: 'node.devicemap-pressed', style: {'outline-width': 2, 'outline-color': theme.accent, 'outline-opacity': 0.6}}, + {selector: '.devicemap-dimmed', style: {opacity: DIMMED_OPACITY}}, + ], + onRendered: (c, cy) => { + if (viewport) viewport.attach(cy); + bindPointer(c, cy); + }, + }); + const coreDestroy = core.destroy; + + const card = { + fitShown: false, + hintShown: false, + hintText: '', + inView: true, + + async start() { + viewport = window.DeviceMapViewport.create({ + container: this.$refs.canvas, + getCy: () => this.cy(), + reducedMotion: () => this.reducedMotion(), + onFitShown: value => { this.fitShown = value; }, + onHint: kind => this.showHint(kind), + }); + // Flussanimation nur, solange die Karte im Bild ist. + io = new IntersectionObserver(entries => { + this.inView = entries.some(entry => entry.isIntersecting); + if (this.inView) this.flowAnimator().start(); + }); + io.observe(this.$el); + await this.load(); + }, + + fit() { + if (viewport) viewport.fitAnimated(); + }, + + showHint(kind) { + this.hintText = kind === 'two_fingers' ? t('device_map.hint.two_fingers') : t(wheelKey()); + this.hintShown = true; + clearTimeout(hintTimer); + hintTimer = setTimeout(() => { this.hintShown = false; }, HINT_MS); + }, + + destroy() { + if (io) { io.disconnect(); io = null; } + clearTimeout(hintTimer); + if (viewport) { viewport.destroy(); viewport = null; } + coreDestroy.call(this); + }, + }; + + return Object.defineProperties({}, { + ...Object.getOwnPropertyDescriptors(core), + ...Object.getOwnPropertyDescriptors(card), + }); + }; + + const register = () => { + if (window.Alpine) window.Alpine.data('deviceMapCard', deviceMapCard); + }; + if (window.Alpine) register(); else document.addEventListener('alpine:init', register, {once: true}); +})(); diff --git a/dashboard/test/devicemap-card.test.mjs b/dashboard/test/devicemap-card.test.mjs new file mode 100644 index 000000000..5ee94b58c --- /dev/null +++ b/dashboard/test/devicemap-card.test.mjs @@ -0,0 +1,154 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JSDOM } from 'jsdom'; +import { installI18n } from './helpers/i18n.mjs'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const jsDir = path.join(here, '..', 'internal', 'webui', 'static', 'js'); +const files = ['theme.js', 'devicemap-model.js', 'devicemap-graph.js', 'devicemap-wiring.js', 'devicemap-subdevices.js', 'devicemap-dataflow.js', 'devicemap-node-svg.js', 'devicemap-labels.js', 'devicemap-live.js', 'devicemap-viewport.js', 'devicemap-card.js']; + +// Plain JSON copy, objects from the vm context have another prototype. +const plain = value => JSON.parse(JSON.stringify(value)); + +function routes(table) { + return async url => { + const key = Object.keys(table).find(prefix => String(url).endsWith(prefix)); + if (!key) return { ok: false, status: 404, json: async () => ({}) }; + return { ok: true, status: 200, json: async () => JSON.parse(JSON.stringify(table[key])) }; + }; +} + +const DEVICES = [ + { id: 'pv', name: 'PV', entities: [{ unique_id: 'pv1', unit_of_measurement: 'W', value: '500' }] }, + { id: 'wb', name: 'Wallbox', entities: [{ unique_id: 'wb1', unit_of_measurement: 'W', value: '300' }] }, +]; + +const TABLE = { + '/api/v1/devices': DEVICES, + '/api/v1/device/map': { version: 2, nodes: [{ device_id: 'pv', x: 100, y: 100 }, { device_id: 'wb', x: 300, y: 100 }], edges: [] }, + '/api/v1/energy': { entities: [ + { device_id: 'pv', entity_id: 'pv1', value: 500, unit: 'W', role: { role: 'pv', source: 'override' } }, + { device_id: 'wb', entity_id: 'wb1', value: 300, unit: 'W', role: { role: 'wallbox', source: 'override' } }, + ], balance: { grid_import: 0, grid_export: 200 } }, + '/api/v1/energy/roles': { assignments: {}, groups: {}, categories: {} }, + '/api/v1/device/icons': [], + '/api/v1/device/map/flows': { + nodes: [{ virtual_id: 'rule:r1', kind: 'rule', label: 'R1' }], + edges: [{ id: 'e1', cat: 'trigger', from: { device_id: 'pv' }, to: { virtual_id: 'rule:r1' } }], + unresolved: [], + }, +}; + +// The data attributes the template renders (sub-brief 4b). Overrides per test. +const ATTRS = { + wiring: 'off', energy: 'on', balance: 'on', data: 'off', + 'role-edges': 'off', 'automation-links': 'on', 'edge-style': '', width: '', tap: 'none', +}; + +// Builds a fresh jsdom with the overview panel and one card section per call. +function createCard(overrides = {}, { table = TABLE, panelActive = true } = {}) { + const dom = new JSDOM(`
`, { runScripts: 'outside-only', pretendToBeVisual: true, url: 'http://localhost/' }); + const window = dom.window; + window.fetch = routes(table); + installI18n(window); + const registry = {}; + const observers = []; + const scope = { selected: [], selectDevice(id) { this.selected.push(id); } }; + window.Alpine = { + data: (name, fn) => { registry[name] = fn; }, + store: () => ({}), + $data: el => (el && el.id === 'overview-panel' ? scope : null), + }; + window.IntersectionObserver = class { + constructor(callback) { this.callback = callback; observers.push(this); } + observe() {} + disconnect() {} + }; + window.ResizeObserver = class { observe() {} disconnect() {} }; + const context = dom.getInternalVMContext(); + for (const name of files) vm.runInContext(fs.readFileSync(path.join(jsDir, name), 'utf8'), context); + + const section = window.document.createElement('section'); + section.className = 'device-map-card'; + const attrs = { ...ATTRS, ...overrides }; + for (const [key, value] of Object.entries(attrs)) section.setAttribute(`data-map-${key}`, value); + window.document.body.append(section); + const canvas = window.document.createElement('div'); + section.append(canvas); + + const component = registry.deviceMapCard(); + component.$el = section; + component.$refs = { canvas }; + return { component, window, scope, observers, section }; +} + +test('options come from the data attributes', async () => { + const { component } = createCard({ data: 'on', energy: 'off' }); + await component.load(); + const list = component.elements(); + assert.ok(list.some(element => String(element.data.id).startsWith('data-')), 'data edges are drawn'); + assert.ok(!list.some(element => element.classes && element.classes.includes('devicemap-flow')), 'no energy flow edges'); +}); + +test('tap highlight toggles focus', async () => { + const { component } = createCard({ tap: 'highlight' }); + await component.load(); + component.onNodeTap('pv'); + assert.equal(component.focusId, 'pv'); + component.onNodeTap('pv'); + assert.equal(component.focusId, null); +}); + +test('tap modal opens only real devices', async () => { + const { component, scope } = createCard({ tap: 'modal' }); + await component.load(); + component.onNodeTap('pv'); + component.onNodeTap('group:uv'); + component.onNodeTap('balance'); + component.onNodeTap('sub:meter-1'); + component.onNodeTap('rule:r1'); + assert.deepEqual(plain(scope.selected), ['pv']); +}); + +test('tap none does nothing', async () => { + const { component, scope } = createCard({ tap: 'none' }); + await component.load(); + component.onNodeTap('pv'); + assert.equal(component.focusId, null); + assert.deepEqual(plain(scope.selected), []); +}); + +test('inactive when the overview is hidden or the card is out of view', async () => { + const hidden = createCard({}, { panelActive: false }); + await hidden.component.start(); + assert.equal(hidden.component.isActive(), false, 'overview panel not active'); + + const shown = createCard(); + await shown.component.start(); + assert.equal(shown.component.isActive(), true, 'active and in view'); + shown.observers[0].callback([{ isIntersecting: false }]); + assert.equal(shown.component.isActive(), false, 'scrolled out of view'); +}); + +test('two cards keep their own options', async () => { + const dom = createCard({ tap: 'highlight' }); + const second = createCard({ tap: 'modal' }); + await dom.component.load(); + await second.component.load(); + dom.component.onNodeTap('pv'); + second.component.onNodeTap('pv'); + assert.equal(dom.component.focusId, 'pv', 'first card highlights'); + assert.equal(second.component.focusId, null, 'second card does not'); + assert.deepEqual(plain(second.scope.selected), ['pv'], 'second card opens the modal'); + assert.deepEqual(plain(dom.scope.selected), [], 'first card does not open it'); +}); + +test('dimmed opacity is 25 percent', async () => { + const { component } = createCard(); + const style = plain(component.graphStyle()); + assert.deepEqual(style[style.length - 1], { selector: '.devicemap-dimmed', style: { opacity: 0.25 } }); +}); From 0d553bd050071b680e62808857353499855fdc12 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:11:36 +0100 Subject: [PATCH 07/17] feat(overview): render the device map card with glass label, fit pill and tap modes Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 6 + dashboard/internal/webui/catalogs/en.json | 6 + dashboard/internal/webui/static/css/base.css | 126 ++++++++++++++++++ .../internal/webui/static/css/manager.css | 20 --- .../internal/webui/templates/overview.html | 18 ++- dashboard/internal/webui/webui_test.go | 34 +++++ 6 files changed, 189 insertions(+), 21 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index ddb769ae7..fcb806c02 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -2135,6 +2135,12 @@ "device_icon_category.mobility": "Mobilität", "device_icon_category.storage": "Speicher", "device_icon_category.switching": "Schalten und Steckdosen", + "device_map.aria": "Anlage, Live-Ansicht der Geräte und Energieflüsse", + "device_map.fit": "Einpassen", + "device_map.hint.two_fingers": "Zum Bewegen zwei Finger", + "device_map.hint.wheel": "Strg + Mausrad zum Zoomen", + "device_map.hint.wheel_mac": "⌘ + Mausrad zum Zoomen", + "device_map.title": "Anlage", "device_picker.confirm.one": "{n} übernehmen", "device_picker.confirm.other": "{n} übernehmen", "device_picker.confirm_none": "Übernehmen", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 2a38b7e12..af83840d3 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -2135,6 +2135,12 @@ "device_icon_category.mobility": "Mobility", "device_icon_category.storage": "Storage", "device_icon_category.switching": "Switching and sockets", + "device_map.aria": "Plant, live view of devices and energy flows", + "device_map.fit": "Fit", + "device_map.hint.two_fingers": "Use two fingers to move", + "device_map.hint.wheel": "Ctrl + scroll to zoom", + "device_map.hint.wheel_mac": "⌘ + scroll to zoom", + "device_map.title": "Plant", "device_picker.confirm.one": "Add {n}", "device_picker.confirm.other": "Add {n}", "device_picker.confirm_none": "Add", diff --git a/dashboard/internal/webui/static/css/base.css b/dashboard/internal/webui/static/css/base.css index 021995f5d..7f4e84254 100644 --- a/dashboard/internal/webui/static/css/base.css +++ b/dashboard/internal/webui/static/css/base.css @@ -2413,3 +2413,129 @@ small { color: var(--text-muted); } .sk-split-wide { grid-template-columns: minmax(17rem, 23rem) 1fr; } @media (max-width: 720px) { .sk-split-wide { grid-template-columns: 1fr; } .sk-split-wide .sk-detail { display: none; } } +/* --- Karte ------------------------------------------------------------------ + Randlos: die Map fuellt die ganze Karte, Titel und Pille liegen als Glas + darueber. Die Karte nimmt die Zellenhoehe (.layout-grid-item > * hat + height:100%), mindestens 18rem. */ +.device-map-card { + --devicemap-halo: var(--panel); + position: relative; + height: 100%; + min-height: 18rem; + border: 1px solid var(--border-soft); + border-radius: 12px; + overflow: hidden; + background: var(--panel); + isolation: isolate; +} +/* Eigener Stapelkontext: Cytoscape setzt z-index auf seine Canvases, ohne + ihn laegen sie ueber Glas-Label und Pille. */ +.device-map-card-stage { position: absolute; inset: 0; z-index: 0; } +/* Ein Finger scrollt die Seite, alles andere entscheidet devicemap-karte.js. + pan-y laesst dem Browser nur das senkrechte Scrollen, Pinch landet bei uns. */ +.device-map-card-canvas { position: absolute; inset: 0; touch-action: pan-y; } + +/* Kantenschatten oben: Knoten unter dem Glas-Label bleiben lesbar, ohne dass + eine harte Linie die Map anschneidet. */ +.device-map-card-edge { + position: absolute; inset: 0 0 auto 0; height: 3.25rem; z-index: 1; + background: linear-gradient(to bottom, color-mix(in srgb, var(--panel) 78%, transparent), transparent); + pointer-events: none; +} + +/* Glas: halbtransparentes Panel mit Blur, die helle Oberkante faengt Licht. + Klein und leicht, weil es nur beschriftet. */ +.device-map-card-title, .device-map-card-fit, .device-map-card-hint { + background: color-mix(in srgb, var(--panel) 62%, transparent); + -webkit-backdrop-filter: blur(16px) saturate(180%); + backdrop-filter: blur(16px) saturate(180%); + border: 1px solid color-mix(in srgb, var(--border) 70%, transparent); + border-top-color: color-mix(in srgb, var(--text-strong) 14%, transparent); + box-shadow: 0 2px 10px rgb(0 0 0 / .18); + color: var(--text-strong); +} +.device-map-card-title { + position: absolute; top: .6rem; left: .6rem; z-index: 2; + margin: 0; padding: .28rem .75rem; + border-radius: 999px; + font-size: .82rem; font-weight: 650; letter-spacing: .01em; line-height: 1.3; + pointer-events: none; +} +.device-map-card-empty { position: absolute; inset: auto 0 45% 0; z-index: 2; margin: 0; text-align: center; color: var(--text-muted); font-size: .9rem; } + +/* Pille "Einpassen": der Rueckweg nach Zoom oder Verschieben. Erscheint als + Material (Blur + Scale + Opacity aus der Ecke, an der sie sitzt), 200 ms + hinein, 120 ms hinaus auf demselben Weg. */ +.device-map-card-fit { + position: absolute; right: .6rem; bottom: .6rem; z-index: 3; + display: inline-flex; align-items: center; gap: .35rem; + padding: .34rem .8rem .34rem .65rem; + border-radius: 999px; + font: inherit; font-size: .8rem; font-weight: 600; + cursor: pointer; + transform-origin: 100% 100%; + opacity: 0; transform: scale(.96); filter: blur(4px); + pointer-events: none; + transition: opacity 120ms var(--ease-out), transform 120ms var(--ease-out), filter 120ms var(--ease-out); +} +.device-map-card-fit.is-shown { + opacity: 1; transform: none; filter: none; + pointer-events: auto; + transition-duration: 200ms; +} +.device-map-card-fit.is-shown:active { transform: scale(.97); transition-duration: 100ms; } +.device-map-card-fit svg { width: .95rem; height: .95rem; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.device-map-card-fit:focus-visible { outline: none; box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 45%, transparent); } +@media (hover: hover) and (pointer: fine) { + .device-map-card-fit.is-shown:hover { border-color: var(--accent-line); } +} + +/* Hinweis "Zum Bewegen zwei Finger" / "Strg + Mausrad zum Zoomen": mittig, + gleiche Materialisierung wie die Pille, aus der Mitte. */ +.device-map-card-hint { + position: absolute; left: 50%; top: 50%; z-index: 3; + padding: .5rem .95rem; + border-radius: 12px; + font-size: .86rem; font-weight: 600; white-space: nowrap; + pointer-events: none; + opacity: 0; transform: translate(-50%, -50%) scale(.96); filter: blur(4px); + transition: opacity 120ms var(--ease-out), transform 120ms var(--ease-out), filter 120ms var(--ease-out); +} +.device-map-card-hint.is-shown { opacity: 1; transform: translate(-50%, -50%); filter: none; transition-duration: 200ms; } + +/* Weniger Bewegung: nur Opacity, keine Groessen- oder Schaerfeaenderung. */ +@media (prefers-reduced-motion: reduce) { + .device-map-card-fit, .device-map-card-fit.is-shown, .device-map-card-fit.is-shown:active { transform: none; filter: none; transition-property: opacity; } + .device-map-card-hint, .device-map-card-hint.is-shown { transform: translate(-50%, -50%); filter: none; transition-property: opacity; } +} +/* Weniger Transparenz: deckendes Panel statt Glas. */ +@media (prefers-reduced-transparency: reduce) { + .device-map-card-title, .device-map-card-fit, .device-map-card-hint { background: var(--panel); -webkit-backdrop-filter: none; backdrop-filter: none; } + .device-map-card-edge { background: linear-gradient(to bottom, var(--panel), transparent); } +} +@media (prefers-contrast: more) { + .device-map-card-title, .device-map-card-fit, .device-map-card-hint { background: var(--panel); border-color: var(--text-muted); } +} + +/* Name and live value under each node (devicemap-labels.js). Typography from + the draft: name bold 11px, value 10.5px lighter. The halo uses the canvas + background (approved point 8 in the plan). */ +.devicemap-labels { position: absolute; inset: 0; overflow: hidden; pointer-events: none; border-radius: var(--radius-lg); } +.devicemap-node-label { position: absolute; left: 0; top: 0; display: grid; justify-items: center; gap: 1px; white-space: nowrap; transform-origin: 50% 0; + text-shadow: 0 0 2px var(--devicemap-halo, var(--bg)), 0 0 2px var(--devicemap-halo, var(--bg)), 0 0 3px var(--devicemap-halo, var(--bg)), 0 0 4px var(--devicemap-halo, var(--bg)); + transition: opacity 200ms var(--ease-out); } +.devicemap-node-label.is-dimmed { opacity: .18; } +.devicemap-node-label.is-hidden { opacity: 0; } +@media (prefers-reduced-motion: reduce) { .devicemap-node-label { transition-delay: 0ms !important; } } +/* Off pill: a grey capsule around the value and "· Aus" of a switched-off node. */ +.devicemap-node-reading { display: inline-flex; align-items: center; gap: .35em; padding: 0 7px; border-radius: 999px; + background-color: transparent; transition: opacity 250ms var(--ease-out), background-color 250ms var(--ease-out); } +.devicemap-node-label.is-off .devicemap-node-reading { background-color: var(--panel-alt); } +.devicemap-node-label.is-substitute .devicemap-node-value { color: var(--flow-substitute); font-weight: 600; } +.devicemap-node-note { font-size: 9.5px; color: var(--text-muted); line-height: 1.25; } +.devicemap-node-off { font-size: 10.5px; font-weight: 600; color: var(--text-muted); line-height: 1.25; } +@media (prefers-reduced-motion: reduce) { .devicemap-node-reading { transition-duration: 150ms; } } +.devicemap-node-name { font-size: 11px; font-weight: 600; color: var(--text-strong); line-height: 1.25; } +.devicemap-node-value { font-size: 10.5px; color: var(--text-subtle); font-variant-numeric: tabular-nums; line-height: 1.25; } + +.device-map-card .devicemap-node-label.is-dimmed { opacity: .25; } diff --git a/dashboard/internal/webui/static/css/manager.css b/dashboard/internal/webui/static/css/manager.css index 65817ef2c..77a5dc410 100644 --- a/dashboard/internal/webui/static/css/manager.css +++ b/dashboard/internal/webui/static/css/manager.css @@ -430,22 +430,6 @@ select.schema-control { background-size: var(--devicemap-grid-px, 40px) var(--devicemap-grid-px, 40px); background-position: var(--devicemap-grid-x, 0px) var(--devicemap-grid-y, 0px); } -/* Name and live value under each node (devicemap-labels.js). Typography from - the draft: name bold 11px, value 10.5px lighter. The halo uses the canvas - background (approved point 8 in the plan). */ -.devicemap-labels { position: absolute; inset: 0; overflow: hidden; pointer-events: none; border-radius: var(--radius-lg); } -.devicemap-node-label { position: absolute; left: 0; top: 0; display: grid; justify-items: center; gap: 1px; white-space: nowrap; transform-origin: 50% 0; - text-shadow: 0 0 2px var(--bg), 0 0 2px var(--bg), 0 0 3px var(--bg), 0 0 4px var(--bg); - transition: opacity 200ms var(--ease-out); } -.devicemap-node-label.is-dimmed { opacity: .18; } -.devicemap-node-label.is-hidden { opacity: 0; } -@media (prefers-reduced-motion: reduce) { .devicemap-node-label { transition-delay: 0ms !important; } } -/* Off pill: a grey capsule around the value and "· Aus" of a switched-off node. */ -.devicemap-node-reading { display: inline-flex; align-items: center; gap: .35em; padding: 0 7px; border-radius: 999px; - background-color: transparent; transition: opacity 250ms var(--ease-out), background-color 250ms var(--ease-out); } -.devicemap-node-label.is-off .devicemap-node-reading { background-color: var(--panel-alt); } -.devicemap-node-label.is-substitute .devicemap-node-value { color: var(--flow-substitute); font-weight: 600; } -.devicemap-node-note { font-size: 9.5px; color: var(--text-muted); line-height: 1.25; } .devicemap-chain-warning { display: inline-flex; color: var(--warn-line); pointer-events: auto; } .devicemap-chain-warning svg { width: .9rem; height: .9rem; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; } /* The tiles sit first in the scrolling body, so they scroll away with the list and the header stays short. */ @@ -461,10 +445,6 @@ select.schema-control { @media (max-width: 720px) { .devicemap-chain-finding .energy-chain-finding-inner { padding-left: 1.9rem; } } -.devicemap-node-off { font-size: 10.5px; font-weight: 600; color: var(--text-muted); line-height: 1.25; } -@media (prefers-reduced-motion: reduce) { .devicemap-node-reading { transition-duration: 150ms; } } -.devicemap-node-name { font-size: 11px; font-weight: 600; color: var(--text-strong); line-height: 1.25; } -.devicemap-node-value { font-size: 10.5px; color: var(--text-subtle); font-variant-numeric: tabular-nums; line-height: 1.25; } .devicemap-overlay { position: absolute; inset: .75rem .75rem auto .75rem; z-index: 2; display: flex; flex-direction: column; align-items: flex-start; gap: .55rem; diff --git a/dashboard/internal/webui/templates/overview.html b/dashboard/internal/webui/templates/overview.html index eefbd5dd3..6f1b77145 100644 --- a/dashboard/internal/webui/templates/overview.html +++ b/dashboard/internal/webui/templates/overview.html @@ -151,7 +151,7 @@

{{t "overview.history.title"}}

{{end}} -{{define "layout-item"}}{{$root := .Root}}{{with .Item}}{{$item := .}}
{{if eq .Type "energy_flow"}}{{template "energy-flow-card" $root}}{{else if eq .Type "device"}}{{with index $root.LayoutDevices .Ref}}{{if eq $item.Display "compact"}}{{template "compact-card" (compactCardForItem . $item)}}{{else}}{{template "device-tile" (deviceTileForItem . $item.VisibleCategories)}}{{end}}{{end}}{{else if eq .Type "entity_value"}}{{with index $root.LayoutEntities .Ref}}{{template "entity-value-card" .}}{{end}}{{else if eq .Type "entity_group"}}{{template "entity-group-card" (entityGroupForItem $item $root.LayoutEntities)}}{{else if eq .Type "diagnostics"}}{{template "diagnostics-summary-card" $root}}{{else if eq .Type "energy_band"}}{{template "energy-band-card" $root}}{{else if eq .Type "energy_ring"}}{{template "energy-ring-card" $root}}{{else if eq .Type "energy_board"}}{{template "energy-board-card" $root}}{{else if eq .Type "energy_day"}}{{template "energy-day-card" $root}}{{else if eq .Type "energy_schema"}}{{template "energy-schema-card" $root}}{{else if eq .Type "energy_status"}}{{template "energy-status-card" $root}}{{else if eq .Type "energy_stats"}}{{template "energy-stats-card" $root}}{{else if eq .Type "battery_status"}}{{if eq $item.Display "trajectory"}}{{template "battery-trajectory-card" $root}}{{else}}{{template "battery-column-card" $root}}{{end}}{{else if eq .Type "history_view"}}{{template "history-view-card" (historyViewCard $item $root.HistoryViews)}}{{end}}
{{end}}{{end}} +{{define "layout-item"}}{{$root := .Root}}{{with .Item}}{{$item := .}}
{{if eq .Type "energy_flow"}}{{template "energy-flow-card" $root}}{{else if eq .Type "device"}}{{with index $root.LayoutDevices .Ref}}{{if eq $item.Display "compact"}}{{template "compact-card" (compactCardForItem . $item)}}{{else}}{{template "device-tile" (deviceTileForItem . $item.VisibleCategories)}}{{end}}{{end}}{{else if eq .Type "entity_value"}}{{with index $root.LayoutEntities .Ref}}{{template "entity-value-card" .}}{{end}}{{else if eq .Type "entity_group"}}{{template "entity-group-card" (entityGroupForItem $item $root.LayoutEntities)}}{{else if eq .Type "diagnostics"}}{{template "diagnostics-summary-card" $root}}{{else if eq .Type "energy_band"}}{{template "energy-band-card" $root}}{{else if eq .Type "energy_ring"}}{{template "energy-ring-card" $root}}{{else if eq .Type "energy_board"}}{{template "energy-board-card" $root}}{{else if eq .Type "energy_day"}}{{template "energy-day-card" $root}}{{else if eq .Type "energy_schema"}}{{template "energy-schema-card" $root}}{{else if eq .Type "energy_status"}}{{template "energy-status-card" $root}}{{else if eq .Type "energy_stats"}}{{template "energy-stats-card" $root}}{{else if eq .Type "battery_status"}}{{if eq $item.Display "trajectory"}}{{template "battery-trajectory-card" $root}}{{else}}{{template "battery-column-card" $root}}{{end}}{{else if eq .Type "device_map"}}{{template "device-map-card" $item}}{{else if eq .Type "history_view"}}{{template "history-view-card" (historyViewCard $item $root.HistoryViews)}}{{end}}
{{end}}{{end}} {{define "layout-item-fragment"}}{{template "layout-item" (layoutItem . .FragmentItem)}}{{end}} {{define "energy-flow-card"}} @@ -470,6 +470,22 @@

{{t "energy_stats.title"}}

ihr DOM einmal auf und schreibt danach nur Werte hinein. Ein x-for/x-bind-Geruest hier waere eine zweite Fassung derselben Karte - die Lovelace-Variante haette sie nicht. */}} +{{define "device-map-card"}} +
+
+ + +
+ +

{{t "device_map.title"}}

+

{{t "energy.plant.empty"}}

+ +
+
+{{end}} {{define "battery-column-card"}}
{{end}} {{define "battery-trajectory-card"}}
{{end}} diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index c985ff563..c43086757 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -5094,3 +5094,37 @@ func TestScenarioCardsShareTheFindingMark(t *testing.T) { } } } + +// TestOverviewRendersDeviceMapCard prueft die Geraetekarte im Uebersichtsraster: +// Alpine-Komponente, Optionen aus den data-map-*-Attributen des Items, der +// Tour-Anker und der uebersetzte Text der Einpass-Pille. +func TestOverviewRendersDeviceMapCard(t *testing.T) { + store := settings.NewStore(t.TempDir()) + if err := store.SaveLayout(settings.Layout{Pages: []settings.Page{{ + ID: "overview", Name: "Overview", Order: 0, + Groups: []settings.Group{{ID: "main", Name: "Main", Items: []settings.Item{ + {ID: "map", Type: "device_map", Span: "full", Visible: true, MapTap: "modal", MapData: "on"}, + }}}, + }}}); err != nil { + t.Fatal(err) + } + + recorder := httptest.NewRecorder() + Overview(registry.New(), nil, store).ServeHTTP(recorder, httptest.NewRequest("GET", "/?fragment=overview-live", nil)) + if recorder.Code != 200 { + t.Fatalf("got status %d", recorder.Code) + } + body := recorder.Body.String() + for _, marker := range []string{ + `data-layout-item-kind="device_map"`, + `x-data="deviceMapCard()"`, + `data-map-tap="modal"`, + `data-map-data="on"`, + `data-tour="device-map-card"`, + `Einpassen`, + } { + if !strings.Contains(body, marker) { + t.Fatalf("device_map card does not contain %q: %s", marker, body) + } + } +} From d6ab60781a5594a3dc92ed7e93eedd69703f664a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:13:35 +0100 Subject: [PATCH 08/17] fix(overview): clear the refresh timer when a live map is destroyed destroy() left a pending registry refresh armed, so a map that was already gone could fetch energy once more. The timer is now cleared and the pending flag reset. Also covers the card hint timer, the two-card test on one window, and a live-core test for the cleared refresh. Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/devicemap-live.js | 4 + dashboard/test/devicemap-card.test.mjs | 105 ++++++++++++++---- dashboard/test/devicemap-live.test.mjs | 24 ++++ 3 files changed, 109 insertions(+), 24 deletions(-) diff --git a/dashboard/internal/webui/static/js/devicemap-live.js b/dashboard/internal/webui/static/js/devicemap-live.js index efbc5b50a..50709c1bf 100644 --- a/dashboard/internal/webui/static/js/devicemap-live.js +++ b/dashboard/internal/webui/static/js/devicemap-live.js @@ -86,6 +86,10 @@ destroy() { this._offs.forEach(off => off()); this._offs = []; + // A refresh still waiting in the window would fetch energy after the + // map is gone. + if (this._timer) { clearTimeout(this._timer); this._timer = null; } + this._pending = false; this.flowAnimator().stop(); if (labels) { labels.destroy(); labels = null; } if (cy) { cy.destroy(); cy = null; } diff --git a/dashboard/test/devicemap-card.test.mjs b/dashboard/test/devicemap-card.test.mjs index 5ee94b58c..08911c0ca 100644 --- a/dashboard/test/devicemap-card.test.mjs +++ b/dashboard/test/devicemap-card.test.mjs @@ -49,8 +49,9 @@ const ATTRS = { 'role-edges': 'off', 'automation-links': 'on', 'edge-style': '', width: '', tap: 'none', }; -// Builds a fresh jsdom with the overview panel and one card section per call. -function createCard(overrides = {}, { table = TABLE, panelActive = true } = {}) { +// Builds one jsdom with the overview panel and one card section per entry of +// the list. All cards share the window, the panel scope and the observers. +function createCards(overridesList, { table = TABLE, panelActive = true } = {}) { const dom = new JSDOM(`
`, { runScripts: 'outside-only', pretendToBeVisual: true, url: 'http://localhost/' }); const window = dom.window; window.fetch = routes(table); @@ -72,18 +73,26 @@ function createCard(overrides = {}, { table = TABLE, panelActive = true } = {}) const context = dom.getInternalVMContext(); for (const name of files) vm.runInContext(fs.readFileSync(path.join(jsDir, name), 'utf8'), context); - const section = window.document.createElement('section'); - section.className = 'device-map-card'; - const attrs = { ...ATTRS, ...overrides }; - for (const [key, value] of Object.entries(attrs)) section.setAttribute(`data-map-${key}`, value); - window.document.body.append(section); - const canvas = window.document.createElement('div'); - section.append(canvas); - - const component = registry.deviceMapCard(); - component.$el = section; - component.$refs = { canvas }; - return { component, window, scope, observers, section }; + const components = overridesList.map(overrides => { + const section = window.document.createElement('section'); + section.className = 'device-map-card'; + const attrs = { ...ATTRS, ...overrides }; + for (const [key, value] of Object.entries(attrs)) section.setAttribute(`data-map-${key}`, value); + window.document.body.append(section); + const canvas = window.document.createElement('div'); + section.append(canvas); + const component = registry.deviceMapCard(); + component.$el = section; + component.$refs = { canvas }; + return component; + }); + return { components, window, scope, observers }; +} + +// One card in its own window, the common case for the tests below. +function createCard(overrides = {}, opts) { + const page = createCards([overrides], opts); + return { ...page, component: page.components[0] }; } test('options come from the data attributes', async () => { @@ -135,16 +144,64 @@ test('inactive when the overview is hidden or the card is out of view', async () }); test('two cards keep their own options', async () => { - const dom = createCard({ tap: 'highlight' }); - const second = createCard({ tap: 'modal' }); - await dom.component.load(); - await second.component.load(); - dom.component.onNodeTap('pv'); - second.component.onNodeTap('pv'); - assert.equal(dom.component.focusId, 'pv', 'first card highlights'); - assert.equal(second.component.focusId, null, 'second card does not'); - assert.deepEqual(plain(second.scope.selected), ['pv'], 'second card opens the modal'); - assert.deepEqual(plain(dom.scope.selected), [], 'first card does not open it'); + const { components, scope } = createCards([{ tap: 'highlight' }, { tap: 'modal' }]); + const [highlight, modal] = components; + await highlight.load(); + await modal.load(); + highlight.onNodeTap('pv'); + modal.onNodeTap('pv'); + assert.equal(highlight.focusId, 'pv', 'the highlight card focuses'); + assert.equal(modal.focusId, null, 'the modal card does not focus'); + assert.deepEqual(plain(scope.selected), ['pv'], 'only the modal card opens the device'); + highlight.onNodeTap('wb'); + assert.equal(highlight.focusId, 'wb', 'the highlight card keeps its own focus'); + assert.equal(modal.focusId, null, 'the modal card keeps no focus'); +}); + +// Captures setTimeout and clearTimeout of the card's window, so the hint +// timer runs only when the test fires it. +function fakeTimers(window) { + const pending = new Map(); + let now = 0; + let nextId = 1; + window.setTimeout = (fn, ms) => { const id = nextId++; pending.set(id, { fn, due: now + ms }); return id; }; + window.clearTimeout = id => { pending.delete(id); }; + return { + pending, + advance(ms) { + now += ms; + for (const [id, timer] of [...pending]) { + if (timer.due <= now) { pending.delete(id); timer.fn(); } + } + }, + }; +} + +test('hint shows the two finger text and hides after 1500 ms', async () => { + const { component, window } = createCard(); + const timers = fakeTimers(window); + component.showHint('two_fingers'); + assert.equal(component.hintShown, true); + assert.equal(component.hintText, window.I18n.t('device_map.hint.two_fingers')); + timers.advance(1499); + assert.equal(component.hintShown, true, 'still shown before 1500 ms'); + timers.advance(1); + assert.equal(component.hintShown, false, 'hidden after 1500 ms'); +}); + +test('wheel hint uses the Mac text on a Mac and the Ctrl text elsewhere', async () => { + const mac = createCard(); + Object.defineProperty(mac.window.navigator, 'platform', { value: 'MacIntel', configurable: true }); + fakeTimers(mac.window); + mac.component.showHint('wheel'); + assert.equal(mac.component.hintText, mac.window.I18n.t('device_map.hint.wheel_mac')); + + const linux = createCard(); + Object.defineProperty(linux.window.navigator, 'platform', { value: 'Linux x86_64', configurable: true }); + fakeTimers(linux.window); + linux.component.showHint('wheel'); + assert.equal(linux.component.hintText, linux.window.I18n.t('device_map.hint.wheel')); + assert.notEqual(linux.component.hintText, mac.component.hintText); }); test('dimmed opacity is 25 percent', async () => { diff --git a/dashboard/test/devicemap-live.test.mjs b/dashboard/test/devicemap-live.test.mjs index 7012a3971..ec824a4ed 100644 --- a/dashboard/test/devicemap-live.test.mjs +++ b/dashboard/test/devicemap-live.test.mjs @@ -164,3 +164,27 @@ test('the focus set of a device holds its trigger edge, so dimming leaves it', a assert.doesNotThrow(() => component.setFocus('pv')); assert.equal(component.focusId, 'pv'); }); + +test('destroy clears the pending refresh, so no energy fetch follows', async () => { + const energyCalls = []; + const { component, window } = createLive(TABLE, { isActive: () => true }); + window.fetch = async url => { if (String(url).endsWith('/api/v1/energy')) energyCalls.push(String(url)); return routes(TABLE)(url); }; + await component.load(); + const loaded = energyCalls.length; + const cleared = []; + const realClear = window.clearTimeout; + window.clearTimeout = id => { cleared.push(id); realClear(id); }; + component.onRegistryUpdated(); + const pendingTimer = component._timer; + assert.ok(pendingTimer, 'the refresh window is armed'); + assert.equal(energyCalls.length, loaded + 1, 'the first update fetches energy at once'); + component.onRegistryUpdated(); + assert.equal(component._pending, true, 'a second update inside the window is pending'); + component.destroy(); + assert.ok(cleared.includes(pendingTimer), 'destroy clears the armed refresh timer'); + assert.equal(component._timer, null); + assert.equal(component._pending, false, 'destroy drops the pending update'); + // Real timer: the refresh window is 1000 ms, wait past it. + await new Promise(resolve => setTimeout(resolve, 1100)); + assert.equal(energyCalls.length, loaded + 1, 'the cleared timer does not fetch energy again'); +}); From e6275a07cc14e5ccc1fc45615f53dd6892c6de57 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:15:53 +0100 Subject: [PATCH 09/17] feat(overview): load the device map card lazily and keep it out of the grid swap Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/httpapi/access_test.go | 14 ++++ .../internal/webui/static/js/dashboard.js | 3 +- dashboard/internal/webui/webui.go | 17 +++++ dashboard/internal/webui/webui_test.go | 73 +++++++++++++++++++ dashboard/test/dashboard.overview.test.mjs | 5 ++ 5 files changed, 111 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/httpapi/access_test.go b/dashboard/internal/httpapi/access_test.go index 573726f59..b79e3a423 100644 --- a/dashboard/internal/httpapi/access_test.go +++ b/dashboard/internal/httpapi/access_test.go @@ -380,3 +380,17 @@ func TestMigratedGuestPassesEveryViewGate(t *testing.T) { assertPassedGate(t, recorder, path) } } + +// Die Device-Map-Karte auf der Uebersicht holt ihre Verbindungen mit einer +// Sitzung, die nur view_overview hat. Die Route haengt an /api/v1/device/map/ +// (groupAnyView), darf also nicht mit 403 abgewiesen werden. +func TestDeviceMapFlowsAllowOverviewOnlyAccount(t *testing.T) { + router, manager := newRestrictedTestRouter(t, nil) + cookie, _ := loginWithRoles(t, router, manager, "olaf", []string{auth.RoleViewOverview}) + + response := httptest.NewRecorder() + router.ServeHTTP(response, sessionRequest(t, "/api/v1/device/map/flows", cookie, true)) + if response.Code == http.StatusForbidden { + t.Fatalf("/api/v1/device/map/flows with only view_overview: status 403, body %s", response.Body) + } +} diff --git a/dashboard/internal/webui/static/js/dashboard.js b/dashboard/internal/webui/static/js/dashboard.js index 41496e615..94d96623b 100644 --- a/dashboard/internal/webui/static/js/dashboard.js +++ b/dashboard/internal/webui/static/js/dashboard.js @@ -1258,7 +1258,8 @@ // Browser-Speicher in ihrem eigenen Takt (history-view-card.js) und // braucht keinen Push-Zweig. Ohne diesen Eintrag erzwaenge eine // einzige Verlaufskachel den teuren Tausch bei jedem Tick. - const selfServed = new Set(['history_view']); + // Die Device-Map-Karte hoert selbst auf registry-updated und behaelt dabei Cytoscape und Zoom. + const selfServed = new Set(['history_view', 'device_map']); const items = [...this.$root.querySelectorAll('[data-layout-item-kind]')]; // Leeres Raster heisst hier "nicht die Uebersicht" (das Geraete-Panel // benutzt dieselbe Komponente) oder "noch nichts geladen". Beide Male diff --git a/dashboard/internal/webui/webui.go b/dashboard/internal/webui/webui.go index 1daff5d7c..1e382f209 100644 --- a/dashboard/internal/webui/webui.go +++ b/dashboard/internal/webui/webui.go @@ -638,6 +638,8 @@ func defaultLayout(devices []registry.DeviceView) settings.Layout { // base.html laedt es fuer jede Karte dieser Gruppe ohnehin mit. Die URLs // muessen buchstabengleich mit data-panel-script des Verlaufs-Panels sein, // sonst laedt das Panel sie ein zweites Mal (loadSingleAsset, dashboard.js). +// device_map laedt Cytoscape und den Graphen-Stapel des Energie-Panels mit. +// devicemap-viewport.js und devicemap-card.js fehlen dort, sie tragen ?v=1. var energyCardScripts = map[string][]string{ "energy_band": {"/static/js/energy-band.js?v=2"}, "energy_ring": {"/static/js/energy-ring.js?v=2"}, @@ -648,6 +650,21 @@ var energyCardScripts = map[string][]string{ "energy_stats": {"/static/js-deps/apexcharts.min.js", "/static/js/energy-stats-model.js?v=5", "/static/js/energy-stats-card.js?v=5"}, "battery_status": {"/static/js/battery-status.js?v=2"}, "history_view": {"/static/js-deps/apexcharts.min.js", "/static/js/history-chart.js?v=5", "/static/js/history-view-card.js?v=2"}, + "device_map": { + "/static/js-deps/cytoscape.min.js", + "/static/js/devicemap-model.js?v=16", + "/static/js/devicemap-subdevices.js?v=1", + "/static/js/energy-chains.js?v=2", + "/static/js/devicemap-graph.js?v=12", + "/static/js/devicemap-wiring.js?v=3", + "/static/js/devicemap-dataflow.js?v=5", + "/static/js/devicemap-node-svg.js?v=7", + "/static/js/devicemap-labels.js?v=6", + "/static/js/devicemap-switch.js?v=2", + "/static/js/devicemap-live.js?v=1", + "/static/js/devicemap-viewport.js?v=1", + "/static/js/devicemap-card.js?v=1", + }, } // requiredEnergyCardScripts liefert die Skripte aller sichtbaren Karten diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index c43086757..5f8b534cd 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -8,6 +8,8 @@ import ( "net/http/httptest" "os" "path/filepath" + "reflect" + "regexp" "strings" "testing" "time" @@ -5128,3 +5130,74 @@ func TestOverviewRendersDeviceMapCard(t *testing.T) { } } } + +// TestDeviceMapCardScriptsMatchEnergyPanel prueft, dass die Skripte der +// Device-Map-Karte dieselben URLs wie das Energie-Panel laden. Eine +// abweichende Schreibweise (anderes ?v=) laedt das Skript doppelt +// (loadSingleAsset, dashboard.js). +func TestDeviceMapCardScriptsMatchEnergyPanel(t *testing.T) { + source, err := fs.ReadFile(templateFS, "templates/base.html") + if err != nil { + t.Fatal(err) + } + match := regexp.MustCompile(`id="energy-panel"[^>]*data-panel-script="([^"]*)"`).FindSubmatch(source) + if match == nil { + t.Fatal("energy-panel hat kein data-panel-script in base.html") + } + want := []string{ + "/static/js-deps/cytoscape.min.js", + "/static/js/devicemap-model.js?v=16", + "/static/js/devicemap-subdevices.js?v=1", + "/static/js/energy-chains.js?v=2", + "/static/js/devicemap-graph.js?v=12", + "/static/js/devicemap-wiring.js?v=3", + "/static/js/devicemap-dataflow.js?v=5", + "/static/js/devicemap-node-svg.js?v=7", + "/static/js/devicemap-labels.js?v=6", + "/static/js/devicemap-switch.js?v=2", + "/static/js/devicemap-live.js?v=1", + "/static/js/devicemap-viewport.js?v=1", + "/static/js/devicemap-card.js?v=1", + } + if !reflect.DeepEqual(energyCardScripts["device_map"], want) { + t.Fatalf("energyCardScripts[device_map] = %v", energyCardScripts["device_map"]) + } + panelScripts := strings.Split(string(match[1]), ",") + for _, script := range energyCardScripts["device_map"] { + file := strings.SplitN(script, "?", 2)[0] + for _, panelScript := range panelScripts { + if strings.HasSuffix(strings.SplitN(panelScript, "?", 2)[0], file) && !strings.HasSuffix(panelScript, script) { + t.Errorf("%s steht im Energie-Panel als %s, device_map laedt %s", file, panelScript, script) + } + } + } +} + +// TestDeviceMapCardScriptsLoadOncePerLayout prueft, dass zwei Device-Map- +// Karten im Raster jedes Skript genau einmal ausliefern. +func TestDeviceMapCardScriptsLoadOncePerLayout(t *testing.T) { + layout := settings.Layout{Pages: []settings.Page{{ + ID: "overview", Name: "Overview", Order: 0, + Groups: []settings.Group{{ID: "main", Name: "Main", Items: []settings.Item{ + {ID: "map-a", Type: "device_map", Visible: true}, + {ID: "map-b", Type: "device_map", Visible: true}, + }}}, + }}} + scripts := requiredEnergyCardScripts(layout, "") + want := energyCardScripts["device_map"] + if len(want) == 0 { + t.Fatal("device_map hat keine Skripte in energyCardScripts") + } + if len(scripts) != len(want) { + t.Fatalf("got %d scripts %v, want %d", len(scripts), scripts, len(want)) + } + seen := map[string]int{} + for _, script := range scripts { + seen[script]++ + } + for _, script := range want { + if seen[script] != 1 { + t.Errorf("%s geladen %d mal, want 1", script, seen[script]) + } + } +} diff --git a/dashboard/test/dashboard.overview.test.mjs b/dashboard/test/dashboard.overview.test.mjs index d09996eb5..b37753d46 100644 --- a/dashboard/test/dashboard.overview.test.mjs +++ b/dashboard/test/dashboard.overview.test.mjs @@ -477,6 +477,11 @@ test('liveGridPushCovers treats history_view as covered, it needs no push data', assert.equal(panel.liveGridPushCovers({energy: {}}), true); }); +test('liveGridPushCovers treats device_map as covered, the card listens to registry-updated itself', () => { + const { panel } = overviewPanel(['device_map', 'energy_flow']); + assert.equal(panel.liveGridPushCovers({energy: {}}), true); +}); + test('liveGridPushCovers still swaps when only history_view is present but another kind is uncovered', () => { const { panel } = overviewPanel(['diagnostics', 'history_view']); assert.equal(panel.liveGridPushCovers({energy: {}}), false); From 6eecf34a5092238b9f0054e70a68f5f5b4be3e0a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:18:53 +0100 Subject: [PATCH 10/17] feat(layout-editor): offer the device map card with its options Adds the device_map card to the layout editor palette and its nine options (four layers, role edges, automation links, edge style, line width, tap) to the options dialog, with defaults and load/save mapping. Catalog keys for de and en are added for the card and the new options. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 16 ++++ dashboard/internal/webui/catalogs/en.json | 16 ++++ .../internal/webui/static/js/layout-editor.js | 42 ++++++++- dashboard/test/layout-editor.test.mjs | 89 +++++++++++++++++++ 4 files changed, 162 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index fcb806c02..3a19be464 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3555,6 +3555,8 @@ "layout_editor.card.battery_status.description": "Vorrat und Restlaufzeit", "layout_editor.card.battery_status.title": "Speicher: Statuskarte", "layout_editor.card.device.description": "Gerät", + "layout_editor.card.device_map.description": "Die Anordnung der Device-Map mit Live-Werten und Energiefluss", + "layout_editor.card.device_map.title": "Device-Map", "layout_editor.card.diagnostics.description": "Diagnosen", "layout_editor.card.diagnostics.title": "Diagnosen", "layout_editor.card.energy_band.description": "Bilanzband", @@ -3593,6 +3595,12 @@ "layout_editor.device.display_label": "Darstellung", "layout_editor.device.label": "Gerät: {name}", "layout_editor.device.ref_label": "Gerät", + "layout_editor.device_map.automation_links": "Automationslinks", + "layout_editor.device_map.edge_style": "Kantenstil", + "layout_editor.device_map.layers": "Ebenen", + "layout_editor.device_map.role_edges": "Rollenkanten", + "layout_editor.device_map.tap": "Antippen eines Geräts", + "layout_editor.device_map.width": "Linienbreite nach Leistung", "layout_editor.energy_band.animate": "Fluss animieren", "layout_editor.energy_band.bundle_threshold": "Kleinstflüsse", "layout_editor.energy_band.height_reference": "Höhenbezug", @@ -3670,6 +3678,8 @@ "layout_editor.option.display_size.s": "S", "layout_editor.option.display_size.xl": "XL", "layout_editor.option.display_size.xs": "XS", + "layout_editor.option.edge_curved": "Gebogen", + "layout_editor.option.edge_straight": "Gerade", "layout_editor.option.entity_labels.entity": "Leistung + Entität", "layout_editor.option.entity_labels.power": "nur Leistung", "layout_editor.option.flow_scale.speed": "Animationsgeschwindigkeit", @@ -3685,6 +3695,9 @@ "layout_editor.option.label_mode.abs": "Absolutwerte", "layout_editor.option.label_mode.both": "beides", "layout_editor.option.label_mode.pct": "Prozent", + "layout_editor.option.map_follow": "Wie in der Device-Map", + "layout_editor.option.off": "Aus", + "layout_editor.option.on": "An", "layout_editor.option.scale_mode.linear": "linear (echte Anteile)", "layout_editor.option.scale_mode.sqrt": "Wurzel (kleine sichtbar)", "layout_editor.option.sort.fixed": "feste Reihenfolge", @@ -3697,6 +3710,9 @@ "layout_editor.option.stats_period.last": "zuletzt gewählter", "layout_editor.option.stroke_mode.const": "konstant", "layout_editor.option.stroke_mode.power": "nach Leistung", + "layout_editor.option.tap_highlight": "Hervorheben", + "layout_editor.option.tap_modal": "Geräte-Modal öffnen", + "layout_editor.option.tap_none": "Nichts", "layout_editor.option.unit.auto": "automatisch", "layout_editor.option.unit.kw": "immer kW", "layout_editor.option.unit.w": "immer W", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index af83840d3..16f970627 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3555,6 +3555,8 @@ "layout_editor.card.battery_status.description": "Reserve and remaining time", "layout_editor.card.battery_status.title": "Battery: status card", "layout_editor.card.device.description": "Device", + "layout_editor.card.device_map.description": "The device map layout with live values and energy flow", + "layout_editor.card.device_map.title": "Device map", "layout_editor.card.diagnostics.description": "Diagnostics", "layout_editor.card.diagnostics.title": "Diagnostics", "layout_editor.card.energy_band.description": "Balance band", @@ -3593,6 +3595,12 @@ "layout_editor.device.display_label": "Display", "layout_editor.device.label": "Device: {name}", "layout_editor.device.ref_label": "Device", + "layout_editor.device_map.automation_links": "Automation links", + "layout_editor.device_map.edge_style": "Edge style", + "layout_editor.device_map.layers": "Layers", + "layout_editor.device_map.role_edges": "Role edges", + "layout_editor.device_map.tap": "Tapping a device", + "layout_editor.device_map.width": "Line width by power", "layout_editor.energy_band.animate": "Animate flow", "layout_editor.energy_band.bundle_threshold": "Small flows", "layout_editor.energy_band.height_reference": "Height reference", @@ -3670,6 +3678,8 @@ "layout_editor.option.display_size.s": "S", "layout_editor.option.display_size.xl": "XL", "layout_editor.option.display_size.xs": "XS", + "layout_editor.option.edge_curved": "Curved", + "layout_editor.option.edge_straight": "Straight", "layout_editor.option.entity_labels.entity": "Power + entity", "layout_editor.option.entity_labels.power": "power only", "layout_editor.option.flow_scale.speed": "Animation speed", @@ -3685,6 +3695,9 @@ "layout_editor.option.label_mode.abs": "Absolute values", "layout_editor.option.label_mode.both": "both", "layout_editor.option.label_mode.pct": "Percent", + "layout_editor.option.map_follow": "As in the device map", + "layout_editor.option.off": "Off", + "layout_editor.option.on": "On", "layout_editor.option.scale_mode.linear": "linear (true shares)", "layout_editor.option.scale_mode.sqrt": "square root (small ones visible)", "layout_editor.option.sort.fixed": "fixed order", @@ -3697,6 +3710,9 @@ "layout_editor.option.stats_period.last": "last selected", "layout_editor.option.stroke_mode.const": "constant", "layout_editor.option.stroke_mode.power": "by power", + "layout_editor.option.tap_highlight": "Highlight", + "layout_editor.option.tap_modal": "Open device details", + "layout_editor.option.tap_none": "Nothing", "layout_editor.option.unit.auto": "automatic", "layout_editor.option.unit.kw": "always kW", "layout_editor.option.unit.w": "always W", diff --git a/dashboard/internal/webui/static/js/layout-editor.js b/dashboard/internal/webui/static/js/layout-editor.js index f6c2bc9e1..cd40e73ef 100644 --- a/dashboard/internal/webui/static/js/layout-editor.js +++ b/dashboard/internal/webui/static/js/layout-editor.js @@ -229,6 +229,8 @@ energy_schema:'', energy_status:'', energy_stats: '', + // Drei Knoten mit zwei Kanten - die Device-Map als Graph. + device_map: '', // Die Saeule der Batteriekarte: ein Zellenumriss mit Fahne und einem // gefuellten unteren Teil, derselbe Aufbau wie die echte Karte. battery_status:'', @@ -277,6 +279,15 @@ {role: 'speed-reference-watts', field: 'speedReferenceWatts', json: 'speed_reference_watts', kind: 'number'}, {role: 'history-range-hours', field: 'historyRangeHours', json: 'history_range_hours', kind: 'select'}, {role: 'history-aggregate', field: 'historyAggregate', json: 'history_aggregate', kind: 'select'}, + {role: 'map-wiring', field: 'mapWiring', json: 'map_wiring', kind: 'checkbox'}, + {role: 'map-energy', field: 'mapEnergy', json: 'map_energy', kind: 'checkbox'}, + {role: 'map-balance', field: 'mapBalance', json: 'map_balance', kind: 'checkbox'}, + {role: 'map-data', field: 'mapData', json: 'map_data', kind: 'checkbox'}, + {role: 'map-role-edges', field: 'mapRoleEdges', json: 'map_role_edges', kind: 'checkbox'}, + {role: 'map-automation-links', field: 'mapAutomationLinks', json: 'map_automation_links', kind: 'checkbox'}, + {role: 'map-edge-style', field: 'mapEdgeStyle', json: 'map_edge_style', kind: 'select'}, + {role: 'map-width', field: 'mapWidth', json: 'map_width', kind: 'select'}, + {role: 'map-tap', field: 'mapTap', json: 'map_tap', kind: 'select'}, ]; const ENERGY_OPTION_BY_ROLE = Object.fromEntries(ENERGY_OPTIONS.map(o => [o.role, o])); const ENERGY_OPTION_FIELDS = ENERGY_OPTIONS.map(o => o.field); @@ -297,6 +308,9 @@ // den Wert zwar mit, zeigt aber kein Feld dafuer. battery_status: {batteryWindow: '6'}, energy_stats: {statsChart: 'off'}, + // Die neun Vorgaben spiegeln die Device-Map: vier Lagen, zwei Schalter + // und drei Auswahlfelder, "" heisst "wie in der Device-Map". + device_map: {mapWiring: 'off', mapEnergy: 'on', mapBalance: 'on', mapData: 'off', mapRoleEdges: 'off', mapAutomationLinks: 'off', mapEdgeStyle: '', mapWidth: '', mapTap: 'highlight'}, }; const defaultEnergyOptions = type => ({...ENERGY_OPTION_DEFAULTS[type]}); @@ -421,6 +435,28 @@ + `` + checkboxFieldHTML('stats-chart', 'layout_editor.energy_stats.stats_chart', item.statsChart === 'on'); }, + // Die Lagen sind Schalter mit den Namen der Device-Map-Ebenen. Kantenstil, + // Linienbreite und Antippen stehen als Auswahl darunter; "" heisst jeweils + // "wie in der Device-Map". + // i18n-keys: layout_editor.option.map_follow, layout_editor.option.edge_curved, + // layout_editor.option.edge_straight, layout_editor.option.on, + // layout_editor.option.off, layout_editor.option.tap_none, + // layout_editor.option.tap_highlight, layout_editor.option.tap_modal + device_map: item => + `
${escapeHTML(t('layout_editor.device_map.layers'))}
` + + checkboxFieldHTML('map-wiring', 'devicemap.layer.wiring', item.mapWiring === 'on') + + checkboxFieldHTML('map-energy', 'devicemap.layer.energy', item.mapEnergy === 'on') + + checkboxFieldHTML('map-balance', 'devicemap.layer.balance', item.mapBalance === 'on') + + checkboxFieldHTML('map-data', 'devicemap.layer.data', item.mapData === 'on') + + checkboxFieldHTML('map-role-edges', 'layout_editor.device_map.role_edges', item.mapRoleEdges === 'on') + + checkboxFieldHTML('map-automation-links', 'layout_editor.device_map.automation_links', item.mapAutomationLinks === 'on') + + '
' + + selectFieldHTML('map-edge-style', 'layout_editor.device_map.edge_style', item.mapEdgeStyle || '', + [['', 'layout_editor.option.map_follow'], ['curved', 'layout_editor.option.edge_curved'], ['straight', 'layout_editor.option.edge_straight']]) + + selectFieldHTML('map-width', 'layout_editor.device_map.width', item.mapWidth || '', + [['', 'layout_editor.option.map_follow'], ['on', 'layout_editor.option.on'], ['off', 'layout_editor.option.off']]) + + selectFieldHTML('map-tap', 'layout_editor.device_map.tap', item.mapTap || 'highlight', + [['none', 'layout_editor.option.tap_none'], ['highlight', 'layout_editor.option.tap_highlight'], ['modal', 'layout_editor.option.tap_modal']]), }; // Karten mit Typ-Minimum >= 2 (die fuenf Energiegrafik-Alternativen ausser @@ -689,6 +725,9 @@ // Generisch wie entity-group: Quelle, Serien und Zeitraum waehlt man // im Optionen-Modal, mehrere Verlaufskacheln je Seite sind erlaubt. {id: 'history-view', type: 'history_view', ref: '', title: t('layout_editor.card.history_view.title'), desc: t('layout_editor.card.history_view.description')}, + // Eine Karte je Anlage: die Lagen, Kanten und das Antippen stellt man im + // Optionen-Modal ein, darum kein Ref. + {id: 'device-map', type: 'device_map', ref: '', title: t('layout_editor.card.device_map.title'), desc: t('layout_editor.card.device_map.description')}, ]; const geraete = (devices || []).map(d => ({id: 'device:'+d.id, type: 'device', ref: d.id, title: d.name || d.id, desc: t('layout_editor.card.device.description')})); // Ein Eintrag je Entitaet: die Wert-Karte. Bis 2026-09 stand daneben ein @@ -1621,6 +1660,7 @@ // statt die Option-ID wiederzuverwenden. {id: 'entity-value', type: 'entity_value', ref: ''}, {id: 'history-view', type: 'history_view', ref: ''}, + {id: 'device-map', type: 'device_map', ref: ''}, ]; for (const device of this.devices) { options.push({id: `device:${device.id}`, type: 'device', ref: device.id}); @@ -1655,7 +1695,7 @@ // vorkommt. Die ID bleibt der letzte Rueckfall - fuer Layouts, die noch // aus der Zeit der Katalog-IDs stammen. const byKind = this.itemOptions.find(option => option.type === item.type && (option.ref || '') === (item.ref || '')); - if (byKind) return t(`layout_editor.card.${byKind.type}.title`); // i18n-keys: layout_editor.card.energy_flow.title, layout_editor.card.diagnostics.title, layout_editor.card.energy_band.title, layout_editor.card.energy_ring.title, layout_editor.card.energy_board.title, layout_editor.card.energy_day.title, layout_editor.card.energy_schema.title, layout_editor.card.energy_status.title, layout_editor.card.energy_stats.title, layout_editor.card.battery_status.title, layout_editor.card.entity_value.title, layout_editor.card.history_view.title + if (byKind) return t(`layout_editor.card.${byKind.type}.title`); // i18n-keys: layout_editor.card.energy_flow.title, layout_editor.card.diagnostics.title, layout_editor.card.energy_band.title, layout_editor.card.energy_ring.title, layout_editor.card.energy_board.title, layout_editor.card.energy_day.title, layout_editor.card.energy_schema.title, layout_editor.card.energy_status.title, layout_editor.card.energy_stats.title, layout_editor.card.battery_status.title, layout_editor.card.entity_value.title, layout_editor.card.history_view.title, layout_editor.card.device_map.title const byID = this.itemOptions.find(option => option.id === item.id); if (byID) return t(`layout_editor.card.${byID.type}.title`); return item.ref || item.id; diff --git a/dashboard/test/layout-editor.test.mjs b/dashboard/test/layout-editor.test.mjs index 00d93a142..a2edf2670 100644 --- a/dashboard/test/layout-editor.test.mjs +++ b/dashboard/test/layout-editor.test.mjs @@ -340,6 +340,95 @@ test('ENERGY_OPTION_BY_ROLE maps a select role to its camelCase field and a chec ); }); +test('der Katalog bietet die Device-Map mit Titel und Beschreibung an', () => { + const { factory } = loadLayoutPage(); + const entry = factory.catalog([]).karten.find(card => card.type === 'device_map'); + assert.ok(entry, 'die Device-Map fehlt im Kartenregister'); + assert.equal(entry.id, 'device-map'); + assert.equal(entry.ref, ''); + assert.equal(entry.title, 'Device-Map'); + assert.equal(entry.desc, 'Die Anordnung der Device-Map mit Live-Werten und Energiefluss'); +}); + +test('ein neues device_map-Item bekommt die neun Vorgaben der Device-Map', () => { + const { factory } = loadLayoutPage(); + assert.deepEqual(JSON.parse(JSON.stringify(factory.defaultEnergyOptions('device_map'))), { + mapEnergy: 'on', mapBalance: 'on', mapWiring: 'off', mapData: 'off', + mapRoleEdges: 'off', mapAutomationLinks: 'off', mapEdgeStyle: '', mapWidth: '', mapTap: 'highlight', + }); +}); + +test('das Optionsmodal der Device-Map zeigt vier Lagen, zwei Schalter und drei Auswahlfelder', () => { + const { factory } = loadLayoutPage(); + const html = factory.energyOptionsHTML({type: 'device_map', mapEnergy: 'on', mapBalance: 'on', mapWiring: 'off', mapData: 'off', mapRoleEdges: 'off', mapAutomationLinks: 'off', mapEdgeStyle: '', mapWidth: '', mapTap: 'highlight'}); + assert.equal(html.match(/ { + const { component } = loadLayoutPage(); + const item = {id: 'm', type: 'device_map', span: '2', visible: true, mapEnergy: 'on', mapBalance: 'on', mapWiring: 'off', mapData: 'off', mapRoleEdges: 'off', mapAutomationLinks: 'off', mapEdgeStyle: '', mapWidth: '', mapTap: 'highlight'}; + optionChange(component, item, {dataset: {role: 'map-data'}, checked: true}); + assert.equal(item.mapData, 'on'); + optionChange(component, item, {dataset: {role: 'map-data'}, checked: false}); + assert.equal(item.mapData, 'off'); + optionChange(component, item, {dataset: {role: 'map-tap'}, value: 'modal'}); + assert.equal(item.mapTap, 'modal'); + optionChange(component, item, {dataset: {role: 'map-edge-style'}, value: 'straight'}); + assert.equal(item.mapEdgeStyle, 'straight'); +}); + +test('save() schreibt die Device-Map-Felder als map_*-JSON', async () => { + let sentBody = null; + const { component } = loadLayoutPage({ + fetchImpl: async (url, options) => { + if (options?.method === 'PUT') { sentBody = JSON.parse(options.body); return jsonResponse({}); } + throw new Error(`unexpected fetch ${url}`); + }, + }); + component.pages = [{ + id: 'page-1', name: '', order: 0, + groups: [{id: 'group-1', name: 'Dashboard', items: [ + {id: 'm', type: 'device_map', ref: '', span: '2', visible: true, visibleCategories: [], flowScale: '', + mapEnergy: 'on', mapBalance: 'on', mapWiring: 'off', mapData: 'on', mapRoleEdges: 'off', mapAutomationLinks: 'off', + mapEdgeStyle: '', mapWidth: '', mapTap: 'modal'}, + ]}], + }]; + await component.save(); + const item = sentBody.pages[0].groups[0].items[0]; + assert.equal(item.map_data, 'on'); + assert.equal(item.map_tap, 'modal'); + assert.equal(item.map_energy, 'on'); + assert.equal(item.map_edge_style, undefined, 'ein leerer Kantenstil wird nicht geschickt, der Server setzt ""'); + for (const leaked of ['mapData', 'mapTap', 'mapEdgeStyle', 'mapEnergy']) { + assert.equal(leaked in item, false, `${leaked} must not leak into the saved JSON`); + } +}); + +test('load() uebernimmt map_edge_style "" als "Wie in der Device-Map" und haelt es leer', async () => { + const layout = { + version: 3, + pages: [{id: 'page-1', name: '', order: 0, groups: [{ + id: 'group-1', name: 'Dashboard', + items: [{id: 'm', type: 'device_map', ref: '', span: '2', visible: true, map_edge_style: '', map_data: 'on', map_tap: 'modal'}], + }]}], + }; + const { component, factory } = loadLayoutPage({ + fetchImpl: async url => (url === '/api/v1/layout' ? jsonResponse(layout) : jsonResponse([])), + }); + await component.load(); + const item = component.pages[0].groups[0].items[0]; + assert.equal(item.mapEdgeStyle, ''); + assert.equal(item.mapData, 'on'); + assert.equal(item.mapTap, 'modal'); + const html = factory.energyOptionsHTML(item); + assert.match(html, /