this repo has no description
1package pages
2
3import (
4 "bytes"
5 "embed"
6 "fmt"
7 "html/template"
8 "io"
9 "io/fs"
10 "log"
11 "net/http"
12 "path"
13 "path/filepath"
14 "slices"
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/bluesky-social/indigo/atproto/syntax"
22 "github.com/microcosm-cc/bluemonday"
23 "github.com/sotangled/tangled/appview/auth"
24 "github.com/sotangled/tangled/appview/db"
25 "github.com/sotangled/tangled/types"
26)
27
28//go:embed templates/* static/*
29var files embed.FS
30
31type Pages struct {
32 t map[string]*template.Template
33}
34
35func NewPages() *Pages {
36 templates := make(map[string]*template.Template)
37
38 // Walk through embedded templates directory and parse all .html files
39 err := fs.WalkDir(files, "templates", func(path string, d fs.DirEntry, err error) error {
40 if err != nil {
41 return err
42 }
43
44 if !d.IsDir() && strings.HasSuffix(path, ".html") {
45 name := strings.TrimPrefix(path, "templates/")
46 name = strings.TrimSuffix(name, ".html")
47
48 // add fragments as templates
49 if strings.HasPrefix(path, "templates/fragments/") {
50 tmpl, err := template.New(name).
51 Funcs(funcMap()).
52 ParseFS(files, path)
53 if err != nil {
54 return fmt.Errorf("setting up fragment: %w", err)
55 }
56
57 templates[name] = tmpl
58 log.Printf("loaded fragment: %s", name)
59 }
60
61 // layouts and fragments are applied first
62 if !strings.HasPrefix(path, "templates/layouts/") &&
63 !strings.HasPrefix(path, "templates/fragments/") {
64 // Add the page template on top of the base
65 tmpl, err := template.New(name).
66 Funcs(funcMap()).
67 ParseFS(files, "templates/layouts/*.html", "templates/fragments/*.html", path)
68 if err != nil {
69 return fmt.Errorf("setting up template: %w", err)
70 }
71
72 templates[name] = tmpl
73 log.Printf("loaded template: %s", name)
74 }
75
76 return nil
77 }
78 return nil
79 })
80 if err != nil {
81 log.Fatalf("walking template dir: %v", err)
82 }
83
84 log.Printf("total templates loaded: %d", len(templates))
85
86 return &Pages{
87 t: templates,
88 }
89}
90
91type LoginParams struct {
92}
93
94func (p *Pages) execute(name string, w io.Writer, params any) error {
95 return p.t[name].ExecuteTemplate(w, "layouts/base", params)
96}
97
98func (p *Pages) executePlain(name string, w io.Writer, params any) error {
99 return p.t[name].Execute(w, params)
100}
101
102func (p *Pages) executeRepo(name string, w io.Writer, params any) error {
103 return p.t[name].ExecuteTemplate(w, "layouts/repobase", params)
104}
105
106func (p *Pages) Login(w io.Writer, params LoginParams) error {
107 return p.executePlain("user/login", w, params)
108}
109
110type TimelineParams struct {
111 LoggedInUser *auth.User
112 Timeline []db.TimelineEvent
113 DidHandleMap map[string]string
114}
115
116func (p *Pages) Timeline(w io.Writer, params TimelineParams) error {
117 return p.execute("timeline", w, params)
118}
119
120type SettingsParams struct {
121 LoggedInUser *auth.User
122 PubKeys []db.PublicKey
123}
124
125func (p *Pages) Settings(w io.Writer, params SettingsParams) error {
126 return p.execute("settings", w, params)
127}
128
129type KnotsParams struct {
130 LoggedInUser *auth.User
131 Registrations []db.Registration
132}
133
134func (p *Pages) Knots(w io.Writer, params KnotsParams) error {
135 return p.execute("knots", w, params)
136}
137
138type KnotParams struct {
139 LoggedInUser *auth.User
140 Registration *db.Registration
141 Members []string
142 IsOwner bool
143}
144
145func (p *Pages) Knot(w io.Writer, params KnotParams) error {
146 return p.execute("knot", w, params)
147}
148
149type NewRepoParams struct {
150 LoggedInUser *auth.User
151 Knots []string
152}
153
154func (p *Pages) NewRepo(w io.Writer, params NewRepoParams) error {
155 return p.execute("repo/new", w, params)
156}
157
158type ProfilePageParams struct {
159 LoggedInUser *auth.User
160 UserDid string
161 UserHandle string
162 Repos []db.Repo
163 CollaboratingRepos []db.Repo
164 ProfileStats ProfileStats
165 FollowStatus db.FollowStatus
166 DidHandleMap map[string]string
167 AvatarUri string
168}
169
170type ProfileStats struct {
171 Followers int
172 Following int
173}
174
175func (p *Pages) ProfilePage(w io.Writer, params ProfilePageParams) error {
176 return p.execute("user/profile", w, params)
177}
178
179type FollowFragmentParams struct {
180 UserDid string
181 FollowStatus db.FollowStatus
182}
183
184func (p *Pages) FollowFragment(w io.Writer, params FollowFragmentParams) error {
185 return p.executePlain("fragments/follow", w, params)
186}
187
188type StarFragmentParams struct {
189 IsStarred bool
190 RepoAt syntax.ATURI
191 Stats db.RepoStats
192}
193
194func (p *Pages) StarFragment(w io.Writer, params StarFragmentParams) error {
195 return p.executePlain("fragments/star", w, params)
196}
197
198type RepoDescriptionParams struct {
199 RepoInfo RepoInfo
200}
201
202func (p *Pages) EditRepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
203 return p.executePlain("fragments/editRepoDescription", w, params)
204}
205
206func (p *Pages) RepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
207 return p.executePlain("fragments/repoDescription", w, params)
208}
209
210type RepoInfo struct {
211 Name string
212 OwnerDid string
213 OwnerHandle string
214 Description string
215 Knot string
216 RepoAt syntax.ATURI
217 IsStarred bool
218 Stats db.RepoStats
219 Roles RolesInRepo
220}
221
222type RolesInRepo struct {
223 Roles []string
224}
225
226func (r RolesInRepo) SettingsAllowed() bool {
227 return slices.Contains(r.Roles, "repo:settings")
228}
229
230func (r RolesInRepo) IsOwner() bool {
231 return slices.Contains(r.Roles, "repo:owner")
232}
233
234func (r RolesInRepo) IsCollaborator() bool {
235 return slices.Contains(r.Roles, "repo:collaborator")
236}
237
238func (r RepoInfo) OwnerWithAt() string {
239 if r.OwnerHandle != "" {
240 return fmt.Sprintf("@%s", r.OwnerHandle)
241 } else {
242 return r.OwnerDid
243 }
244}
245
246func (r RepoInfo) FullName() string {
247 return path.Join(r.OwnerWithAt(), r.Name)
248}
249
250func (r RepoInfo) GetTabs() [][]string {
251 tabs := [][]string{
252 {"overview", "/"},
253 {"issues", "/issues"},
254 {"pulls", "/pulls"},
255 }
256
257 if r.Roles.SettingsAllowed() {
258 tabs = append(tabs, []string{"settings", "/settings"})
259 }
260
261 return tabs
262}
263
264// each tab on a repo could have some metadata:
265//
266// issues -> number of open issues etc.
267// settings -> a warning icon to setup branch protection? idk
268//
269// we gather these bits of info here, because go templates
270// are difficult to program in
271func (r RepoInfo) TabMetadata() map[string]any {
272 meta := make(map[string]any)
273
274 meta["issues"] = r.Stats.IssueCount.Open
275 meta["pulls"] = r.Stats.PullCount.Open
276
277 // more stuff?
278
279 return meta
280}
281
282type RepoIndexParams struct {
283 LoggedInUser *auth.User
284 RepoInfo RepoInfo
285 Active string
286 TagMap map[string][]string
287 types.RepoIndexResponse
288 HTMLReadme template.HTML
289 Raw bool
290}
291
292func (p *Pages) RepoIndexPage(w io.Writer, params RepoIndexParams) error {
293 params.Active = "overview"
294 if params.IsEmpty {
295 return p.executeRepo("repo/empty", w, params)
296 }
297
298 if params.ReadmeFileName != "" {
299 var htmlString string
300 ext := filepath.Ext(params.ReadmeFileName)
301 switch ext {
302 case ".md", ".markdown", ".mdown", ".mkdn", ".mkd":
303 htmlString = renderMarkdown(params.Readme)
304 params.Raw = false
305 params.HTMLReadme = template.HTML(bluemonday.UGCPolicy().Sanitize(htmlString))
306 default:
307 htmlString = string(params.Readme)
308 params.Raw = true
309 params.HTMLReadme = template.HTML(bluemonday.NewPolicy().Sanitize(htmlString))
310 }
311 }
312
313 return p.executeRepo("repo/index", w, params)
314}
315
316type RepoLogParams struct {
317 LoggedInUser *auth.User
318 RepoInfo RepoInfo
319 types.RepoLogResponse
320 Active string
321}
322
323func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error {
324 params.Active = "overview"
325 return p.execute("repo/log", w, params)
326}
327
328type RepoCommitParams struct {
329 LoggedInUser *auth.User
330 RepoInfo RepoInfo
331 Active string
332 types.RepoCommitResponse
333}
334
335func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error {
336 params.Active = "overview"
337 return p.executeRepo("repo/commit", w, params)
338}
339
340type RepoTreeParams struct {
341 LoggedInUser *auth.User
342 RepoInfo RepoInfo
343 Active string
344 BreadCrumbs [][]string
345 BaseTreeLink string
346 BaseBlobLink string
347 types.RepoTreeResponse
348}
349
350type RepoTreeStats struct {
351 NumFolders uint64
352 NumFiles uint64
353}
354
355func (r RepoTreeParams) TreeStats() RepoTreeStats {
356 numFolders, numFiles := 0, 0
357 for _, f := range r.Files {
358 if !f.IsFile {
359 numFolders += 1
360 } else if f.IsFile {
361 numFiles += 1
362 }
363 }
364
365 return RepoTreeStats{
366 NumFolders: uint64(numFolders),
367 NumFiles: uint64(numFiles),
368 }
369}
370
371func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error {
372 params.Active = "overview"
373 return p.execute("repo/tree", w, params)
374}
375
376type RepoBranchesParams struct {
377 LoggedInUser *auth.User
378 RepoInfo RepoInfo
379 types.RepoBranchesResponse
380}
381
382func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error {
383 return p.executeRepo("repo/branches", w, params)
384}
385
386type RepoTagsParams struct {
387 LoggedInUser *auth.User
388 RepoInfo RepoInfo
389 types.RepoTagsResponse
390}
391
392func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error {
393 return p.executeRepo("repo/tags", w, params)
394}
395
396type RepoBlobParams struct {
397 LoggedInUser *auth.User
398 RepoInfo RepoInfo
399 Active string
400 BreadCrumbs [][]string
401 types.RepoBlobResponse
402}
403
404func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error {
405 style := styles.Get("bw")
406 b := style.Builder()
407 b.Add(chroma.LiteralString, "noitalic")
408 style, _ = b.Build()
409
410 if params.Lines < 5000 {
411 c := params.Contents
412 formatter := chromahtml.New(
413 chromahtml.InlineCode(true),
414 chromahtml.WithLineNumbers(true),
415 chromahtml.WithLinkableLineNumbers(true, "L"),
416 chromahtml.Standalone(false),
417 )
418
419 lexer := lexers.Get(filepath.Base(params.Path))
420 if lexer == nil {
421 lexer = lexers.Fallback
422 }
423
424 iterator, err := lexer.Tokenise(nil, c)
425 if err != nil {
426 return fmt.Errorf("chroma tokenize: %w", err)
427 }
428
429 var code bytes.Buffer
430 err = formatter.Format(&code, style, iterator)
431 if err != nil {
432 return fmt.Errorf("chroma format: %w", err)
433 }
434
435 params.Contents = code.String()
436 }
437
438 params.Active = "overview"
439 return p.executeRepo("repo/blob", w, params)
440}
441
442type Collaborator struct {
443 Did string
444 Handle string
445 Role string
446}
447
448type RepoSettingsParams struct {
449 LoggedInUser *auth.User
450 RepoInfo RepoInfo
451 Collaborators []Collaborator
452 Active string
453 // TODO: use repoinfo.roles
454 IsCollaboratorInviteAllowed bool
455}
456
457func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error {
458 params.Active = "settings"
459 return p.executeRepo("repo/settings", w, params)
460}
461
462type RepoIssuesParams struct {
463 LoggedInUser *auth.User
464 RepoInfo RepoInfo
465 Active string
466 Issues []db.Issue
467 DidHandleMap map[string]string
468
469 FilteringByOpen bool
470}
471
472func (p *Pages) RepoIssues(w io.Writer, params RepoIssuesParams) error {
473 params.Active = "issues"
474 return p.executeRepo("repo/issues/issues", w, params)
475}
476
477type RepoSingleIssueParams struct {
478 LoggedInUser *auth.User
479 RepoInfo RepoInfo
480 Active string
481 Issue db.Issue
482 Comments []db.Comment
483 IssueOwnerHandle string
484 DidHandleMap map[string]string
485
486 State string
487}
488
489func (p *Pages) RepoSingleIssue(w io.Writer, params RepoSingleIssueParams) error {
490 params.Active = "issues"
491 if params.Issue.Open {
492 params.State = "open"
493 } else {
494 params.State = "closed"
495 }
496 return p.execute("repo/issues/issue", w, params)
497}
498
499type RepoNewIssueParams struct {
500 LoggedInUser *auth.User
501 RepoInfo RepoInfo
502 Active string
503}
504
505func (p *Pages) RepoNewIssue(w io.Writer, params RepoNewIssueParams) error {
506 params.Active = "issues"
507 return p.executeRepo("repo/issues/new", w, params)
508}
509
510type RepoNewPullParams struct {
511 LoggedInUser *auth.User
512 RepoInfo RepoInfo
513 Branches []types.Branch
514 Active string
515}
516
517func (p *Pages) RepoNewPull(w io.Writer, params RepoNewPullParams) error {
518 params.Active = "pulls"
519 return p.executeRepo("repo/pulls/new", w, params)
520}
521
522type RepoPullsParams struct {
523 LoggedInUser *auth.User
524 RepoInfo RepoInfo
525 Pulls []db.Pull
526 Active string
527 DidHandleMap map[string]string
528 FilteringBy db.PullState
529}
530
531func (p *Pages) RepoPulls(w io.Writer, params RepoPullsParams) error {
532 params.Active = "pulls"
533 return p.executeRepo("repo/pulls/pulls", w, params)
534}
535
536type RepoSinglePullParams struct {
537 LoggedInUser *auth.User
538 RepoInfo RepoInfo
539 DidHandleMap map[string]string
540 Pull db.Pull
541 PullOwnerHandle string
542 Comments []db.PullComment
543 Active string
544 MergeCheck types.MergeCheckResponse
545}
546
547func (p *Pages) RepoSinglePull(w io.Writer, params RepoSinglePullParams) error {
548 params.Active = "pulls"
549 return p.executeRepo("repo/pulls/pull", w, params)
550}
551
552func (p *Pages) Static() http.Handler {
553 sub, err := fs.Sub(files, "static")
554 if err != nil {
555 log.Fatalf("no static dir found? that's crazy: %v", err)
556 }
557 // Custom handler to apply Cache-Control headers for font files
558 return Cache(http.StripPrefix("/static/", http.FileServer(http.FS(sub))))
559}
560
561func Cache(h http.Handler) http.Handler {
562 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
563 if strings.HasSuffix(r.URL.Path, ".css") {
564 // on day for css files
565 w.Header().Set("Cache-Control", "public, max-age=86400")
566 } else {
567 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
568 }
569 h.ServeHTTP(w, r)
570 })
571}
572
573func (p *Pages) Error500(w io.Writer) error {
574 return p.execute("errors/500", w, nil)
575}
576
577func (p *Pages) Error404(w io.Writer) error {
578 return p.execute("errors/404", w, nil)
579}
580
581func (p *Pages) Error503(w io.Writer) error {
582 return p.execute("errors/503", w, nil)
583}