1package pages
2
3import (
4 "bytes"
5 "embed"
6 "fmt"
7 "html"
8 "html/template"
9 "io"
10 "io/fs"
11 "log"
12 "net/http"
13 "path"
14 "path/filepath"
15 "strings"
16
17 "github.com/alecthomas/chroma/v2"
18 chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
19 "github.com/alecthomas/chroma/v2/lexers"
20 "github.com/alecthomas/chroma/v2/styles"
21 "github.com/dustin/go-humanize"
22 "github.com/sotangled/tangled/appview/auth"
23 "github.com/sotangled/tangled/appview/db"
24 "github.com/sotangled/tangled/types"
25)
26
27//go:embed templates/* static/*
28var files embed.FS
29
30type Pages struct {
31 t map[string]*template.Template
32}
33
34func funcMap() template.FuncMap {
35 return template.FuncMap{
36 "split": func(s string) []string {
37 return strings.Split(s, "\n")
38 },
39 "splitOn": func(s, sep string) []string {
40 return strings.Split(s, sep)
41 },
42 "add": func(a, b int) int {
43 return a + b
44 },
45 "sub": func(a, b int) int {
46 return a - b
47 },
48 "cond": func(cond interface{}, a, b string) string {
49 if cond == nil {
50 return b
51 }
52
53 if boolean, ok := cond.(bool); boolean && ok {
54 return a
55 }
56
57 return b
58 },
59 "didOrHandle": func(did, handle string) string {
60 if handle != "" {
61 return fmt.Sprintf("@%s", handle)
62 } else {
63 return did
64 }
65 },
66 "assoc": func(values ...string) ([][]string, error) {
67 if len(values)%2 != 0 {
68 return nil, fmt.Errorf("invalid assoc call, must have an even number of arguments")
69 }
70 pairs := make([][]string, 0)
71 for i := 0; i < len(values); i += 2 {
72 pairs = append(pairs, []string{values[i], values[i+1]})
73 }
74 return pairs, nil
75 },
76 "append": func(s []string, values ...string) []string {
77 s = append(s, values...)
78 return s
79 },
80 "timeFmt": humanize.Time,
81 "byteFmt": humanize.Bytes,
82 "length": func(v []string) int {
83 return len(v)
84 },
85 "splitN": func(s, sep string, n int) []string {
86 return strings.SplitN(s, sep, n)
87 },
88 "escapeHtml": func(s string) template.HTML {
89 if s == "" {
90 return template.HTML("<br>")
91 }
92 return template.HTML(s)
93 },
94 "unescapeHtml": func(s string) string {
95 return html.UnescapeString(s)
96 },
97 "nl2br": func(text string) template.HTML {
98 return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1))
99 },
100 "unwrapText": func(text string) string {
101 paragraphs := strings.Split(text, "\n\n")
102
103 for i, p := range paragraphs {
104 lines := strings.Split(p, "\n")
105 paragraphs[i] = strings.Join(lines, " ")
106 }
107
108 return strings.Join(paragraphs, "\n\n")
109 },
110 "sequence": func(n int) []struct{} {
111 return make([]struct{}, n)
112 },
113 }
114}
115
116func NewPages() *Pages {
117 templates := make(map[string]*template.Template)
118
119 // Walk through embedded templates directory and parse all .html files
120 err := fs.WalkDir(files, "templates", func(path string, d fs.DirEntry, err error) error {
121 if err != nil {
122 return err
123 }
124
125 if !d.IsDir() && strings.HasSuffix(path, ".html") {
126 name := strings.TrimPrefix(path, "templates/")
127 name = strings.TrimSuffix(name, ".html")
128
129 if !strings.HasPrefix(path, "templates/layouts/") {
130 // Add the page template on top of the base
131 tmpl, err := template.New(name).
132 Funcs(funcMap()).
133 ParseFS(files, "templates/layouts/*.html", path)
134 if err != nil {
135 return fmt.Errorf("setting up template: %w", err)
136 }
137
138 templates[name] = tmpl
139 log.Printf("loaded template: %s", name)
140 }
141
142 return nil
143 }
144 return nil
145 })
146 if err != nil {
147 log.Fatalf("walking template dir: %v", err)
148 }
149
150 log.Printf("total templates loaded: %d", len(templates))
151
152 return &Pages{
153 t: templates,
154 }
155}
156
157type LoginParams struct {
158}
159
160func (p *Pages) execute(name string, w io.Writer, params any) error {
161 return p.t[name].ExecuteTemplate(w, "layouts/base", params)
162}
163
164func (p *Pages) executePlain(name string, w io.Writer, params any) error {
165 return p.t[name].Execute(w, params)
166}
167
168func (p *Pages) executeRepo(name string, w io.Writer, params any) error {
169 return p.t[name].ExecuteTemplate(w, "layouts/repobase", params)
170}
171
172func (p *Pages) Login(w io.Writer, params LoginParams) error {
173 return p.executePlain("user/login", w, params)
174}
175
176type TimelineParams struct {
177 LoggedInUser *auth.User
178 Timeline []db.TimelineEvent
179 DidHandleMap map[string]string
180}
181
182func (p *Pages) Timeline(w io.Writer, params TimelineParams) error {
183 return p.execute("timeline", w, params)
184}
185
186type SettingsParams struct {
187 LoggedInUser *auth.User
188 PubKeys []db.PublicKey
189}
190
191func (p *Pages) Settings(w io.Writer, params SettingsParams) error {
192 return p.execute("settings/keys", w, params)
193}
194
195type KnotsParams struct {
196 LoggedInUser *auth.User
197 Registrations []db.Registration
198}
199
200func (p *Pages) Knots(w io.Writer, params KnotsParams) error {
201 return p.execute("knots", w, params)
202}
203
204type KnotParams struct {
205 LoggedInUser *auth.User
206 Registration *db.Registration
207 Members []string
208 IsOwner bool
209}
210
211func (p *Pages) Knot(w io.Writer, params KnotParams) error {
212 return p.execute("knot", w, params)
213}
214
215type NewRepoParams struct {
216 LoggedInUser *auth.User
217 Knots []string
218}
219
220func (p *Pages) NewRepo(w io.Writer, params NewRepoParams) error {
221 return p.execute("repo/new", w, params)
222}
223
224type ProfilePageParams struct {
225 LoggedInUser *auth.User
226 UserDid string
227 UserHandle string
228 Repos []db.Repo
229 CollaboratingRepos []db.Repo
230 ProfileStats ProfileStats
231 FollowStatus db.FollowStatus
232}
233
234type ProfileStats struct {
235 Followers int
236 Following int
237}
238
239func (p *Pages) ProfilePage(w io.Writer, params ProfilePageParams) error {
240 return p.execute("user/profile", w, params)
241}
242
243type RepoInfo struct {
244 Name string
245 OwnerDid string
246 OwnerHandle string
247 Description string
248 SettingsAllowed bool
249}
250
251func (r RepoInfo) OwnerWithAt() string {
252 if r.OwnerHandle != "" {
253 return fmt.Sprintf("@%s", r.OwnerHandle)
254 } else {
255 return r.OwnerDid
256 }
257}
258
259func (r RepoInfo) FullName() string {
260 return path.Join(r.OwnerWithAt(), r.Name)
261}
262
263func (r RepoInfo) GetTabs() [][]string {
264 tabs := [][]string{
265 {"overview", "/"},
266 {"issues", "/issues"},
267 {"pulls", "/pulls"},
268 }
269
270 if r.SettingsAllowed {
271 tabs = append(tabs, []string{"settings", "/settings"})
272 }
273
274 return tabs
275}
276
277type RepoIndexParams struct {
278 LoggedInUser *auth.User
279 RepoInfo RepoInfo
280 Active string
281 types.RepoIndexResponse
282}
283
284func (p *Pages) RepoIndexPage(w io.Writer, params RepoIndexParams) error {
285 params.Active = "overview"
286 if params.IsEmpty {
287 return p.executeRepo("repo/empty", w, params)
288 }
289 return p.executeRepo("repo/index", w, params)
290}
291
292type RepoLogParams struct {
293 LoggedInUser *auth.User
294 RepoInfo RepoInfo
295 types.RepoLogResponse
296}
297
298func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error {
299 return p.execute("repo/log", w, params)
300}
301
302type RepoCommitParams struct {
303 LoggedInUser *auth.User
304 RepoInfo RepoInfo
305 Active string
306 types.RepoCommitResponse
307}
308
309func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error {
310 params.Active = "overview"
311 return p.executeRepo("repo/commit", w, params)
312}
313
314type RepoTreeParams struct {
315 LoggedInUser *auth.User
316 RepoInfo RepoInfo
317 Active string
318 BreadCrumbs [][]string
319 BaseTreeLink string
320 BaseBlobLink string
321 types.RepoTreeResponse
322}
323
324type RepoTreeStats struct {
325 NumFolders uint64
326 NumFiles uint64
327}
328
329func (r RepoTreeParams) TreeStats() RepoTreeStats {
330 numFolders, numFiles := 0, 0
331 for _, f := range r.Files {
332 if !f.IsFile {
333 numFolders += 1
334 } else if f.IsFile {
335 numFiles += 1
336 }
337 }
338
339 return RepoTreeStats{
340 NumFolders: uint64(numFolders),
341 NumFiles: uint64(numFiles),
342 }
343}
344
345func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error {
346 params.Active = "overview"
347 return p.execute("repo/tree", w, params)
348}
349
350type RepoBranchesParams struct {
351 LoggedInUser *auth.User
352 RepoInfo RepoInfo
353 types.RepoBranchesResponse
354}
355
356func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error {
357 return p.executeRepo("repo/branches", w, params)
358}
359
360type RepoTagsParams struct {
361 LoggedInUser *auth.User
362 RepoInfo RepoInfo
363 types.RepoTagsResponse
364}
365
366func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error {
367 return p.executeRepo("repo/tags", w, params)
368}
369
370type RepoBlobParams struct {
371 LoggedInUser *auth.User
372 RepoInfo RepoInfo
373 Active string
374 BreadCrumbs [][]string
375 types.RepoBlobResponse
376}
377
378func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error {
379 style := styles.Get("bw")
380 b := style.Builder()
381 b.Add(chroma.LiteralString, "noitalic")
382 style, _ = b.Build()
383
384 if params.Lines < 5000 {
385 c := params.Contents
386 formatter := chromahtml.New(
387 chromahtml.InlineCode(true),
388 chromahtml.WithLineNumbers(true),
389 chromahtml.WithLinkableLineNumbers(true, "L"),
390 chromahtml.Standalone(false),
391 )
392
393 lexer := lexers.Get(filepath.Base(params.Path))
394 if lexer == nil {
395 lexer = lexers.Fallback
396 }
397
398 iterator, err := lexer.Tokenise(nil, c)
399 if err != nil {
400 return fmt.Errorf("chroma tokenize: %w", err)
401 }
402
403 var code bytes.Buffer
404 err = formatter.Format(&code, style, iterator)
405 if err != nil {
406 return fmt.Errorf("chroma format: %w", err)
407 }
408
409 params.Contents = code.String()
410 }
411
412 params.Active = "overview"
413 return p.executeRepo("repo/blob", w, params)
414}
415
416type Collaborator struct {
417 Did string
418 Handle string
419 Role string
420}
421
422type RepoSettingsParams struct {
423 LoggedInUser *auth.User
424 RepoInfo RepoInfo
425 Collaborators []Collaborator
426 Active string
427 IsCollaboratorInviteAllowed bool
428}
429
430func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error {
431 params.Active = "settings"
432 return p.executeRepo("repo/settings", w, params)
433}
434
435type RepoIssuesParams struct {
436 LoggedInUser *auth.User
437 RepoInfo RepoInfo
438 Active string
439 Issues []db.Issue
440}
441
442func (p *Pages) RepoIssues(w io.Writer, params RepoIssuesParams) error {
443 params.Active = "issues"
444 return p.executeRepo("repo/issues/issues", w, params)
445}
446
447type RepoSingleIssueParams struct {
448 LoggedInUser *auth.User
449 RepoInfo RepoInfo
450 Active string
451 Issue db.Issue
452 Comments []db.Comment
453 IssueOwnerHandle string
454
455 State string
456}
457
458func (p *Pages) RepoSingleIssue(w io.Writer, params RepoSingleIssueParams) error {
459 params.Active = "issues"
460 if params.Issue.Open {
461 params.State = "open"
462 } else {
463 params.State = "closed"
464 }
465 return p.execute("repo/issues/issue", w, params)
466}
467
468type RepoNewIssueParams struct {
469 LoggedInUser *auth.User
470 RepoInfo RepoInfo
471 Active string
472}
473
474func (p *Pages) RepoNewIssue(w io.Writer, params RepoNewIssueParams) error {
475 params.Active = "issues"
476 return p.executeRepo("repo/issues/new", w, params)
477}
478
479func (p *Pages) Static() http.Handler {
480 sub, err := fs.Sub(files, "static")
481 if err != nil {
482 log.Fatalf("no static dir found? that's crazy: %v", err)
483 }
484 return http.StripPrefix("/static/", http.FileServer(http.FS(sub)))
485}
486
487func (p *Pages) Error500(w io.Writer) error {
488 return p.execute("errors/500", w, nil)
489}
490
491func (p *Pages) Error404(w io.Writer) error {
492 return p.execute("errors/404", w, nil)
493}
494
495func (p *Pages) Error503(w io.Writer) error {
496 return p.execute("errors/503", w, nil)
497}