render.gno

2.02 Kb ยท 76 lines
 1package polls
 2
 3import (
 4	"time"
 5
 6	"gno.land/p/moul/md"
 7	"gno.land/p/nt/avl"
 8	"gno.land/p/nt/mux"
 9	"gno.land/p/nt/ufmt"
10	pollsv1 "gno.land/p/zenao/polls/v1"
11)
12
13var router *mux.Router
14
15const PollsPagePath = ""
16const DetailPollPagePath = "{id}"
17
18func init() {
19	router = mux.NewRouter()
20	router.HandleFunc(PollsPagePath, PollsPageHandler)
21	router.HandleFunc(DetailPollPagePath, DetailPollPageHandler)
22}
23
24func Render(path string) string {
25	return router.Render(path)
26}
27
28func PollsPageHandler(res *mux.ResponseWriter, req *mux.Request) {
29	res.Write(md.H1("Welcome to the polls factory ๐Ÿญ"))
30	res.Write(md.H3("Here are the latest (20. max) polls:"))
31	i := 0
32	polls.Iterate("", "", func(id string, pollRaw interface{}) bool {
33		poll := pollRaw.(*Poll)
34		res.Write(md.BulletItem(md.Link(poll.Question, "polls:"+id)))
35		i++
36		if i >= 20 {
37			return true
38		}
39		return false
40	})
41	res.Write(md.HorizontalRule())
42	res.Write(md.Link("Create a new poll ๐Ÿ—ณ๏ธ", "polls$help#func-NewPoll"))
43}
44
45func DetailPollPageHandler(res *mux.ResponseWriter, req *mux.Request) {
46	id := req.GetVar("id")
47	pollRaw, ok := polls.Get(id)
48	if !ok {
49		res.Write(md.H1("Poll not found"))
50		return
51	}
52	poll := pollRaw.(*Poll)
53	res.Write(poll.Render())
54}
55
56func (p *Poll) Render() string {
57	s := ""
58	s += md.H1(p.Question + "โ“")
59	if p.Kind == pollsv1.POLL_KIND_MULTIPLE_CHOICE {
60		s += md.Paragraph("Multiple choices allowed โœ…")
61	} else {
62		s += md.Paragraph("Only one choice allowed โŒ")
63	}
64	s += md.Paragraph(md.Italic("Duration: " + time.Duration(p.Duration*int64(time.Second)).String() + "โŒ›"))
65	s += md.Paragraph(md.Italic("Created by " + p.CreatedBy + "๐Ÿ‘ค"))
66	s += md.Paragraph(md.Italic("Created at " + time.Unix(p.CreatedAt, 0).Format("2006-01-02 15:04:05") + "๐Ÿ•’"))
67	s += md.HorizontalRule()
68	s += md.H2("Results:  ๐Ÿ“Š")
69	p.Results.Iterate("", "", func(option string, choices interface{}) bool {
70		choicesTree := choices.(*avl.Tree)
71		s += md.BulletItem(md.Bold(option)) + "\n" +
72			"  " + md.BulletItem("Votes: "+ufmt.Sprintf("%d", choicesTree.Size()))
73		return false
74	})
75	return s
76}