erratademo.gno
2.61 Kb · 93 lines
1// Package erratademo embeds the accepted corrections for a documentation page.
2package erratademo
3
4import (
5 "chain"
6 "strconv"
7 "strings"
8
9 "gno.land/p/g132vz03ycpaagtef4jmxjakstkppgyc5wn3r807/errata/v0"
10 "gno.land/p/nt/mux/v0"
11 "gno.land/r/g132vz03ycpaagtef4jmxjakstkppgyc5wn3r807/erratabank/v1"
12)
13
14const pageSize = 20
15
16var (
17 owner address
18 bookID int
19 realmURL string
20 router = mux.NewRouter()
21)
22
23func init(cur realm) {
24 owner = cur.Previous().Address()
25 realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land") + ":"
26 router.HandleFunc("", renderGuide)
27}
28
29// SetBook connects this page to an existing book. The deployer can do this once.
30func SetBook(cur realm, id int) {
31 if !cur.IsCurrent() {
32 panic("invalid realm context")
33 }
34 if cur.Previous().Address() != owner {
35 panic("demo deployer only")
36 }
37 if bookID != 0 {
38 panic("demo book already set")
39 }
40 if _, ok := erratabank.GetBook(id); !ok {
41 panic("book not found")
42 }
43 bookID = id
44 chain.Emit("DemoBookSet", "book", strconv.Itoa(id))
45}
46
47// BookID returns the configured book, or zero if the page is unlinked.
48func BookID() int {
49 return bookID
50}
51
52func Render(path string) string {
53 return router.Render(path)
54}
55
56func renderGuide(w *mux.ResponseWriter, req *mux.Request) {
57 w.Write("# Erratabank Quickstart\n\n")
58 w.Write("To report an error, give the page or section, explain what is wrong, and suggest a correction. Reports are public and permanent on-chain.\n\n")
59 w.Write("The maintainer decides which reports to accept. Accepted corrections appear here automatically, with any rewards paid so far.\n\n")
60 w.Write("## Section 1. Formatting examples\n\nOpen a fenced code block with two backticks on their own line.\n\n")
61 w.Write("## Section 2. Notes\n\nInclude the expected output when a correction changes an example.\n\n")
62 if bookID == 0 {
63 w.Write("The maintainer has yet to link this guide to a book.\n\n")
64 w.Write(errata.RenderSection("Errata", nil))
65 return
66 }
67 page := 1
68 if value := req.Query.Get("page"); value != "" {
69 var err error
70 page, err = strconv.Atoi(value)
71 if err != nil || page < 1 || page-1 > int(^uint(0)>>1)/pageSize {
72 w.Write("Errata page not found.\n")
73 return
74 }
75 }
76
77 entries := erratabank.AcceptedEntriesPage(bookID, (page-1)*pageSize, pageSize+1)
78 if page > 1 && len(entries) == 0 {
79 w.Write("Errata page not found.\n")
80 return
81 }
82 more := len(entries) > pageSize
83 if more {
84 entries = entries[:pageSize]
85 }
86 w.Write(errata.RenderSection("Errata", entries))
87 if page > 1 {
88 w.Write("\n[Previous](" + realmURL + "?page=" + strconv.Itoa(page-1) + ")")
89 }
90 if more {
91 w.Write("\n[Next](" + realmURL + "?page=" + strconv.Itoa(page+1) + ")")
92 }
93}