this repo has no description
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 return p.executeRepo("repo/index", w, params)
287}
288
289type RepoLogParams struct {
290 LoggedInUser *auth.User
291 RepoInfo RepoInfo
292 types.RepoLogResponse
293}
294
295func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error {
296 return p.execute("repo/log", w, params)
297}
298
299type RepoCommitParams struct {
300 LoggedInUser *auth.User
301 RepoInfo RepoInfo
302 Active string
303 types.RepoCommitResponse
304}
305
306func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error {
307 params.Active = "overview"
308 return p.executeRepo("repo/commit", w, params)
309}
310
311type RepoTreeParams struct {
312 LoggedInUser *auth.User
313 RepoInfo RepoInfo
314 Active string
315 BreadCrumbs [][]string
316 BaseTreeLink string
317 BaseBlobLink string
318 types.RepoTreeResponse
319}
320
321type RepoTreeStats struct {
322 NumFolders uint64
323 NumFiles uint64
324}
325
326func (r RepoTreeParams) TreeStats() RepoTreeStats {
327 numFolders, numFiles := 0, 0
328 for _, f := range r.Files {
329 if !f.IsFile {
330 numFolders += 1
331 } else if f.IsFile {
332 numFiles += 1
333 }
334 }
335
336 return RepoTreeStats{
337 NumFolders: uint64(numFolders),
338 NumFiles: uint64(numFiles),
339 }
340}
341
342func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error {
343 params.Active = "overview"
344 return p.execute("repo/tree", w, params)
345}
346
347type RepoBranchesParams struct {
348 LoggedInUser *auth.User
349 RepoInfo RepoInfo
350 types.RepoBranchesResponse
351}
352
353func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error {
354 return p.executeRepo("repo/branches", w, params)
355}
356
357type RepoTagsParams struct {
358 LoggedInUser *auth.User
359 RepoInfo RepoInfo
360 types.RepoTagsResponse
361}
362
363func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error {
364 return p.executeRepo("repo/tags", w, params)
365}
366
367type RepoBlobParams struct {
368 LoggedInUser *auth.User
369 RepoInfo RepoInfo
370 Active string
371 BreadCrumbs [][]string
372 types.RepoBlobResponse
373}
374
375func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error {
376 style := styles.Get("bw")
377 b := style.Builder()
378 b.Add(chroma.LiteralString, "noitalic")
379 style, _ = b.Build()
380
381 if params.Lines < 5000 {
382 c := params.Contents
383 formatter := chromahtml.New(
384 chromahtml.InlineCode(true),
385 chromahtml.WithLineNumbers(true),
386 chromahtml.WithLinkableLineNumbers(true, "L"),
387 chromahtml.Standalone(false),
388 )
389
390 lexer := lexers.Get(filepath.Base(params.Path))
391 if lexer == nil {
392 lexer = lexers.Fallback
393 }
394
395 iterator, err := lexer.Tokenise(nil, c)
396 if err != nil {
397 return fmt.Errorf("chroma tokenize: %w", err)
398 }
399
400 var code bytes.Buffer
401 err = formatter.Format(&code, style, iterator)
402 if err != nil {
403 return fmt.Errorf("chroma format: %w", err)
404 }
405
406 params.Contents = code.String()
407 }
408
409 params.Active = "overview"
410 return p.executeRepo("repo/blob", w, params)
411}
412
413type Collaborator struct {
414 Did string
415 Handle string
416 Role string
417}
418
419type RepoSettingsParams struct {
420 LoggedInUser *auth.User
421 RepoInfo RepoInfo
422 Collaborators []Collaborator
423 Active string
424 IsCollaboratorInviteAllowed bool
425}
426
427func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error {
428 params.Active = "settings"
429 return p.executeRepo("repo/settings", w, params)
430}
431
432func (p *Pages) Static() http.Handler {
433 sub, err := fs.Sub(files, "static")
434 if err != nil {
435 log.Fatalf("no static dir found? that's crazy: %v", err)
436 }
437 return http.StripPrefix("/static/", http.FileServer(http.FS(sub)))
438}
439
440func (p *Pages) Error500(w io.Writer) error {
441 return p.execute("errors/500", w, nil)
442}
443
444func (p *Pages) Error404(w io.Writer) error {
445 return p.execute("errors/404", w, nil)
446}
447
448func (p *Pages) Error503(w io.Writer) error {
449 return p.execute("errors/503", w, nil)
450}