render.gno
1.94 Kb · 69 lines
1package profiles
2
3import (
4 "strconv"
5 "strings"
6
7 "gno.land/p/moul/md/v0"
8 "gno.land/p/nt/markdown/sanitize/v0"
9 "gno.land/p/nt/mux/v0"
10)
11
12// rankingLimit is how many players the gnoweb page lists.
13const rankingLimit = 50
14
15var router = mux.NewRouter()
16
17func init() {
18 router.HandleFunc("", renderHome)
19 router.HandleFunc("json/profile/{addr}", func(res *mux.ResponseWriter, req *mux.Request) {
20 res.Write(ProfileJSON(req.GetVar("addr")))
21 })
22 router.HandleFunc("json/players/{offset}/{count}", func(res *mux.ResponseWriter, req *mux.Request) {
23 offset, err1 := strconv.Atoi(req.GetVar("offset"))
24 count, err2 := strconv.Atoi(req.GetVar("count"))
25 if err1 != nil || err2 != nil {
26 panic("profiles: invalid page")
27 }
28 res.Write(PlayersJSON(offset, count))
29 })
30}
31
32// Render serves the ranking page ("") and the raw JSON views the web client
33// reads ("json/profile/{addr}", "json/players/{offset}/{count}").
34func Render(path string) string {
35 return router.Render(path)
36}
37
38func renderHome(res *mux.ResponseWriter, _ *mux.Request) {
39 res.Write(md.H1("Gnoslinger top guns"))
40 if ranking.Size() == 0 {
41 res.Write(md.Paragraph("Nobody has played yet."))
42 } else {
43 var b strings.Builder
44 b.WriteString("| Rank | Player | Victory points | Games played |\n|---|---|---|---|\n")
45 rank := 0
46 ranking.Iterate("", "", func(_ string, v any) bool {
47 p := v.(*Profile)
48 rank++
49 b.WriteString("| " + strconv.Itoa(rank) + " | " + label(p.Addr) +
50 " | " + strconv.Itoa(p.VictoryPoints) + " | " + strconv.Itoa(p.GamesPlayed) + " |\n")
51 return rank >= rankingLimit
52 })
53 res.Write(b.String() + "\n")
54 }
55 res.Write(md.H2("Scored games"))
56 var l []string
57 for _, g := range Games() {
58 l = append(l, md.InlineCode(g))
59 }
60 res.Write(md.BulletList(l))
61}
62
63// label shows an address by its registered name when it has one.
64func label(a address) string {
65 if name := Name(a); name != "" {
66 return md.Bold(sanitize.InlineText(name))
67 }
68 return md.InlineCode(sanitize.InlineText(a.String()))
69}