Compare commits

...
4 Commits
Author SHA1 Message Date
Sebi 918c71f283 Merge pull request 'feat(regions): show checker regions on a map' (#169) from feat/region-map into main
ci / build (push) Waiting for needed jobs
ci / image (push) Waiting for needed jobs
ci / test (push) In progress
release / release (push) In progress
ci / lint (push) In progress
2026-11-28 19:50:13 +00:00
Sebastian UnterschützandClaude Opus 5.5 23717afec9 feat(regions): public region list and touch-friendly maps
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / image (pull_request) Waiting for needed jobs
ci / build (pull_request) Waiting for needed jobs
ci / lint (pull_request) In progress
ci / test (pull_request) In progress
GET /api/v1/public/regions lists the platform regions with their
location and whether a checker is online, without authentication and to
any origin, for the website's front page. Each instance answers from
memory for 30 seconds; organizations' own regions are never listed.

On touch screens one finger scrolls the page and two move the map, the
pins are larger, and a tap no longer leaves rows highlighted. The
gesture hints are translated, and the regions table drops the key and
owner columns on phones so the location fits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-28 20:48:30 +01:00
Sebastian UnterschützandClaude Opus 5.5 6c246b145f feat(regions): label the map pins and link them to the region list
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m17s
ci / test (pull_request) Successful in 12m34s
ci / build (pull_request) Canceled after 4m21s
ci / image (pull_request) Canceled after 0s
Pins carry the region's name, turn dark when the region is selected and
show a green dot while a checker of the region is live. Hovering a pin
highlights its row in the list and the other way round, and a region
ticked in the list pans into view. Scrolling the page no longer zooms
the map, and the attribution stays compact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-28 20:31:11 +01:00
Sebastian UnterschützandClaude Opus 5.5 3562f8224e feat(regions): show checker regions on a map
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m48s
ci / build (pull_request) Canceled after 30s
ci / test (pull_request) Successful in 12m42s
ci / image (pull_request) Canceled after 0s
Regions get an optional location. Platform admins set it for platform
regions and org admins for their own, by clicking the map on the regions
page or entering the coordinates; PATCH /org/regions/:id and
/admin/regions/:id set or remove it.

The monitor form shows the located regions on a map from the
self-hosted ZB-Server Maps: a click on a marker ticks or unticks the
region, and the checkbox list stays the source of truth. MapLibre loads
only on pages with a map, and the map stays hidden if the map server
cannot be reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-28 20:17:27 +01:00
25 changed files with 3335 additions and 1800 deletions

No files matched your search

+7
View File
@@ -22,6 +22,9 @@ func paged(o obj) obj {
// show them.
var endpoints = []endpoint{
// Account
{method: "GET", path: "/api/v1/public/regions", tag: "Public", summary: "Platform regions with their locations", public: true,
description: "For websites showing where the platform checks from: no authentication, any origin (CORS), cached for up to a minute. Lists platform regions only; `latitude`/`longitude` are absent for regions without a location, and `online` is set while a checker of the region is connected.",
resp: obj{"regions": []publicRegion{}}},
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account", public: true,
description: "Depending on the installation, sign-up is open, limited to the first user, or closed. Where addresses are confirmed, answers `{\"status\": \"verification_sent\"}` and mails a link; the account signs in after confirming. Otherwise starts a session, and `org_name`/`org_slug`, if given, create a first organization. One account per mailbox (+suffixes and Gmail dots count as the same address); a client address may create only a few accounts a day (`429 signup_limit`).",
req: signupRequest{}, resp: sessionStarted},
@@ -268,6 +271,8 @@ var endpoints = []endpoint{
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
{method: "DELETE", path: "/api/v1/org/regions/:id", tag: "Organization", summary: "Delete an own region", perm: "org.manage", sessionOnly: true,
status: http.StatusNoContent},
{method: "PATCH", path: "/api/v1/org/regions/:id", tag: "Organization", summary: "Set or remove the location of an own region", perm: "org.manage", sessionOnly: true,
description: "Null for both coordinates removes the location.", req: regionLocation{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/agents", tag: "Organization", summary: "List own checkers and status page servers", perm: "org.manage",
resp: obj{"agents": []agentView{}}},
{method: "POST", path: "/api/v1/org/agents", tag: "Organization", summary: "Create an agent token", perm: "org.manage", sessionOnly: true,
@@ -366,6 +371,8 @@ var endpoints = []endpoint{
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
{method: "DELETE", path: "/api/v1/admin/regions/:id", tag: "Platform", summary: "Delete a platform region", perm: "platform admin",
status: http.StatusNoContent},
{method: "PATCH", path: "/api/v1/admin/regions/:id", tag: "Platform", summary: "Set or remove the location of a platform region", perm: "platform admin",
description: "Null for both coordinates removes the location.", req: regionLocation{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/agents", tag: "Platform", summary: "List platform agents", perm: "platform admin",
resp: obj{"agents": []agentView{}}},
{method: "POST", path: "/api/v1/admin/agents", tag: "Platform", summary: "Create a platform agent token", perm: "platform admin",
+2
View File
@@ -76,6 +76,7 @@ var auditActions = map[string]string{
"DELETE /api/v1/org/groups/:id": "group.delete",
"POST /api/v1/org/regions": "region.create",
"DELETE /api/v1/org/regions/:id": "region.delete",
"PATCH /api/v1/org/regions/:id": "region.update",
"POST /api/v1/org/agents": "agent.create",
"DELETE /api/v1/org/agents/:id": "agent.delete",
"POST /api/v1/org/statuspages": "statuspage.create",
@@ -129,6 +130,7 @@ var auditActions = map[string]string{
"PATCH /api/v1/org/agents/:id": "agent.update",
"POST /api/v1/admin/regions": "platform.region_create",
"DELETE /api/v1/admin/regions/:id": "platform.region_delete",
"PATCH /api/v1/admin/regions/:id": "platform.region_update",
"POST /api/v1/admin/agents": "platform.agent_create",
"DELETE /api/v1/admin/agents/:id": "platform.agent_delete",
}
+1 -1
View File
@@ -939,7 +939,7 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
return nil, err
}
checked := slices.Contains(assigned, r.ID) || (idParam == "" && i == 0)
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live})
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live, Lat: r.Latitude, Lon: r.Longitude})
}
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
+1 -1
View File
@@ -670,7 +670,7 @@ func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, a
if err != nil {
return v, err
}
wr := web.Region{ID: r.ID.String(), Key: r.Key, Name: r.Name, Platform: r.OrgID == nil, Manageable: manageable(r), Instances: n}
wr := web.Region{ID: r.ID.String(), Key: r.Key, Name: r.Name, Platform: r.OrgID == nil, Manageable: manageable(r), Instances: n, Lat: r.Latitude, Lon: r.Longitude}
v.Regions = append(v.Regions, wr)
if wr.Manageable {
v.OwnRegions = append(v.OwnRegions, wr)
+82
View File
@@ -0,0 +1,82 @@
package api
import (
"encoding/json"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// publicRegionsTTL is how long an instance serves the platform regions
// from memory, so the endpoint costs the database next to nothing however
// often a front page asks.
const publicRegionsTTL = 30 * time.Second
// publicRegion is a platform region as anyone may see it. Organizations'
// own regions are never listed.
type publicRegion struct {
Key string `json:"key"`
Name string `json:"name"`
// Latitude and longitude are absent for regions without a location.
Latitude *float64 `json:"latitude,omitempty"`
Longitude *float64 `json:"longitude,omitempty"`
// Online is set while at least one checker of the region is connected.
Online bool `json:"online"`
}
type publicRegionsCache struct {
mu sync.Mutex
body []byte
expires time.Time
}
// listPublicRegions answers without authentication and to any origin, for
// a website showing where the platform checks from.
func (s *Server) listPublicRegions(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Cache-Control", "public, max-age=60")
body, err := s.publicRegionsBody(c)
if err != nil {
internalError(c, err)
return
}
c.Data(http.StatusOK, "application/json; charset=utf-8", body)
}
func (s *Server) publicRegionsBody(c *gin.Context) ([]byte, error) {
cache := &s.publicRegions
cache.mu.Lock()
defer cache.mu.Unlock()
if cache.body != nil && time.Now().Before(cache.expires) {
return cache.body, nil
}
ctx := c.Request.Context()
var rows []store.Region
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListPlatformRegions(ctx)
return err
})
if err != nil {
return nil, err
}
out := make([]publicRegion, len(rows))
for i, r := range rows {
n, err := s.sched.Instances(ctx, r.ID.String())
if err != nil {
return nil, err
}
out[i] = publicRegion{Key: r.Key, Name: r.Name, Latitude: r.Latitude, Longitude: r.Longitude, Online: n > 0}
}
body, err := json.Marshal(gin.H{"regions": out})
if err != nil {
return nil, err
}
cache.body, cache.expires = body, time.Now().Add(publicRegionsTTL)
return body, nil
}
+86 -8
View File
@@ -28,6 +28,14 @@ type regionView struct {
// regions.
Own bool `json:"own"`
Instances int64 `json:"instances"`
// Latitude and longitude place the region on the map; both are absent
// for regions without a location.
Latitude *float64 `json:"latitude,omitempty"`
Longitude *float64 `json:"longitude,omitempty"`
}
func newRegionView(r store.Region, org uuid.UUID, instances int64) regionView {
return regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: instances, Latitude: r.Latitude, Longitude: r.Longitude}
}
func (s *Server) viewRegions(ctx context.Context, rows []store.Region, org uuid.UUID) ([]regionView, error) {
@@ -37,7 +45,7 @@ func (s *Server) viewRegions(ctx context.Context, rows []store.Region, org uuid.
if err != nil {
return nil, err
}
out[i] = regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: n}
out[i] = newRegionView(r, org, n)
}
return out, nil
}
@@ -67,6 +75,7 @@ func (s *Server) listOrgRegions(c *gin.Context) {
type regionRequest struct {
Key string `json:"key" binding:"required,max=40"`
Name string `json:"name" binding:"max=100"`
regionLocation
}
func (r *regionRequest) normalize() bool {
@@ -78,6 +87,20 @@ func (r *regionRequest) normalize() bool {
return regionKeyRE.MatchString(r.Key)
}
// regionLocation is where a region's checkers stand; null for both
// coordinates means no location.
type regionLocation struct {
Latitude *float64 `json:"latitude"`
Longitude *float64 `json:"longitude"`
}
func (l regionLocation) valid() bool {
if l.Latitude == nil || l.Longitude == nil {
return l.Latitude == nil && l.Longitude == nil
}
return *l.Latitude >= -90 && *l.Latitude <= 90 && *l.Longitude >= -180 && *l.Longitude <= 180
}
func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
var req regionRequest
if !bind(c, &req) {
@@ -87,11 +110,15 @@ func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID
fail(c, http.StatusUnprocessableEntity, "invalid_region_key")
return
}
if !req.valid() {
fail(c, http.StatusUnprocessableEntity, "invalid_location")
return
}
ctx := c.Request.Context()
var row store.Region
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
var err error
row, err = q.CreateRegion(ctx, store.CreateRegionParams{OrgID: org, Key: req.Key, Name: req.Name})
row, err = q.CreateRegion(ctx, store.CreateRegionParams{OrgID: org, Key: req.Key, Name: req.Name, Latitude: req.Latitude, Longitude: req.Longitude})
return err
})
if isUniqueViolation(err, "regions_owner_key_key") {
@@ -102,7 +129,41 @@ func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID
internalError(c, err)
return
}
c.JSON(http.StatusCreated, regionView{ID: row.ID, Key: row.Key, Name: row.Name, Own: org != nil})
v := newRegionView(row, uuid.Nil, 0)
v.Own = org != nil
c.JSON(http.StatusCreated, v)
}
// updateRegion sets or removes a region's location.
func (s *Server) updateRegion(c *gin.Context, scope tenant.Scope) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req regionLocation
if !bind(c, &req) {
return
}
if !req.valid() {
fail(c, http.StatusUnprocessableEntity, "invalid_location")
return
}
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, scope, func(q *store.Queries) error {
n, err = q.UpdateRegionLocation(ctx, store.UpdateRegionLocationParams{ID: id, Latitude: req.Latitude, Longitude: req.Longitude})
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
c.Status(http.StatusNoContent)
}
func (s *Server) deleteRegion(c *gin.Context, scope tenant.Scope) {
@@ -141,6 +202,9 @@ func (s *Server) createOrgRegion(c *gin.Context) {
// hides platform regions from writes in an org scope.
func (s *Server) deleteOrgRegion(c *gin.Context) { s.deleteRegion(c, current(c).scope()) }
// updateOrgRegion, like deleteOrgRegion, reaches the org's own regions only.
func (s *Server) updateOrgRegion(c *gin.Context) { s.updateRegion(c, current(c).scope()) }
type agentView struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
@@ -323,11 +387,25 @@ func (s *Server) adminListRegions(c *gin.Context) {
func (s *Server) adminCreateRegion(c *gin.Context) { s.createRegion(c, tenant.System(), nil) }
func (s *Server) adminDeleteRegion(c *gin.Context) {
// The system scope could reach org regions; only platform ones are meant.
if s.platformRegion(c) {
s.deleteRegion(c, tenant.System())
}
}
func (s *Server) adminUpdateRegion(c *gin.Context) {
if s.platformRegion(c) {
s.updateRegion(c, tenant.System())
}
}
// platformRegion reports whether the region in the path is a platform one,
// answering the request otherwise: the system scope could reach org
// regions, but only platform ones are meant.
func (s *Server) platformRegion(c *gin.Context) bool {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
return false
}
ctx := c.Request.Context()
var r store.Region
@@ -337,13 +415,13 @@ func (s *Server) adminDeleteRegion(c *gin.Context) {
})
if errors.Is(err, pgx.ErrNoRows) || (err == nil && r.OrgID != nil) {
fail(c, http.StatusNotFound, "not_found")
return
return false
}
if err != nil {
internalError(c, err)
return
return false
}
s.deleteRegion(c, tenant.System())
return true
}
func (s *Server) adminListAgents(c *gin.Context) { s.listAgents(c, tenant.System(), nil) }
+127
View File
@@ -2,6 +2,7 @@ package api_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -200,3 +201,129 @@ func TestAgentInstallConsole(t *testing.T) {
t.Error("an agent on the platform's release is marked outdated")
}
}
func TestRegionLocations(t *testing.T) {
e := newEnv(t)
_, platformRegion := e.platformChecker(t, uniq("loc-"))
a := e.browser(t)
a.signup("a@"+uniq("a")+".test", uniq("org-a-"))
b := e.browser(t)
b.signup("b@"+uniq("b")+".test", uniq("org-b-"))
location := func(br *browser, id string) (any, any) {
t.Helper()
_, body := br.do("GET", "/api/v1/org/regions", nil)
for _, r := range body["regions"].([]any) {
if r := r.(map[string]any); r["id"] == id {
return r["latitude"], r["longitude"]
}
}
t.Fatalf("region %s not listed", id)
return nil, nil
}
st, body := a.do("POST", "/api/v1/org/regions", map[string]any{"key": "berlin", "latitude": 52.52, "longitude": 13.405})
if st != http.StatusCreated || body["latitude"] != 52.52 || body["longitude"] != 13.405 {
t.Fatalf("create region with location = %d %v", st, body)
}
berlin := body["id"].(string)
plain := a.createRegion("plain")
if lat, lon := location(a, plain); lat != nil || lon != nil {
t.Errorf("region without location lists %v, %v", lat, lon)
}
for _, tc := range []struct {
what string
body map[string]any
}{
{"latitude only", map[string]any{"latitude": 10.0}},
{"latitude out of range", map[string]any{"latitude": 91.0, "longitude": 0.0}},
{"longitude out of range", map[string]any{"latitude": 0.0, "longitude": -181.0}},
} {
st, body := a.do("PATCH", "/api/v1/org/regions/"+plain, tc.body)
expect(t, tc.what, st, body, http.StatusUnprocessableEntity, "invalid_location")
}
st, body = a.do("POST", "/api/v1/org/regions", map[string]any{"key": "half", "longitude": 3.0})
expect(t, "create with half a location", st, body, http.StatusUnprocessableEntity, "invalid_location")
st, body = a.do("PATCH", "/api/v1/org/regions/"+plain, map[string]any{"latitude": -33.8688, "longitude": 151.2093})
expect(t, "set location", st, body, http.StatusNoContent, "")
if lat, lon := location(a, plain); lat != -33.8688 || lon != 151.2093 {
t.Errorf("location after PATCH = %v, %v", lat, lon)
}
st, body = a.do("PATCH", "/api/v1/org/regions/"+berlin, map[string]any{"latitude": nil, "longitude": nil})
expect(t, "remove location", st, body, http.StatusNoContent, "")
if lat, lon := location(a, berlin); lat != nil || lon != nil {
t.Errorf("location after removal = %v, %v", lat, lon)
}
st, body = b.do("PATCH", "/api/v1/org/regions/"+plain, map[string]any{"latitude": 1.0, "longitude": 1.0})
expect(t, "other org sets location", st, body, http.StatusNotFound, "not_found")
st, body = a.do("PATCH", "/api/v1/org/regions/"+platformRegion, map[string]any{"latitude": 1.0, "longitude": 1.0})
expect(t, "org sets platform location", st, body, http.StatusNotFound, "not_found")
st, body = a.do("PATCH", "/api/v1/admin/regions/"+platformRegion, map[string]any{"latitude": 1.0, "longitude": 1.0})
expect(t, "non-admin sets platform location", st, body, http.StatusForbidden, "forbidden")
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(context.Background(), a.userIDSelf())
})
if err != nil {
t.Fatal(err)
}
st, body = a.do("PATCH", "/api/v1/admin/regions/"+plain, map[string]any{"latitude": 1.0, "longitude": 1.0})
expect(t, "admin sets org region location", st, body, http.StatusNotFound, "not_found")
st, body = a.do("PATCH", "/api/v1/admin/regions/"+platformRegion, map[string]any{"latitude": 50.1109, "longitude": 8.6821})
expect(t, "admin sets platform location", st, body, http.StatusNoContent, "")
if lat, lon := location(b, platformRegion); lat != 50.1109 || lon != 8.6821 {
t.Errorf("platform location seen by org B = %v, %v", lat, lon)
}
t.Run("public list", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, a.base+"/api/v1/public/regions", nil)
req.Header.Set("Origin", "https://www.example.org")
// The browser's transport trusts the test server; no cookie jar, so no session.
resp, err := (&http.Client{Transport: a.hc.Transport}).Do(req)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
var body struct {
Regions []map[string]any `json:"regions"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil || resp.StatusCode != http.StatusOK {
t.Fatalf("GET public regions = %d %v", resp.StatusCode, err)
}
if got := resp.Header.Get("Access-Control-Allow-Origin"); got != "*" {
t.Errorf("CORS header = %q, want *", got)
}
var found map[string]any
for _, r := range body.Regions {
if r["name"] == "Office plain" || r["key"] == "berlin" {
t.Errorf("public list shows an org region: %v", r)
}
if _, leaked := r["id"]; leaked {
t.Errorf("public list exposes region ids: %v", r)
}
if r["latitude"] == 50.1109 {
found = r
}
}
if _, isBool := found["online"].(bool); found == nil || found["longitude"] != 8.6821 || !isBool {
t.Errorf("platform region in public list = %v, want its location and online state", found)
}
})
_, _, html := a.page("/monitors/new")
if !strings.Contains(html, `data-region-map="select"`) || !strings.Contains(html, `data-lat="50.1109"`) || !strings.Contains(html, `data-lat="-33.8688"`) {
t.Errorf("monitor form lacks the region map or markers")
}
_, _, html = b.page("/monitors/new")
if !strings.Contains(html, `data-region-map="select"`) || strings.Contains(html, `data-lat="-33.8688"`) {
t.Errorf("org B monitor form: want the platform marker only")
}
_, _, html = a.page("/settings/regions")
if !strings.Contains(html, `data-region-map="edit"`) || !strings.Contains(html, `data-location-toggle="location-`+plain+`"`) {
t.Errorf("regions page lacks the map or the location form")
}
}
+7
View File
@@ -67,6 +67,9 @@ type Server struct {
// snapshots lets status page servers asking for the same page at once
// share one build of it.
snapshots singleflight.Group
// publicRegions caches the answer of the public region list.
publicRegions publicRegionsCache
}
// Deps are the external resources a Server needs.
@@ -127,6 +130,8 @@ func (s *Server) Mount(r gin.IRouter) {
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit(), s.accountGate())
r.GET("/api/openapi.json", s.openAPIJSON)
// Public data for websites: no session, no CSRF.
r.GET("/api/v1/public/regions", s.listPublicRegions)
r.GET("/install.sh", s.installScript)
g.GET("/api/docs", s.apiDocsPage)
@@ -203,6 +208,7 @@ func (s *Server) Mount(r gin.IRouter) {
org.GET("/regions", s.listOrgRegions)
org.POST("/regions", sessionOnly(), can(authz.OrgManage), s.createOrgRegion)
org.DELETE("/regions/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgRegion)
org.PATCH("/regions/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgRegion)
org.GET("/agents", can(authz.OrgManage), s.listOrgAgents)
org.POST("/agents", sessionOnly(), can(authz.OrgManage), s.createOrgAgent)
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
@@ -237,6 +243,7 @@ func (s *Server) Mount(r gin.IRouter) {
admin.GET("/regions", s.adminListRegions)
admin.POST("/regions", s.adminCreateRegion)
admin.DELETE("/regions/:id", s.adminDeleteRegion)
admin.PATCH("/regions/:id", s.adminUpdateRegion)
admin.GET("/support/settings", s.adminGetSupportSettings)
admin.PUT("/support/settings", s.adminSetSupportSettings)
admin.GET("/support/tickets", s.adminListTickets)
+13
View File
@@ -129,6 +129,7 @@
"audit.action.platform.org_suspension": "Organisation gesperrt oder entsperrt",
"audit.action.platform.region_create": "Plattform-Region erstellt",
"audit.action.platform.region_delete": "Plattform-Region gelöscht",
"audit.action.platform.region_update": "Standort einer Plattform-Region geändert",
"audit.action.platform.status_page_delete": "Statusseite durch Admin gelöscht",
"audit.action.platform.status_page_suspension": "Statusseite gesperrt oder entsperrt",
"audit.action.platform.user_delete": "Account durch Admin gelöscht",
@@ -136,6 +137,7 @@
"audit.action.platform.user_suspension": "Account gesperrt oder entsperrt",
"audit.action.region.create": "Region erstellt",
"audit.action.region.delete": "Region gelöscht",
"audit.action.region.update": "Standort einer Region geändert",
"audit.action.role.create": "Rolle erstellt",
"audit.action.role.delete": "Rolle gelöscht",
"audit.action.role.update": "Rolle geändert",
@@ -587,6 +589,7 @@
"error.invalid_maintenance_time": "Prüfe Beginn, Wochentage und letzten Tag.",
"error.invalid_matchers": "Lege 1 bis 20 Label-Matcher mit gültigen Label-Namen und regulären Ausdrücken an.",
"error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.",
"error.invalid_location": "Breitengrad (−90 bis 90) und Längengrad (−180 bis 180) angeben, oder keins von beiden.",
"error.invalid_monitor": "Einer der Monitore existiert nicht oder ist doppelt aufgeführt.",
"error.invalid_permissions": "Mindestens eine Berechtigung auswählen.",
"error.invalid_query": "Gib eine PromQL-Abfrage mit höchstens 2000 Zeichen ein.",
@@ -1361,6 +1364,16 @@
"one": "{{.Count}} aktiv",
"other": "{{.Count}} aktiv"
},
"regions.latitude": "Breitengrad",
"regions.location": "Standort",
"regions.location_clear": "Standort entfernen",
"regions.location_for": "Standort von {{.Name}}: auf die Karte klicken oder die Koordinaten eingeben.",
"regions.location_pick_hint": "Ein Klick auf die Karte setzt die Koordinaten einer neuen Region oder der Region, deren Standort du gerade setzt.",
"regions.location_set": "Setzen",
"regions.longitude": "Längengrad",
"regions.map_ctrl_key": "Strg",
"regions.map_scroll_hint": "{{.Key}} + Scrollen zoomt die Karte.",
"regions.map_touch_hint": "Mit zwei Fingern verschiebst du die Karte.",
"regions.own": "diese Organisation",
"regions.owner": "Besitzer",
"regions.platform": "Plattform",
+13
View File
@@ -129,6 +129,7 @@
"audit.action.platform.org_suspension": "Organization suspended or reinstated",
"audit.action.platform.region_create": "Platform region created",
"audit.action.platform.region_delete": "Platform region deleted",
"audit.action.platform.region_update": "Platform region location changed",
"audit.action.platform.status_page_delete": "Status page deleted by admin",
"audit.action.platform.status_page_suspension": "Status page suspended or reinstated",
"audit.action.platform.user_delete": "Account deleted by admin",
@@ -136,6 +137,7 @@
"audit.action.platform.user_suspension": "Account suspended or reinstated",
"audit.action.region.create": "Region created",
"audit.action.region.delete": "Region deleted",
"audit.action.region.update": "Region location changed",
"audit.action.role.create": "Role created",
"audit.action.role.delete": "Role deleted",
"audit.action.role.update": "Role changed",
@@ -587,6 +589,7 @@
"error.invalid_maintenance_time": "Check start, weekdays and last day.",
"error.invalid_matchers": "Add 1 to 20 label matchers with valid label names and regular expressions.",
"error.invalid_method": "Only GET and HEAD requests are supported.",
"error.invalid_location": "Give latitude (−90 to 90) and longitude (−180 to 180), or neither.",
"error.invalid_monitor": "One of the monitors does not exist or is listed twice.",
"error.invalid_permissions": "Choose at least one permission.",
"error.invalid_query": "Enter a PromQL query of at most 2000 characters.",
@@ -1361,6 +1364,16 @@
"one": "{{.Count}} live",
"other": "{{.Count}} live"
},
"regions.latitude": "Latitude",
"regions.location": "Location",
"regions.location_clear": "Remove location",
"regions.location_for": "Location of {{.Name}}: click the map or enter the coordinates.",
"regions.location_pick_hint": "Click the map to fill in the coordinates of a new region, or of the region whose location you are setting.",
"regions.location_set": "Set",
"regions.longitude": "Longitude",
"regions.map_ctrl_key": "Ctrl",
"regions.map_scroll_hint": "Use {{.Key}} + scroll to zoom the map.",
"regions.map_touch_hint": "Use two fingers to move the map.",
"regions.own": "this organization",
"regions.owner": "Owner",
"regions.platform": "platform",
@@ -0,0 +1,16 @@
-- +goose Up
-- Where a region's checkers stand, so the monitor form can show them on a
-- map. Both coordinates are set or neither is.
ALTER TABLE regions
ADD COLUMN latitude double precision,
ADD COLUMN longitude double precision,
ADD CONSTRAINT regions_location_check CHECK (
(latitude IS NULL AND longitude IS NULL)
OR (latitude BETWEEN -90 AND 90 AND longitude BETWEEN -180 AND 180)
);
-- +goose Down
ALTER TABLE regions
DROP CONSTRAINT regions_location_check,
DROP COLUMN latitude,
DROP COLUMN longitude;
+48 -10
View File
@@ -56,18 +56,26 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
}
const createRegion = `-- name: CreateRegion :one
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
RETURNING key, name, created_at, id, org_id
INSERT INTO regions (org_id, key, name, latitude, longitude) VALUES ($1, $2, $3, $4, $5)
RETURNING key, name, created_at, id, org_id, latitude, longitude
`
type CreateRegionParams struct {
OrgID *uuid.UUID
Key string
Name string
OrgID *uuid.UUID
Key string
Name string
Latitude *float64
Longitude *float64
}
func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) {
row := q.db.QueryRow(ctx, createRegion, arg.OrgID, arg.Key, arg.Name)
row := q.db.QueryRow(ctx, createRegion,
arg.OrgID,
arg.Key,
arg.Name,
arg.Latitude,
arg.Longitude,
)
var i Region
err := row.Scan(
&i.Key,
@@ -75,6 +83,8 @@ func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Reg
&i.CreatedAt,
&i.ID,
&i.OrgID,
&i.Latitude,
&i.Longitude,
)
return i, err
}
@@ -113,7 +123,7 @@ INSERT INTO regions (org_id, key, name)
VALUES (NULL, $1, coalesce(nullif($2::text, ''), $1))
ON CONFLICT ON CONSTRAINT regions_owner_key_key
DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END
RETURNING key, name, created_at, id, org_id
RETURNING key, name, created_at, id, org_id, latitude, longitude
`
type EnsurePlatformRegionParams struct {
@@ -131,6 +141,8 @@ func (q *Queries) EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRe
&i.CreatedAt,
&i.ID,
&i.OrgID,
&i.Latitude,
&i.Longitude,
)
return i, err
}
@@ -181,7 +193,7 @@ func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (GetAgen
}
const getRegion = `-- name: GetRegion :one
SELECT key, name, created_at, id, org_id FROM regions WHERE id = $1
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions WHERE id = $1
`
func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) {
@@ -193,6 +205,8 @@ func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) {
&i.CreatedAt,
&i.ID,
&i.OrgID,
&i.Latitude,
&i.Longitude,
)
return i, err
}
@@ -257,7 +271,7 @@ func (q *Queries) ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgent
}
const listPlatformRegions = `-- name: ListPlatformRegions :many
SELECT key, name, created_at, id, org_id FROM regions WHERE org_id IS NULL ORDER BY name, key
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions WHERE org_id IS NULL ORDER BY name, key
`
func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
@@ -275,6 +289,8 @@ func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
&i.CreatedAt,
&i.ID,
&i.OrgID,
&i.Latitude,
&i.Longitude,
); err != nil {
return nil, err
}
@@ -287,7 +303,7 @@ func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
}
const listVisibleRegions = `-- name: ListVisibleRegions :many
SELECT key, name, created_at, id, org_id FROM regions ORDER BY org_id IS NULL, name, key
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions ORDER BY org_id IS NULL, name, key
`
// Row-level security limits this to platform regions and the scope's org;
@@ -307,6 +323,8 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
&i.CreatedAt,
&i.ID,
&i.OrgID,
&i.Latitude,
&i.Longitude,
); err != nil {
return nil, err
}
@@ -437,3 +455,23 @@ func (q *Queries) TouchAgent(ctx context.Context, arg TouchAgentParams) error {
_, err := q.db.Exec(ctx, touchAgent, arg.ID, arg.Release)
return err
}
const updateRegionLocation = `-- name: UpdateRegionLocation :execrows
UPDATE regions SET latitude = $1, longitude = $2
WHERE id = $3
`
type UpdateRegionLocationParams struct {
Latitude *float64
Longitude *float64
ID uuid.UUID
}
// Null coordinates remove the location.
func (q *Queries) UpdateRegionLocation(ctx context.Context, arg UpdateRegionLocationParams) (int64, error) {
result, err := q.db.Exec(ctx, updateRegionLocation, arg.Latitude, arg.Longitude, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
+2
View File
@@ -384,6 +384,8 @@ type Region struct {
CreatedAt time.Time
ID uuid.UUID
OrgID *uuid.UUID
Latitude *float64
Longitude *float64
}
type Role struct {
+2
View File
@@ -460,6 +460,8 @@ type Querier interface {
UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error)
UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error)
UpdatePlatformIDP(ctx context.Context, arg UpdatePlatformIDPParams) (PlatformIdentityProvider, error)
// Null coordinates remove the location.
UpdateRegionLocation(ctx context.Context, arg UpdateRegionLocationParams) (int64, error)
UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error)
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
+6 -1
View File
@@ -1,7 +1,12 @@
-- name: CreateRegion :one
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
INSERT INTO regions (org_id, key, name, latitude, longitude) VALUES ($1, $2, $3, $4, $5)
RETURNING *;
-- name: UpdateRegionLocation :execrows
-- Null coordinates remove the location.
UPDATE regions SET latitude = sqlc.narg(latitude), longitude = sqlc.narg(longitude)
WHERE id = sqlc.arg(id);
-- name: EnsurePlatformRegion :one
-- An empty name names a new region after its key and keeps an existing name.
INSERT INTO regions (org_id, key, name)
+58
View File
@@ -118,3 +118,61 @@
font-size: max(16px, 1em);
}
}
/* Region maps: a labelled pin per region, filled when it is selected;
its dot is green while a checker of the region is live. */
.region-pin {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 9px 3px 5px;
border: 1px solid var(--color-rule);
border-radius: 9999px;
background: var(--color-paper);
color: var(--color-ink);
font: 500 11px/1.3 var(--font-sans);
white-space: nowrap;
cursor: pointer;
box-shadow: 0 1px 4px rgb(0 0 0 / 0.25);
transition: background-color 0.15s, color 0.15s, transform 0.15s, box-shadow 0.15s;
}
.region-pin-dot {
flex: none;
width: 8px;
height: 8px;
border-radius: 9999px;
background: var(--color-unknown);
box-shadow: 0 0 0 2px var(--color-paper);
}
.region-pin:not([data-live="0"]) .region-pin-dot { background: var(--color-up); }
.region-pin.is-checked {
border-color: var(--color-ink);
background: var(--color-ink);
color: var(--color-paper);
}
.region-pin.is-checked .region-pin-dot { box-shadow: 0 0 0 2px var(--color-ink); }
.maplibregl-marker.is-hover,
.maplibregl-marker:hover { z-index: 3; }
.is-hover > .region-pin,
.region-pin:hover {
transform: scale(1.1);
box-shadow: 0 2px 8px rgb(0 0 0 / 0.35);
}
@media (pointer: coarse) {
.region-pin {
padding: 6px 11px 6px 8px;
font-size: 12px;
}
}
.region-pin:focus-visible { outline: 2px solid var(--color-maintenance); outline-offset: 2px; }
.region-pick {
width: 14px;
height: 14px;
border: 2px solid var(--color-paper);
border-radius: 9999px;
background: var(--color-down);
box-shadow: 0 1px 4px rgb(0 0 0 / 0.4);
}
.region-row { transition: background-color 0.15s; }
.region-row.is-hover { background: color-mix(in srgb, var(--color-ink) 7%, transparent); }
.region-map .maplibregl-ctrl-attrib { font-size: 10px; }
+171
View File
@@ -588,4 +588,175 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) {
};
for (const t of ed.querySelectorAll("[data-md-tab]")) t.addEventListener("click", () => show(t.dataset.mdTab));
}
// Region maps show the [data-lat][data-lon] elements inside the element
// [data-region-items] selects, on the map server's tiles. MapLibre loads
// only on pages with a map, and the map stays hidden when it cannot.
let maplibre;
const loadMaplibre = (server) =>
(maplibre ??= window.maplibregl
? Promise.resolve(window.maplibregl)
: new Promise((resolve, reject) => {
const css = Object.assign(document.createElement("link"), { rel: "stylesheet", href: `${server}/vendor/maplibre-gl.css` });
const js = Object.assign(document.createElement("script"), { src: `${server}/vendor/maplibre-gl.js` });
js.onload = () => (window.maplibregl ? resolve(window.maplibregl) : reject(new Error("no MapLibre")));
js.onerror = reject;
document.head.append(css, js);
}));
const darkScheme = window.matchMedia?.("(prefers-color-scheme: dark)");
const mapStyle = (server) => `${server}/style-${darkScheme?.matches ? "dark" : "light"}.json`;
// A click on the map fills the coordinates of the location form last
// opened or focused, else the one marked [data-location-default].
let locationTarget = document.querySelector("[data-location-default]");
document.addEventListener("focusin", (ev) => {
const form = ev.target.closest?.("[data-location-form]");
if (form) locationTarget = form;
});
document.addEventListener("click", (ev) => {
const toggle = ev.target.closest("[data-location-toggle]");
if (toggle) {
const row = document.getElementById(toggle.dataset.locationToggle);
row.hidden = !row.hidden;
const form = row.querySelector("[data-location-form]");
if (!row.hidden) {
locationTarget = form;
row.querySelector("[data-location-field]")?.focus();
} else if (locationTarget === form) {
locationTarget = document.querySelector("[data-location-default]");
}
}
const clear = ev.target.closest("[data-location-clear]");
if (clear) {
const form = clear.closest("form");
for (const f of form.querySelectorAll("[data-location-field]")) f.value = "";
form.requestSubmit();
}
});
const initRegionMap = async (box) => {
const server = box.dataset.mapServer;
let gl;
try {
gl = await loadMaplibre(server);
} catch {
return;
}
const items = [...document.querySelectorAll(`${box.dataset.regionItems} [data-lat][data-lon]`)];
const lngLat = (item) => [Number(item.dataset.lon), Number(item.dataset.lat)];
box.hidden = false;
let map;
try {
// Scrolling the page must not zoom the map; the buttons, a double
// click and pinching do. On touch screens one finger scrolls the page
// and two move the map.
const touch = window.matchMedia?.("(pointer: coarse)").matches ?? false;
map = new gl.Map({
container: box,
style: mapStyle(server),
center: [10.45, 51.17],
zoom: 3,
// With cooperative gestures, scrolling zooms only with Ctrl or ⌘.
scrollZoom: touch,
cooperativeGestures: touch,
locale: {
"CooperativeGesturesHandler.MobileHelpText": box.dataset.touchHint,
"CooperativeGesturesHandler.WindowsHelpText": box.dataset.scrollHint.replace("{key}", box.dataset.ctrlKey),
"CooperativeGesturesHandler.MacHelpText": box.dataset.scrollHint.replace("{key}", "⌘"),
},
attributionControl: { compact: true },
});
} catch {
box.hidden = true;
return;
}
let styled = false;
map.on("styledata", () => (styled = true));
map.on("error", () => {
if (!styled) box.hidden = true;
});
map.addControl(new gl.NavigationControl({ showCompass: false }), "top-right");
darkScheme?.addEventListener("change", () => map.setStyle(mapStyle(server)));
// The map may start hidden, as with the regions of passive monitor
// types, so it fits the markers once it has a size.
let fitted = false;
const fit = () => {
map.resize();
if (fitted || !box.clientWidth) return;
fitted = true;
const points = items.map(lngLat);
if (points.length > 1) {
const bounds = points.slice(1).reduce((b, p) => b.extend(p), new gl.LngLatBounds(points[0], points[0]));
// Labels run to the right of their point.
map.fitBounds(bounds, { padding: { top: 40, bottom: 40, left: 40, right: 130 }, maxZoom: 6, duration: 0 });
} else if (points.length === 1) {
map.jumpTo({ center: points[0], zoom: 5 });
}
};
new ResizeObserver(fit).observe(box);
fit();
const selecting = box.dataset.regionMap === "select";
for (const item of items) {
// The list row (a label or table row) and the marker light up together.
const row = item.closest("label, tr") ?? item;
row.classList.add("region-row");
const pin = Object.assign(document.createElement("button"), { type: "button", className: "region-pin", title: item.dataset.name });
pin.dataset.live = item.dataset.live;
pin.append(Object.assign(document.createElement("span"), { className: "region-pin-dot" }), Object.assign(document.createElement("span"), { textContent: item.dataset.name }));
const holder = document.createElement("div");
holder.append(pin);
const marker = new gl.Marker({ element: holder, anchor: "left", offset: [-8, 0] }).setLngLat(lngLat(item)).addTo(map);
const hover = (on) => {
holder.classList.toggle("is-hover", on);
row.classList.toggle("is-hover", on);
};
// Mouse only: a tap would leave the highlight behind.
for (const el of [pin, row]) {
el.addEventListener("pointerenter", (ev) => ev.pointerType === "mouse" && hover(true));
el.addEventListener("pointerleave", () => hover(false));
}
if (selecting) {
// The checkbox stays the source of truth; its change event keeps
// the form's own behaviour.
const paint = () => {
pin.classList.toggle("is-checked", item.checked);
row.classList.toggle("is-checked", item.checked);
pin.setAttribute("aria-pressed", String(item.checked));
};
paint();
item.addEventListener("change", () => {
paint();
// A region ticked in the list comes into view on the map.
const bounds = map.getBounds?.();
if (item.checked && bounds && !bounds.contains(marker.getLngLat())) map.easeTo({ center: marker.getLngLat() });
});
pin.addEventListener("click", (ev) => {
ev.stopPropagation();
if (!item.matches(":disabled")) item.click();
});
} else {
pin.addEventListener("click", (ev) => {
ev.stopPropagation();
item.querySelector("[data-location-toggle]")?.click();
});
}
}
if (selecting) return;
let pick;
map.on("click", (ev) => {
if (!locationTarget) return;
const at = ev.lngLat.wrap ? ev.lngLat.wrap() : ev.lngLat;
const round = (v) => String(Math.round(v * 10000) / 10000);
locationTarget.querySelector('[data-location-field="latitude"]').value = round(at.lat);
locationTarget.querySelector('[data-location-field="longitude"]').value = round(at.lng);
const point = [at.lng, at.lat];
pick ??= new gl.Marker({ element: Object.assign(document.createElement("div"), { className: "region-pick" }) })
.setLngLat(point)
.addTo(map);
pick.setLngLat(point);
});
};
for (const box of document.querySelectorAll("[data-region-map]")) initRegionMap(box);
})();
+46 -15
View File
@@ -84,8 +84,8 @@ type DashboardView struct {
// ArrangeURL turns it on or off, empty when not offered.
Arrange bool
ArrangeURL string
Range string
Ranges []RangeOption
Range string
Ranges []RangeOption
// Unchecked counts the monitors no region has reported for recently.
Unchecked int
// DeadRegions are regions of the monitors without a live checker.
@@ -721,6 +721,19 @@ type RegionOption struct {
Own bool
Checked bool
Live int64
// Lat and Lon place the region on the map; both are nil without a
// location.
Lat, Lon *float64
}
// RegionsMapped reports whether any region of the form has a location.
func (f MonitorForm) RegionsMapped() bool {
for _, r := range f.Regions {
if r.HasLocation() {
return true
}
}
return false
}
// MonitorForm is the data of the monitor editor; ID is empty for new ones.
@@ -1119,20 +1132,38 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
<fieldset class="mb-4" data-hide-for="heartbeat alertmanager" hidden?={ passiveType(f.Type) } disabled?={ f.Type == "heartbeat" }>
<legend class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.regions") }</legend>
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "monitors.regions_hint") }</p>
for _, r := range f.Regions {
<label class="mb-1.5 flex items-center gap-2 text-sm">
<input type="checkbox" name="regions" value={ r.ID } data-multi checked?={ r.Checked } class="accent-ink"/>
{ r.Name }
<span class="font-mono text-xs text-muted">
if r.Own {
{ i18n.T(ctx, "regions.own") }
} else {
{ i18n.T(ctx, "regions.platform") }
}
· { i18n.T(ctx, "regions.live", "Count", int(r.Live)) }
</span>
</label>
if f.RegionsMapped() {
@regionMap("select", "#monitor-regions")
}
<div id="monitor-regions">
for _, r := range f.Regions {
<label class="-mx-2 mb-0.5 flex items-center gap-2 px-2 py-1 text-sm">
<input
type="checkbox"
name="regions"
value={ r.ID }
data-multi
checked?={ r.Checked }
class="accent-ink"
if r.HasLocation() {
data-lat={ coord(r.Lat) }
data-lon={ coord(r.Lon) }
}
data-name={ r.Name }
data-live={ strconv.FormatInt(r.Live, 10) }
/>
{ r.Name }
<span class="font-mono text-xs text-muted">
if r.Own {
{ i18n.T(ctx, "regions.own") }
} else {
{ i18n.T(ctx, "regions.platform") }
}
· { i18n.T(ctx, "regions.live", "Count", int(r.Live)) }
</span>
</label>
}
</div>
</fieldset>
@checkbox(i18n.T(ctx, "sso.field.enabled"), "enabled", f.Enabled)
@submit(i18n.T(ctx, "common.save"))
File diff suppressed because it is too large. Load diff
+71
View File
@@ -0,0 +1,71 @@
package web
import (
"strconv"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
// MapServer serves the map tiles, styles and the MapLibre library the
// region maps load.
const MapServer = "https://maps.zb-server.de"
// coord formats a coordinate for an attribute or input, empty for none.
func coord(f *float64) string {
if f == nil {
return ""
}
return strconv.FormatFloat(*f, 'f', -1, 64)
}
// HasLocation reports whether r has a place on the map.
func (r RegionOption) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
// HasLocation reports whether r has a place on the map.
func (r Region) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
// regionMap is a map of the regions marked with data-lat and data-lon
// inside the element items selects. In "select" mode a click on a marker
// toggles the region's checkbox; in "edit" mode a click on the map fills
// the active [data-location-form]. The script shows it once the map loads.
templ regionMap(mode, items string) {
<div
data-region-map={ mode }
data-region-items={ items }
data-map-server={ MapServer }
data-touch-hint={ i18n.T(ctx, "regions.map_touch_hint") }
data-scroll-hint={ i18n.T(ctx, "regions.map_scroll_hint", "Key", "{key}") }
data-ctrl-key={ i18n.T(ctx, "regions.map_ctrl_key") }
hidden
class="region-map mb-3 h-60 w-full overflow-hidden border border-rule sm:h-72"
></div>
}
// locationFields are the coordinate inputs of a region; empty ones remove
// the location.
templ locationFields(lat, lon *float64) {
<div class="flex flex-wrap gap-3">
for _, f := range []struct {
label, name, value, min, max string
}{
{i18n.T(ctx, "regions.latitude"), "latitude", coord(lat), "-90", "90"},
{i18n.T(ctx, "regions.longitude"), "longitude", coord(lon), "-180", "180"},
} {
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ f.label }</span>
<input
type="number"
step="any"
name={ f.name }
data-number
data-nullable
data-location-field={ f.name }
value={ f.value }
min={ f.min }
max={ f.max }
class="w-36 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink"
/>
</label>
}
</div>
}
+263
View File
@@ -0,0 +1,263 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1118
package web
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import (
"strconv"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
// MapServer serves the map tiles, styles and the MapLibre library the
// region maps load.
const MapServer = "https://maps.zb-server.de"
// coord formats a coordinate for an attribute or input, empty for none.
func coord(f *float64) string {
if f == nil {
return ""
}
return strconv.FormatFloat(*f, 'f', -1, 64)
}
// HasLocation reports whether r has a place on the map.
func (r RegionOption) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
// HasLocation reports whether r has a place on the map.
func (r Region) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
// regionMap is a map of the regions marked with data-lat and data-lon
// inside the element items selects. In "select" mode a click on a marker
// toggles the region's checkbox; in "edit" mode a click on the map fills
// the active [data-location-form]. The script shows it once the map loads.
func regionMap(mode, items string) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div data-region-map=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(mode).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 33, Col: 24}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\" data-region-items=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(items).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 34, Col: 27}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\" data-map-server=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templruntime.NewAttributeExpression(MapServer).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 35, Col: 29}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\" data-touch-hint=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_touch_hint")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 36, Col: 57}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "\" data-scroll-hint=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_scroll_hint", "Key", "{key}")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 37, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\" data-ctrl-key=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_ctrl_key")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 38, Col: 53}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\" hidden class=\"region-map mb-3 h-60 w-full overflow-hidden border border-rule sm:h-72\"></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
// locationFields are the coordinate inputs of a region; empty ones remove
// the location.
func locationFields(lat, lon *float64) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<div class=\"flex flex-wrap gap-3\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, f := range []struct {
label, name, value, min, max string
}{
{i18n.T(ctx, "regions.latitude"), "latitude", coord(lat), "-90", "90"},
{i18n.T(ctx, "regions.longitude"), "longitude", coord(lon), "-180", "180"},
} {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<label class=\"mb-4 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(f.label)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 55, Col: 94}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</span> <input type=\"number\" step=\"any\" name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.name).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 59, Col: 18}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "\" data-number data-nullable data-location-field=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.name).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 62, Col: 33}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.value).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 63, Col: 20}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "\" min=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.min).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 64, Col: 16}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "\" max=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.max).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 65, Col: 16}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var14)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "\" class=\"w-36 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink\"></label>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
var _ = templruntime.GeneratedTemplate
+56 -7
View File
@@ -1,6 +1,10 @@
package web
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
import (
"strconv"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
)
// Region is a row in a region list.
type Region struct {
@@ -12,6 +16,9 @@ type Region struct {
// Manageable regions can be deleted on the current page.
Manageable bool
Instances int64
// Lat and Lon place the region on the map; both are nil without a
// location.
Lat, Lon *float64
}
// Agent is a checker or status page server.
@@ -65,23 +72,33 @@ type RegionsView struct {
templ regionsBody(v RegionsView) {
<section class="mb-12">
@sectionHeading("regions.list")
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "regions.location_pick_hint") }</p>
@regionMap("edit", "#region-list")
<div class="overflow-x-auto">
<table class="w-full text-left text-sm">
<thead class="border-b border-rule text-xs uppercase tracking-wider text-muted">
<tr>
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "sso.field.name") }</th>
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.key") }</th>
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.owner") }</th>
<th class="hidden py-2 pr-4 font-medium sm:table-cell">{ i18n.T(ctx, "regions.key") }</th>
<th class="hidden py-2 pr-4 font-medium sm:table-cell">{ i18n.T(ctx, "regions.owner") }</th>
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.instances") }</th>
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.location") }</th>
<th class="py-2"></th>
</tr>
</thead>
<tbody class="divide-y divide-rule">
<tbody id="region-list" class="divide-y divide-rule">
for _, r := range v.Regions {
<tr>
<tr
if r.HasLocation() {
data-lat={ coord(r.Lat) }
data-lon={ coord(r.Lon) }
}
data-name={ r.Name }
data-live={ strconv.FormatInt(r.Instances, 10) }
>
<td class="py-2.5 pr-4">{ r.Name }</td>
<td class="py-2.5 pr-4 font-mono text-xs">{ r.Key }</td>
<td class="py-2.5 pr-4">
<td class="hidden py-2.5 pr-4 font-mono text-xs sm:table-cell">{ r.Key }</td>
<td class="hidden py-2.5 pr-4 sm:table-cell">
if r.Platform {
<span class="text-muted">{ i18n.T(ctx, "regions.platform") }</span>
} else {
@@ -91,12 +108,41 @@ templ regionsBody(v RegionsView) {
<td class="py-2.5 pr-4 font-mono text-xs">
<span class={ templ.KV("text-up", r.Instances > 0), templ.KV("text-unknown", r.Instances == 0) }>●</span> { i18n.T(ctx, "regions.live", "Count", int(r.Instances)) }
</td>
<td class="py-2.5 pr-4 font-mono text-xs">
if r.HasLocation() {
{ coord(r.Lat) }, { coord(r.Lon) }
} else {
<span class="text-muted">–</span>
}
if r.Manageable {
<button type="button" data-location-toggle={ "location-" + r.ID } class="ml-2 font-sans text-muted hover:text-ink">{ i18n.T(ctx, "regions.location_set") }</button>
}
</td>
<td class="py-2.5 text-right">
if r.Manageable {
<button type="button" data-delete={ v.APIBase + "/regions/" + r.ID } data-confirm={ i18n.T(ctx, "regions.delete_confirm") } class="text-muted hover:text-down">{ i18n.T(ctx, "regions.delete") }</button>
}
</td>
</tr>
if r.Manageable {
<tr id={ "location-" + r.ID } hidden>
<td colspan="6" class="py-3">
<form data-api={ v.APIBase + "/regions/" + r.ID } data-method="patch" data-next={ v.Next } data-location-form>
@formError()
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "regions.location_for", "Name", r.Name) }</p>
<div class="flex flex-wrap items-end gap-4">
@locationFields(r.Lat, r.Lon)
<div class="mb-4 flex gap-3">
<button type="submit" class="bg-ink px-3 py-1.5 text-sm font-medium text-paper hover:opacity-90 disabled:opacity-50">{ i18n.T(ctx, "common.save") }</button>
if r.HasLocation() {
<button type="button" data-location-clear class="text-sm text-muted hover:text-down">{ i18n.T(ctx, "regions.location_clear") }</button>
}
</div>
</div>
</form>
</td>
</tr>
}
}
</tbody>
</table>
@@ -109,6 +155,9 @@ templ regionsBody(v RegionsView) {
@formError()
@valueField(i18n.T(ctx, "regions.key"), "key", "", "office-berlin", true)
@valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Office Berlin", false)
<div data-location-form data-location-default>
@locationFields(nil, nil)
</div>
@submit(i18n.T(ctx, "regions.create"))
</form>
</section>
File diff suppressed because it is too large. Load diff
+106
View File
@@ -0,0 +1,106 @@
<!doctype html><html><body data-msg-network="net">
<form id="monitor">
<div id="select-map" data-region-map="select" data-region-items="#monitor-regions" data-map-server="stub" data-touch-hint="t" data-scroll-hint="{key} s" data-ctrl-key="Ctrl" hidden style="width:300px;height:200px"></div>
<div id="monitor-regions">
<label><input type="checkbox" name="regions" value="r1" data-multi checked data-lat="50.11" data-lon="8.68" data-name="Frankfurt" data-live="2"></label>
<label><input type="checkbox" name="regions" value="r2" data-multi data-lat="40.71" data-lon="-74.0" data-name="New York" data-live="0"></label>
<label><input type="checkbox" name="regions" value="r3" data-multi data-name="Office" data-live="1"></label>
</div>
</form>
<div id="edit-map" data-region-map="edit" data-region-items="#region-list" data-map-server="stub" data-touch-hint="t" data-scroll-hint="{key} s" data-ctrl-key="Ctrl" hidden style="width:300px;height:200px"></div>
<table><tbody id="region-list">
<tr data-lat="50.11" data-lon="8.68" data-name="Frankfurt" data-live="2"><td><button type="button" id="toggle" data-location-toggle="location-r1">set</button></td></tr>
<tr id="location-r1" hidden><td><form data-api="/org/regions/r1" data-method="patch" data-next="#saved" data-location-form id="row-form">
<input name="latitude" data-number data-nullable data-location-field="latitude" value="50.11">
<input name="longitude" data-number data-nullable data-location-field="longitude" value="8.68">
<button type="submit">save</button><button type="button" id="clear" data-location-clear>clear</button>
</form></td></tr>
</tbody></table>
<form data-api="/org/regions" id="create"><div data-location-form data-location-default>
<input name="latitude" data-number data-nullable data-location-field="latitude">
<input name="longitude" data-number data-nullable data-location-field="longitude">
</div></form>
<pre id="out"></pre>
<script>
const sent = [];
window.axios = { create: () => ({ interceptors: { request: { use() {} } }, request: async (cfg) => { sent.push(cfg); return { data: {} }; } }) };
const maps = [];
window.maplibregl = {
Map: class {
constructor(opts) { this.container = opts.container; this.handlers = {}; this.style = opts.style; maps.push(this); }
on(ev, fn) { (this.handlers[ev] ??= []).push(fn); }
fire(ev, arg) { for (const fn of this.handlers[ev] ?? []) fn(arg); }
addControl() {}
resize() {}
fitBounds(b) { this.bounds = b.points; }
jumpTo(o) { this.center = o.center; }
setStyle(s) { this.style = s; }
},
Marker: class {
constructor(o) { this.el = o.element; }
setLngLat(p) { this.at = p; this.el.dataset.at = p.join(","); return this; }
getLngLat() { return this.at; }
addTo(map) { map.container.append(this.el); return this; }
},
NavigationControl: class {},
LngLatBounds: class {
constructor(a) { this.points = [a]; }
extend(p) { this.points.push(p); return this; }
},
};
</script>
<script src="../assets/app.js"></script>
<script>
(async () => {
const out = [];
const check = (name, got, want) => {
const g = JSON.stringify(got), w = JSON.stringify(want);
out.push((g === w ? "PASS " : "FAIL ") + name + (g === w ? "" : " got=" + g + " want=" + w));
};
await new Promise((r) => setTimeout(r, 50));
const sel = document.getElementById("select-map");
const markers = () => [...sel.querySelectorAll(".region-pin")];
const box = (v) => document.querySelector(`[value="${v}"]`);
check("select map shown", sel.hidden, false);
check("light style", maps[0].style, "stub/style-light.json");
check("markers for located regions", markers().map((m) => m.title), ["Frankfurt", "New York"]);
check("fits all markers", maps[0].bounds, [[8.68, 50.11], [-74, 40.71]]);
check("checked marker filled", markers().map((m) => m.classList.contains("is-checked")), [true, false]);
check("idle region marked", markers()[1].dataset.live, "0");
markers()[1].click();
check("marker click ticks checkbox", box("r2").checked, true);
check("marker follows", markers()[1].classList.contains("is-checked"), true);
check("row follows", box("r2").closest("label").classList.contains("is-checked"), true);
markers()[0].dispatchEvent(new PointerEvent("pointerenter", { pointerType: "touch" }));
check("a tap leaves no highlight", box("r1").closest("label").classList.contains("is-hover"), false);
markers()[0].dispatchEvent(new PointerEvent("pointerenter", { pointerType: "mouse" }));
check("hovering a marker lights its row", box("r1").closest("label").classList.contains("is-hover"), true);
box("r2").closest("label").dispatchEvent(new PointerEvent("pointerenter", { pointerType: "mouse" }));
check("hovering a row lights its marker", markers()[1].parentElement.classList.contains("is-hover"), true);
box("r1").click();
check("checkbox untick clears marker", markers()[0].classList.contains("is-checked"), false);
const edit = maps[1];
const click = (lat, lng) => edit.fire("click", { lngLat: { lat, lng, wrap() { return { lat, lng: lng > 180 ? lng - 360 : lng }; } } });
click(48.137154, 11.576124);
const create = document.getElementById("create");
check("map click fills create form", [create.elements.latitude.value, create.elements.longitude.value], ["48.1372", "11.5761"]);
check("pick marker shown", document.querySelector("#edit-map .region-pick")?.dataset.at, "11.576124,48.137154");
document.querySelector("#edit-map .region-pin").click();
check("marker click opens its row", document.getElementById("location-r1").hidden, false);
click(52.52, 373.4);
const row = document.getElementById("row-form");
check("map click fills open row", [row.elements.latitude.value, row.elements.longitude.value], ["52.52", "13.4"]);
check("create form untouched", create.elements.latitude.value, "48.1372");
document.getElementById("clear").click();
await new Promise((r) => setTimeout(r, 50));
check("clear sends nulls", sent.at(-1) && [sent.at(-1).method, sent.at(-1).url, sent.at(-1).data], ["patch", "/org/regions/r1", { latitude: null, longitude: null }]);
document.getElementById("toggle").click();
check("toggle closes row", document.getElementById("location-r1").hidden, true);
click(1, 2);
check("closed row falls back to create form", create.elements.latitude.value, "1");
document.getElementById("out").textContent = out.join("\n");
})();
</script>
</body></html>
+15
View File
@@ -0,0 +1,15 @@
<!doctype html><html><body data-msg-network="net">
<div id="map" data-region-map="select" data-region-items="#items" data-map-server="./missing" data-touch-hint="t" data-scroll-hint="{key} s" data-ctrl-key="Ctrl" hidden></div>
<div id="items"><input type="checkbox" data-lat="1" data-lon="2" data-name="x" data-live="1"></div>
<pre id="out"></pre>
<script>
window.axios = { create: () => ({ interceptors: { request: { use() {} } } }) };
</script>
<script src="../assets/app.js"></script>
<script>
setTimeout(() => {
const ok = document.getElementById("map").hidden && !document.querySelector(".region-pin");
document.getElementById("out").textContent = (ok ? "PASS" : "FAIL") + " map stays hidden when MapLibre cannot load";
}, 500);
</script>
</body></html>