diff --git a/changelog/highlights/318.json b/changelog/highlights/318.json new file mode 100644 index 000000000..d4bfc4611 --- /dev/null +++ b/changelog/highlights/318.json @@ -0,0 +1,28 @@ +{ + "de": { + "*": "Die Device-Map als Karte auf der Übersicht, mit Live-Werten, Energiefluss und Zoom" + }, + "en": { + "*": "Add a device map card to the overview" + }, + "tour": { + "*": { + "steps": [ + { + "device": "any", + "need": "edit_layout", + "panel": "overview-panel", + "target": "device-map-card", + "text": { + "de": "Die Anordnung aus der Device-Map gibt es jetzt als Karte mit Live-Werten und Energiefluss. Du fügst sie im Layout-Editor hinzu und wählst dort die Ebenen. Zoomen geht mit Strg und Mausrad oder mit zwei Fingern, „Einpassen“ holt die ganze Anlage zurück.", + "en": "The device map layout is now available as a card with live values and energy flow. Add it in the layout editor and choose its layers there. Zoom with Ctrl and the mouse wheel or with two fingers, Fit brings the whole plant back." + }, + "title": { + "de": "Device-Map auf der Übersicht", + "en": "Device map on the overview" + } + } + ] + } + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index c07cff8e1..7f3527294 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,10 +1,17 @@ # Changelog -## v0.12.1-pre.1 (2026-12-03) +## v0.12.1-pre.2 (2026-12-04) ### Features - **dashboard:** A compact header whose status chip names the cause of a problem (#316) (6f5aa61) +- **overview:** add the device_map card type to the layout settings (a226f60) +- **overview:** add viewport gestures and fit spring for map cards (62c9456) +- **overview:** add the device map card component (a99435a) +- **overview:** render the device map card with glass label, fit pill and tap modes (0d553bd) +- **overview:** load the device map card lazily and keep it out of the grid swap (e6275a0) +- **layout-editor:** offer the device map card with its options (6eecf34) +- **overview:** add a device map card to the overview (#318) - **health:** derive a ranked issue list from the node state (c7c1a75) - **health:** report issues and level, count only installed services (f290fb2) - **dashboard:** one title row with a status chip that names its cause (0c99637) @@ -15,12 +22,17 @@ ### Fixes +- **energy:** show role edges with the data layer on the live core (124761f) +- **overview:** make viewport attach idempotent (7d40301) +- **overview:** clear the refresh timer when a live map is destroyed (d6ab607) +- **overview:** cancel the fit spring on re-render and refresh energy on wake (371fcb9) - **dashboard:** format the status chip values for the locale (ce581a5) - **health:** warn when the storage medium reports its end of life (327b355) - **dashboard:** record the cache-bust marks for the prerelease line (7490abd) ### Refactors +- **energy:** move the plant renderer into a shared devicemap-live core (99e8dbd) - **settings:** retire status_bar_items, the status popover shows every value (4a944fb) - **settings:** drop the status field chooser from settings and installer (1b4cce1) @@ -34,10 +46,16 @@ ### Style +- **overview:** give the device map card the same title header as the other cards (9926343) +- **overview:** drop the glass label from the device map card comment (979149d) - **dashboard:** style the title row and the status chip (d28e19e) - **dashboard:** give update, guest and example notes one slim row form (10a1384) - **dashboard:** darken the install button on hover so its label keeps contrast (8cb0b15) +### Chores + +- **dashboard:** bump asset versions and document the device map card (fa9b369) + ## v0.12.0 (2026-12-02) ### Features diff --git a/dashboard/VERSION b/dashboard/VERSION index 6e96d4b15..7e5116881 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.12.1-pre.1 +v0.12.1-pre.2 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/settings/cardcatalog.go b/dashboard/internal/settings/cardcatalog.go index befb98a52..acdb1cfba 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 + // Kopfzeile, 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") + } +} diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 380a5e596..af7310617 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,4 +1,12 @@ version,date,asset,v,note +v0.12.1-pre.2,2026-12-03,css/base.css,57, +v0.12.1-pre.2,2026-12-03,css/manager.css,55, +v0.12.1-pre.2,2026-12-03,js/dashboard.js,58, +v0.12.1-pre.2,2026-12-03,js/devicemap-card.js,1, +v0.12.1-pre.2,2026-12-03,js/devicemap-live.js,1, +v0.12.1-pre.2,2026-12-03,js/devicemap-viewport.js,1, +v0.12.1-pre.2,2026-12-03,js/energy-plant.js,8, +v0.12.1-pre.2,2026-12-03,js/layout-editor.js,20, v0.12.1-pre.1,2026-12-03,css/base.css,56, v0.12.1-pre.1,2026-12-03,css/onboarding.css,9, v0.12.1-pre.1,2026-12-03,css/settings-controls.css,23, diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index ddb769ae7..3a19be464 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", @@ -3549,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", @@ -3587,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", @@ -3664,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", @@ -3679,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", @@ -3691,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 2a38b7e12..16f970627 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", @@ -3549,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", @@ -3587,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", @@ -3664,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", @@ -3679,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", @@ -3691,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/css/base.css b/dashboard/internal/webui/static/css/base.css index 021995f5d..cd39da6ae 100644 --- a/dashboard/internal/webui/static/css/base.css +++ b/dashboard/internal/webui/static/css/base.css @@ -2413,3 +2413,117 @@ 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 ------------------------------------------------------------------ + Kopf wie bei Statistik und Bilanz, darunter fuellt die Map den Rest der + Karte. Pille und Hinweis 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; + display: flex; + flex-direction: column; + 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 Pille und Hinweis. */ +.device-map-card-header { padding: 1rem 1.1rem 0; } +.device-map-card-header h3 { margin: 0; font-size: 1rem; overflow-wrap: anywhere; } +.device-map-card-stage { position: relative; flex: 1 1 auto; min-height: 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; } + +/* Glas: halbtransparentes Panel mit Blur, die helle Oberkante faengt Licht. + Klein und leicht, weil es nur beschriftet. */ +.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-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-fit, .device-map-card-hint { background: var(--panel); -webkit-backdrop-filter: none; backdrop-filter: none; } +} +@media (prefers-contrast: more) { + .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/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/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/internal/webui/static/js/devicemap-live.js b/dashboard/internal/webui/static/js/devicemap-live.js new file mode 100644 index 000000000..a7a9e5381 --- /dev/null +++ b/dashboard/internal/webui/static/js/devicemap-live.js @@ -0,0 +1,438 @@ +// 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(); + // Back on the panel: the energy values went stale while it was hidden. + if (this.isActive()) this.refreshEnergy(); + }); + } + 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 = []; + // 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; } + }, + + 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 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: 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)); + } + } + 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 : []; + // 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; + }, + + 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 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(() => { + 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/devicemap-viewport.js b/dashboard/internal/webui/static/js/devicemap-viewport.js new file mode 100644 index 000000000..6ead29004 --- /dev/null +++ b/dashboard/internal/webui/static/js/devicemap-viewport.js @@ -0,0 +1,277 @@ +// 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.max(1, 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 => { + // Eine laufende Feder gehoert zur alten Instanz und stoppt vor dem Neubinden. + cancel(); + // 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); + 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/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/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/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 970131984..73165beb5 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -72,7 +72,7 @@ - +