render_reply.gno
2.40 Kb ยท 107 lines
1package boards2
2
3import (
4 "strconv"
5 "strings"
6
7 "gno.land/p/gnoland/boards"
8 "gno.land/p/jeronimoalbi/pager"
9 "gno.land/p/moul/md"
10 "gno.land/p/nt/mux"
11)
12
13func renderReply(res *mux.ResponseWriter, req *mux.Request) {
14 name := req.GetVar("board")
15 board, found := gBoards.GetByName(name)
16 if !found {
17 res.Write("Board does not exist: " + name)
18 return
19 }
20
21 rawID := req.GetVar("thread")
22 tID, err := strconv.Atoi(rawID)
23 if err != nil {
24 res.Write("Invalid thread ID: " + rawID)
25 return
26 }
27
28 rawID = req.GetVar("reply")
29 rID, err := strconv.Atoi(rawID)
30 if err != nil {
31 res.Write("Invalid reply ID: " + rawID)
32 return
33 }
34
35 thread, found := board.Threads.Get(boards.ID(tID))
36 if !found {
37 res.Write("Thread does not exist with ID: " + req.GetVar("thread"))
38 return
39 }
40
41 reply, found := thread.Replies.Get(boards.ID(rID))
42 if !found {
43 res.Write("Reply does not exist with ID: " + rawID)
44 return
45 }
46
47 // Call render even for hidden replies to display children.
48 // Original comment content will be hidden under the hood.
49 // See: #3480
50 res.Write(renderPostInner(reply))
51}
52
53func renderTopLevelReplies(post *boards.Post, path, indent string, levels int) string {
54 p, err := pager.New(path, post.Replies.Size(), pager.WithPageSize(pageSizeReplies))
55 if err != nil {
56 panic(err)
57 }
58
59 var (
60 b strings.Builder
61 commentsIndent = indent + "> "
62 )
63
64 render := func(reply *boards.Post) bool {
65 b.WriteString(indent + "\n" + renderPost(reply, "", commentsIndent, levels-1))
66 return false
67 }
68
69 b.WriteString("\n" + md.HorizontalRule() + "Sort by: ")
70
71 r := parseRealmPath(path)
72 sortOrder := r.Query.Get("order")
73 if sortOrder == "desc" {
74 r.Query.Set("order", "asc")
75 b.WriteString(md.Link("newest first", r.String()) + "\n")
76
77 } else {
78 r.Query.Set("order", "desc")
79 b.WriteString(md.Link("oldest first", r.String()) + "\n")
80 }
81
82 count := p.PageSize()
83 if sortOrder == "desc" {
84 count = -count // Reverse iterate
85 }
86
87 post.Replies.Iterate(p.Offset(), count, render)
88
89 if p.HasPages() {
90 b.WriteString(md.HorizontalRule())
91 b.WriteString(pager.Picker(p))
92 }
93 return b.String()
94}
95
96func renderSubReplies(post *boards.Post, indent string, levels int) string {
97 var (
98 b strings.Builder
99 commentsIndent = indent + "> "
100 )
101
102 post.Replies.Iterate(0, post.Replies.Size(), func(reply *boards.Post) bool {
103 b.WriteString(indent + "\n" + renderPost(reply, "", commentsIndent, levels-1))
104 return false
105 })
106 return b.String()
107}