this repo has no description
1package pages 2 3import ( 4 "bytes" 5 "crypto/sha256" 6 "embed" 7 "encoding/hex" 8 "fmt" 9 "html/template" 10 "io" 11 "io/fs" 12 "log/slog" 13 "net/http" 14 "os" 15 "path/filepath" 16 "strings" 17 "sync" 18 19 "tangled.sh/tangled.sh/core/api/tangled" 20 "tangled.sh/tangled.sh/core/appview/commitverify" 21 "tangled.sh/tangled.sh/core/appview/config" 22 "tangled.sh/tangled.sh/core/appview/db" 23 "tangled.sh/tangled.sh/core/appview/oauth" 24 "tangled.sh/tangled.sh/core/appview/pages/markup" 25 "tangled.sh/tangled.sh/core/appview/pages/repoinfo" 26 "tangled.sh/tangled.sh/core/appview/pagination" 27 "tangled.sh/tangled.sh/core/idresolver" 28 "tangled.sh/tangled.sh/core/patchutil" 29 "tangled.sh/tangled.sh/core/types" 30 31 "github.com/alecthomas/chroma/v2" 32 chromahtml "github.com/alecthomas/chroma/v2/formatters/html" 33 "github.com/alecthomas/chroma/v2/lexers" 34 "github.com/alecthomas/chroma/v2/styles" 35 "github.com/bluesky-social/indigo/atproto/identity" 36 "github.com/bluesky-social/indigo/atproto/syntax" 37 "github.com/go-git/go-git/v5/plumbing" 38 "github.com/go-git/go-git/v5/plumbing/object" 39) 40 41//go:embed templates/* static 42var Files embed.FS 43 44type Pages struct { 45 mu sync.RWMutex 46 cache *TmplCache[string, *template.Template] 47 48 avatar config.AvatarConfig 49 resolver *idresolver.Resolver 50 dev bool 51 embedFS fs.FS 52 templateDir string // Path to templates on disk for dev mode 53 rctx *markup.RenderContext 54 logger *slog.Logger 55} 56 57func NewPages(config *config.Config, res *idresolver.Resolver) *Pages { 58 // initialized with safe defaults, can be overriden per use 59 rctx := &markup.RenderContext{ 60 IsDev: config.Core.Dev, 61 CamoUrl: config.Camo.Host, 62 CamoSecret: config.Camo.SharedSecret, 63 Sanitizer: markup.NewSanitizer(), 64 } 65 66 p := &Pages{ 67 mu: sync.RWMutex{}, 68 cache: NewTmplCache[string, *template.Template](), 69 dev: config.Core.Dev, 70 avatar: config.Avatar, 71 rctx: rctx, 72 resolver: res, 73 templateDir: "appview/pages", 74 logger: slog.Default().With("component", "pages"), 75 } 76 77 if p.dev { 78 p.embedFS = os.DirFS(p.templateDir) 79 } else { 80 p.embedFS = Files 81 } 82 83 return p 84} 85 86func (p *Pages) pathToName(s string) string { 87 return strings.TrimSuffix(strings.TrimPrefix(s, "templates/"), ".html") 88} 89 90// reverse of pathToName 91func (p *Pages) nameToPath(s string) string { 92 return "templates/" + s + ".html" 93} 94 95func (p *Pages) fragmentPaths() ([]string, error) { 96 var fragmentPaths []string 97 err := fs.WalkDir(p.embedFS, "templates", func(path string, d fs.DirEntry, err error) error { 98 if err != nil { 99 return err 100 } 101 if d.IsDir() { 102 return nil 103 } 104 if !strings.HasSuffix(path, ".html") { 105 return nil 106 } 107 if !strings.Contains(path, "fragments/") { 108 return nil 109 } 110 fragmentPaths = append(fragmentPaths, path) 111 return nil 112 }) 113 if err != nil { 114 return nil, err 115 } 116 117 return fragmentPaths, nil 118} 119 120func (p *Pages) fragments() (*template.Template, error) { 121 fragmentPaths, err := p.fragmentPaths() 122 if err != nil { 123 return nil, err 124 } 125 126 funcs := p.funcMap() 127 128 // parse all fragments together 129 allFragments := template.New("").Funcs(funcs) 130 for _, f := range fragmentPaths { 131 name := p.pathToName(f) 132 133 pf, err := template.New(name). 134 Funcs(funcs). 135 ParseFS(p.embedFS, f) 136 if err != nil { 137 return nil, err 138 } 139 140 allFragments, err = allFragments.AddParseTree(name, pf.Tree) 141 if err != nil { 142 return nil, err 143 } 144 } 145 146 return allFragments, nil 147} 148 149// parse without memoization 150func (p *Pages) rawParse(stack ...string) (*template.Template, error) { 151 paths, err := p.fragmentPaths() 152 if err != nil { 153 return nil, err 154 } 155 for _, s := range stack { 156 paths = append(paths, p.nameToPath(s)) 157 } 158 159 funcs := p.funcMap() 160 top := stack[len(stack)-1] 161 parsed, err := template.New(top). 162 Funcs(funcs). 163 ParseFS(p.embedFS, paths...) 164 if err != nil { 165 return nil, err 166 } 167 168 return parsed, nil 169} 170 171func (p *Pages) parse(stack ...string) (*template.Template, error) { 172 key := strings.Join(stack, "|") 173 174 // never cache in dev mode 175 if cached, exists := p.cache.Get(key); !p.dev && exists { 176 return cached, nil 177 } 178 179 result, err := p.rawParse(stack...) 180 if err != nil { 181 return nil, err 182 } 183 184 p.cache.Set(key, result) 185 return result, nil 186} 187 188func (p *Pages) parseBase(top string) (*template.Template, error) { 189 stack := []string{ 190 "layouts/base", 191 top, 192 } 193 return p.parse(stack...) 194} 195 196func (p *Pages) parseRepoBase(top string) (*template.Template, error) { 197 stack := []string{ 198 "layouts/base", 199 "layouts/repobase", 200 top, 201 } 202 return p.parse(stack...) 203} 204 205func (p *Pages) parseProfileBase(top string) (*template.Template, error) { 206 stack := []string{ 207 "layouts/base", 208 "layouts/profilebase", 209 top, 210 } 211 return p.parse(stack...) 212} 213 214func (p *Pages) executePlain(name string, w io.Writer, params any) error { 215 tpl, err := p.parse(name) 216 if err != nil { 217 return err 218 } 219 220 return tpl.Execute(w, params) 221} 222 223func (p *Pages) execute(name string, w io.Writer, params any) error { 224 tpl, err := p.parseBase(name) 225 if err != nil { 226 return err 227 } 228 229 return tpl.ExecuteTemplate(w, "layouts/base", params) 230} 231 232func (p *Pages) executeRepo(name string, w io.Writer, params any) error { 233 tpl, err := p.parseRepoBase(name) 234 if err != nil { 235 return err 236 } 237 238 return tpl.ExecuteTemplate(w, "layouts/base", params) 239} 240 241func (p *Pages) executeProfile(name string, w io.Writer, params any) error { 242 tpl, err := p.parseProfileBase(name) 243 if err != nil { 244 return err 245 } 246 247 return tpl.ExecuteTemplate(w, "layouts/base", params) 248} 249 250func (p *Pages) Favicon(w io.Writer) error { 251 return p.executePlain("favicon", w, nil) 252} 253 254type LoginParams struct { 255 ReturnUrl string 256} 257 258func (p *Pages) Login(w io.Writer, params LoginParams) error { 259 return p.executePlain("user/login", w, params) 260} 261 262func (p *Pages) Signup(w io.Writer) error { 263 return p.executePlain("user/signup", w, nil) 264} 265 266func (p *Pages) CompleteSignup(w io.Writer) error { 267 return p.executePlain("user/completeSignup", w, nil) 268} 269 270type TermsOfServiceParams struct { 271 LoggedInUser *oauth.User 272 Content template.HTML 273} 274 275func (p *Pages) TermsOfService(w io.Writer, params TermsOfServiceParams) error { 276 filename := "terms.md" 277 filePath := filepath.Join("legal", filename) 278 markdownBytes, err := os.ReadFile(filePath) 279 if err != nil { 280 return fmt.Errorf("failed to read %s: %w", filename, err) 281 } 282 283 p.rctx.RendererType = markup.RendererTypeDefault 284 htmlString := p.rctx.RenderMarkdown(string(markdownBytes)) 285 sanitized := p.rctx.SanitizeDefault(htmlString) 286 params.Content = template.HTML(sanitized) 287 288 return p.execute("legal/terms", w, params) 289} 290 291type PrivacyPolicyParams struct { 292 LoggedInUser *oauth.User 293 Content template.HTML 294} 295 296func (p *Pages) PrivacyPolicy(w io.Writer, params PrivacyPolicyParams) error { 297 filename := "privacy.md" 298 filePath := filepath.Join("legal", filename) 299 markdownBytes, err := os.ReadFile(filePath) 300 if err != nil { 301 return fmt.Errorf("failed to read %s: %w", filename, err) 302 } 303 304 p.rctx.RendererType = markup.RendererTypeDefault 305 htmlString := p.rctx.RenderMarkdown(string(markdownBytes)) 306 sanitized := p.rctx.SanitizeDefault(htmlString) 307 params.Content = template.HTML(sanitized) 308 309 return p.execute("legal/privacy", w, params) 310} 311 312type TimelineParams struct { 313 LoggedInUser *oauth.User 314 Timeline []db.TimelineEvent 315 Repos []db.Repo 316} 317 318func (p *Pages) Timeline(w io.Writer, params TimelineParams) error { 319 return p.execute("timeline/timeline", w, params) 320} 321 322type UserProfileSettingsParams struct { 323 LoggedInUser *oauth.User 324 Tabs []map[string]any 325 Tab string 326} 327 328func (p *Pages) UserProfileSettings(w io.Writer, params UserProfileSettingsParams) error { 329 return p.execute("user/settings/profile", w, params) 330} 331 332type UserKeysSettingsParams struct { 333 LoggedInUser *oauth.User 334 PubKeys []db.PublicKey 335 Tabs []map[string]any 336 Tab string 337} 338 339func (p *Pages) UserKeysSettings(w io.Writer, params UserKeysSettingsParams) error { 340 return p.execute("user/settings/keys", w, params) 341} 342 343type UserEmailsSettingsParams struct { 344 LoggedInUser *oauth.User 345 Emails []db.Email 346 Tabs []map[string]any 347 Tab string 348} 349 350func (p *Pages) UserEmailsSettings(w io.Writer, params UserEmailsSettingsParams) error { 351 return p.execute("user/settings/emails", w, params) 352} 353 354type KnotBannerParams struct { 355 Registrations []db.Registration 356} 357 358func (p *Pages) KnotBanner(w io.Writer, params KnotBannerParams) error { 359 return p.executePlain("knots/fragments/banner", w, params) 360} 361 362type KnotsParams struct { 363 LoggedInUser *oauth.User 364 Registrations []db.Registration 365} 366 367func (p *Pages) Knots(w io.Writer, params KnotsParams) error { 368 return p.execute("knots/index", w, params) 369} 370 371type KnotParams struct { 372 LoggedInUser *oauth.User 373 Registration *db.Registration 374 Members []string 375 Repos map[string][]db.Repo 376 IsOwner bool 377} 378 379func (p *Pages) Knot(w io.Writer, params KnotParams) error { 380 return p.execute("knots/dashboard", w, params) 381} 382 383type KnotListingParams struct { 384 *db.Registration 385} 386 387func (p *Pages) KnotListing(w io.Writer, params KnotListingParams) error { 388 return p.executePlain("knots/fragments/knotListing", w, params) 389} 390 391type SpindlesParams struct { 392 LoggedInUser *oauth.User 393 Spindles []db.Spindle 394} 395 396func (p *Pages) Spindles(w io.Writer, params SpindlesParams) error { 397 return p.execute("spindles/index", w, params) 398} 399 400type SpindleListingParams struct { 401 db.Spindle 402} 403 404func (p *Pages) SpindleListing(w io.Writer, params SpindleListingParams) error { 405 return p.executePlain("spindles/fragments/spindleListing", w, params) 406} 407 408type SpindleDashboardParams struct { 409 LoggedInUser *oauth.User 410 Spindle db.Spindle 411 Members []string 412 Repos map[string][]db.Repo 413} 414 415func (p *Pages) SpindleDashboard(w io.Writer, params SpindleDashboardParams) error { 416 return p.execute("spindles/dashboard", w, params) 417} 418 419type NewRepoParams struct { 420 LoggedInUser *oauth.User 421 Knots []string 422} 423 424func (p *Pages) NewRepo(w io.Writer, params NewRepoParams) error { 425 return p.execute("repo/new", w, params) 426} 427 428type ForkRepoParams struct { 429 LoggedInUser *oauth.User 430 Knots []string 431 RepoInfo repoinfo.RepoInfo 432} 433 434func (p *Pages) ForkRepo(w io.Writer, params ForkRepoParams) error { 435 return p.execute("repo/fork", w, params) 436} 437 438type ProfileCard struct { 439 UserDid string 440 UserHandle string 441 FollowStatus db.FollowStatus 442 Punchcard *db.Punchcard 443 Profile *db.Profile 444 Stats ProfileStats 445 Active string 446} 447 448type ProfileStats struct { 449 RepoCount int64 450 StarredCount int64 451 StringCount int64 452 FollowersCount int64 453 FollowingCount int64 454} 455 456func (p *ProfileCard) GetTabs() [][]any { 457 tabs := [][]any{ 458 {"overview", "overview", "square-chart-gantt", nil}, 459 {"repos", "repos", "book-marked", p.Stats.RepoCount}, 460 {"starred", "starred", "star", p.Stats.StarredCount}, 461 {"strings", "strings", "line-squiggle", p.Stats.StringCount}, 462 } 463 464 return tabs 465} 466 467type ProfileOverviewParams struct { 468 LoggedInUser *oauth.User 469 Repos []db.Repo 470 CollaboratingRepos []db.Repo 471 ProfileTimeline *db.ProfileTimeline 472 Card *ProfileCard 473 Active string 474} 475 476func (p *Pages) ProfileOverview(w io.Writer, params ProfileOverviewParams) error { 477 params.Active = "overview" 478 return p.executeProfile("user/overview", w, params) 479} 480 481type ProfileReposParams struct { 482 LoggedInUser *oauth.User 483 Repos []db.Repo 484 Card *ProfileCard 485 Active string 486} 487 488func (p *Pages) ProfileRepos(w io.Writer, params ProfileReposParams) error { 489 params.Active = "repos" 490 return p.executeProfile("user/repos", w, params) 491} 492 493type ProfileStarredParams struct { 494 LoggedInUser *oauth.User 495 Repos []db.Repo 496 Card *ProfileCard 497 Active string 498} 499 500func (p *Pages) ProfileStarred(w io.Writer, params ProfileStarredParams) error { 501 params.Active = "starred" 502 return p.executeProfile("user/starred", w, params) 503} 504 505type ProfileStringsParams struct { 506 LoggedInUser *oauth.User 507 Strings []db.String 508 Card *ProfileCard 509 Active string 510} 511 512func (p *Pages) ProfileStrings(w io.Writer, params ProfileStringsParams) error { 513 params.Active = "strings" 514 return p.executeProfile("user/strings", w, params) 515} 516 517type FollowCard struct { 518 UserDid string 519 FollowStatus db.FollowStatus 520 FollowersCount int64 521 FollowingCount int64 522 Profile *db.Profile 523} 524 525type ProfileFollowersParams struct { 526 LoggedInUser *oauth.User 527 Followers []FollowCard 528 Card *ProfileCard 529 Active string 530} 531 532func (p *Pages) ProfileFollowers(w io.Writer, params ProfileFollowersParams) error { 533 params.Active = "overview" 534 return p.executeProfile("user/followers", w, params) 535} 536 537type ProfileFollowingParams struct { 538 LoggedInUser *oauth.User 539 Following []FollowCard 540 Card *ProfileCard 541 Active string 542} 543 544func (p *Pages) ProfileFollowing(w io.Writer, params ProfileFollowingParams) error { 545 params.Active = "overview" 546 return p.executeProfile("user/following", w, params) 547} 548 549type FollowFragmentParams struct { 550 UserDid string 551 FollowStatus db.FollowStatus 552} 553 554func (p *Pages) FollowFragment(w io.Writer, params FollowFragmentParams) error { 555 return p.executePlain("user/fragments/follow", w, params) 556} 557 558type EditBioParams struct { 559 LoggedInUser *oauth.User 560 Profile *db.Profile 561} 562 563func (p *Pages) EditBioFragment(w io.Writer, params EditBioParams) error { 564 return p.executePlain("user/fragments/editBio", w, params) 565} 566 567type EditPinsParams struct { 568 LoggedInUser *oauth.User 569 Profile *db.Profile 570 AllRepos []PinnedRepo 571} 572 573type PinnedRepo struct { 574 IsPinned bool 575 db.Repo 576} 577 578func (p *Pages) EditPinsFragment(w io.Writer, params EditPinsParams) error { 579 return p.executePlain("user/fragments/editPins", w, params) 580} 581 582type RepoStarFragmentParams struct { 583 IsStarred bool 584 RepoAt syntax.ATURI 585 Stats db.RepoStats 586} 587 588func (p *Pages) RepoStarFragment(w io.Writer, params RepoStarFragmentParams) error { 589 return p.executePlain("repo/fragments/repoStar", w, params) 590} 591 592type RepoDescriptionParams struct { 593 RepoInfo repoinfo.RepoInfo 594} 595 596func (p *Pages) EditRepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error { 597 return p.executePlain("repo/fragments/editRepoDescription", w, params) 598} 599 600func (p *Pages) RepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error { 601 return p.executePlain("repo/fragments/repoDescription", w, params) 602} 603 604type RepoIndexParams struct { 605 LoggedInUser *oauth.User 606 RepoInfo repoinfo.RepoInfo 607 Active string 608 TagMap map[string][]string 609 CommitsTrunc []*object.Commit 610 TagsTrunc []*types.TagReference 611 BranchesTrunc []types.Branch 612 // ForkInfo *types.ForkInfo 613 HTMLReadme template.HTML 614 Raw bool 615 EmailToDidOrHandle map[string]string 616 VerifiedCommits commitverify.VerifiedCommits 617 Languages []types.RepoLanguageDetails 618 Pipelines map[string]db.Pipeline 619 types.RepoIndexResponse 620} 621 622func (p *Pages) RepoIndexPage(w io.Writer, params RepoIndexParams) error { 623 params.Active = "overview" 624 if params.IsEmpty { 625 return p.executeRepo("repo/empty", w, params) 626 } 627 628 p.rctx.RepoInfo = params.RepoInfo 629 p.rctx.RepoInfo.Ref = params.Ref 630 p.rctx.RendererType = markup.RendererTypeRepoMarkdown 631 632 if params.ReadmeFileName != "" { 633 ext := filepath.Ext(params.ReadmeFileName) 634 switch ext { 635 case ".md", ".markdown", ".mdown", ".mkdn", ".mkd": 636 params.Raw = false 637 htmlString := p.rctx.RenderMarkdown(params.Readme) 638 sanitized := p.rctx.SanitizeDefault(htmlString) 639 params.HTMLReadme = template.HTML(sanitized) 640 default: 641 params.Raw = true 642 } 643 } 644 645 return p.executeRepo("repo/index", w, params) 646} 647 648type RepoLogParams struct { 649 LoggedInUser *oauth.User 650 RepoInfo repoinfo.RepoInfo 651 TagMap map[string][]string 652 types.RepoLogResponse 653 Active string 654 EmailToDidOrHandle map[string]string 655 VerifiedCommits commitverify.VerifiedCommits 656 Pipelines map[string]db.Pipeline 657} 658 659func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error { 660 params.Active = "overview" 661 return p.executeRepo("repo/log", w, params) 662} 663 664type RepoCommitParams struct { 665 LoggedInUser *oauth.User 666 RepoInfo repoinfo.RepoInfo 667 Active string 668 EmailToDidOrHandle map[string]string 669 Pipeline *db.Pipeline 670 DiffOpts types.DiffOpts 671 672 // singular because it's always going to be just one 673 VerifiedCommit commitverify.VerifiedCommits 674 675 types.RepoCommitResponse 676} 677 678func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error { 679 params.Active = "overview" 680 return p.executeRepo("repo/commit", w, params) 681} 682 683type RepoTreeParams struct { 684 LoggedInUser *oauth.User 685 RepoInfo repoinfo.RepoInfo 686 Active string 687 BreadCrumbs [][]string 688 TreePath string 689 types.RepoTreeResponse 690} 691 692type RepoTreeStats struct { 693 NumFolders uint64 694 NumFiles uint64 695} 696 697func (r RepoTreeParams) TreeStats() RepoTreeStats { 698 numFolders, numFiles := 0, 0 699 for _, f := range r.Files { 700 if !f.IsFile { 701 numFolders += 1 702 } else if f.IsFile { 703 numFiles += 1 704 } 705 } 706 707 return RepoTreeStats{ 708 NumFolders: uint64(numFolders), 709 NumFiles: uint64(numFiles), 710 } 711} 712 713func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error { 714 params.Active = "overview" 715 return p.executeRepo("repo/tree", w, params) 716} 717 718type RepoBranchesParams struct { 719 LoggedInUser *oauth.User 720 RepoInfo repoinfo.RepoInfo 721 Active string 722 types.RepoBranchesResponse 723} 724 725func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error { 726 params.Active = "overview" 727 return p.executeRepo("repo/branches", w, params) 728} 729 730type RepoTagsParams struct { 731 LoggedInUser *oauth.User 732 RepoInfo repoinfo.RepoInfo 733 Active string 734 types.RepoTagsResponse 735 ArtifactMap map[plumbing.Hash][]db.Artifact 736 DanglingArtifacts []db.Artifact 737} 738 739func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error { 740 params.Active = "overview" 741 return p.executeRepo("repo/tags", w, params) 742} 743 744type RepoArtifactParams struct { 745 LoggedInUser *oauth.User 746 RepoInfo repoinfo.RepoInfo 747 Artifact db.Artifact 748} 749 750func (p *Pages) RepoArtifactFragment(w io.Writer, params RepoArtifactParams) error { 751 return p.executePlain("repo/fragments/artifact", w, params) 752} 753 754type RepoBlobParams struct { 755 LoggedInUser *oauth.User 756 RepoInfo repoinfo.RepoInfo 757 Active string 758 Unsupported bool 759 IsImage bool 760 IsVideo bool 761 ContentSrc string 762 BreadCrumbs [][]string 763 ShowRendered bool 764 RenderToggle bool 765 RenderedContents template.HTML 766 *tangled.RepoBlob_Output 767 // Computed fields for template compatibility 768 Contents string 769 Lines int 770 SizeHint uint64 771 IsBinary bool 772} 773 774func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error { 775 var style *chroma.Style = styles.Get("catpuccin-latte") 776 777 if params.ShowRendered { 778 switch markup.GetFormat(params.Path) { 779 case markup.FormatMarkdown: 780 p.rctx.RepoInfo = params.RepoInfo 781 p.rctx.RendererType = markup.RendererTypeRepoMarkdown 782 htmlString := p.rctx.RenderMarkdown(params.Contents) 783 sanitized := p.rctx.SanitizeDefault(htmlString) 784 params.RenderedContents = template.HTML(sanitized) 785 } 786 } 787 788 c := params.Contents 789 formatter := chromahtml.New( 790 chromahtml.InlineCode(false), 791 chromahtml.WithLineNumbers(true), 792 chromahtml.WithLinkableLineNumbers(true, "L"), 793 chromahtml.Standalone(false), 794 chromahtml.WithClasses(true), 795 ) 796 797 lexer := lexers.Get(filepath.Base(params.Path)) 798 if lexer == nil { 799 lexer = lexers.Fallback 800 } 801 802 iterator, err := lexer.Tokenise(nil, c) 803 if err != nil { 804 return fmt.Errorf("chroma tokenize: %w", err) 805 } 806 807 var code bytes.Buffer 808 err = formatter.Format(&code, style, iterator) 809 if err != nil { 810 return fmt.Errorf("chroma format: %w", err) 811 } 812 813 params.Contents = code.String() 814 params.Active = "overview" 815 return p.executeRepo("repo/blob", w, params) 816} 817 818type Collaborator struct { 819 Did string 820 Handle string 821 Role string 822} 823 824type RepoSettingsParams struct { 825 LoggedInUser *oauth.User 826 RepoInfo repoinfo.RepoInfo 827 Collaborators []Collaborator 828 Active string 829 Branches []types.Branch 830 Spindles []string 831 CurrentSpindle string 832 Secrets []*tangled.RepoListSecrets_Secret 833 834 // TODO: use repoinfo.roles 835 IsCollaboratorInviteAllowed bool 836} 837 838func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error { 839 params.Active = "settings" 840 return p.executeRepo("repo/settings", w, params) 841} 842 843type RepoGeneralSettingsParams struct { 844 LoggedInUser *oauth.User 845 RepoInfo repoinfo.RepoInfo 846 Active string 847 Tabs []map[string]any 848 Tab string 849 Branches []types.Branch 850} 851 852func (p *Pages) RepoGeneralSettings(w io.Writer, params RepoGeneralSettingsParams) error { 853 params.Active = "settings" 854 return p.executeRepo("repo/settings/general", w, params) 855} 856 857type RepoAccessSettingsParams struct { 858 LoggedInUser *oauth.User 859 RepoInfo repoinfo.RepoInfo 860 Active string 861 Tabs []map[string]any 862 Tab string 863 Collaborators []Collaborator 864} 865 866func (p *Pages) RepoAccessSettings(w io.Writer, params RepoAccessSettingsParams) error { 867 params.Active = "settings" 868 return p.executeRepo("repo/settings/access", w, params) 869} 870 871type RepoPipelineSettingsParams struct { 872 LoggedInUser *oauth.User 873 RepoInfo repoinfo.RepoInfo 874 Active string 875 Tabs []map[string]any 876 Tab string 877 Spindles []string 878 CurrentSpindle string 879 Secrets []map[string]any 880} 881 882func (p *Pages) RepoPipelineSettings(w io.Writer, params RepoPipelineSettingsParams) error { 883 params.Active = "settings" 884 return p.executeRepo("repo/settings/pipelines", w, params) 885} 886 887type RepoIssuesParams struct { 888 LoggedInUser *oauth.User 889 RepoInfo repoinfo.RepoInfo 890 Active string 891 Issues []db.Issue 892 Page pagination.Page 893 FilteringByOpen bool 894} 895 896func (p *Pages) RepoIssues(w io.Writer, params RepoIssuesParams) error { 897 params.Active = "issues" 898 return p.executeRepo("repo/issues/issues", w, params) 899} 900 901type RepoSingleIssueParams struct { 902 LoggedInUser *oauth.User 903 RepoInfo repoinfo.RepoInfo 904 Active string 905 Issue *db.Issue 906 Comments []db.Comment 907 IssueOwnerHandle string 908 909 OrderedReactionKinds []db.ReactionKind 910 Reactions map[db.ReactionKind]int 911 UserReacted map[db.ReactionKind]bool 912 913 State string 914} 915 916type ThreadReactionFragmentParams struct { 917 ThreadAt syntax.ATURI 918 Kind db.ReactionKind 919 Count int 920 IsReacted bool 921} 922 923func (p *Pages) ThreadReactionFragment(w io.Writer, params ThreadReactionFragmentParams) error { 924 return p.executePlain("repo/fragments/reaction", w, params) 925} 926 927func (p *Pages) RepoSingleIssue(w io.Writer, params RepoSingleIssueParams) error { 928 params.Active = "issues" 929 if params.Issue.Open { 930 params.State = "open" 931 } else { 932 params.State = "closed" 933 } 934 return p.executeRepo("repo/issues/issue", w, params) 935} 936 937type RepoNewIssueParams struct { 938 LoggedInUser *oauth.User 939 RepoInfo repoinfo.RepoInfo 940 Active string 941} 942 943func (p *Pages) RepoNewIssue(w io.Writer, params RepoNewIssueParams) error { 944 params.Active = "issues" 945 return p.executeRepo("repo/issues/new", w, params) 946} 947 948type EditIssueCommentParams struct { 949 LoggedInUser *oauth.User 950 RepoInfo repoinfo.RepoInfo 951 Issue *db.Issue 952 Comment *db.Comment 953} 954 955func (p *Pages) EditIssueCommentFragment(w io.Writer, params EditIssueCommentParams) error { 956 return p.executePlain("repo/issues/fragments/editIssueComment", w, params) 957} 958 959type SingleIssueCommentParams struct { 960 LoggedInUser *oauth.User 961 RepoInfo repoinfo.RepoInfo 962 Issue *db.Issue 963 Comment *db.Comment 964} 965 966func (p *Pages) SingleIssueCommentFragment(w io.Writer, params SingleIssueCommentParams) error { 967 return p.executePlain("repo/issues/fragments/issueComment", w, params) 968} 969 970type RepoNewPullParams struct { 971 LoggedInUser *oauth.User 972 RepoInfo repoinfo.RepoInfo 973 Branches []types.Branch 974 Strategy string 975 SourceBranch string 976 TargetBranch string 977 Title string 978 Body string 979 Active string 980} 981 982func (p *Pages) RepoNewPull(w io.Writer, params RepoNewPullParams) error { 983 params.Active = "pulls" 984 return p.executeRepo("repo/pulls/new", w, params) 985} 986 987type RepoPullsParams struct { 988 LoggedInUser *oauth.User 989 RepoInfo repoinfo.RepoInfo 990 Pulls []*db.Pull 991 Active string 992 FilteringBy db.PullState 993 Stacks map[string]db.Stack 994 Pipelines map[string]db.Pipeline 995} 996 997func (p *Pages) RepoPulls(w io.Writer, params RepoPullsParams) error { 998 params.Active = "pulls" 999 return p.executeRepo("repo/pulls/pulls", w, params) 1000} 1001 1002type ResubmitResult uint64 1003 1004const ( 1005 ShouldResubmit ResubmitResult = iota 1006 ShouldNotResubmit 1007 Unknown 1008) 1009 1010func (r ResubmitResult) Yes() bool { 1011 return r == ShouldResubmit 1012} 1013func (r ResubmitResult) No() bool { 1014 return r == ShouldNotResubmit 1015} 1016func (r ResubmitResult) Unknown() bool { 1017 return r == Unknown 1018} 1019 1020type RepoSinglePullParams struct { 1021 LoggedInUser *oauth.User 1022 RepoInfo repoinfo.RepoInfo 1023 Active string 1024 Pull *db.Pull 1025 Stack db.Stack 1026 AbandonedPulls []*db.Pull 1027 MergeCheck types.MergeCheckResponse 1028 ResubmitCheck ResubmitResult 1029 Pipelines map[string]db.Pipeline 1030 1031 OrderedReactionKinds []db.ReactionKind 1032 Reactions map[db.ReactionKind]int 1033 UserReacted map[db.ReactionKind]bool 1034} 1035 1036func (p *Pages) RepoSinglePull(w io.Writer, params RepoSinglePullParams) error { 1037 params.Active = "pulls" 1038 return p.executeRepo("repo/pulls/pull", w, params) 1039} 1040 1041type RepoPullPatchParams struct { 1042 LoggedInUser *oauth.User 1043 RepoInfo repoinfo.RepoInfo 1044 Pull *db.Pull 1045 Stack db.Stack 1046 Diff *types.NiceDiff 1047 Round int 1048 Submission *db.PullSubmission 1049 OrderedReactionKinds []db.ReactionKind 1050 DiffOpts types.DiffOpts 1051} 1052 1053// this name is a mouthful 1054func (p *Pages) RepoPullPatchPage(w io.Writer, params RepoPullPatchParams) error { 1055 return p.execute("repo/pulls/patch", w, params) 1056} 1057 1058type RepoPullInterdiffParams struct { 1059 LoggedInUser *oauth.User 1060 RepoInfo repoinfo.RepoInfo 1061 Pull *db.Pull 1062 Round int 1063 Interdiff *patchutil.InterdiffResult 1064 OrderedReactionKinds []db.ReactionKind 1065 DiffOpts types.DiffOpts 1066} 1067 1068// this name is a mouthful 1069func (p *Pages) RepoPullInterdiffPage(w io.Writer, params RepoPullInterdiffParams) error { 1070 return p.execute("repo/pulls/interdiff", w, params) 1071} 1072 1073type PullPatchUploadParams struct { 1074 RepoInfo repoinfo.RepoInfo 1075} 1076 1077func (p *Pages) PullPatchUploadFragment(w io.Writer, params PullPatchUploadParams) error { 1078 return p.executePlain("repo/pulls/fragments/pullPatchUpload", w, params) 1079} 1080 1081type PullCompareBranchesParams struct { 1082 RepoInfo repoinfo.RepoInfo 1083 Branches []types.Branch 1084 SourceBranch string 1085} 1086 1087func (p *Pages) PullCompareBranchesFragment(w io.Writer, params PullCompareBranchesParams) error { 1088 return p.executePlain("repo/pulls/fragments/pullCompareBranches", w, params) 1089} 1090 1091type PullCompareForkParams struct { 1092 RepoInfo repoinfo.RepoInfo 1093 Forks []db.Repo 1094 Selected string 1095} 1096 1097func (p *Pages) PullCompareForkFragment(w io.Writer, params PullCompareForkParams) error { 1098 return p.executePlain("repo/pulls/fragments/pullCompareForks", w, params) 1099} 1100 1101type PullCompareForkBranchesParams struct { 1102 RepoInfo repoinfo.RepoInfo 1103 SourceBranches []types.Branch 1104 TargetBranches []types.Branch 1105} 1106 1107func (p *Pages) PullCompareForkBranchesFragment(w io.Writer, params PullCompareForkBranchesParams) error { 1108 return p.executePlain("repo/pulls/fragments/pullCompareForksBranches", w, params) 1109} 1110 1111type PullResubmitParams struct { 1112 LoggedInUser *oauth.User 1113 RepoInfo repoinfo.RepoInfo 1114 Pull *db.Pull 1115 SubmissionId int 1116} 1117 1118func (p *Pages) PullResubmitFragment(w io.Writer, params PullResubmitParams) error { 1119 return p.executePlain("repo/pulls/fragments/pullResubmit", w, params) 1120} 1121 1122type PullActionsParams struct { 1123 LoggedInUser *oauth.User 1124 RepoInfo repoinfo.RepoInfo 1125 Pull *db.Pull 1126 RoundNumber int 1127 MergeCheck types.MergeCheckResponse 1128 ResubmitCheck ResubmitResult 1129 Stack db.Stack 1130} 1131 1132func (p *Pages) PullActionsFragment(w io.Writer, params PullActionsParams) error { 1133 return p.executePlain("repo/pulls/fragments/pullActions", w, params) 1134} 1135 1136type PullNewCommentParams struct { 1137 LoggedInUser *oauth.User 1138 RepoInfo repoinfo.RepoInfo 1139 Pull *db.Pull 1140 RoundNumber int 1141} 1142 1143func (p *Pages) PullNewCommentFragment(w io.Writer, params PullNewCommentParams) error { 1144 return p.executePlain("repo/pulls/fragments/pullNewComment", w, params) 1145} 1146 1147type RepoCompareParams struct { 1148 LoggedInUser *oauth.User 1149 RepoInfo repoinfo.RepoInfo 1150 Forks []db.Repo 1151 Branches []types.Branch 1152 Tags []*types.TagReference 1153 Base string 1154 Head string 1155 Diff *types.NiceDiff 1156 DiffOpts types.DiffOpts 1157 1158 Active string 1159} 1160 1161func (p *Pages) RepoCompare(w io.Writer, params RepoCompareParams) error { 1162 params.Active = "overview" 1163 return p.executeRepo("repo/compare/compare", w, params) 1164} 1165 1166type RepoCompareNewParams struct { 1167 LoggedInUser *oauth.User 1168 RepoInfo repoinfo.RepoInfo 1169 Forks []db.Repo 1170 Branches []types.Branch 1171 Tags []*types.TagReference 1172 Base string 1173 Head string 1174 1175 Active string 1176} 1177 1178func (p *Pages) RepoCompareNew(w io.Writer, params RepoCompareNewParams) error { 1179 params.Active = "overview" 1180 return p.executeRepo("repo/compare/new", w, params) 1181} 1182 1183type RepoCompareAllowPullParams struct { 1184 LoggedInUser *oauth.User 1185 RepoInfo repoinfo.RepoInfo 1186 Base string 1187 Head string 1188} 1189 1190func (p *Pages) RepoCompareAllowPullFragment(w io.Writer, params RepoCompareAllowPullParams) error { 1191 return p.executePlain("repo/fragments/compareAllowPull", w, params) 1192} 1193 1194type RepoCompareDiffParams struct { 1195 LoggedInUser *oauth.User 1196 RepoInfo repoinfo.RepoInfo 1197 Diff types.NiceDiff 1198} 1199 1200func (p *Pages) RepoCompareDiff(w io.Writer, params RepoCompareDiffParams) error { 1201 return p.executePlain("repo/fragments/diff", w, []any{params.RepoInfo.FullName, &params.Diff}) 1202} 1203 1204type PipelinesParams struct { 1205 LoggedInUser *oauth.User 1206 RepoInfo repoinfo.RepoInfo 1207 Pipelines []db.Pipeline 1208 Active string 1209} 1210 1211func (p *Pages) Pipelines(w io.Writer, params PipelinesParams) error { 1212 params.Active = "pipelines" 1213 return p.executeRepo("repo/pipelines/pipelines", w, params) 1214} 1215 1216type LogBlockParams struct { 1217 Id int 1218 Name string 1219 Command string 1220 Collapsed bool 1221} 1222 1223func (p *Pages) LogBlock(w io.Writer, params LogBlockParams) error { 1224 return p.executePlain("repo/pipelines/fragments/logBlock", w, params) 1225} 1226 1227type LogLineParams struct { 1228 Id int 1229 Content string 1230} 1231 1232func (p *Pages) LogLine(w io.Writer, params LogLineParams) error { 1233 return p.executePlain("repo/pipelines/fragments/logLine", w, params) 1234} 1235 1236type WorkflowParams struct { 1237 LoggedInUser *oauth.User 1238 RepoInfo repoinfo.RepoInfo 1239 Pipeline db.Pipeline 1240 Workflow string 1241 LogUrl string 1242 Active string 1243} 1244 1245func (p *Pages) Workflow(w io.Writer, params WorkflowParams) error { 1246 params.Active = "pipelines" 1247 return p.executeRepo("repo/pipelines/workflow", w, params) 1248} 1249 1250type PutStringParams struct { 1251 LoggedInUser *oauth.User 1252 Action string 1253 1254 // this is supplied in the case of editing an existing string 1255 String db.String 1256} 1257 1258func (p *Pages) PutString(w io.Writer, params PutStringParams) error { 1259 return p.execute("strings/put", w, params) 1260} 1261 1262type StringsDashboardParams struct { 1263 LoggedInUser *oauth.User 1264 Card ProfileCard 1265 Strings []db.String 1266} 1267 1268func (p *Pages) StringsDashboard(w io.Writer, params StringsDashboardParams) error { 1269 return p.execute("strings/dashboard", w, params) 1270} 1271 1272type StringTimelineParams struct { 1273 LoggedInUser *oauth.User 1274 Strings []db.String 1275} 1276 1277func (p *Pages) StringsTimeline(w io.Writer, params StringTimelineParams) error { 1278 return p.execute("strings/timeline", w, params) 1279} 1280 1281type SingleStringParams struct { 1282 LoggedInUser *oauth.User 1283 ShowRendered bool 1284 RenderToggle bool 1285 RenderedContents template.HTML 1286 String db.String 1287 Stats db.StringStats 1288 Owner identity.Identity 1289} 1290 1291func (p *Pages) SingleString(w io.Writer, params SingleStringParams) error { 1292 var style *chroma.Style = styles.Get("catpuccin-latte") 1293 1294 if params.ShowRendered { 1295 switch markup.GetFormat(params.String.Filename) { 1296 case markup.FormatMarkdown: 1297 p.rctx.RendererType = markup.RendererTypeRepoMarkdown 1298 htmlString := p.rctx.RenderMarkdown(params.String.Contents) 1299 sanitized := p.rctx.SanitizeDefault(htmlString) 1300 params.RenderedContents = template.HTML(sanitized) 1301 } 1302 } 1303 1304 c := params.String.Contents 1305 formatter := chromahtml.New( 1306 chromahtml.InlineCode(false), 1307 chromahtml.WithLineNumbers(true), 1308 chromahtml.WithLinkableLineNumbers(true, "L"), 1309 chromahtml.Standalone(false), 1310 chromahtml.WithClasses(true), 1311 ) 1312 1313 lexer := lexers.Get(filepath.Base(params.String.Filename)) 1314 if lexer == nil { 1315 lexer = lexers.Fallback 1316 } 1317 1318 iterator, err := lexer.Tokenise(nil, c) 1319 if err != nil { 1320 return fmt.Errorf("chroma tokenize: %w", err) 1321 } 1322 1323 var code bytes.Buffer 1324 err = formatter.Format(&code, style, iterator) 1325 if err != nil { 1326 return fmt.Errorf("chroma format: %w", err) 1327 } 1328 1329 params.String.Contents = code.String() 1330 return p.execute("strings/string", w, params) 1331} 1332 1333func (p *Pages) Home(w io.Writer, params TimelineParams) error { 1334 return p.execute("timeline/home", w, params) 1335} 1336 1337func (p *Pages) Static() http.Handler { 1338 if p.dev { 1339 return http.StripPrefix("/static/", http.FileServer(http.Dir("appview/pages/static"))) 1340 } 1341 1342 sub, err := fs.Sub(Files, "static") 1343 if err != nil { 1344 p.logger.Error("no static dir found? that's crazy", "err", err) 1345 panic(err) 1346 } 1347 // Custom handler to apply Cache-Control headers for font files 1348 return Cache(http.StripPrefix("/static/", http.FileServer(http.FS(sub)))) 1349} 1350 1351func Cache(h http.Handler) http.Handler { 1352 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 1353 path := strings.Split(r.URL.Path, "?")[0] 1354 1355 if strings.HasSuffix(path, ".css") { 1356 // on day for css files 1357 w.Header().Set("Cache-Control", "public, max-age=86400") 1358 } else { 1359 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") 1360 } 1361 h.ServeHTTP(w, r) 1362 }) 1363} 1364 1365func CssContentHash() string { 1366 cssFile, err := Files.Open("static/tw.css") 1367 if err != nil { 1368 slog.Debug("Error opening CSS file", "err", err) 1369 return "" 1370 } 1371 defer cssFile.Close() 1372 1373 hasher := sha256.New() 1374 if _, err := io.Copy(hasher, cssFile); err != nil { 1375 slog.Debug("Error hashing CSS file", "err", err) 1376 return "" 1377 } 1378 1379 return hex.EncodeToString(hasher.Sum(nil))[:8] // Use first 8 chars of hash 1380} 1381 1382func (p *Pages) Error500(w io.Writer) error { 1383 return p.execute("errors/500", w, nil) 1384} 1385 1386func (p *Pages) Error404(w io.Writer) error { 1387 return p.execute("errors/404", w, nil) 1388} 1389 1390func (p *Pages) ErrorKnot404(w io.Writer) error { 1391 return p.execute("errors/knot404", w, nil) 1392} 1393 1394func (p *Pages) Error503(w io.Writer) error { 1395 return p.execute("errors/503", w, nil) 1396}