diff --git a/cmd/server/dagi_area_comparison_test.go b/cmd/server/dagi_area_comparison_test.go index ed9a85112..63e610aa8 100644 --- a/cmd/server/dagi_area_comparison_test.go +++ b/cmd/server/dagi_area_comparison_test.go @@ -101,16 +101,19 @@ func TestDagiAreaComparisonPostnummerGroups(t *testing.T) { if rowByCode(rows, "1051") != nil || rowByCode(rows, "1801") != nil { t.Error("a street-postcode member is its own row") } - if g := rowByCode(rows, "1050"); g == nil || g.Nodes != 1 || g.RepeatersPer100Km2 == nil { - t.Errorf("1050 group %+v, want Kbh K counted, with a density", g) + // No density for postnumre (owner, 2026-12-02), the groups included. + if g := rowByCode(rows, "1050"); g == nil || g.Nodes != 1 || g.Repeaters != 1 || g.RepeatersPer100Km2 != nil || g.ObserversPer100Km2 != nil { + t.Errorf("1050 group %+v, want Kbh K counted, with no density", g) } } -// Christiansø is a row with no density (nil, "—" in the UI); every other -// area has one, postnumre included (#1032: their areaM2 is land). +// Density (owner, 2026-12-02): kommuner, landsdele and regioner have +// repeaters per 100 km² over the active repeaters only, and observers per +// 100 km²; Christiansø has none (nil, "—" in the UI); postnumre have none +// at all, the street-postcode groups included, though their counts stay. func TestDagiAreaComparisonDensity(t *testing.T) { w := newWorld1002(t, cfg1002()) - for _, layer := range []string{"kommune", "landsdel", "region", "postnummer"} { + for _, layer := range []string{"kommune", "landsdel", "region"} { for _, r := range w.comparison(layer).Rows { if r.OutsideKommune { continue @@ -119,26 +122,50 @@ func TestDagiAreaComparisonDensity(t *testing.T) { t.Errorf("%s %s: density nil", layer, r.Code) continue } - if want := float64(r.Repeaters) / (r.AreaKm2 / 100); math.Abs(*r.RepeatersPer100Km2-want) > 1e-9 { - t.Errorf("%s %s: repeaters/100 km² %v, want %v (unrounded)", layer, r.Code, *r.RepeatersPer100Km2, want) + if r.ActiveRepeaters > r.Repeaters || r.ActiveRepeaters < 0 { + t.Errorf("%s %s: %d active of %d repeaters", layer, r.Code, r.ActiveRepeaters, r.Repeaters) + } + if want := float64(r.ActiveRepeaters) / (r.AreaKm2 / 100); math.Abs(*r.RepeatersPer100Km2-want) > 1e-9 { + t.Errorf("%s %s: repeaters/100 km² %v, want %v (active only, unrounded)", layer, r.Code, *r.RepeatersPer100Km2, want) } if want := float64(r.Observers) / (r.AreaKm2 / 100); math.Abs(*r.ObserversPer100Km2-want) > 1e-9 { t.Errorf("%s %s: observers/100 km² %v, want %v", layer, r.Code, *r.ObserversPer100Km2, want) } } } + counted := 0 + for _, r := range w.comparison("postnummer").Rows { + if r.RepeatersPer100Km2 != nil || r.ObserversPer100Km2 != nil { + t.Errorf("postnummer %s (group %v): density %v / %v, want none", r.Code, r.Group, r.RepeatersPer100Km2, r.ObserversPer100Km2) + } + counted += r.Repeaters + if r.ActiveRepeaters > r.Repeaters { + t.Errorf("postnummer %s: %d active of %d repeaters", r.Code, r.ActiveRepeaters, r.Repeaters) + } + } + if counted == 0 { + t.Error("postnumre count no repeater: the counts must stay") + } chr := rowByCode(w.comparison("kommune").Rows, "0411") - if chr == nil || !chr.OutsideKommune || chr.Nodes != 1 || chr.RepeatersPer100Km2 != nil || chr.ObserversPer100Km2 != nil { + if chr == nil || !chr.OutsideKommune || chr.Nodes != 1 || chr.Repeaters != 1 || chr.ActiveRepeaters != 1 || chr.RepeatersPer100Km2 != nil || chr.ObserversPer100Km2 != nil { t.Errorf("Christiansø %+v", chr) } - body := w.get("/api/analytics/dagi-areas?layer=kommune").Body.String() - i := strings.Index(body, `"code":"0411"`) - if i < 0 || !strings.Contains(body[i:i+800], `"repeatersPer100Km2":null`) || !strings.Contains(body[i:i+800], `"observersPer100Km2":null`) { - t.Errorf("Christiansø densities are not null in the body") + for _, layer := range []string{"kommune", "postnummer"} { + body := w.get("/api/analytics/dagi-areas?layer=" + layer).Body.String() + if strings.Contains(body, `"repeatersPer100Km2":0`) && layer == "postnummer" { + t.Errorf("postnummer body has a zero density, want null") + } + code := map[string]string{"kommune": `"code":"0411"`, "postnummer": `"code":"8200"`}[layer] + i := strings.Index(body, code) + if i < 0 || !strings.Contains(body[i:i+800], `"repeatersPer100Km2":null`) || !strings.Contains(body[i:i+800], `"observersPer100Km2":null`) { + t.Errorf("%s %s: densities are not null in the body", layer, code) + } + if !strings.Contains(body[i:i+800], `"activeRepeaters":`) { + t.Errorf("%s %s: no activeRepeaters in the body", layer, code) + } } } -// The gap flags, from a row's numbers (research §2 "Coverage gaps"). func TestDagiAreaGaps(t *testing.T) { for _, c := range []struct { name string diff --git a/cmd/server/dagi_area_stats.go b/cmd/server/dagi_area_stats.go index 422188f77..e1ed871b4 100644 --- a/cmd/server/dagi_area_stats.go +++ b/cmd/server/dagi_area_stats.go @@ -168,13 +168,16 @@ type DagiAreaRow struct { OutsideKommune bool `json:"outsideKommune,omitempty"` Group bool `json:"group,omitempty"` // AreaKm2 is the asset's areaM2: land only, postnumre too (#1032). - AreaKm2 float64 `json:"areaKm2"` - Nodes int `json:"nodes"` - Repeaters int `json:"repeaters"` - Rooms int `json:"rooms"` - Companions int `json:"companions"` - Sensors int `json:"sensors"` - OtherRoles int `json:"otherRoles"` + AreaKm2 float64 `json:"areaKm2"` + Nodes int `json:"nodes"` + Repeaters int `json:"repeaters"` + // ActiveRepeaters is how many of Repeaters are active + // (classifyNodeHealth); the rest are degraded or silent. + ActiveRepeaters int `json:"activeRepeaters"` + Rooms int `json:"rooms"` + Companions int `json:"companions"` + Sensors int `json:"sensors"` + OtherRoles int `json:"otherRoles"` // Active, Degraded and Silent are classifyNodeHealth's buckets. Active int `json:"active"` Degraded int `json:"degraded"` @@ -188,10 +191,11 @@ type DagiAreaRow struct { // relay-based definition Topology uses). nil: no such transmission. AvgHopsHeard *float64 `json:"avgHopsHeard"` AvgHopsRelayed *float64 `json:"avgHopsRelayed"` - // RepeatersPer100Km2 is every repeater with a position in the area - // (active, degraded or silent) divided by AreaKm2 in units of 100 km², - // unrounded; ObserversPer100Km2 the same for Observers (#1002 M2). Both - // nil for Christiansø (outside the kommune division, 0.35 km²). + // RepeatersPer100Km2 is the active repeaters with a position in the + // area (ActiveRepeaters: not degraded or silent) divided by AreaKm2 in + // units of 100 km², unrounded; ObserversPer100Km2 the same for + // Observers (#1002 M2; owner, 2026-12-02). Both nil for Christiansø + // (outside the kommune division, 0.35 km²) and for every postnummer. RepeatersPer100Km2 *float64 `json:"repeatersPer100Km2"` ObserversPer100Km2 *float64 `json:"observersPer100Km2"` // Gaps flags missing coverage (#1002 M2, dagiAreaGaps): "no-nodes", @@ -631,7 +635,7 @@ func (st *dagiAreaStats) row(si int32) DagiAreaRow { sl := &st.table.slots[si] c := &st.rows[si] r := DagiAreaRow{Code: sl.key, Name: sl.name, OutsideKommune: sl.outsideKommune, Group: sl.grouped, - AreaKm2: sl.areaM2 / 1e6, Nodes: c.nodes, Repeaters: c.repeaters, Rooms: c.rooms, Companions: c.companions, + AreaKm2: sl.areaM2 / 1e6, Nodes: c.nodes, Repeaters: c.repeaters, ActiveRepeaters: c.activeRepeaters, Rooms: c.rooms, Companions: c.companions, Sensors: c.sensors, OtherRoles: c.otherRoles, Active: c.active, Degraded: c.degraded, Silent: c.silent, New7d: c.new7d, Observers: c.observers, Heard: c.heard, Relayed: c.relayed} if c.heardHopN > 0 { @@ -642,9 +646,11 @@ func (st *dagiAreaStats) row(si int32) DagiAreaRow { v := float64(c.relayedHopSum) / float64(c.relayedHopN) r.AvgHopsRelayed = &v } - if !sl.outsideKommune && sl.areaM2 > 0 { + // No density for postnumre (owner, 2026-12-02): most are < 20 km², so + // one repeater gives an extreme value. Their counts stay. + if sl.layer != DagiPostnummer && !sl.outsideKommune && sl.areaM2 > 0 { per100 := sl.areaM2 / 1e8 // m² → units of 100 km² - rep, obs := float64(c.repeaters)/per100, float64(c.observers)/per100 + rep, obs := float64(c.activeRepeaters)/per100, float64(c.observers)/per100 r.RepeatersPer100Km2, r.ObserversPer100Km2 = &rep, &obs } r.Gaps = dagiAreaGaps(c) diff --git a/cmd/server/dagi_area_stats_test.go b/cmd/server/dagi_area_stats_test.go index 04cbd2577..d64ccceb2 100644 --- a/cmd/server/dagi_area_stats_test.go +++ b/cmd/server/dagi_area_stats_test.go @@ -239,8 +239,17 @@ func TestDagiAreaNodeCounts(t *testing.T) { if ov.Region == nil || ov.Region.Code != "1082" { t.Errorf("Aarhus region %+v, want 1082", ov.Region) } - if r.AreaKm2 < 400 || r.AreaKm2 > 550 || r.RepeatersPer100Km2 == nil || math.Abs(*r.RepeatersPer100Km2-5/(r.AreaKm2/100)) > 1e-9 { - t.Errorf("Aarhus area %v km², density %v", r.AreaKm2, r.RepeatersPer100Km2) + // Density counts the active repeaters only (owner, 2026-12-02): Aarhus + // stale is degraded, so 4 of the 5; the row keeps the 5. + if r.ActiveRepeaters != 4 { + t.Errorf("Aarhus active repeaters %d, want 4 (stale is degraded)", r.ActiveRepeaters) + } + if r.AreaKm2 < 400 || r.AreaKm2 > 550 || r.RepeatersPer100Km2 == nil || math.Abs(*r.RepeatersPer100Km2-4/(r.AreaKm2/100)) > 1e-9 { + t.Errorf("Aarhus area %v km², density %v, want 4 active / area", r.AreaKm2, r.RepeatersPer100Km2) + } + // A postnummer has counts and no density, the overview too. + if p := w.overview("postnr=8200").Row; p.Repeaters != 1 || p.ActiveRepeaters != 1 || p.RepeatersPer100Km2 != nil || p.ObserversPer100Km2 != nil { + t.Errorf("8200 %+v, want 1 repeater, 1 active, no density", p) } // Midtjylland: Aarhus 7 and Hvide Sande (Ringkøbing-Skjern); the node at // sea is in no kommune and so in no region. diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index 678fac0e1..0ce4796be 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -80,7 +80,7 @@ func routeDescriptions() map[string]routeMeta { {Status: "404", Description: "An unknown code, or DAGI is off (dagi.enabled false)."}, }}, - "GET /api/analytics/dagi-area": {Summary: "Overview of one DAGI area (kommune, landsdel, region, postnummer)", Description: "#1002 M1: the Areas (DAGI) tab's numbers for one area, from one background pass over every area per analytics cycle (no per-request compute). {layer, param, generatedAt, windowFrom, windowTo, partialWindow, coveredHours, credit, region? (a kommune's region), row: {code, name, outsideKommune?, group?, areaKm2, nodes, repeaters, rooms, companions, sensors, otherRoles, active, degraded, silent, new7d, observers, heard, relayed, avgHopsHeard, avgHopsRelayed, repeatersPer100Km2, observersPer100Km2, gaps?}, heardPerHour[24], relayedPerHour[24], busiestRepeaters: [{publicKey, name, relayed}] (at most 5), totals: {nodes, unpositioned, outsideDenmark}}. Nodes count by their own position through the DAGI filter's membership, so row.nodes equals /api/nodes' total for the same param. Traffic covers the last 24 h: heard counts a transmission once per area with an observation by an observer whose node is in the area; relayed once per area with a resolved relay hop on a node in the area. Hidden identities (nodeBlacklist, hiddenNamePrefixes, and for observers and relays also the observer blacklist) are left out of every count and list; a blacklist or hidden-prefix change is never served from an older pass. region, area and window do not apply. areaKm2 is the land area (postnumre are clipped to the coast, #1032). repeatersPer100Km2 and observersPer100Km2 are unrounded and null for Christiansø; gaps as in GET /api/analytics/dagi-areas.", Tag: "analytics", + "GET /api/analytics/dagi-area": {Summary: "Overview of one DAGI area (kommune, landsdel, region, postnummer)", Description: "#1002 M1: the Areas (DAGI) tab's numbers for one area, from one background pass over every area per analytics cycle (no per-request compute). {layer, param, generatedAt, windowFrom, windowTo, partialWindow, coveredHours, credit, region? (a kommune's region), row: {code, name, outsideKommune?, group?, areaKm2, nodes, repeaters, activeRepeaters, rooms, companions, sensors, otherRoles, active, degraded, silent, new7d, observers, heard, relayed, avgHopsHeard, avgHopsRelayed, repeatersPer100Km2, observersPer100Km2, gaps?}, heardPerHour[24], relayedPerHour[24], busiestRepeaters: [{publicKey, name, relayed}] (at most 5), totals: {nodes, unpositioned, outsideDenmark}}. Nodes count by their own position through the DAGI filter's membership, so row.nodes equals /api/nodes' total for the same param. Traffic covers the last 24 h: heard counts a transmission once per area with an observation by an observer whose node is in the area; relayed once per area with a resolved relay hop on a node in the area. Hidden identities (nodeBlacklist, hiddenNamePrefixes, and for observers and relays also the observer blacklist) are left out of every count and list; a blacklist or hidden-prefix change is never served from an older pass. region, area and window do not apply. areaKm2 is the land area (postnumre are clipped to the coast, #1032). activeRepeaters is how many of repeaters are active (the rest are degraded or silent). repeatersPer100Km2 (active repeaters only) and observersPer100Km2 are unrounded and null for Christiansø and for every postnummer; gaps as in GET /api/analytics/dagi-areas.", Tag: "analytics", QueryParams: []paramMeta{ {Name: "kommune", Description: "A kommunekode, e.g. 0751. Exactly one of kommune, landsdel, dkregion and postnr.", Type: "string"}, {Name: "landsdel", Description: "A landsdel id_lokalid.", Type: "string"}, @@ -91,7 +91,7 @@ func routeDescriptions() map[string]routeMeta { {Status: "400", Description: "None or more than one DAGI param, or an unknown code (unknown kommune, ...)."}, {Status: "404", Description: "DAGI is off (dagi.enabled false, or the asset does not load)."}, }}, - "GET /api/analytics/dagi-areas": {Summary: "Comparison of every DAGI area of one layer", Description: "#1002 M2: the Areas (DAGI) tab's comparison table, from the same background pass as GET /api/analytics/dagi-area (no per-request compute). {layer, param, generatedAt, windowFrom, windowTo, partialWindow, coveredHours, credit, totals: {nodes, unpositioned, outsideDenmark}, rows: [row]}, where row is dagi-area's row: {code, name, outsideKommune?, group?, areaKm2, nodes, repeaters, rooms, companions, sensors, otherRoles, active, degraded, silent, new7d, observers, heard, relayed, avgHopsHeard, avgHopsRelayed, repeatersPer100Km2, observersPer100Km2, gaps?}. Every area of the layer is a row, the empty ones too (kommune 99, landsdel 11, region 5, postnummer 605 with the three street-postcode groups as one row each, keyed by the group key), in /api/config/dagi's order (by code). repeatersPer100Km2 is every repeater with a position in the area (active, degraded or silent) divided by areaKm2 (DAGI land area) in units of 100 km², unrounded; observersPer100Km2 the same for observers; both null for Christiansø. gaps lists no-nodes, no-repeater (nodes, none a repeater), no-observer (repeaters, but no observer in the area heard anything in 24 h) and nothing-heard (nodes, but nothing heard or relayed in the area in 24 h); absent when none. Hidden identities are left out as in dagi-area. A DAGI selection, region, area and window do not apply.", Tag: "analytics", + "GET /api/analytics/dagi-areas": {Summary: "Comparison of every DAGI area of one layer", Description: "#1002 M2: the Areas (DAGI) tab's comparison table, from the same background pass as GET /api/analytics/dagi-area (no per-request compute). {layer, param, generatedAt, windowFrom, windowTo, partialWindow, coveredHours, credit, totals: {nodes, unpositioned, outsideDenmark}, rows: [row]}, where row is dagi-area's row: {code, name, outsideKommune?, group?, areaKm2, nodes, repeaters, activeRepeaters, rooms, companions, sensors, otherRoles, active, degraded, silent, new7d, observers, heard, relayed, avgHopsHeard, avgHopsRelayed, repeatersPer100Km2, observersPer100Km2, gaps?}. Every area of the layer is a row, the empty ones too (kommune 99, landsdel 11, region 5, postnummer 605 with the three street-postcode groups as one row each, keyed by the group key), in /api/config/dagi's order (by code). activeRepeaters is how many of repeaters are active (the rest are degraded or silent). repeatersPer100Km2 is the active repeaters with a position in the area (not degraded or silent) divided by areaKm2 (DAGI land area) in units of 100 km², unrounded; observersPer100Km2 the same for observers; both null for Christiansø and for every postnummer row, the street-postcode groups included (most postnumre are under 20 km², so one repeater would give an extreme value); the counts stay. gaps lists no-nodes, no-repeater (nodes, none a repeater), no-observer (repeaters, but no observer in the area heard anything in 24 h) and nothing-heard (nodes, but nothing heard or relayed in the area in 24 h); absent when none. Hidden identities are left out as in dagi-area. A DAGI selection, region, area and window do not apply.", Tag: "analytics", QueryParams: []paramMeta{ {Name: "layer", Description: "The layer to compare.", Type: "string", Required: true, Enum: []string{"kommune", "landsdel", "region", "postnummer"}}, }, diff --git a/docs/user-guide/area-filter.md b/docs/user-guide/area-filter.md index 5a7096b35..67024abe3 100644 --- a/docs/user-guide/area-filter.md +++ b/docs/user-guide/area-filter.md @@ -135,14 +135,14 @@ What the numbers mean: - **Packets heard**: packets heard in the last 24 hours by at least one observer in the area. A packet heard by three observers in the area counts once. - **Packets relayed**: packets in the last 24 hours with at least one relay hop, resolved to a full key, on a node in the area. - **Avg hops, heard** and **Avg hops, relayed**: the mean path length of those two sets of packets. The relayed number uses the relay-based rule the Topology tab uses, so the two can differ. -- **Repeaters / 100 km²**: every repeater with a position in the area, active or silent, divided by the area's DAGI land area in units of 100 km², shown with two decimals (Sydjylland: 83 repeaters on 8,649 km² is 0.96). The card and the table's cells say how it is computed when you hover them. Postnumre are clipped to the coast like the kommuner, so their area is land only. Christiansø (0.35 km²) has no density. +- **Repeaters / 100 km²**: the active repeaters with a position in the area (not degraded or silent) divided by the area's DAGI land area in units of 100 km², shown with two decimals (83 active repeaters on 8,649 km² is 0.96). The card and the table's cells say how it is computed when you hover them. The **Repeaters** number stays the total and names the inactive ones: "12 (3 inactive)". Kommuner, landsdele and regioner have a density; postnumre have none (most are under 20 km², so a single repeater would read as an extreme value), so a postnummer shows only its counts. Christiansø (0.35 km²) has no density. - **Busiest repeaters**: the five repeaters in the area that relayed the most packets in the last 24 hours. The numbers cover the whole network and the last 24 hours: the Region and time-window filters do not apply to this tab, and it says so. If the server holds less than 24 hours of traffic, the tab says how many hours the packet numbers cover. Nodes without a position, and nodes outside Denmark, are in no area; the tab counts them below the card. -**Compare** (below the overview) lists every area of one layer: Region, Landsdel, Kommune or Postnummer (605 rows; the Copenhagen street postcodes are one row per group). With no area picked it shows the kommuner; with one picked, the layer one finer (a kommune's postnumre). On a desktop, click a column header to sort: names A–Å, numbers highest first, the density on its unrounded value, and an area with no value (Christiansø's density) last. On a phone the list shows the name and the sorted number with its label, with a **Sort** menu. Tap a row to pick that area: the overview and the link follow, the page scrolls up to the overview, and the list keeps its order. Rows read as the area filter names them, so a street-postcode group is "1050–1473 København K". When the overview comes from a newer analytics pass than the list, the list's numbers are updated in place, so the two agree. The **Gaps** column flags *No nodes*, *No repeater* (nodes, but none a repeater), *No observer* (repeaters, but no observer in the area heard anything in 24 hours) and *Nothing heard* (nodes, but no packet heard or relayed in the area in 24 hours). The layer and the sort are in the link: `#/analytics?tab=dagi-areas&layer=postnummer&sort=heard`. +**Compare** (below the overview) lists every area of one layer: Region, Landsdel, Kommune or Postnummer (605 rows; the Copenhagen street postcodes are one row per group). With no area picked it shows the kommuner; with one picked, the layer one finer (a kommune's postnumre). On a desktop, click a column header to sort: names A–Å, numbers highest first, the density on its unrounded value, and an area with no value (Christiansø's density) last. The Postnummer layer has no density column and no density sort; a link that asks for one sorts by Repeaters instead. On a phone the list shows the name and the sorted number with its label, with a **Sort** menu. Tap a row to pick that area: the overview and the link follow, the page scrolls up to the overview, and the list keeps its order. Rows read as the area filter names them, so a street-postcode group is "1050–1473 København K". When the overview comes from a newer analytics pass than the list, the list's numbers are updated in place, so the two agree. The **Gaps** column flags *No nodes*, *No repeater* (nodes, but none a repeater), *No observer* (repeaters, but no observer in the area heard anything in 24 hours) and *Nothing heard* (nodes, but no packet heard or relayed in the area in 24 hours). The layer and the sort are in the link: `#/analytics?tab=dagi-areas&layer=postnummer&sort=heard`. -**Show map** (next to the layers, off by default on every screen) colours every area of the compared layer by the sorted number; sorted by name, it colours by repeater density. The colours are five quantile classes on the unrounded values, from light to dark in the light theme (dark to bright in the dark theme), and the legend under the map gives each class's range in the table's format. An area with no value is grey (*No data*), and so is Christiansø, which is left out of the scale (one node on 0.35 km² would put every other kommune in the lowest class). The other small areas stay in the scale. One repeater in a tiny postnummer (Birkholm is 0.88 km², Dyssegård 1.18 km²) gives it a very high density; a linear scale would then push almost every other area into the lowest colour. A quantile class instead holds about a fifth of the areas, whatever their values, so such an area only lands in the top class, and the top class's range in the legend shows how far it reaches. Postnumre are clipped to the coast, like the kommuner, so a coastal density is per km² of land. Tap an area on the map to pick it: the overview and the link follow as for a row tap, but the page stays where it is, so the map stays under your finger for the next tap. A theme change (the dark-mode switch, a customizer colour or a colour-blind preset) recolours the map at once, without loading anything. The boundaries load only when you tap **Show map**, once per layer (about 180–460 KB, or about 80–177 KB when the server gzips its answers, see `compression.gzip`); a new sort only recolours them. The map's attribution carries the DAGI credit. Whether the map is shown is in the link: `…&layer=kommune&map=1`. The colours are in the customizer's Theme tab under *Areas (DAGI) map*. +**Show map** (next to the layers, off by default on every screen) colours every area of the compared layer by the sorted number; sorted by name, it colours by repeater density (by the repeater count for postnumre, which have no density). The colours are five quantile classes on the unrounded values, from light to dark in the light theme (dark to bright in the dark theme), and the legend under the map gives each class's range in the table's format. An area with no value is grey (*No data*), and so is Christiansø, which is left out of the scale (one node on 0.35 km² would put every other kommune in the lowest class). The other small areas stay in the scale. One extreme value would push almost every other area into the lowest colour on a linear scale; a quantile class instead holds about a fifth of the areas, whatever their values, so such an area only lands in the top class, and the top class's range in the legend shows how far it reaches. Tap an area on the map to pick it: the overview and the link follow as for a row tap, but the page stays where it is, so the map stays under your finger for the next tap. A theme change (the dark-mode switch, a customizer colour or a colour-blind preset) recolours the map at once, without loading anything. The boundaries load only when you tap **Show map**, once per layer (about 180–460 KB, or about 80–177 KB when the server gzips its answers, see `compression.gzip`); a new sort only recolours them. The map's attribution carries the DAGI credit. Whether the map is shown is in the link: `…&layer=kommune&map=1`. The colours are in the customizer's Theme tab under *Areas (DAGI) map*. Hidden nodes (`nodeBlacklist`, `hiddenNamePrefixes`) are in no number and no list, and observers and relays that are hidden (also by `observerBlacklist`) add nothing. Every area of every layer is computed in one background pass per analytics cycle (`analytics.recomputeIntervalSeconds.dagiAreas`, default 300 s). A change to the blacklist or the hidden prefixes takes effect on the next request. diff --git a/public/analytics-dagi-areas.js b/public/analytics-dagi-areas.js index 27fb30c29..24d0836a0 100644 --- a/public/analytics-dagi-areas.js +++ b/public/analytics-dagi-areas.js @@ -28,7 +28,10 @@ * Repeater density has one convention (owner, 2026-11-30): per 100 km² with * two decimals (fmtDensity), with a tooltip saying how it is computed * (densityTitle). Sorting uses the unrounded value. M3's choropleth legend - * is to use the same fmtDensity (exported). + * is to use the same fmtDensity (exported). Since 2026-12-02 (owner) the + * density counts active repeaters only; the repeater count stays the + * total and names the inactive ones ("12 (3 inactive)"); postnumre have no + * density at all (hasDensity): no column, no sort option, no map metric. * * M3: "Show map" (off by default on every screen size, owner decision 11) * colours every area of the comparison's layer by the sorted metric @@ -60,7 +63,10 @@ var SVG_NS = 'http://www.w3.org/2000/svg'; /** How repeater density is computed (dagiAreaStats.row, cmd/server/dagi_area_stats.go). */ - var DENSITY_HOW = 'Repeaters per 100 km²: every repeater with a position in the area, active or silent, divided by the area\'s DAGI land area in units of 100 km².'; + var DENSITY_HOW = 'Repeaters per 100 km²: the active repeaters with a position in the area (not degraded or silent), divided by the area\'s DAGI land area in units of 100 km².'; + /** The density note for the postnummer layer (owner, 2026-12-02). */ + var NO_DENSITY = 'Postnumre have no density: most are under 20 km², so a single repeater would read as an extreme value. Compare them by their counts.'; + var DENSITY_KEY = 'repeatersPer100Km2'; // The comparison's layers, coarse to fine, and the param a row picks with. var LAYERS = ['region', 'landsdel', 'kommune', 'postnummer']; @@ -96,6 +102,18 @@ function plural(n, one, many) { return fmtInt(n) + ' ' + (n === 1 ? one : many); } + /** Whether a layer has a density: not postnumre (owner, 2026-12-02; + * the server sends null for them). */ + function hasDensity(layer) { return layer !== 'postnummer'; } + + /** The repeaters that are not active (degraded or silent); 0 without an + * active count. */ + function inactiveRepeaters(r) { + var a = r && r.activeRepeaters; + if (a == null || !isFinite(Number(a))) return 0; + return Math.max(0, (Number(r.repeaters) || 0) - Number(a)); + } + /** Repeater (or observer) density: per 100 km², two decimals, '—' for * none. The one convention for the overview, the table and the legend. */ function fmtDensity(v) { return fmtDec(v, 2); } @@ -111,9 +129,10 @@ } if (r.repeatersPer100Km2 == null) return 'No density for this area: it has no DAGI land area. It sorts last. ' + DENSITY_HOW; var units = (Number(r.areaKm2) || 0) / 100; - return DENSITY_HOW + ' Here: ' + plural(Number(r.repeaters) || 0, 'repeater', 'repeaters') + ' ÷ ' + units.toFixed(2) + + var off = inactiveRepeaters(r); + return DENSITY_HOW + ' Here: ' + plural(Number(r.activeRepeaters) || 0, 'active repeater', 'active repeaters') + ' ÷ ' + units.toFixed(2) + ' (' + fmtInt(Math.round(Number(r.areaKm2) || 0)) + ' km²) = ' + fmtDensity(r.repeatersPer100Km2) + - '. Sorted on the unrounded value.'; + (off > 0 ? ' (' + fmtInt(off) + ' inactive not counted)' : '') + '. Sorted on the unrounded value.'; } /** The card's sub-heading: layer and code, a kommune's region, the area. */ @@ -139,7 +158,7 @@ var quiet = (Number(r.degraded) || 0) + (Number(r.silent) || 0); var cards = [ ['nodes', fmtInt(r.nodes), 'Nodes', ''], - ['repeaters', fmtInt(r.repeaters), 'Repeaters', ''], + ['repeaters', fmtInt(r.repeaters), 'Repeaters', inactiveRepeaters(r) > 0 ? fmtInt(inactiveRepeaters(r)) + ' inactive' : ''], ['rooms', fmtInt(r.rooms), 'Rooms', ''], ['companions', fmtInt(r.companions), 'Companions', ''], ['sensors', fmtInt(r.sensors), 'Sensors', ''], @@ -149,8 +168,10 @@ ['active', fmtInt(r.active), 'Active', ''], ['quiet', fmtInt(quiet), 'Quiet', fmtInt(r.degraded) + ' degraded · ' + fmtInt(r.silent) + ' silent'], ['new', fmtInt(r.new7d), 'New (7 days)', ''], - ['observers', fmtInt(r.observers), 'Observers', 'heard something, 24 h'], - ['density', fmtDensity(r.repeatersPer100Km2), 'Repeaters / 100 km²', '', densityTitle(r)], + ['observers', fmtInt(r.observers), 'Observers', 'heard something, 24 h'] + ); + if (hasDensity(resp.layer)) cards.push(['density', fmtDensity(r.repeatersPer100Km2), 'Repeaters / 100 km²', '', densityTitle(r)]); + cards.push( ['hops-heard', fmtDec(r.avgHopsHeard, 1), 'Avg hops, heard', 'packets heard here'], ['hops-relayed', fmtDec(r.avgHopsRelayed, 1), 'Avg hops, relayed', 'packets relayed here'], ['heard', fmtInt(r.heard), 'Packets heard (24 h)', heardH == null ? '' : fmtDec(heardH, 1) + ' per hour'], @@ -298,7 +319,11 @@ var METRIC_KEYS = METRICS.map(function (m) { return m.key; }); function cellText(r, key) { - if (key === 'repeatersPer100Km2') return fmtDensity(r[key]); + if (key === DENSITY_KEY) return fmtDensity(r[key]); + if (key === 'repeaters') { + var off = inactiveRepeaters(r); + return fmtInt(r[key]) + (off > 0 ? ' (' + fmtInt(off) + ' inactive)' : ''); + } if (key === 'avgHopsHeard') return fmtDec(r[key], 1); return fmtInt(r[key]); } @@ -341,15 +366,22 @@ return new URLSearchParams(q >= 0 ? h.slice(q + 1) : ''); } + /** A sort `layer` can show: the density falls back to the repeater + * count on a layer without one (postnumre). */ + function layerSort(layer, sort) { + return sort === DENSITY_KEY && !hasDensity(layer) ? 'repeaters' : sort; + } + /** The comparison's layer and sort from the hash, checked; the layer * defaults to one finer than the selected entry's (kommune without one). */ function parseView(hash, entry) { var p = hashQuery(hash); var layer = p.get('layer'), sort = p.get('sort'); var dflt = entry && FINER[entry.layer] ? FINER[entry.layer] : DEFAULT_LAYER; + layer = LAYERS.indexOf(layer) >= 0 ? layer : dflt; return { - layer: LAYERS.indexOf(layer) >= 0 ? layer : dflt, - sort: METRIC_KEYS.indexOf(sort) >= 0 ? sort : DEFAULT_SORT, + layer: layer, + sort: layerSort(layer, METRIC_KEYS.indexOf(sort) >= 0 ? sort : DEFAULT_SORT), map: p.get('map') === '1', }; } @@ -365,9 +397,10 @@ /* ---------- the map (M3) ---------- */ /** The metric the map colours by: the sort, or repeater density for the - * name sort (a name has no colour). */ - function mapMetric(sort) { - return sort && sort !== 'name' && METRIC_KEYS.indexOf(sort) >= 0 ? sort : 'repeatersPer100Km2'; + * name sort (a name has no colour); on a layer without a density + * (postnumre) the repeater count instead. */ + function mapMetric(sort, layer) { + return layerSort(layer, sort && sort !== 'name' && METRIC_KEYS.indexOf(sort) >= 0 ? sort : DENSITY_KEY); } /** A value of `key` in the comparison's own format. */ @@ -491,9 +524,11 @@ var selWrap = make(doc, 'label', 'analytics-dagi-sort-select'); selWrap.appendChild(make(doc, 'span', '', 'Sort')); var select = make(doc, 'select'); + var densityOpt = null; METRICS.forEach(function (m) { var o = make(doc, 'option', '', m.option); o.value = m.key; + if (m.key === DENSITY_KEY) densityOpt = o; select.appendChild(o); }); select.addEventListener('change', function () { cmp.sortBy(select.value, true); }); @@ -531,7 +566,7 @@ var th = make(doc, 'th'); th.setAttribute('data-k', m.key); th.setAttribute('scope', 'col'); - if (m.key === 'repeatersPer100Km2') th.setAttribute('title', DENSITY_HOW); + if (m.key === DENSITY_KEY) th.setAttribute('title', DENSITY_HOW); var b = make(doc, 'button', 'analytics-dagi-sort', m.label); b.type = 'button'; b.addEventListener('click', function () { cmp.sortBy(m.key, true); }); @@ -556,7 +591,9 @@ wrap.appendChild(table); sec.appendChild(wrap); // The tooltip's text, also visible: a phone has no hover. - sec.appendChild(make(doc, 'p', 'analytics-dagi-density-note text-muted', DENSITY_HOW + ' Christiansø (0.35 km², outside the kommune division) has none.')); + var DENSITY_NOTE = DENSITY_HOW + ' Christiansø (0.35 km², outside the kommune division) has none.'; + var densityNote = make(doc, 'p', 'analytics-dagi-density-note text-muted', DENSITY_NOTE); + sec.appendChild(densityNote); cmp.el = sec; function writeView() { @@ -593,7 +630,7 @@ for (var i = 1; i < METRICS.length; i++) { var k = METRICS[i].key; tds[i].textContent = cellText(r, k); - if (k === 'repeatersPer100Km2') tds[i].setAttribute('title', densityTitle(r)); + if (k === DENSITY_KEY) tds[i].setAttribute('title', densityTitle(r)); } var gtd = tds[METRICS.length]; gtd.textContent = ''; @@ -611,13 +648,20 @@ else th.removeAttribute('aria-sort'); }); table.setAttribute('data-sort', cmp.sort); + // A layer without a density (postnumre): style.css hides its column + // by data-layer (one attribute, no per-row work); the phone select + // does not offer it, and the note says why. + var dens = hasDensity(cmp.layer); + if (cmp.layer) table.setAttribute('data-layer', cmp.layer); + densityOpt.hidden = densityOpt.disabled = !dens; + densityNote.textContent = dens ? DENSITY_NOTE : NO_DENSITY; select.value = cmp.sort; layerBtns.forEach(function (b) { b.setAttribute('aria-pressed', b.getAttribute('data-layer') === cmp.layer ? 'true' : 'false'); }); } /** Put the existing rows in `sort` order: appendChild moves each node. */ cmp.sortBy = function (key, fromUser) { - if (METRIC_KEYS.indexOf(key) < 0) return; + if (METRIC_KEYS.indexOf(key) < 0 || layerSort(cmp.layer, key) !== key) return; cmp.sort = key; markHeaders(); if (fromUser) writeView(); @@ -672,7 +716,7 @@ if (watch) cmp.unwatchTheme = watch(cmp.mapObj.choro.themeSignature, function () { cmp.recolour(); }); } var my = ++cmp.mapToken; - var key = mapMetric(cmp.sort); + var key = mapMetric(cmp.sort, cmp.layer); mapStatus.hidden = false; mapStatus.textContent = 'Loading map…'; return cmp.mapObj.choro.show(cmp.layer, cmp.rows, function (r) { return r[key]; }, metricFormat(key)).then(function () { @@ -689,7 +733,7 @@ /** A metric or theme change: restyle the drawn shapes, no request. */ cmp.recolour = function () { if (!cmp.mapOn || !cmp.mapObj || cmp.mapObj.choro.layer() !== cmp.layer || !cmp.trs.length) return; - var key = mapMetric(cmp.sort); + var key = mapMetric(cmp.sort, cmp.layer); cmp.mapObj.choro.restyle(cmp.rows, function (r) { return r[key]; }, metricFormat(key)); buildLegend(key); }; @@ -787,6 +831,7 @@ /** Show `layer` sorted by `sort`: the rows are fetched and built when * the layer changes, else only re-sorted. */ cmp.show = function (layer, sort, fromUser) { + sort = layerSort(layer, sort); if (layer === cmp.layer) { if (sort !== cmp.sort || fromUser) cmp.sortBy(sort, fromUser); cmp.markSelected(ctx.dagi.selectedEntry && ctx.dagi.selectedEntry()); @@ -1005,6 +1050,7 @@ densityTitle: densityTitle, _test: { fmtInt: fmtInt, fmtDec: fmtDec, perHour: perHour, areaMeta: areaMeta, statCards: statCards, notices: notices, sparkPoints: sparkPoints, FILTER_NOTE: FILTER_NOTE, PROMPT: PROMPT, fmtDensity: fmtDensity, densityTitle: densityTitle, DENSITY_HOW: DENSITY_HOW, sortOrder: sortOrder, nameRanks: nameRanks, parseView: parseView, viewParams: viewParams, - LAYERS: LAYERS, METRICS: METRICS, DEFAULT_SORT: DEFAULT_SORT, revealNode: revealNode, mapMetric: mapMetric, metricFormat: metricFormat } + LAYERS: LAYERS, METRICS: METRICS, DEFAULT_SORT: DEFAULT_SORT, revealNode: revealNode, mapMetric: mapMetric, metricFormat: metricFormat, + hasDensity: hasDensity, inactiveRepeaters: inactiveRepeaters, NO_DENSITY: NO_DENSITY } }; })(); diff --git a/public/style.css b/public/style.css index 24c5cafce..27d469ea7 100644 --- a/public/style.css +++ b/public/style.css @@ -7898,6 +7898,8 @@ body.embed .warmup-pills { display: none !important; } .analytics-dagi-pick { min-height: 32px; padding: 0; border: 0; background: none; color: var(--link-color); font: inherit; text-align: left; cursor: pointer; overflow-wrap: anywhere; } .analytics-dagi-gap { display: inline-block; margin: 1px 4px 1px 0; padding: 0 6px; border: 1px solid var(--warning); border-radius: 10px; font-size: 11px; color: var(--text); white-space: nowrap; } .analytics-dagi-density-note { margin: 6px 0 0; font-size: 12px; } +/* #1002 (owner, 2026-12-02): postnumre have no density, so no density column. */ +.analytics-dagi-table[data-layer="postnummer"] [data-k="repeatersPer100Km2"] { display: none; } /* #1002 M3 — Areas (DAGI) choropleth: the "Show map" button, the map and its legend (public/dagi-choropleth.js fills the shapes from the --dagi-choro-* tokens). */ diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 643104ee2..bc42eef1b 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -350,6 +350,7 @@ {"file":"test-issue-1002-m1-dagi-areas-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":40,"measurementNote":"New suite; #1002 M1 Analytics Areas (DAGI) tab against the real /api/config/dagi and /api/analytics/dagi-area: a 375x560 cold start with real taps in light and dark (tab, DAGI sheet, search, pick Aarhus, one kommune=0751 request, the Nodes card equal to /api/nodes), a deep link with an answered overview (every card, sparklines, busiest tap, notices, credit, two cards per row), an unknown code never sent, no M3c notice on this tab, the selection kept across tabs and asked once on return, DAGI off, and 1440x900 light and dark. About 40s locally; no CI duration measured yet. Assigned to shard 1, the lightest by meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-1002-m2-dagi-comparison-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":30,"measurementNote":"New suite; #1002 M2 Analytics Areas (DAGI) comparison against the real /api/analytics/dagi-areas (real rows, synthetic numbers routed in the server shape where it sorts or measures): a 375x560 cold start with real taps shows the 99 kommune rows as a list, a sort select change moves the same row nodes and writes sort=; a row tap picks the area (kommune= and layer= in the URL, one overview request, the card, the row marked, no new table request); at 1440x900 a header click sorts (aria-sort), the density tooltip, Christiansø last with a dash, and the Postnummer button loads the real 605 rows with the street-postcode groups; a layer=region&sort=heard deep link restores both and another tab drops them; perf at a plain 4x CPU throttling, best of 3: first render of 605 rows <= 250 ms, one re-sort <= 100 ms. About 30s locally; no CI duration measured yet. Assigned to shard 3, the lightest by meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-1002-m3-dagi-choropleth-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":15,"measurementNote":"New suite; #1002 M3 Analytics Areas (DAGI) choropleth against the real /api/config/dagi/polygons (never stubbed) and /api/analytics/dagi-areas (real rows, synthetic numbers routed in the server's shape): a 375x560 cold start with real taps in light and dark (no polygon request before Show map, exactly one after, 99 shapes, legend, DAGI credit in the attribution, map=1, Christiansø in the no-data colour, a sort change restyles with no request), a 1440x900 map=1 deep link with a header sort and a click on Aarhus, the decode+draw+first-frame budget of 250 ms at 4x CPU throttle (kommune, postnummer, best of 3), and the polygon bytes on the wire logged per layer. About 8s locally against the instrumented frontend; no CI duration measured yet. Assigned to shard 2, the lightest by meanSeconds.","secondsByExecution":[]}, + {"file":"test-issue-1002-density-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":15,"measurementNote":"New suite; #1002 density follow-up (owner 2026-12-02) against the real /api/analytics/dagi-areas: every postnummer row (groups too) has null densities and every row activeRepeaters; with synthetic numbers routed in the server shape, 1440x900 shows Repeaters as N (M inactive), hides the density header and cells for postnumre while Heard still sorts; 375x560 with real taps offers no density sort for postnumre (falls back to Repeaters, in the URL), the inactive cell fits the screen, kommuner offer it again; a postnummer map=1 link colours by the repeater count. About 15s locally; no CI duration measured yet. Assigned to shard 2, the lightest by meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-740-m3a-dagi-filter-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":10,"measurementNote":"New suite; #740 M3a the Danish areas (DAGI) filter on the Nodes page against the real GET /api/config/dagi: at 375x560 touch in light and dark from a cold #/nodes with real taps only, the trigger opens a bottom sheet inside the viewport (no sideways scroll, 44 px rows, no autofocus in the search), aar finds Aarhus and the postcodes, a tap puts kommune=0751 in the URL and the request (that one /api/nodes answer is fulfilled from a real fixture node, as the fixture has no Danish node), labels the trigger and shows the hidden-count notice, and the clear button takes it all away again; unmocked: kommune=0860 shows the server count and an empty list, an unknown code is never sent and leaves the URL, the most specific of several params wins; at 1440x900 keyboard pick, Escape and a search or tab change keeping the param; first open and a search timed at 4x CPU throttling; the saved pick across a reload and a street postcode link. About 9s locally; no CI duration measured yet. Assigned to shard 3, the lightest by the sum of meanSeconds."}, {"file":"test-issue-996-role-pill-counts-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":15,"measurementNote":"New suite; #996 the Nodes role pills follow the Area and DAGI filters against the real Go server: at 375x560 touch from a cold #/nodes with real taps the unfiltered pills equal the server counts, Kommune Aarhus picked from the sheet search (its one kommune=0751 answer fulfilled from real fixture nodes of mixed roles with the whole-table counts left in) gives pills equal to the listed rows' roles, the clear button brings the server counts back, and Hjørring (kommune 0860, unmocked, nobody in it) lists nothing with every pill 0; at 1440x900 a warm tab (#/nodes, #/map, then #/nodes?kommune=0860) shows every pill 0 too. About 12s locally; no CI duration measured yet. Assigned to shard 3, the lightest by the sum of meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-740-m3b-packets-live-dagi-e2e.js","shard":1,"env":{"CHROMIUM_REQUIRE":"1"},"output":"e2e","meanSeconds":8,"measurementNote":"New suite; #740 M3b live WebSocket packets on the Packets page follow the DAGI filter by the server's rule (the ADVERT sender is in the member set; a known area nobody is in matches nothing; an unknown or unchecked code is never sent), with one member-set request per selection change, picked with the real dagi-filter.js control. Fully stubbed (page.route and routeWebSocket), no server needed. About 8 s locally; no CI duration measured yet. Assigned to shard 1, the lightest by the sum of meanSeconds."}, diff --git a/test-analytics-dagi-areas-compare.js b/test-analytics-dagi-areas-compare.js index ee7a33f90..9dd59cc2d 100644 --- a/test-analytics-dagi-areas-compare.js +++ b/test-analytics-dagi-areas-compare.js @@ -21,7 +21,7 @@ function test(name, fn) { queue.push([name, fn]); } const realDagi = loadPublic('dagi-filter.js', { document: makeDoc(), Intl, fetch: () => new Promise(() => {}), localStorage: { getItem: () => null, setItem() {}, removeItem() {} } }).DagiFilter; function row(code, name, over) { - return Object.assign({ code, name, areaKm2: 100, nodes: 0, repeaters: 0, rooms: 0, companions: 0, sensors: 0, otherRoles: 0, active: 0, degraded: 0, + return Object.assign({ code, name, areaKm2: 100, nodes: 0, repeaters: 0, activeRepeaters: 0, rooms: 0, companions: 0, sensors: 0, otherRoles: 0, active: 0, degraded: 0, silent: 0, new7d: 0, observers: 0, heard: 0, relayed: 0, avgHopsHeard: null, avgHopsRelayed: null, repeatersPer100Km2: 0, observersPer100Km2: 0, gaps: ['no-nodes'] }, over || {}); } @@ -30,11 +30,11 @@ function kommuner() { layer: 'kommune', param: 'kommune', generatedAt: '2026-12-01T10:00:00Z', windowFrom: '2026-11-30T10:00:00Z', windowTo: '2026-12-01T10:00:00Z', partialWindow: false, coveredHours: 24, credit: 'DAGI credit', totals: { nodes: 120, unpositioned: 3, outsideDenmark: 2 }, rows: [ - row('0101', 'København', { nodes: 30, repeaters: 22, areaKm2: 90.1, repeatersPer100Km2: 22 / 0.901, observers: 4, heard: 900, active: 20, gaps: undefined }), - row('0147', 'Frederiksberg', { nodes: 5, repeaters: 4, areaKm2: 8.7, repeatersPer100Km2: 4 / 0.087, heard: 300, active: 4, gaps: ['no-observer'] }), - row('0411', 'Christiansø', { outsideKommune: true, nodes: 1, repeaters: 1, areaKm2: 0.35, repeatersPer100Km2: null, observersPer100Km2: null, gaps: ['no-observer', 'nothing-heard'] }), - row('0751', 'Aarhus', { nodes: 80, repeaters: 71, areaKm2: 468.9, repeatersPer100Km2: 71 / 4.689, observers: 12, heard: 14233, active: 64, avgHopsHeard: 4.24, gaps: undefined }), - row('0580', 'Aabenraa', { nodes: 4, repeaters: 4, areaKm2: 940, repeatersPer100Km2: 4 / 9.4, heard: 0, gaps: ['no-observer', 'nothing-heard'] }), + row('0101', 'København', { nodes: 30, repeaters: 22, activeRepeaters: 19, areaKm2: 90.1, repeatersPer100Km2: 19 / 0.901, observers: 4, heard: 900, active: 20, gaps: undefined }), + row('0147', 'Frederiksberg', { nodes: 5, repeaters: 4, activeRepeaters: 4, areaKm2: 8.7, repeatersPer100Km2: 4 / 0.087, heard: 300, active: 4, gaps: ['no-observer'] }), + row('0411', 'Christiansø', { outsideKommune: true, nodes: 1, repeaters: 1, activeRepeaters: 1, areaKm2: 0.35, repeatersPer100Km2: null, observersPer100Km2: null, gaps: ['no-observer', 'nothing-heard'] }), + row('0751', 'Aarhus', { nodes: 80, repeaters: 71, activeRepeaters: 60, areaKm2: 468.9, repeatersPer100Km2: 60 / 4.689, observers: 12, heard: 14233, active: 64, avgHopsHeard: 4.24, gaps: undefined }), + row('0580', 'Aabenraa', { nodes: 4, repeaters: 4, activeRepeaters: 4, areaKm2: 940, repeatersPer100Km2: 4 / 9.4, heard: 0, gaps: ['no-observer', 'nothing-heard'] }), row('0727', 'Odder', { areaKm2: 224 }), row('0400', 'Bornholm', { areaKm2: 588 }), ], @@ -125,13 +125,14 @@ test('density: two decimals everywhere, a dash for none', () => { test('density tooltip: how it is computed, with the area\'s own numbers', () => { const t = world().mod._test; - const s = t.densityTitle({ repeaters: 83, areaKm2: 8649.2, repeatersPer100Km2: 83 / 86.492 }); + const s = t.densityTitle({ repeaters: 90, activeRepeaters: 83, areaKm2: 8649.2, repeatersPer100Km2: 83 / 86.492 }); assert.ok(s.includes(t.DENSITY_HOW), s); - assert.ok(/every repeater with a position in the area, active or silent/.test(t.DENSITY_HOW), t.DENSITY_HOW); + assert.ok(/the active repeaters with a position in the area \(not degraded or silent\)/.test(t.DENSITY_HOW), t.DENSITY_HOW); assert.ok(/DAGI land area in units of 100 km²/.test(t.DENSITY_HOW), t.DENSITY_HOW); - assert.ok(s.includes('83 repeaters ÷ 86.49 (8,649 km²) = 0.96'), s); + assert.ok(s.includes('83 active repeaters ÷ 86.49 (8,649 km²) = 0.96'), s); + assert.ok(s.includes('7 inactive'), 'the inactive ones are named: ' + s); assert.ok(/unrounded/.test(s), s); - assert.ok(t.densityTitle({ repeaters: 1, areaKm2: 200, repeatersPer100Km2: 0.5 }).includes('1 repeater ÷ 2.00 (200 km²) = 0.50')); + assert.ok(t.densityTitle({ repeaters: 1, activeRepeaters: 1, areaKm2: 200, repeatersPer100Km2: 0.5 }).includes('1 active repeater ÷ 2.00 (200 km²) = 0.50')); const chr = t.densityTitle({ outsideKommune: true, repeaters: 1, areaKm2: 0.35, repeatersPer100Km2: null }); assert.ok(/Christiansø is outside the kommune division/.test(chr), chr); }); @@ -150,8 +151,103 @@ test('the overview density card uses the same convention and the tooltip', async await w.render(); await settle(); const card = w.box.all().find((e) => e.getAttribute('data-stat') === 'density'); - assert.strictEqual(card.children[0].textContent, (71 / 4.689).toFixed(2)); - assert.ok(card.getAttribute('title').includes('71 repeaters ÷ 4.69 (469 km²)'), card.getAttribute('title')); + assert.strictEqual(card.children[0].textContent, (60 / 4.689).toFixed(2)); + assert.ok(card.getAttribute('title').includes('60 active repeaters ÷ 4.69 (469 km²)'), card.getAttribute('title')); +}); + +/* ---------- active-only density, no density for postnumre (owner, 2026-12-02) ---------- */ + +function postnumre() { + return Object.assign(kommuner(), { + layer: 'postnummer', param: 'postnr', + rows: [ + row('8000', 'Aarhus C', { nodes: 12, repeaters: 12, activeRepeaters: 9, areaKm2: 12.3, repeatersPer100Km2: null, observersPer100Km2: null, heard: 500, gaps: undefined }), + row('1050', 'København K', { group: true, nodes: 3, repeaters: 2, activeRepeaters: 2, areaKm2: 6.6, repeatersPer100Km2: null, observersPer100Km2: null, heard: 900, gaps: undefined }), + row('4970', 'Rødby', { nodes: 1, repeaters: 1, activeRepeaters: 0, areaKm2: 210, repeatersPer100Km2: null, observersPer100Km2: null, heard: 0 }), + ], + }); +} + +test('the repeaters cell keeps the total and names the inactive ones; it sorts on the total', async () => { + const w = world(); + await w.render(); + await settle(); + assert.strictEqual(w.cell('0101', 'repeaters').textContent, '22 (3 inactive)'); + assert.strictEqual(w.cell('0751', 'repeaters').textContent, '71 (11 inactive)'); + assert.strictEqual(w.cell('0147', 'repeaters').textContent, '4', 'none inactive: the plain count'); + assert.strictEqual(w.cell('0727', 'repeaters').textContent, '0'); + w.header('repeaters').children[0].click(); + assert.deepStrictEqual(w.codes().slice(0, 2), ['0751', '0101'], 'sorted on the total'); + const t = w.mod._test; + assert.strictEqual(t.metricFormat('repeaters')(12), '12', 'a legend value has no inactive part'); + assert.strictEqual(t.inactiveRepeaters({ repeaters: 5, activeRepeaters: 7 }), 0, 'never negative'); + assert.strictEqual(t.inactiveRepeaters({ repeaters: 5 }), 0, 'no active count: no inactive part'); +}); + +test('the overview: the repeaters card names the inactive ones; a postnummer has no density card', async () => { + const kom = world({ entry: { layer: 'kommune', param: 'kommune', code: '0751', name: 'Aarhus', label: 'Aarhus', title: 'Kommune' } }); + await kom.render(); + await settle(); + const card = (w, k) => w.box.all().find((e) => e.getAttribute('data-stat') === k); + assert.ok(card(kom, 'repeaters').textContent.includes('11 inactive'), card(kom, 'repeaters').textContent); + assert.strictEqual(card(kom, 'repeaters').children[0].textContent, '71'); + assert.ok(card(kom, 'density')); + const t = kom.mod._test; + const pn = Object.assign({}, postnumre().rows[0]); + const keys = t.statCards({ layer: 'postnummer', coveredHours: 24, row: pn }).map((c) => c[0]); + assert.ok(keys.indexOf('density') < 0, 'a postnummer density card: ' + keys); + assert.ok(keys.indexOf('repeaters') >= 0); + const kkeys = t.statCards({ layer: 'kommune', coveredHours: 24, row: kommuner().rows[0] }).map((c) => c[0]); + assert.ok(kkeys.indexOf('density') >= 0, 'a kommune lost its density card'); +}); + +test('postnummer layer: no density column, sort option or map metric; the counts, sorting and note still work', async () => { + const w = world({ hash: '#/analytics?tab=dagi-areas&layer=postnummer&sort=repeatersPer100Km2', answers: { postnummer: postnumre() } }); + await w.render(); + await settle(); + const t = w.mod._test; + const table = w.box.find('analytics-dagi-table')[0]; + assert.strictEqual(table.getAttribute('data-layer'), 'postnummer'); + assert.strictEqual(table.getAttribute('data-sort'), 'repeaters', 'a density link falls back to the repeater count'); + assert.deepStrictEqual(w.codes(), ['8000', '1050', '4970']); + assert.strictEqual(w.cell('8000', 'repeaters').textContent, '12 (3 inactive)'); + assert.strictEqual(w.cell('4970', 'repeaters').textContent, '1 (1 inactive)'); + const sel = w.box.find('analytics-dagi-sort-select')[0].children.find((c) => c.tagName === 'SELECT'); + const opt = sel.children.find((o) => o.value === 'repeatersPer100Km2'); + assert.ok(opt.hidden && opt.disabled, 'the density option is offered for postnumre'); + assert.ok(sel.children.filter((o) => o.value !== 'repeatersPer100Km2').every((o) => !o.hidden && !o.disabled)); + const note = w.box.find('analytics-dagi-density-note')[0].textContent; + assert.ok(/Postnumre have no density/.test(note) && !note.includes(t.DENSITY_HOW), note); + // A density sort cannot be reached; the other sorts work. + w.header('repeatersPer100Km2').children[0].click(); + assert.strictEqual(table.getAttribute('data-sort'), 'repeaters'); + w.header('heard').children[0].click(); + assert.deepStrictEqual(w.codes(), ['1050', '8000', '4970']); + assert.strictEqual(t.mapMetric('name', 'postnummer'), 'repeaters'); + assert.strictEqual(t.mapMetric('repeatersPer100Km2', 'postnummer'), 'repeaters'); + assert.strictEqual(t.mapMetric('heard', 'postnummer'), 'heard'); + assert.strictEqual(t.mapMetric('name', 'kommune'), 'repeatersPer100Km2'); + assert.strictEqual(t.mapMetric('repeatersPer100Km2', 'region'), 'repeatersPer100Km2'); + assert.strictEqual(t.LAYERS.filter(t.hasDensity).join(','), 'region,landsdel,kommune'); + // Back to kommuner: the density is there again. + w.box.all().find((e) => e.getAttribute && e.getAttribute('data-layer') === 'kommune' && e.tagName === 'BUTTON').click(); + await settle(); + assert.strictEqual(table.getAttribute('data-layer'), 'kommune'); + assert.ok(!opt.hidden && !opt.disabled); + assert.ok(w.box.find('analytics-dagi-density-note')[0].textContent.includes(t.DENSITY_HOW)); + sel.value = 'repeatersPer100Km2'; + sel.fire('change', { target: sel }); + assert.strictEqual(table.getAttribute('data-sort'), 'repeatersPer100Km2'); + // A switch to postnumre with the density sort writes the fallback. + w.box.all().find((e) => e.getAttribute && e.getAttribute('data-layer') === 'postnummer' && e.tagName === 'BUTTON').click(); + await settle(); + assert.strictEqual(table.getAttribute('data-sort'), 'repeaters'); + assert.ok(/layer=postnummer/.test(w.hash) && /sort=repeaters(&|$)/.test(w.hash), w.hash); +}); + +test('style.css hides the density column for the postnummer layer (header and cells)', () => { + const css = require('fs').readFileSync(require('path').join(__dirname, 'public/style.css'), 'utf8'); + assert.ok(/\.analytics-dagi-table\[data-layer="postnummer"\] \[data-k="repeatersPer100Km2"\]\s*\{\s*display:\s*none;?\s*\}/.test(css), 'no hide rule'); }); /* ---------- sorting ---------- */ @@ -185,7 +281,9 @@ test('layer and sort round-trip through the URL; bad values fall back', () => { for (const m of t.METRICS) { const hash = URLState.updateHashParams(t.viewParams({ layer, sort: m.key }), '#/analytics?tab=dagi-areas&kommune=0751'); const v = t.parseView(hash, null); - assert.deepStrictEqual([v.layer, v.sort], [layer, m.key], hash); + // Postnumre have no density: that sort falls back to the count. + const want = layer === 'postnummer' && m.key === 'repeatersPer100Km2' ? 'repeaters' : m.key; + assert.deepStrictEqual([v.layer, v.sort], [layer, want], hash); assert.ok(hash.includes('kommune=0751') && hash.includes('tab=dagi-areas'), hash); } } @@ -209,9 +307,9 @@ test('no selection: the kommune comparison, every row, values and gaps as text', await settle(); assert.deepStrictEqual(w.calls, ['/api/analytics/dagi-areas?layer=kommune']); assert.deepStrictEqual(w.codes(), ['0400', '0411', '0147', '0101', '0727', '0580', '0751'], 'name order (Danish: aa is å, last)'); - assert.strictEqual(w.cell('0101', 'repeatersPer100Km2').textContent, (22 / 0.901).toFixed(2)); + assert.strictEqual(w.cell('0101', 'repeatersPer100Km2').textContent, (19 / 0.901).toFixed(2)); assert.strictEqual(w.cell('0411', 'repeatersPer100Km2').textContent, '—'); - assert.ok(w.cell('0751', 'repeatersPer100Km2').getAttribute('title').includes('71 repeaters ÷ 4.69')); + assert.ok(w.cell('0751', 'repeatersPer100Km2').getAttribute('title').includes('60 active repeaters ÷ 4.69')); assert.strictEqual(w.cell('0751', 'heard').textContent, '14,233'); assert.strictEqual(w.cell('0580', 'gaps').textContent, 'No observerNothing heard'); assert.strictEqual(w.cell('0751', 'gaps').textContent, ''); @@ -404,7 +502,7 @@ test('R1: revealNode scrolls only a card that is out of view, smooth unless redu test('N1: an overview from a newer pass patches the same row nodes and re-sorts; the same pass fetches nothing', async () => { const newer = kommuner(); newer.generatedAt = '2026-12-01T10:05:00Z'; - newer.rows[0] = row('0101', 'København', { nodes: 31, repeaters: 23, areaKm2: 90.1, repeatersPer100Km2: 23 / 0.901, observers: 4, heard: 99999, active: 20, gaps: ['no-observer'] }); + newer.rows[0] = row('0101', 'København', { nodes: 31, repeaters: 23, activeRepeaters: 23, areaKm2: 90.1, repeatersPer100Km2: 23 / 0.901, observers: 4, heard: 99999, active: 20, gaps: ['no-observer'] }); newer.rows[1].gaps = ['nothing-heard']; // Frederiksberg: No observer -> Nothing heard newer.rows[4].gaps = []; // F4: Aabenraa loses its gaps const w = world({ hash: '#/analytics?tab=dagi-areas&sort=heard', overviewGeneratedAt: '2026-12-01T10:05:00Z' }); @@ -423,7 +521,7 @@ test('N1: an overview from a newer pass patches the same row nodes and re-sorts; assert.deepStrictEqual(w.calls, ['/api/analytics/dagi-areas?layer=kommune', '/api/analytics/dagi-area?kommune=0101', '/api/analytics/dagi-areas?layer=kommune']); assert.strictEqual(w.cell('0101', 'heard').textContent, '99,999', 'the cell was not patched'); assert.strictEqual(w.cell('0101', 'repeatersPer100Km2').textContent, (23 / 0.901).toFixed(2)); - assert.ok(w.cell('0101', 'repeatersPer100Km2').getAttribute('title').includes('23 repeaters')); + assert.ok(w.cell('0101', 'repeatersPer100Km2').getAttribute('title').includes('23 active repeaters')); assert.strictEqual(w.cell('0101', 'gaps').textContent, 'No observer'); assert.strictEqual(w.cell('0147', 'gaps').textContent, 'Nothing heard', 'the old gaps were kept'); assert.strictEqual(cls('0101'), 'analytics-dagi-row analytics-dagi-row-gaps', 'a row that gained gaps'); diff --git a/test-analytics-dagi-areas-map.js b/test-analytics-dagi-areas-map.js index b002ac145..1279e085e 100644 --- a/test-analytics-dagi-areas-map.js +++ b/test-analytics-dagi-areas-map.js @@ -282,6 +282,14 @@ test('a layer change with the map shown loads that layer\'s polygons; without th assert.ok(!/sea/i.test(note), 'a stale "include sea" legend note: ' + note); }); +test('postnumre have no density (owner, 2026-12-02): sorted by name, the map colours by the repeater count', async () => { + const w = world({ hash: '#/analytics?tab=dagi-areas&layer=postnummer&map=1' }); + await w.render(); await settle(); + const title = w.q('analytics-dagi-legend-title').textContent; + assert.ok(/^Colour: Repeaters \(/.test(title) && !/100 km²/.test(title), title); + assert.strictEqual(w.fill('0751'), 'c5', 'Aarhus has the most repeaters'); +}); + test('a link with map=1 shows the map with the table (the choice is in the URL)', async () => { const w = world({ hash: '#/analytics?tab=dagi-areas&layer=kommune&map=1' }); await w.render(); await settle(); diff --git a/test-issue-1002-density-e2e.js b/test-issue-1002-density-e2e.js new file mode 100644 index 000000000..3a5dca1fe --- /dev/null +++ b/test-issue-1002-density-e2e.js @@ -0,0 +1,192 @@ +#!/usr/bin/env node +/* Issue #1002 follow-up — the density columns (owner decision 2026-12-02). + * + * Against the real Go server. The real GET /api/analytics/dagi-areas is + * checked first: every postnummer row (the street-postcode groups too) has + * null densities, every kommune row but Christiansø has them, and every row + * carries activeRepeaters. The UI cases answer the comparison request with + * the real rows (real codes and names) and synthetic numbers in the + * server's shape, so some repeaters are inactive. + * + * 1. 1440x900: the kommune table shows "12 (3 inactive)" in Repeaters and + * the density column; the Postnummer button hides the density header + * and cells (computed style), the other columns stay, a Heard header + * click still sorts, and the note says postnumre have no density. + * 2. 375x560 (touch), real taps: on postnumre the sort select offers no + * density, the Repeaters sort shows "N (M inactive)" with its label on + * one line inside the screen, nothing scrolls sideways; back on + * kommuner the density option is offered again. + * 3. 375x560: a layer=postnummer&map=1 link colours the map by the + * repeater count (legend), never by density. + * + * Screenshots go to DAGI_SHOTS_DIR when set. + * Defaults to localhost:13581 — NEVER point at prod (AGENTS.md). CI sets BASE_URL. + * Run: BASE_URL=http://localhost:13581 node test-issue-1002-density-e2e.js + */ +'use strict'; +const path = require('path'); +const { chromium } = require('playwright'); +const { tapWhenSettled } = require('./tests/e2e-tap'); + +const BASE = process.env.BASE_URL || 'http://localhost:13581'; +const SHOTS = process.env.DAGI_SHOTS_DIR || ''; + +let passed = 0, failed = 0; +async function step(name, fn) { + try { await fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { failed++; console.error(' ✗ ' + name + ': ' + e.message); } +} +function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); } + +// Synthetic numbers on the real rows, in the server's semantics: density +// over the active repeaters, none for postnumre or Christiansø. +function populate(resp) { + const dens = resp.layer !== 'postnummer'; + resp.rows.forEach((r, i) => { + const n = (i * 37) % 23; + r.nodes = n; r.repeaters = Math.floor(n * 0.8); r.activeRepeaters = Math.max(0, r.repeaters - (i % 4)); + r.active = Math.floor(n * 0.6); r.observers = n % 4; + r.heard = r.observers ? (i * 811) % 5000 : 0; r.relayed = r.repeaters ? (i * 97) % 900 : 0; + r.repeatersPer100Km2 = dens && !r.outsideKommune ? r.activeRepeaters / (r.areaKm2 / 100) : null; + r.observersPer100Km2 = dens && !r.outsideKommune ? r.observers / (r.areaKm2 / 100) : null; + r.gaps = undefined; + }); + return resp; +} + +(async () => { + const browser = await chromium.launch({ + headless: true, + executablePath: process.env.CHROMIUM_PATH || undefined, + args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'], + }); + console.log(`\n=== #1002 density (active only, none for postnumre) against ${BASE} ===\n`); + const errors = []; + + async function cold(viewport, touch) { + const ctx = await browser.newContext({ viewport, hasTouch: touch, isMobile: touch }); + await ctx.addInitScript(() => { + try { + localStorage.setItem('meshcore-theme', 'light'); + localStorage.removeItem('meshcore-dagi-filter'); + ['row-swipe', 'tab-swipe', 'edge-drawer', 'pull-refresh'] + .forEach((k) => localStorage.setItem('meshcore-gesture-hints-' + k, 'seen')); + } catch (_) {} + }); + const page = await ctx.newPage(); + page.setDefaultTimeout(20000); + page.on('console', (m) => { if (m.type() === 'error' && !/tile|net::ERR|Failed to load resource/i.test(m.text())) errors.push(m.text()); }); + page.on('pageerror', (e) => errors.push(String(e))); + await ctx.route(/\/api\/analytics\/dagi-areas\?/, async (route) => { + const real = await (await route.fetch()).json(); + route.fulfill({ json: populate(real) }); + }); + return { ctx, page }; + } + async function shot(page, name) { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name + '.png'), fullPage: false }); } + const rowsShown = (page, n) => page.waitForFunction((count) => document.querySelectorAll('.analytics-dagi-row').length === count, n); + const shown = (page, sel) => page.evaluate((s) => Array.from(document.querySelectorAll(s)).map((e) => getComputedStyle(e).display !== 'none'), sel); + const noSideways = (page, w) => page.evaluate((width) => document.documentElement.scrollWidth <= width, w); + const layerBtn = (l) => `.analytics-dagi-layer[data-layer="${l}"]`; + + await step('the real API: postnumre (groups too) have no density, kommuner have one but Christiansø, activeRepeaters on every row', async () => { + const get = async (l) => { const r = await fetch(BASE + '/api/analytics/dagi-areas?layer=' + l); assert(r.ok, l + ' HTTP ' + r.status); return r.json(); }; + const pn = await get('postnummer'); + assert(pn.rows.length === 605, 'postnummer rows ' + pn.rows.length); + const groups = pn.rows.filter((r) => r.group); + assert(groups.length === 3, 'groups ' + groups.length); + for (const r of pn.rows) { + assert(r.repeatersPer100Km2 === null && r.observersPer100Km2 === null, 'postnummer ' + r.code + ' density ' + r.repeatersPer100Km2 + '/' + r.observersPer100Km2); + assert(typeof r.activeRepeaters === 'number', 'postnummer ' + r.code + ' activeRepeaters ' + r.activeRepeaters); + } + const km = await get('kommune'); + for (const r of km.rows) { + assert(typeof r.activeRepeaters === 'number' && r.activeRepeaters <= r.repeaters, 'kommune ' + r.code + ' activeRepeaters'); + if (r.outsideKommune) assert(r.repeatersPer100Km2 === null, 'Christiansø has a density'); + else assert(typeof r.repeatersPer100Km2 === 'number' && typeof r.observersPer100Km2 === 'number', 'kommune ' + r.code + ' no density'); + } + }); + + await step('1440x900: Repeaters reads "N (M inactive)"; postnumre hide the density header and cells, the rest still sorts', async () => { + const { ctx, page } = await cold({ width: 1440, height: 900 }, false); + await page.goto(BASE + '/#/analytics?tab=dagi-areas', { waitUntil: 'domcontentloaded' }); + await rowsShown(page, 99); + const cells = await page.$$eval('.analytics-dagi-row td[data-k="repeaters"]', (tds) => tds.map((t) => t.textContent)); + assert(cells.some((t) => /^\d+ \(\d+ inactive\)$/.test(t)), 'no "(N inactive)" cell: ' + cells.slice(0, 8).join('|')); + assert(cells.some((t) => /^\d+$/.test(t)), 'no plain count'); + assert((await shown(page, '.analytics-dagi-table th[data-k="repeatersPer100Km2"]')).every(Boolean), 'kommune density header hidden'); + assert((await shown(page, '.analytics-dagi-row td[data-k="repeatersPer100Km2"]')).every(Boolean), 'kommune density cells hidden'); + await shot(page, 'density-desktop-kommune'); + await page.click(layerBtn('postnummer')); + await rowsShown(page, 605); + assert(!(await shown(page, '.analytics-dagi-table th[data-k="repeatersPer100Km2"]')).some(Boolean), 'postnummer density header shown'); + assert(!(await shown(page, '.analytics-dagi-row td[data-k="repeatersPer100Km2"]')).some(Boolean), 'postnummer density cells shown'); + assert((await shown(page, '.analytics-dagi-table th[data-k="repeaters"], .analytics-dagi-table th[data-k="heard"]')).every(Boolean), 'other headers hidden'); + // The header row and a body row still line up: as many visible cells. + const widths = await page.evaluate(() => { + const vis = (el) => Array.from(el.children).filter((c) => getComputedStyle(c).display !== 'none').length; + return [vis(document.querySelector('.analytics-dagi-table thead tr')), vis(document.querySelector('.analytics-dagi-row'))]; + }); + assert(widths[0] === widths[1], 'header ' + widths[0] + ' vs row ' + widths[1] + ' cells'); + await page.click('.analytics-dagi-table th[data-k="heard"] .analytics-dagi-sort'); + await page.waitForFunction(() => document.querySelector('.analytics-dagi-table').getAttribute('data-sort') === 'heard'); + const heard = await page.$$eval('.analytics-dagi-row td[data-k="heard"]', (tds) => tds.slice(0, 20).map((t) => Number(t.textContent.replace(/,/g, '')))); + assert(heard.every((v, i) => i === 0 || heard[i - 1] >= v), 'not sorted by heard: ' + heard.join(',')); + const note = await page.textContent('.analytics-dagi-density-note'); + assert(/Postnumre have no density/.test(note), note); + await shot(page, 'density-desktop-postnummer'); + await ctx.close(); + }); + + await step('375x560, real taps: postnumre offer no density sort; Repeaters shows "N (M inactive)" inside the screen', async () => { + const { ctx, page } = await cold({ width: 375, height: 560 }, true); + await page.goto(BASE + '/#/analytics?tab=dagi-areas&sort=repeatersPer100Km2', { waitUntil: 'domcontentloaded' }); + await rowsShown(page, 99); + const opts = () => page.$$eval('.analytics-dagi-sort-select option', (os) => os.filter((o) => !o.hidden && !o.disabled).map((o) => o.value)); + assert((await opts()).includes('repeatersPer100Km2'), 'kommune: no density option'); + await tapWhenSettled(page, layerBtn('postnummer'), { minHeight: 24 }); + await rowsShown(page, 605); + assert(!(await opts()).includes('repeatersPer100Km2'), 'postnummer offers density: ' + (await opts()).join(',')); + assert(await page.$eval('.analytics-dagi-table', (t) => t.getAttribute('data-sort')) === 'repeaters', 'the density sort did not fall back to Repeaters'); + assert(/sort=repeaters(&|$)/.test(await page.evaluate(() => location.hash)), 'URL sort'); + const first = await page.evaluate(() => { + const td = Array.from(document.querySelectorAll('.analytics-dagi-row td[data-k="repeaters"]')).find((t) => /inactive/.test(t.textContent)); + if (!td) return null; + td.scrollIntoView(); + const b = td.getBoundingClientRect(); + return { text: td.textContent, label: getComputedStyle(td, '::before').content, right: b.right, h: b.height, shown: getComputedStyle(td).display !== 'none' }; + }); + assert(first && first.shown && /^\d+ \(\d+ inactive\)$/.test(first.text), 'phone cell ' + JSON.stringify(first)); + assert(first.right <= 375 && first.h < 40, 'cell outside the screen or wrapped: ' + JSON.stringify(first)); + assert(!(await shown(page, '.analytics-dagi-row td[data-k="repeatersPer100Km2"]')).some(Boolean), 'phone density cells shown'); + assert(await noSideways(page, 375), 'sideways scroll'); + await shot(page, 'density-phone-postnummer'); + await page.selectOption('.analytics-dagi-sort-select select', 'heard'); + await page.waitForFunction(() => document.querySelector('.analytics-dagi-table').getAttribute('data-sort') === 'heard'); + await tapWhenSettled(page, layerBtn('kommune'), { minHeight: 24 }); + await rowsShown(page, 99); + assert((await opts()).includes('repeatersPer100Km2'), 'kommune lost the density option'); + await page.selectOption('.analytics-dagi-sort-select select', 'repeatersPer100Km2'); + await page.waitForFunction(() => document.querySelector('.analytics-dagi-table').getAttribute('data-sort') === 'repeatersPer100Km2'); + assert((await shown(page, '.analytics-dagi-row td[data-k="repeatersPer100Km2"]')).some(Boolean), 'kommune density cells not shown on the phone'); + await ctx.close(); + }); + + await step('375x560: a postnummer map link colours by the repeater count, never density', async () => { + const { ctx, page } = await cold({ width: 375, height: 560 }, true); + await page.goto(BASE + '/#/analytics?tab=dagi-areas&layer=postnummer&map=1', { waitUntil: 'domcontentloaded' }); + await rowsShown(page, 605); + await page.waitForSelector('.analytics-dagi-legend-title'); + const title = await page.textContent('.analytics-dagi-legend-title'); + assert(/^Colour: Repeaters \(/.test(title) && !/100 km²/.test(title), title); + assert(await noSideways(page, 375), 'sideways scroll'); + await shot(page, 'density-phone-postnummer-map'); + await ctx.close(); + }); + + await step('no console errors', async () => { assert(!errors.length, errors.join(' | ')); }); + + await browser.close(); + console.log(`\n${passed} passed, ${failed} failed`); + process.exit(failed ? 1 : 0); +})().catch((e) => { console.error(e); process.exit(1); }); diff --git a/test-issue-1002-m2-dagi-comparison-e2e.js b/test-issue-1002-m2-dagi-comparison-e2e.js index 9ddd1e85a..10bb96025 100644 --- a/test-issue-1002-m2-dagi-comparison-e2e.js +++ b/test-issue-1002-m2-dagi-comparison-e2e.js @@ -229,7 +229,7 @@ function populate(resp) { assert(await sameNodes(page), 'the rows were rebuilt by the pick'); const cur = await page.evaluate(() => Array.from(document.querySelectorAll('.analytics-dagi-row[aria-current="true"]')).map((r) => r.getAttribute('data-code'))); assert(cur.length === 1 && cur[0] === '0751', 'marked ' + cur.join(',')); - assert(await page.evaluate(() => document.querySelector('.analytics-dagi-card .stat-card[data-stat="density"]').getAttribute('title').includes('every repeater with a position')), 'density card tooltip'); + assert(await page.evaluate(() => document.querySelector('.analytics-dagi-card .stat-card[data-stat="density"]').getAttribute('title').includes('the active repeaters with a position')), 'density card tooltip'); await shot(page, 'm2-phone-picked'); // N3: on a phone the shown number carries its label, visibly and in // the accessibility tree (the header row is only visually hidden). @@ -326,7 +326,9 @@ function populate(resp) { await page.waitForFunction(() => performance.getEntriesByName('dagi-areas:render:frame').length > 0); const render = await entries('dagi-areas:render:frame'); const renderJs = await entries('dagi-areas:render'); - await page.locator('.analytics-dagi-sort-select select').selectOption('repeatersPer100Km2'); + // Postnumre have no density (owner, 2026-12-02): the re-sort is by the + // repeater count, the same numeric sort over the same 605 rows. + await page.locator('.analytics-dagi-sort-select select').selectOption('repeaters'); await page.waitForFunction(() => performance.getEntriesByName('dagi-areas:sort:frame').length > 0); const sort = await entries('dagi-areas:sort:frame'); const sortJs = await entries('dagi-areas:sort');