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} 180 181func (p *Pages) Timeline(w io.Writer, params TimelineParams) error { 182 return p.execute("timeline", w, params) 183} 184 185type SettingsParams struct { 186 LoggedInUser *auth.User 187 PubKeys []db.PublicKey 188} 189 190func (p *Pages) Settings(w io.Writer, params SettingsParams) error { 191 return p.execute("settings/keys", w, params) 192} 193 194type KnotsParams struct { 195 LoggedInUser *auth.User 196 Registrations []db.Registration 197} 198 199func (p *Pages) Knots(w io.Writer, params KnotsParams) error { 200 return p.execute("knots", w, params) 201} 202 203type KnotParams struct { 204 LoggedInUser *auth.User 205 Registration *db.Registration 206 Members []string 207 IsOwner bool 208} 209 210func (p *Pages) Knot(w io.Writer, params KnotParams) error { 211 return p.execute("knot", w, params) 212} 213 214type NewRepoParams struct { 215 LoggedInUser *auth.User 216 Knots []string 217} 218 219func (p *Pages) NewRepo(w io.Writer, params NewRepoParams) error { 220 return p.execute("repo/new", w, params) 221} 222 223type ProfilePageParams struct { 224 LoggedInUser *auth.User 225 UserDid string 226 UserHandle string 227 Repos []db.Repo 228 CollaboratingRepos []db.Repo 229} 230 231func (p *Pages) ProfilePage(w io.Writer, params ProfilePageParams) error { 232 return p.execute("user/profile", w, params) 233} 234 235type RepoInfo struct { 236 Name string 237 OwnerDid string 238 OwnerHandle string 239 Description string 240 SettingsAllowed bool 241} 242 243func (r RepoInfo) OwnerWithAt() string { 244 if r.OwnerHandle != "" { 245 return fmt.Sprintf("@%s", r.OwnerHandle) 246 } else { 247 return r.OwnerDid 248 } 249} 250 251func (r RepoInfo) FullName() string { 252 return path.Join(r.OwnerWithAt(), r.Name) 253} 254 255func (r RepoInfo) GetTabs() [][]string { 256 tabs := [][]string{ 257 {"overview", "/"}, 258 {"issues", "/issues"}, 259 {"pulls", "/pulls"}, 260 } 261 262 if r.SettingsAllowed { 263 tabs = append(tabs, []string{"settings", "/settings"}) 264 } 265 266 return tabs 267} 268 269type RepoIndexParams struct { 270 LoggedInUser *auth.User 271 RepoInfo RepoInfo 272 Active string 273 types.RepoIndexResponse 274} 275 276func (p *Pages) RepoIndexPage(w io.Writer, params RepoIndexParams) error { 277 params.Active = "overview" 278 return p.executeRepo("repo/index", w, params) 279} 280 281type RepoLogParams struct { 282 LoggedInUser *auth.User 283 RepoInfo RepoInfo 284 types.RepoLogResponse 285} 286 287func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error { 288 return p.execute("repo/log", w, params) 289} 290 291type RepoCommitParams struct { 292 LoggedInUser *auth.User 293 RepoInfo RepoInfo 294 Active string 295 types.RepoCommitResponse 296} 297 298func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error { 299 params.Active = "overview" 300 return p.executeRepo("repo/commit", w, params) 301} 302 303type RepoTreeParams struct { 304 LoggedInUser *auth.User 305 RepoInfo RepoInfo 306 Active string 307 BreadCrumbs [][]string 308 BaseTreeLink string 309 BaseBlobLink string 310 types.RepoTreeResponse 311} 312 313type RepoTreeStats struct { 314 NumFolders uint64 315 NumFiles uint64 316} 317 318func (r RepoTreeParams) TreeStats() RepoTreeStats { 319 numFolders, numFiles := 0, 0 320 for _, f := range r.Files { 321 if !f.IsFile { 322 numFolders += 1 323 } else if f.IsFile { 324 numFiles += 1 325 } 326 } 327 328 return RepoTreeStats{ 329 NumFolders: uint64(numFolders), 330 NumFiles: uint64(numFiles), 331 } 332} 333 334func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error { 335 params.Active = "overview" 336 return p.execute("repo/tree", w, params) 337} 338 339type RepoBranchesParams struct { 340 LoggedInUser *auth.User 341 RepoInfo RepoInfo 342 types.RepoBranchesResponse 343} 344 345func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error { 346 return p.executeRepo("repo/branches", w, params) 347} 348 349type RepoTagsParams struct { 350 LoggedInUser *auth.User 351 RepoInfo RepoInfo 352 types.RepoTagsResponse 353} 354 355func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error { 356 return p.executeRepo("repo/tags", w, params) 357} 358 359type RepoBlobParams struct { 360 LoggedInUser *auth.User 361 RepoInfo RepoInfo 362 Active string 363 BreadCrumbs [][]string 364 types.RepoBlobResponse 365} 366 367func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error { 368 style := styles.Get("bw") 369 b := style.Builder() 370 b.Add(chroma.LiteralString, "noitalic") 371 style, _ = b.Build() 372 373 if params.Lines < 5000 { 374 c := params.Contents 375 formatter := chromahtml.New( 376 chromahtml.InlineCode(true), 377 chromahtml.WithLineNumbers(true), 378 chromahtml.WithLinkableLineNumbers(true, "L"), 379 chromahtml.Standalone(false), 380 ) 381 382 lexer := lexers.Get(filepath.Base(params.Path)) 383 if lexer == nil { 384 lexer = lexers.Fallback 385 } 386 387 iterator, err := lexer.Tokenise(nil, c) 388 if err != nil { 389 return fmt.Errorf("chroma tokenize: %w", err) 390 } 391 392 var code bytes.Buffer 393 err = formatter.Format(&code, style, iterator) 394 if err != nil { 395 return fmt.Errorf("chroma format: %w", err) 396 } 397 398 params.Contents = code.String() 399 } 400 401 params.Active = "overview" 402 return p.executeRepo("repo/blob", w, params) 403} 404 405type Collaborator struct { 406 Did string 407 Handle string 408 Role string 409} 410 411type RepoSettingsParams struct { 412 LoggedInUser *auth.User 413 RepoInfo RepoInfo 414 Collaborators []Collaborator 415 Active string 416 IsCollaboratorInviteAllowed bool 417} 418 419func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error { 420 params.Active = "settings" 421 return p.executeRepo("repo/settings", w, params) 422} 423 424func (p *Pages) Static() http.Handler { 425 sub, err := fs.Sub(files, "static") 426 if err != nil { 427 log.Fatalf("no static dir found? that's crazy: %v", err) 428 } 429 return http.StripPrefix("/static/", http.FileServer(http.FS(sub))) 430} 431 432func (p *Pages) Error500(w io.Writer) error { 433 return p.execute("errors/500", w, nil) 434} 435 436func (p *Pages) Error404(w io.Writer) error { 437 return p.execute("errors/404", w, nil) 438} 439 440func (p *Pages) Error503(w io.Writer) error { 441 return p.execute("errors/503", w, nil) 442}