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