Compare commits

..
Author SHA1 Message Date
Sebastian UnterschützandClaude Opus 5.5 282ab27f81 feat(statuspages): page every group on its own and filter outages
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 12m33s
ci / lint (push) Skipped
ci / lint (pull_request) Successful in 11m3s
ci / build (pull_request) Successful in 18m44s
ci / image (pull_request) Successful in 5m29s
Paging all components of a status page at once left out whole groups on
every page, which confused visitors. Every group now shows its first 25
components and pages them on its own (?p.<group>=N), keeping the pages
of the other groups. Links jump back to the group.

Visitors can also show only the components with an outage or degraded
(?problems=1); groups without any are left out. The search stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-28 14:35:24 +01:00
Sebi 9d01b62b98 Merge pull request 'fix(platform): document the methods of the gzip writer' (#166) from fix/lint-compress into main
ci / test (push) Successful in 16m14s
ci / image (push) Successful in 3m36s
release / release (push) Successful in 37m38s
ci / lint (push) Successful in 6m13s
ci / build (push) Successful in 17m22s
2026-11-27 06:19:53 +00:00
Sebastian UnterschützandClaude Opus 5.5 4aa22327c2 fix(platform): document the methods of the gzip writer
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / image (pull_request) Successful in 5m37s
ci / test (pull_request) Successful in 8m55s
ci / build (pull_request) Successful in 20m17s
ci / lint (pull_request) Successful in 12m18s
golangci-lint (revive) requires comments on exported methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-27 07:18:09 +01:00
Sebi 965848017d Merge pull request 'perf(statuspages): paging, search and gzip for large status pages' (#165) from perf/statuspage-editor-large-orgs into main
ci / test (push) Successful in 16m16s
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (push) Failing after 6m35s
release / release (push) Failing after 1h51m43s
2026-11-26 23:12:06 +00:00
Sebastian UnterschützandClaude Opus 5.5 b051f6c430 perf(statuspages): page, search and compress public status pages
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 13m30s
ci / image (pull_request) Skipped
ci / lint (pull_request) Failing after 13m31s
ci / build (pull_request) Skipped
A status page with 3128 components was 30 MB of uncompressed HTML: all
components at once, each with 90 bars carrying a tooltip.

- The status page server gzips text responses.
- Status pages list 50 components at a time (?page=N) and offer a search
  (?q=) over component and group names once they have more than one
  page. Group headings keep the status and count of the whole group.
  Single-file exports still list every component.
- Rows linking a detail page draw their bars as one path per status,
  without tooltips; the detail page keeps them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-27 00:10:27 +01:00
Sebastian UnterschützandClaude Opus 5.5 52d2ce25c9 perf(statuspages): page the monitor list and batch the group import
ci / lint (pull_request) Successful in 10m59s
ci / test (pull_request) Successful in 12m44s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / build (pull_request) Successful in 18m14s
ci / image (pull_request) Canceled after 1m1s
With thousands of monitors on a status page the editor was tens of
megabytes, as every row carried the options of all groups, and
importing the monitor groups updated each monitor in its own statement.

- The monitors of the editor are shown 50 at a time. All rows stay in
  the form, as saving replaces the page's monitors.
- Rows carry their own group only and get the other options from the
  row template once shown or focused.
- The filter matches a monitor's name and group path only, no longer
  the names of the groups in its select.
- The import creates the groups one nesting level at a time and files
  all monitors in one statement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 23:38:08 +01:00
20 changed files with 4943 additions and 3464 deletions

No files matched your search

+1
View File
@@ -88,6 +88,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
return err
}
health.Register(r)
r.Use(platform.Compress())
r.StaticFS("/static", web.Static())
pages.Mount(r)
go pages.Run(ctx)
+41 -30
View File
@@ -256,7 +256,7 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
pageID := uuid.MustParse(c.Param("id"))
p := current(c)
ctx := c.Request.Context()
var created []store.StatusPageGroup
var created []pageGroupView
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
return err
@@ -290,54 +290,66 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
return err
}
mapped := map[uuid.UUID]store.StatusPageGroup{}
var createErr error
// Large organizations have thousands of monitors and hundreds of
// groups, so both are written in a few statements: the groups one
// level of nesting at a time, as parents must exist before their
// children, the monitors all at once.
mapped := map[uuid.UUID]pageGroupView{}
var levels []store.CreateStatusPageGroupsParams
posByParent := map[uuid.UUID]int32{}
tree.walk(func(g store.MonitorGroup, _ int) {
if createErr != nil || !needed[g.ID] {
tree.walk(func(g store.MonitorGroup, depth int) {
if !needed[g.ID] {
return
}
var parentKey uuid.UUID
var parentID *uuid.UUID
if g.ParentID != nil {
if parent, ok := mapped[*g.ParentID]; ok {
pid := parent.ID
parentID = &pid
parentKey = pid
}
}
var parentKey uuid.UUID
if parentID != nil {
parentKey = *parentID
}
pos := posByParent[parentKey]
posByParent[parentKey] = pos + 1
row, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
PageID: pageID,
OrgID: p.Org.ID,
ParentID: parentID,
Name: g.Name,
Position: pos,
})
if err != nil {
createErr = err
return
}
row := pageGroupView{ID: uuid.New(), Name: g.Name, ParentID: parentID, Position: pos}
mapped[g.ID] = row
created = append(created, row)
for len(levels) <= depth {
levels = append(levels, store.CreateStatusPageGroupsParams{PageID: pageID, OrgID: p.Org.ID})
}
l := &levels[depth]
l.Ids = append(l.Ids, row.ID)
l.ParentIds = append(l.ParentIds, parentKey)
l.Names = append(l.Names, row.Name)
l.Positions = append(l.Positions, row.Position)
})
if createErr != nil {
return createErr
for _, l := range levels {
if len(l.Ids) == 0 {
continue
}
if err := q.CreateStatusPageGroups(ctx, l); err != nil {
return err
}
}
set := store.SetStatusPageMonitorGroupsParams{PageID: pageID}
for _, m := range listed {
var gid *uuid.UUID
var gid uuid.UUID
section := ""
if m.MonitorGroupID != nil {
if g, ok := mapped[*m.MonitorGroupID]; ok {
id := g.ID
gid = &id
gid = g.ID
section = g.Name
}
}
if err := q.SetStatusPageMonitorGroup(ctx, store.SetStatusPageMonitorGroupParams{
PageID: pageID, MonitorID: m.MonitorID, GroupID: gid, Section: section,
}); err != nil {
set.MonitorIds = append(set.MonitorIds, m.MonitorID)
set.GroupIds = append(set.GroupIds, gid)
set.Sections = append(set.Sections, section)
}
if len(set.MonitorIds) > 0 {
if err := q.SetStatusPageMonitorGroups(ctx, set); err != nil {
return err
}
}
@@ -351,11 +363,10 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
internalError(c, err)
return
}
out := make([]pageGroupView, 0, len(created))
for _, g := range created {
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
if created == nil {
created = []pageGroupView{}
}
c.JSON(http.StatusOK, gin.H{"groups": out})
c.JSON(http.StatusOK, gin.H{"groups": created})
}
// resolvePageMonitorGroup returns the status page group ID and section label
+8
View File
@@ -1261,6 +1261,13 @@
"page.status.outage": "Größere Störung",
"page.status.unknown": "Status derzeit nicht verfügbar",
"page.today": "Heute",
"page.pages": "Seite {{.Page}} von {{.Pages}}",
"page.search": "Komponenten suchen",
"page.search_submit": "Suchen",
"page.search_clear": "Alle anzeigen",
"page.search_none": "Keine Komponente passt zur Suche.",
"page.filter_problems": "Nur Ausfälle ({{.Count}})",
"page.filter_no_problems": "Keine Komponente hat einen Ausfall.",
"page.updated": "Aktualisiert {{.Time}}",
"pager.earlier": "Frühere",
"pager.first": "Zum Anfang",
@@ -1310,6 +1317,7 @@
"pages.monitors_filter": "Monitore filtern",
"pages.monitors_all": "Alle hinzufügen",
"pages.monitors_none": "Alle entfernen",
"pages.monitors_range": "{from}–{to} von {total}",
"pages.no_group": "Ohne Gruppe",
"pages.open": "Öffnen",
"pages.own_servers": "Die Statusseiten dieser Organisation liefern nur ihre eigenen Statusseiten-Server aus, nicht die der Plattform. Ruf sie über die Adresse deiner Server auf oder verbinde eine eigene Domain, die auf sie zeigt.",
+8
View File
@@ -1261,6 +1261,13 @@
"page.status.outage": "Major outage",
"page.status.unknown": "Status currently unavailable",
"page.today": "Today",
"page.pages": "Page {{.Page}} of {{.Pages}}",
"page.search": "Search components",
"page.search_submit": "Search",
"page.search_clear": "Show all",
"page.search_none": "No component matches the search.",
"page.filter_problems": "Outages only ({{.Count}})",
"page.filter_no_problems": "No component has an outage.",
"page.updated": "Updated {{.Time}}",
"pager.earlier": "Earlier",
"pager.first": "To the start",
@@ -1310,6 +1317,7 @@
"pages.monitors_filter": "Filter monitors",
"pages.monitors_all": "Add all",
"pages.monitors_none": "Remove all",
"pages.monitors_range": "{from}–{to} of {total}",
"pages.no_group": "No group",
"pages.open": "Open",
"pages.own_servers": "Your organization's own status page servers serve its pages; the platform's do not. Open them at the address of your servers or connect a custom domain pointing at them.",
+142
View File
@@ -0,0 +1,142 @@
package platform
import (
"compress/gzip"
"io"
"mime"
"net/http"
"strconv"
"strings"
"sync"
"github.com/gin-gonic/gin"
)
// compressMin is the smallest body worth compressing, for responses that
// state their length.
const compressMin = 1024
var gzipWriters = sync.Pool{New: func() any {
w, _ := gzip.NewWriterLevel(io.Discard, gzip.DefaultCompression)
return w
}}
// Compress gzips text responses (HTML, CSS, JavaScript, JSON, XML, SVG) for
// clients that accept it. Status pages list thousands of components in
// markup that repeats itself, so this shrinks them many times over.
func Compress() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Add("Vary", "Accept-Encoding")
if c.Request.Method == http.MethodHead || !acceptsGzip(c.Request.Header.Get("Accept-Encoding")) {
c.Next()
return
}
w := &gzipWriter{ResponseWriter: c.Writer}
c.Writer = w
defer w.finish()
c.Next()
}
}
// acceptsGzip reports whether an Accept-Encoding header allows gzip.
func acceptsGzip(header string) bool {
for _, part := range strings.Split(header, ",") {
name, params, _ := strings.Cut(part, ";")
name = strings.ToLower(strings.TrimSpace(name))
if name != "gzip" && name != "*" {
continue
}
for _, p := range strings.Split(params, ";") {
k, v, _ := strings.Cut(strings.TrimSpace(p), "=")
if strings.EqualFold(k, "q") {
if q, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil && q == 0 {
return false
}
}
}
return true
}
return false
}
func compressible(contentType string) bool {
mt, _, err := mime.ParseMediaType(contentType)
if err != nil {
return false
}
switch {
case strings.HasPrefix(mt, "text/"):
return true
case mt == "application/json", mt == "application/javascript", mt == "image/svg+xml",
mt == "application/xml", mt == "application/rss+xml", mt == "application/atom+xml":
return true
}
return strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "+xml")
}
// gzipWriter decides at the first write whether to compress, when the
// handler has set the status and headers.
type gzipWriter struct {
gin.ResponseWriter
decided bool
gz *gzip.Writer
}
func (w *gzipWriter) decide() {
w.decided = true
h := w.Header()
switch status := w.Status(); {
case status < 200, status == http.StatusNoContent, status == http.StatusNotModified, status == http.StatusPartialContent:
return
}
if h.Get("Content-Encoding") != "" || !compressible(h.Get("Content-Type")) {
return
}
if n, err := strconv.Atoi(h.Get("Content-Length")); err == nil && n < compressMin {
return
}
h.Set("Content-Encoding", "gzip")
h.Del("Content-Length")
if etag := h.Get("ETag"); etag != "" && !strings.HasPrefix(etag, "W/") {
h.Set("ETag", "W/"+etag)
}
w.gz = gzipWriters.Get().(*gzip.Writer)
w.gz.Reset(w.ResponseWriter)
}
// Write compresses b if decide chose to, which it does at the first write.
func (w *gzipWriter) Write(b []byte) (int, error) {
if !w.decided {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
w.decide()
}
if w.gz == nil {
return w.ResponseWriter.Write(b)
}
return w.gz.Write(b)
}
// WriteString writes s like Write, so strings are compressed as well.
func (w *gzipWriter) WriteString(s string) (int, error) {
return w.Write([]byte(s))
}
// Flush sends what is compressed so far, for responses that stream.
func (w *gzipWriter) Flush() {
if w.gz != nil {
_ = w.gz.Flush()
}
w.ResponseWriter.Flush()
}
func (w *gzipWriter) finish() {
if w.gz == nil {
return
}
_ = w.gz.Close()
w.gz.Reset(io.Discard)
gzipWriters.Put(w.gz)
w.gz = nil
}
+86
View File
@@ -0,0 +1,86 @@
package platform
import (
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
func TestCompress(t *testing.T) {
gin.SetMode(gin.TestMode)
page := strings.Repeat("<li>component</li>", 2000)
r := gin.New()
r.Use(Compress())
r.GET("/page", func(c *gin.Context) {
c.Header("Content-Type", "text/html; charset=utf-8")
c.Status(http.StatusOK)
for i := 0; i < 2000; i++ {
_, _ = c.Writer.WriteString("<li>component</li>")
}
})
r.GET("/small", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
r.GET("/sized", func(c *gin.Context) {
c.Header("Content-Length", strconv.Itoa(len("tiny")))
c.Data(http.StatusOK, "text/plain", []byte("tiny"))
})
r.GET("/png", func(c *gin.Context) { c.Data(http.StatusOK, "image/png", []byte(page)) })
r.GET("/json", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"page": page}) })
r.GET("/notmodified", func(c *gin.Context) { c.Status(http.StatusNotModified) })
get := func(path, accept string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
if accept != "" {
req.Header.Set("Accept-Encoding", accept)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec
}
gunzip := func(t *testing.T, rec *httptest.ResponseRecorder) string {
t.Helper()
zr, err := gzip.NewReader(rec.Body)
if err != nil {
t.Fatalf("gzip.NewReader() error = %v", err)
}
b, err := io.ReadAll(zr)
if err != nil {
t.Fatalf("reading gzip body error = %v", err)
}
return string(b)
}
rec := get("/page", "br, gzip;q=0.8")
if rec.Header().Get("Content-Encoding") != "gzip" || rec.Header().Get("Vary") != "Accept-Encoding" {
t.Fatalf("headers = %v, want gzip with Vary", rec.Header())
}
if rec.Body.Len() >= len(page)/10 {
t.Errorf("compressed size = %d, want far below %d", rec.Body.Len(), len(page))
}
if got := gunzip(t, rec); got != page {
t.Errorf("decompressed body differs: %d bytes, want %d", len(got), len(page))
}
if rec := get("/json", "gzip"); rec.Header().Get("Content-Encoding") != "gzip" || !strings.Contains(gunzip(t, rec), "component") {
t.Errorf("JSON not compressed: %v", rec.Header())
}
for _, tc := range []struct{ path, accept string }{
{"/page", ""},
{"/page", "gzip;q=0, deflate"},
{"/page", "identity"},
{"/sized", "gzip"},
{"/png", "gzip"},
{"/notmodified", "gzip"},
} {
if rec := get(tc.path, tc.accept); rec.Header().Get("Content-Encoding") != "" {
t.Errorf("GET %s with %q compressed, want plain", tc.path, tc.accept)
}
}
if rec := get("/page", "*"); rec.Header().Get("Content-Encoding") != "gzip" {
t.Errorf("Accept-Encoding * not compressed")
}
}
+34
View File
@@ -19,8 +19,10 @@ import (
"log/slog"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
@@ -331,9 +333,41 @@ func (s *Server) serve(c *gin.Context) {
}
s.localizeRequest(c)
c.Header("Cache-Control", "public, max-age=30")
assets.PageSize = componentsPerPage
assets.Pages = sectionPages(c.Request.URL.Query())
if q := c.Query("q"); len(q) <= maxComponentQuery {
assets.Query = q
}
assets.OnlyProblems = c.Query("problems") == "1"
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), assets))
}
// componentsPerPage is how many of its own components a section of a
// status page lists at a time; organizations put thousands on one.
const componentsPerPage = 25
// maxComponentQuery bounds the search for components.
const maxComponentQuery = 100
// maxPagedSections bounds the sections a request pages.
const maxPagedSections = 100
// sectionPages reads the pages of sections a request asks for, as
// "p.<key>=<page from 1>".
func sectionPages(q url.Values) map[string]int {
pages := map[string]int{}
for k, vs := range q {
key, ok := strings.CutPrefix(k, "p.")
if !ok || key == "" || len(vs) == 0 || len(pages) >= maxPagedSections {
continue
}
if n, err := strconv.Atoi(vs[0]); err == nil && n > 1 {
pages[key] = n - 1
}
}
return pages
}
// serveComponent renders one component's public detail page from the cached
// snapshot when the status page has enabled ShowDetails.
func (s *Server) serveComponent(c *gin.Context, e entry, compID string, assets web.PublicAssets) {
+82
View File
@@ -3,6 +3,7 @@ package statuspage
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
@@ -608,3 +609,84 @@ func TestEventsRefreshPagesAtOnce(t *testing.T) {
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
}
}
// Every group of a page with many components lists them a page at a time,
// and visitors can search them or show those with an outage only.
func TestComponentPagingAndSearch(t *testing.T) {
comp := func(id, name, status string) agentapi.Component {
return agentapi.Component{ID: id, Name: name, Status: status, Days: []agentapi.Day{{Date: "2026-11-26", Uptime: 1}}}
}
core := agentapi.Section{Name: "Core"}
for i := 0; i < 120; i++ {
st := agentapi.PageOperational
if i == 7 {
st = agentapi.PageDegraded
}
core.Components = append(core.Components, comp(fmt.Sprintf("c%03d", i), fmt.Sprintf("web-%03d", i), st))
}
edge := agentapi.Section{Name: "Edge"}
for i := 0; i < 10; i++ {
st := agentapi.PageOperational
if i == 3 {
st = agentapi.PageOutage
}
edge.Components = append(edge.Components, comp(fmt.Sprintf("e%d", i), fmt.Sprintf("edge-%d", i), st))
}
core.Children = []agentapi.Section{edge}
other := agentapi.Section{Name: "Other"}
for i := 0; i < 30; i++ {
other.Components = append(other.Components, comp(fmt.Sprintf("o%02d", i), fmt.Sprintf("other-%02d", i), agentapi.PageOperational))
}
now := time.Now()
h := newHarness(t, &fakeSource{pages: map[string]agentapi.PageSnapshot{
"|acme": {Title: "Acme status", Status: agentapi.PageOperational, ShowDetails: true, Sections: []agentapi.Section{core, other}},
"|calm": {Title: "Calm", Status: agentapi.PageOperational, Sections: []agentapi.Section{other}},
}}, t.TempDir(), &now)
if _, body := h.get("status.example.test", "/calm?problems=1"); !strings.Contains(body, "Keine Komponente hat einen Ausfall.") || strings.Contains(body, "other-00") {
t.Errorf("outages only without any lacks the notice")
}
tests := []struct {
path string
has, hasNot []string
}{
// Every group shows its first page.
{"/acme", []string{"web-000", "web-024", "Seite 1 von 5", "edge-0", "edge-9", "other-00", "other-24", "Seite 1 von 2",
`id="g-0"`, `id="g-0.0"`, `id="g-1"`, `href="/acme?p.0=2#g-0"`, `href="/acme?p.1=2#g-1"`, `<path d="M0 0h3v22h-3z"`, "Nur Ausfälle (2)"},
[]string{"web-025", "other-25", `rel="prev"`, "<rect", "Alle anzeigen"}},
// Groups page on their own and keep the others' pages.
{"/acme?p.0=2", []string{"web-025", "web-049", "Seite 2 von 5", `href="/acme#g-0"`, "edge-0", "other-00"}, []string{"web-024", "web-050"}},
{"/acme?p.0=2&p.1=2", []string{"web-025", "other-29", `href="/acme?p.0=3&amp;p.1=2#g-0"`, `href="/acme?p.0=2#g-1"`}, []string{"other-00"}},
{"/acme?p.0=99", []string{"Seite 5 von 5", "web-119", "edge-9"}, nil},
{"/acme?p.0=x", []string{"Seite 1 von 5"}, nil},
// Outages only: degraded and down components, groups without any left out.
{"/acme?problems=1", []string{"web-007", "edge-3", ">Core<", ">Edge<", ">130<", "checked", "Alle anzeigen"},
[]string{"web-000", "edge-0", ">Other<", "Seite 1 von"}},
{"/acme?problems=1&q=edge", []string{"edge-3"}, []string{"web-007", "edge-0"}},
{"/acme?q=EDGE-", []string{"edge-0", "edge-9", `value="EDGE-"`, "Alle anzeigen"}, []string{"web-", "other-"}},
{"/acme?q=edge", []string{"edge-0", "edge-9", ">Core<"}, []string{"web-", ">Other<"}},
{"/acme?q=web-11", []string{"web-110", "web-119"}, []string{"web-109", "edge-"}},
{"/acme?q=nothing", []string{"Keine Komponente passt zur Suche."}, []string{"web-", "edge-"}},
}
for _, tt := range tests {
code, body := h.get("status.example.test", tt.path)
if code != http.StatusOK {
t.Errorf("GET %s = %d", tt.path, code)
continue
}
for _, s := range tt.has {
if !strings.Contains(body, s) {
t.Errorf("GET %s lacks %q", tt.path, s)
}
}
for _, s := range tt.hasNot {
if strings.Contains(body, s) {
t.Errorf("GET %s has %q", tt.path, s)
}
}
}
// The detail page keeps the tooltips of the bars.
if _, body := h.get("status.example.test", "/acme/components/c000"); !strings.Contains(body, "<title>2026-11-26") {
t.Errorf("component page lacks the bar tooltips")
}
}
+7 -1
View File
@@ -90,6 +90,10 @@ type Querier interface {
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error)
CreateStatusPageGroup(ctx context.Context, arg CreateStatusPageGroupParams) (StatusPageGroup, error)
// Creates many groups of a page at once, with ids the caller chose. Parents
// must exist before their children are created; a nil parent id (all
// zeros) means none.
CreateStatusPageGroups(ctx context.Context, arg CreateStatusPageGroupsParams) error
CreateSupportTicket(ctx context.Context, arg CreateSupportTicketParams) (SupportTicket, error)
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
DailyBuckets(ctx context.Context, arg DailyBucketsParams) ([]DailyBucketsRow, error)
@@ -395,7 +399,9 @@ type Querier interface {
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
// Changing the domain drops a previous verification and its checks.
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error
// Files many monitors of a page at once; a nil group id (all zeros) files
// a monitor under none.
SetStatusPageMonitorGroups(ctx context.Context, arg SetStatusPageMonitorGroupsParams) error
SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error)
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
+17 -3
View File
@@ -100,9 +100,23 @@ DELETE FROM status_page_monitors WHERE page_id = $1;
INSERT INTO status_page_monitors (page_id, monitor_id, org_id, section, group_id, label, position)
VALUES ($1, $2, $3, $4, $5, $6, $7);
-- name: SetStatusPageMonitorGroup :exec
UPDATE status_page_monitors SET group_id = $3, section = $4
WHERE page_id = $1 AND monitor_id = $2;
-- name: SetStatusPageMonitorGroups :exec
-- Files many monitors of a page at once; a nil group id (all zeros) files
-- a monitor under none.
UPDATE status_page_monitors spm
SET group_id = nullif(v.group_id, '00000000-0000-0000-0000-000000000000'::uuid), section = v.section
FROM (SELECT unnest(sqlc.arg(monitor_ids)::uuid[]) AS monitor_id, unnest(sqlc.arg(group_ids)::uuid[]) AS group_id,
unnest(sqlc.arg(sections)::text[]) AS section) AS v
WHERE spm.page_id = sqlc.arg(page_id) AND spm.monitor_id = v.monitor_id;
-- name: CreateStatusPageGroups :exec
-- Creates many groups of a page at once, with ids the caller chose. Parents
-- must exist before their children are created; a nil parent id (all
-- zeros) means none.
INSERT INTO status_page_groups (id, page_id, org_id, parent_id, name, position)
SELECT v.id, sqlc.arg(page_id), sqlc.arg(org_id), nullif(v.parent_id, '00000000-0000-0000-0000-000000000000'::uuid), v.name, v.position
FROM (SELECT unnest(sqlc.arg(ids)::uuid[]) AS id, unnest(sqlc.arg(parent_ids)::uuid[]) AS parent_id,
unnest(sqlc.arg(names)::text[]) AS name, unnest(sqlc.arg(positions)::int[]) AS position) AS v;
-- name: ListStatusPageGroups :many
SELECT * FROM status_page_groups
+49 -13
View File
@@ -150,6 +150,37 @@ func (q *Queries) CreateStatusPageGroup(ctx context.Context, arg CreateStatusPag
return i, err
}
const createStatusPageGroups = `-- name: CreateStatusPageGroups :exec
INSERT INTO status_page_groups (id, page_id, org_id, parent_id, name, position)
SELECT v.id, $1, $2, nullif(v.parent_id, '00000000-0000-0000-0000-000000000000'::uuid), v.name, v.position
FROM (SELECT unnest($3::uuid[]) AS id, unnest($4::uuid[]) AS parent_id,
unnest($5::text[]) AS name, unnest($6::int[]) AS position) AS v
`
type CreateStatusPageGroupsParams struct {
PageID uuid.UUID
OrgID uuid.UUID
Ids []uuid.UUID
ParentIds []uuid.UUID
Names []string
Positions []int32
}
// Creates many groups of a page at once, with ids the caller chose. Parents
// must exist before their children are created; a nil parent id (all
// zeros) means none.
func (q *Queries) CreateStatusPageGroups(ctx context.Context, arg CreateStatusPageGroupsParams) error {
_, err := q.db.Exec(ctx, createStatusPageGroups,
arg.PageID,
arg.OrgID,
arg.Ids,
arg.ParentIds,
arg.Names,
arg.Positions,
)
return err
}
const deleteStatusPage = `-- name: DeleteStatusPage :execrows
DELETE FROM status_pages WHERE id = $1
`
@@ -563,24 +594,29 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
return i, err
}
const setStatusPageMonitorGroup = `-- name: SetStatusPageMonitorGroup :exec
UPDATE status_page_monitors SET group_id = $3, section = $4
WHERE page_id = $1 AND monitor_id = $2
const setStatusPageMonitorGroups = `-- name: SetStatusPageMonitorGroups :exec
UPDATE status_page_monitors spm
SET group_id = nullif(v.group_id, '00000000-0000-0000-0000-000000000000'::uuid), section = v.section
FROM (SELECT unnest($2::uuid[]) AS monitor_id, unnest($3::uuid[]) AS group_id,
unnest($4::text[]) AS section) AS v
WHERE spm.page_id = $1 AND spm.monitor_id = v.monitor_id
`
type SetStatusPageMonitorGroupParams struct {
PageID uuid.UUID
MonitorID uuid.UUID
GroupID *uuid.UUID
Section string
type SetStatusPageMonitorGroupsParams struct {
PageID uuid.UUID
MonitorIds []uuid.UUID
GroupIds []uuid.UUID
Sections []string
}
func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error {
_, err := q.db.Exec(ctx, setStatusPageMonitorGroup,
// Files many monitors of a page at once; a nil group id (all zeros) files
// a monitor under none.
func (q *Queries) SetStatusPageMonitorGroups(ctx context.Context, arg SetStatusPageMonitorGroupsParams) error {
_, err := q.db.Exec(ctx, setStatusPageMonitorGroups,
arg.PageID,
arg.MonitorID,
arg.GroupID,
arg.Section,
arg.MonitorIds,
arg.GroupIds,
arg.Sections,
)
return err
}
+62 -5
View File
@@ -241,7 +241,7 @@
if (checkAll) {
const on = checkAll.dataset.checkAll === "on";
checkAll.closest("form")?.querySelectorAll(checkAll.dataset.checkTarget).forEach((box) => {
if (box.closest("[data-row]")?.hidden) return;
if (box.closest("[data-row]")?.hasAttribute("data-filtered-out")) return;
box.checked = on;
if (on) addRowFields(box);
});
@@ -341,15 +341,72 @@
if (ev.target.matches('[data-row] [data-field="include"]') && ev.target.checked) addRowFields(ev.target);
});
// [data-filter-rows] hides the rows of the list it names whose text does
// not contain what is typed.
// Lists with data-page-size show that many of their rows at a time, of
// those a filter leaves; the [data-row-pager] naming the list turns the
// pages. The other rows stay in the DOM, so forms still send them.
// Selects with data-lazy-options hold their chosen option only; the full
// list comes from the form's row template once the row is shown or used.
const fillOptions = (sel) => {
const tpl = sel.closest("form")?.querySelector("template[data-row-fields]");
const full = tpl?.content.querySelector(`select[data-field="${sel.dataset.field}"]`);
if (!full) return;
const value = sel.value;
sel.replaceChildren(...[...full.options].map((o) => o.cloneNode(true)));
sel.value = value;
sel.removeAttribute("data-lazy-options");
};
document.addEventListener("focusin", (ev) => {
if (ev.target.matches?.("select[data-lazy-options]")) fillOptions(ev.target);
});
const showRowPage = (list, page) => {
const rows = [...list.querySelectorAll(":scope > [data-row]")];
const size = Number(list.dataset.pageSize) || rows.length || 1;
const shown = rows.filter((row) => !row.hasAttribute("data-filtered-out"));
const pages = Math.max(1, Math.ceil(shown.length / size));
page = Math.min(Math.max(0, page), pages - 1);
list.dataset.page = String(page);
for (const row of rows) row.hidden = true;
for (const row of shown.slice(page * size, (page + 1) * size)) {
row.hidden = false;
row.querySelectorAll("select[data-lazy-options]").forEach(fillOptions);
}
for (const nav of document.querySelectorAll(`[data-row-pager="#${list.id}"]`)) {
nav.hidden = pages < 2;
nav.querySelector('[data-row-page="prev"]').disabled = page === 0;
nav.querySelector('[data-row-page="next"]').disabled = page >= pages - 1;
const status = nav.querySelector("[data-row-page-status]");
if (status) {
const values = {
from: shown.length ? page * size + 1 : 0,
to: Math.min((page + 1) * size, shown.length),
total: shown.length,
};
status.textContent = status.dataset.template.replace(/\{(\w+)\}/g, (m, k) => values[k] ?? m);
}
}
};
for (const list of document.querySelectorAll("[data-page-size][id]")) showRowPage(list, 0);
document.addEventListener("click", (ev) => {
const btn = ev.target.closest("[data-row-page]");
if (!btn) return;
const list = document.querySelector(btn.closest("[data-row-pager]").dataset.rowPager);
showRowPage(list, Number(list.dataset.page || 0) + (btn.dataset.rowPage === "next" ? 1 : -1));
});
// [data-filter-rows] hides the rows of the list it names whose text, or
// that of their [data-filter-text], does not contain what is typed.
document.addEventListener("input", (ev) => {
const input = ev.target.closest("[data-filter-rows]");
if (!input) return;
const needle = input.value.trim().toLowerCase();
for (const row of document.querySelectorAll(input.dataset.filterRows + " > [data-row]")) {
row.hidden = needle !== "" && !row.textContent.toLowerCase().includes(needle);
const list = document.querySelector(input.dataset.filterRows);
for (const row of list.querySelectorAll(":scope > [data-row]")) {
const text = (row.querySelector("[data-filter-text]") ?? row).textContent;
const out = needle !== "" && !text.toLowerCase().includes(needle);
row.toggleAttribute("data-filtered-out", out);
row.hidden = out;
}
if (list.dataset.pageSize) showRowPage(list, 0);
});
// Only the settings of the selected check type are shown and submitted.
+22
View File
@@ -192,6 +192,28 @@ templ bars(bs []Bar, height int) {
</svg>
}
// pathBars draws bars like bars, in a few paths and without tooltips.
templ pathBars(bs []Bar, height int) {
<svg
viewBox={ "0 0 " + strconv.Itoa(len(bs)*4) + " " + strconv.Itoa(height) }
preserveAspectRatio="none"
class="block w-full"
style={ "height:" + strconv.Itoa(height) + "px" }
role="img"
aria-label={ i18n.T(ctx, "monitors.uptime_chart") }
>
for _, p := range BarPaths(bs, height) {
<path
d={ p.D }
class={ templ.KV("fill-up", p.Status == StatusUp),
templ.KV("fill-degraded", p.Status == StatusDegraded),
templ.KV("fill-down", p.Status == StatusDown),
templ.KV("fill-rule", p.Status == StatusUnknown) }
></path>
}
</svg>
}
templ Dashboard(p Page, me Me, v DashboardView) {
@consoleShell(p, me) {
<div class="mb-6 flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
File diff suppressed because it is too large. Load diff
+178
View File
@@ -3,6 +3,7 @@ package web
import (
"fmt"
"io/fs"
"net/url"
"strconv"
"strings"
"time"
@@ -30,6 +31,183 @@ type PublicAssets struct {
Now time.Time
// NoRefresh leaves out the periodic reload, on pages with a form.
NoRefresh bool
// PageSize is how many of a section's own components the page lists
// at a time; 0 lists all, as in a single-file export.
PageSize int
// Pages holds the zero-based page shown of the sections paged, by
// their PublicSection.Key.
Pages map[string]int
// Query is what the visitor searched the components for; OnlyProblems
// keeps those with an outage or degraded.
Query string
OnlyProblems bool
}
// PublicSection is a section of a status page as a request for it shows
// it: the components of one page of the section's own, its status and
// count those of the whole section.
type PublicSection struct {
Name string
Status string
Total int
// Key identifies the section in the URLs paging it, e.g. "0.2".
Key string
Components []agentapi.Component
Children []PublicSection
// Page is the zero-based page of the section's own components shown,
// of Pages.
Page, Pages int
}
// ComponentView is what a request for a status page shows of its
// components: every section paged on its own, filtered by a search and to
// those with problems if the visitor asked.
type ComponentView struct {
Sections []PublicSection
// Total counts all components, Matches those the filters leave and
// Problems those with an outage or degraded.
Total, Matches, Problems int
Query string
OnlyProblems bool
base string
size int
pages map[string]int
}
// Filterable reports whether the page lists enough components to offer the
// search and filter, or uses them.
func (v ComponentView) Filterable() bool {
return v.size > 0 && v.Total > v.size || v.Query != "" || v.OnlyProblems
}
// Filtered reports whether a search or filter is in use.
func (v ComponentView) Filtered() bool { return v.Query != "" || v.OnlyProblems }
// PageHref links page of the section key, keeping the other sections' pages
// and the filters.
func (v ComponentView) PageHref(key string, page int) string {
q := url.Values{}
if v.Query != "" {
q.Set("q", v.Query)
}
if v.OnlyProblems {
q.Set("problems", "1")
}
for k, p := range v.pages {
if k != key && p > 0 {
q.Set("p."+k, strconv.Itoa(p+1))
}
}
if page > 0 {
q.Set("p."+key, strconv.Itoa(page+1))
}
href := BackHref(v.base)
if len(q) > 0 {
href += "?" + q.Encode()
}
return href + "#g-" + key
}
// ResetHref links the page without search, filter and paging.
func (v ComponentView) ResetHref() string { return BackHref(v.base) }
// Problem reports whether a component counts as an outage for the filter.
func Problem(c agentapi.Component) bool {
return c.Status == agentapi.PageOutage || c.Status == agentapi.PageDegraded
}
// PublicComponents decides which components of sections a request for the
// page shows, as a.Query, a.OnlyProblems and a.Pages ask.
func PublicComponents(sections []agentapi.Section, a PublicAssets) ComponentView {
v := ComponentView{
Query: strings.TrimSpace(a.Query), OnlyProblems: a.OnlyProblems,
base: a.ComponentBase, size: a.PageSize, pages: a.Pages,
}
needle := strings.ToLower(v.Query)
match := func(path []string, c agentapi.Component) bool {
if v.OnlyProblems && !Problem(c) {
return false
}
if needle == "" || strings.Contains(strings.ToLower(c.Name), needle) {
return true
}
for _, p := range path {
if strings.Contains(strings.ToLower(p), needle) {
return true
}
}
return false
}
filtered := v.Filtered()
var walk func(sec agentapi.Section, key string, path []string) (PublicSection, bool)
walk = func(sec agentapi.Section, key string, path []string) (PublicSection, bool) {
ps := PublicSection{Name: sec.Name, Status: secStatusName(sec), Total: SectionTotal(sec), Key: key, Pages: 1}
if sec.Name != "" {
path = append(path, sec.Name)
}
var own []agentapi.Component
for _, c := range sec.Components {
v.Total++
if Problem(c) {
v.Problems++
}
if match(path, c) {
own = append(own, c)
}
}
v.Matches += len(own)
if v.size > 0 && len(own) > v.size {
ps.Pages = (len(own) + v.size - 1) / v.size
ps.Page = min(max(v.pages[key], 0), ps.Pages-1)
own = own[ps.Page*v.size : min((ps.Page+1)*v.size, len(own))]
}
ps.Components = own
// Unnamed sections are top-level lists without children.
if sec.Name != "" {
for i, child := range sec.Children {
if c, ok := walk(child, key+"."+strconv.Itoa(i), path); ok {
ps.Children = append(ps.Children, c)
}
}
}
return ps, !filtered || len(ps.Components) > 0 || len(ps.Children) > 0
}
for i, sec := range sections {
if ps, ok := walk(sec, strconv.Itoa(i), nil); ok {
v.Sections = append(v.Sections, ps)
}
}
return v
}
// BarPath draws the bars of one status of a chart.
type BarPath struct {
Status Status
D string
}
// BarPaths draws bars as one path per status instead of an element with a
// tooltip each: status pages list thousands of components with 90 bars
// each, and their detail pages have the tooltips.
func BarPaths(bs []Bar, height int) []BarPath {
var order []Status
ds := map[Status]*strings.Builder{}
h := strconv.Itoa(height)
for i, b := range bs {
d, ok := ds[b.Status]
if !ok {
d = &strings.Builder{}
ds[b.Status] = d
order = append(order, b.Status)
}
d.WriteString("M" + strconv.Itoa(i*4) + " 0h3v" + h + "h-3z")
}
out := make([]BarPath, 0, len(order))
for _, st := range order {
out = append(out, BarPath{Status: st, D: ds[st].String()})
}
return out
}
// NoticeForm is the button of a notice page that acts on a mailed link,
+62 -11
View File
@@ -94,10 +94,20 @@ templ PublicStatusPage(s agentapi.PageSnapshot, a PublicAssets) {
<p class="text-lg font-medium">{ i18n.T(ctx, "page.status."+s.Status) }</p>
</section>
@pageMaintenance(i18n.T(ctx, "page.maintenance_ongoing"), s.Ongoing(a.Now))
if len(s.Sections) > 0 {
if v := PublicComponents(s.Sections, a); len(s.Sections) > 0 {
if v.Filterable() {
@publicComponentFilter(v, a)
}
<section class="mb-12 border-t border-rule">
for _, sec := range s.Sections {
@publicSection(sec, s, a)
for _, sec := range v.Sections {
@publicSection(sec, v, s, a)
}
if v.Filtered() && v.Matches == 0 {
if v.OnlyProblems && v.Query == "" {
<p class="py-6 text-sm text-muted">{ i18n.T(ctx, "page.filter_no_problems") }</p>
} else {
<p class="py-6 text-sm text-muted">{ i18n.T(ctx, "page.search_none") }</p>
}
}
</section>
}
@@ -158,23 +168,59 @@ templ PublicNoticePage(s agentapi.PageSnapshot, a PublicAssets, title, message s
}
}
// publicComponentFilter searches the components of pages listing too many
// to scan, or narrows them to those with an outage.
templ publicComponentFilter(v ComponentView, a PublicAssets) {
<form method="get" action={ templ.SafeURL(BackHref(a.ComponentBase)) } role="search" class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
<label class="sr-only" for="component-search">{ i18n.T(ctx, "page.search") }</label>
<input id="component-search" type="search" name="q" value={ v.Query } maxlength="100" placeholder={ i18n.T(ctx, "page.search") } class="min-w-0 flex-1 border border-rule bg-transparent px-2 py-1.5"/>
<label class="flex items-center gap-2">
<input type="checkbox" name="problems" value="1" checked?={ v.OnlyProblems }/>
<span>{ i18n.T(ctx, "page.filter_problems", "Count", v.Problems) }</span>
</label>
<button type="submit" class="border border-ink px-3 py-1.5 hover:bg-ink hover:text-paper">{ i18n.T(ctx, "page.search_submit") }</button>
if v.Filtered() {
<a href={ templ.SafeURL(v.ResetHref()) } class="text-muted hover:text-ink">{ i18n.T(ctx, "page.search_clear") }</a>
}
</form>
}
// publicSectionPager turns the pages of a section's own components.
templ publicSectionPager(sec PublicSection, v ComponentView) {
if sec.Pages > 1 {
<nav class="flex flex-wrap items-center gap-x-5 gap-y-2 border-b border-rule py-2 text-sm" aria-label={ i18n.T(ctx, "pager.label") }>
if sec.Page > 0 {
<a href={ templ.SafeURL(v.PageHref(sec.Key, sec.Page-1)) } rel="prev" class="text-muted hover:text-ink">← { i18n.T(ctx, "pager.previous") }</a>
}
<span class="font-mono text-xs text-muted">{ i18n.T(ctx, "page.pages", "Page", sec.Page+1, "Pages", sec.Pages) }</span>
if sec.Page < sec.Pages-1 {
<a href={ templ.SafeURL(v.PageHref(sec.Key, sec.Page+1)) } rel="next" class="ml-auto text-muted hover:text-ink">{ i18n.T(ctx, "pager.next") } →</a>
}
</nav>
}
}
// publicSection renders an unnamed root component list or a collapsible nested
// group matching the monitor dashboard hierarchy.
templ publicSection(sec agentapi.Section, s agentapi.PageSnapshot, a PublicAssets) {
templ publicSection(sec PublicSection, v ComponentView, s agentapi.PageSnapshot, a PublicAssets) {
if sec.Name == "" {
@publicComponentList(sec.Components, s, a)
<div id={ "g-" + sec.Key }>
@publicComponentList(sec.Components, s, a)
@publicSectionPager(sec, v)
</div>
} else {
<details open class="border-b border-rule">
<details open id={ "g-" + sec.Key } class="border-b border-rule">
<summary class="flex cursor-pointer items-center gap-2.5 py-3 text-sm font-medium select-none hover:bg-rule/30">
@statusDot(SectionStatus(sec))
@statusDot(PageStatus(sec.Status))
<span>{ sec.Name }</span>
<span class="font-mono text-xs font-normal text-muted">{ strconv.Itoa(SectionTotal(sec)) }</span>
<span class="ml-auto text-xs font-normal text-muted">{ i18n.T(ctx, "page.component."+string(secStatusName(sec))) }</span>
<span class="font-mono text-xs font-normal text-muted">{ strconv.Itoa(sec.Total) }</span>
<span class="ml-auto text-xs font-normal text-muted">{ i18n.T(ctx, "page.component."+sec.Status) }</span>
</summary>
<div class="ml-4 border-l border-rule pl-4">
@publicComponentList(sec.Components, s, a)
@publicSectionPager(sec, v)
for _, child := range sec.Children {
@publicSection(child, s, a)
@publicSection(child, v, s, a)
}
</div>
</details>
@@ -238,7 +284,12 @@ templ publicComponentBody(comp agentapi.Component, s agentapi.PageSnapshot, clic
}
</span>
</div>
@bars(DayBars(comp.Days), 22)
if clickable {
// The detail page the row links to has the tooltips.
@pathBars(DayBars(comp.Days), 22)
} else {
@bars(DayBars(comp.Days), 22)
}
<div class="mt-1 flex justify-between font-mono text-xs text-muted">
<span>{ i18n.T(ctx, "page.days_ago", "Count", len(comp.Days)) }</span>
<span>{ UptimeText(comp.Uptime) }</span>
File diff suppressed because it is too large. Load diff
+34 -8
View File
@@ -320,11 +320,11 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
<template data-row-fields>
@pageMonitorFields(e, PageMonitorOption{})
</template>
<ul id="page-monitors" class="mb-4 divide-y divide-rule border-y border-rule text-sm">
<ul id="page-monitors" class="mb-4 divide-y divide-rule border-y border-rule text-sm" data-page-size={ strconv.Itoa(monitorPageSize) }>
for _, m := range e.Monitors {
<li data-row class="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-1.5 py-2">
<input type="checkbox" data-field="include" checked?={ m.Included } class="accent-ink" aria-label={ m.Name }/>
<span class="flex flex-wrap items-baseline gap-x-2">
<span data-filter-text class="flex flex-wrap items-baseline gap-x-2">
<span>{ m.Name }</span>
if m.MonitorGroupPath != "" {
<span class="font-mono text-xs text-muted">{ m.MonitorGroupPath }</span>
@@ -339,6 +339,15 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
</li>
}
</ul>
if len(e.Monitors) > monitorPageSize {
// All rows stay in the form, as saving replaces the page's
// monitors; the pager only shows them a page at a time.
<nav data-row-pager="#page-monitors" class="-mt-2 mb-4 flex flex-wrap items-center gap-x-5 gap-y-2 text-sm" aria-label={ i18n.T(ctx, "pager.label") }>
<button type="button" data-row-page="prev" class="text-muted hover:text-ink disabled:opacity-40">← { i18n.T(ctx, "pager.previous") }</button>
<span data-row-page-status data-template={ i18n.T(ctx, "pages.monitors_range") } class="text-xs text-muted"></span>
<button type="button" data-row-page="next" class="text-muted hover:text-ink disabled:opacity-40">{ i18n.T(ctx, "pager.next") } →</button>
</nav>
}
@submit(i18n.T(ctx, "common.save"))
</form>
</section>
@@ -416,16 +425,33 @@ templ verifyButton(pageID, label string) {
// offers to filter them.
const monitorFilterFrom = 15
// monitorPageSize is how many monitors the page editor shows at a time.
const monitorPageSize = 50
// pageMonitorFields are the group and label of m on the page.
templ pageMonitorFields(e PageEditor, m PageMonitorOption) {
<span data-row-extra></span>
<span class="flex gap-2">
<select data-field="group_id" data-nullable aria-label={ i18n.T(ctx, "pages.group") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink">
<option value="">{ i18n.T(ctx, "pages.no_group") }</option>
for _, opt := range e.Groups {
<option value={ opt.ID } selected?={ opt.ID == m.GroupID }>{ opt.Label }</option>
}
</select>
if m.ID == "" {
<select data-field="group_id" data-nullable aria-label={ i18n.T(ctx, "pages.group") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink">
<option value="">{ i18n.T(ctx, "pages.no_group") }</option>
for _, opt := range e.Groups {
<option value={ opt.ID }>{ opt.Label }</option>
}
</select>
} else {
// With thousands of monitors and hundreds of groups the options of
// every row would make the page tens of megabytes: rows carry their
// group only and get the others from the template when shown.
<select data-field="group_id" data-nullable data-lazy-options aria-label={ i18n.T(ctx, "pages.group") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink">
<option value="">{ i18n.T(ctx, "pages.no_group") }</option>
for _, opt := range e.Groups {
if opt.ID == m.GroupID {
<option value={ opt.ID } selected>{ opt.Label }</option>
}
}
</select>
}
<input data-field="label" value={ m.Label } placeholder={ i18n.T(ctx, "pages.label") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink"/>
</span>
}
File diff suppressed because it is too large. Load diff
+72
View File
@@ -0,0 +1,72 @@
<!doctype html><html><body data-msg-network="net">
<form data-api="/org/statuspages/p1/monitors" data-method="put" data-rows="monitors" data-next="#saved" id="sp">
<p><button type="button" id="all" data-check-all="on" data-check-target="[data-field=include]">all</button></p>
<input type="search" id="filter" data-filter-rows="#rows">
<template data-row-fields><span data-row-extra></span><select data-field="group_id" data-nullable><option value="">none</option><option value="g1">G1</option><option value="g2">G2</option></select></template>
<ul id="rows" data-page-size="2"></ul>
<nav data-row-pager="#rows">
<button type="button" id="prev" data-row-page="prev">prev</button>
<span id="status" data-row-page-status data-template="{from}-{to}/{total}"></span>
<button type="button" id="next" data-row-page="next">next</button>
</nav>
<button type="submit">save</button>
</form>
<pre id="out"></pre>
<script>
const sent = [];
window.axios = { create: () => ({ interceptors: { request: { use() {} } }, request: async (cfg) => { sent.push(cfg.data); return { data: {} }; }, post: async () => ({ data: {} }) }) };
const list = document.getElementById("rows");
for (const [id, name, on] of [["m1", "alpha", true], ["m2", "beta", false], ["m3", "gamma", false], ["m4", "alpine", false], ["m5", "delta", true]]) {
list.insertAdjacentHTML("beforeend", `<li data-row><input type="checkbox" data-field="include"${on ? " checked" : ""}><span data-filter-text>${name}</span><input type="hidden" data-field="monitor_id" value="${id}">${on ? '<span data-row-extra></span><select data-field="group_id" data-nullable data-lazy-options><option value="">none</option><option value="g2" selected>G2</option></select>' : ""}</li>`);
}
</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));
};
const visible = () => [...list.children].filter((r) => !r.hidden).map((r) => r.querySelector("[data-filter-text]").textContent);
const status = () => document.getElementById("status").textContent;
const submit = async () => {
sent.length = 0;
document.getElementById("sp").dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
await new Promise((r) => setTimeout(r, 50));
return sent[0] ? (typeof sent[0] === "string" ? JSON.parse(sent[0]) : sent[0]).monitors.map((m) => m.monitor_id) : null;
};
const sel = (id) => document.querySelector(`[value="${id}"]`).closest("[data-row]").querySelector("select");
check("shown row gets all options", [...sel("m1").options].map((o) => o.value), ["", "g1", "g2"]);
check("shown row keeps its group", sel("m1").value, "g2");
check("hidden row stays lean", sel("m5").options.length, 2);
check("first page", visible(), ["alpha", "beta"]);
check("first status", status(), "1-2/5");
check("prev disabled", document.getElementById("prev").disabled, true);
document.getElementById("next").click();
document.getElementById("next").click();
check("last page", visible(), ["delta"]);
check("last status", status(), "5-5/5");
check("next disabled", document.getElementById("next").disabled, true);
check("row shown later gets all options", sel("m5").options.length, 3);
check("rows of all pages sent", await submit(), ["m1", "m5"]);
const filter = document.getElementById("filter");
filter.value = "g1";
filter.dispatchEvent(new Event("input", { bubbles: true }));
check("group options are not searched", visible(), []);
filter.value = "alp";
filter.dispatchEvent(new Event("input", { bubbles: true }));
check("filtered", visible(), ["alpha", "alpine"]);
check("filtered status", status(), "1-2/2");
check("pager hidden for one page", document.querySelector("[data-row-pager]").hidden, true);
filter.value = "a";
filter.dispatchEvent(new Event("input", { bubbles: true }));
check("filter restarts at first page", visible(), ["alpha", "beta"]);
filter.value = "alp";
filter.dispatchEvent(new Event("input", { bubbles: true }));
document.getElementById("all").click();
check("check all ticks filtered rows only", await submit(), ["m1", "m4", "m5"]);
document.getElementById("out").textContent = out.join("\n");
})();
</script>
</body></html>