forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
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" 13 "net/http" 14 "os" 15 "path" 16 "path/filepath" 17 "slices" 18 "strings" 19 20 "tangled.sh/tangled.sh/core/appview/auth" 21 "tangled.sh/tangled.sh/core/appview/db" 22 "tangled.sh/tangled.sh/core/appview/pages/markup" 23 "tangled.sh/tangled.sh/core/appview/pagination" 24 "tangled.sh/tangled.sh/core/appview/state/userutil" 25 "tangled.sh/tangled.sh/core/patchutil" 26 "tangled.sh/tangled.sh/core/types" 27 28 "github.com/alecthomas/chroma/v2" 29 chromahtml "github.com/alecthomas/chroma/v2/formatters/html" 30 "github.com/alecthomas/chroma/v2/lexers" 31 "github.com/alecthomas/chroma/v2/styles" 32 "github.com/bluesky-social/indigo/atproto/syntax" 33 "github.com/go-git/go-git/v5/plumbing/object" 34 "github.com/microcosm-cc/bluemonday" 35) 36 37//go:embed templates/* static 38var Files embed.FS 39 40type Pages struct { 41 t map[string]*template.Template 42 dev bool 43 embedFS embed.FS 44 templateDir string // Path to templates on disk for dev mode 45} 46 47func NewPages(dev bool) *Pages { 48 p := &Pages{ 49 t: make(map[string]*template.Template), 50 dev: dev, 51 embedFS: Files, 52 templateDir: "appview/pages", 53 } 54 55 // Initial load of all templates 56 p.loadAllTemplates() 57 58 return p 59} 60 61func (p *Pages) loadAllTemplates() { 62 templates := make(map[string]*template.Template) 63 var fragmentPaths []string 64 65 // Use embedded FS for initial loading 66 // First, collect all fragment paths 67 err := fs.WalkDir(p.embedFS, "templates", func(path string, d fs.DirEntry, err error) error { 68 if err != nil { 69 return err 70 } 71 if d.IsDir() { 72 return nil 73 } 74 if !strings.HasSuffix(path, ".html") { 75 return nil 76 } 77 if !strings.Contains(path, "fragments/") { 78 return nil 79 } 80 name := strings.TrimPrefix(path, "templates/") 81 name = strings.TrimSuffix(name, ".html") 82 tmpl, err := template.New(name). 83 Funcs(funcMap()). 84 ParseFS(p.embedFS, path) 85 if err != nil { 86 log.Fatalf("setting up fragment: %v", err) 87 } 88 templates[name] = tmpl 89 fragmentPaths = append(fragmentPaths, path) 90 log.Printf("loaded fragment: %s", name) 91 return nil 92 }) 93 if err != nil { 94 log.Fatalf("walking template dir for fragments: %v", err) 95 } 96 97 // Then walk through and setup the rest of the templates 98 err = fs.WalkDir(p.embedFS, "templates", func(path string, d fs.DirEntry, err error) error { 99 if err != nil { 100 return err 101 } 102 if d.IsDir() { 103 return nil 104 } 105 if !strings.HasSuffix(path, "html") { 106 return nil 107 } 108 // Skip fragments as they've already been loaded 109 if strings.Contains(path, "fragments/") { 110 return nil 111 } 112 // Skip layouts 113 if strings.Contains(path, "layouts/") { 114 return nil 115 } 116 name := strings.TrimPrefix(path, "templates/") 117 name = strings.TrimSuffix(name, ".html") 118 // Add the page template on top of the base 119 allPaths := []string{} 120 allPaths = append(allPaths, "templates/layouts/*.html") 121 allPaths = append(allPaths, fragmentPaths...) 122 allPaths = append(allPaths, path) 123 tmpl, err := template.New(name). 124 Funcs(funcMap()). 125 ParseFS(p.embedFS, allPaths...) 126 if err != nil { 127 return fmt.Errorf("setting up template: %w", err) 128 } 129 templates[name] = tmpl 130 log.Printf("loaded template: %s", name) 131 return nil 132 }) 133 if err != nil { 134 log.Fatalf("walking template dir: %v", err) 135 } 136 137 log.Printf("total templates loaded: %d", len(templates)) 138 p.t = templates 139} 140 141// loadTemplateFromDisk loads a template from the filesystem in dev mode 142func (p *Pages) loadTemplateFromDisk(name string) error { 143 if !p.dev { 144 return nil 145 } 146 147 log.Printf("reloading template from disk: %s", name) 148 149 // Find all fragments first 150 var fragmentPaths []string 151 err := filepath.WalkDir(filepath.Join(p.templateDir, "templates"), func(path string, d fs.DirEntry, err error) error { 152 if err != nil { 153 return err 154 } 155 if d.IsDir() { 156 return nil 157 } 158 if !strings.HasSuffix(path, ".html") { 159 return nil 160 } 161 if !strings.Contains(path, "fragments/") { 162 return nil 163 } 164 fragmentPaths = append(fragmentPaths, path) 165 return nil 166 }) 167 if err != nil { 168 return fmt.Errorf("walking disk template dir for fragments: %w", err) 169 } 170 171 // Find the template path on disk 172 templatePath := filepath.Join(p.templateDir, "templates", name+".html") 173 if _, err := os.Stat(templatePath); os.IsNotExist(err) { 174 return fmt.Errorf("template not found on disk: %s", name) 175 } 176 177 // Create a new template 178 tmpl := template.New(name).Funcs(funcMap()) 179 180 // Parse layouts 181 layoutGlob := filepath.Join(p.templateDir, "templates", "layouts", "*.html") 182 layouts, err := filepath.Glob(layoutGlob) 183 if err != nil { 184 return fmt.Errorf("finding layout templates: %w", err) 185 } 186 187 // Create paths for parsing 188 allFiles := append(layouts, fragmentPaths...) 189 allFiles = append(allFiles, templatePath) 190 191 // Parse all templates 192 tmpl, err = tmpl.ParseFiles(allFiles...) 193 if err != nil { 194 return fmt.Errorf("parsing template files: %w", err) 195 } 196 197 // Update the template in the map 198 p.t[name] = tmpl 199 log.Printf("template reloaded from disk: %s", name) 200 return nil 201} 202 203func (p *Pages) executeOrReload(templateName string, w io.Writer, base string, params any) error { 204 // In dev mode, reload the template from disk before executing 205 if p.dev { 206 if err := p.loadTemplateFromDisk(templateName); err != nil { 207 log.Printf("warning: failed to reload template %s from disk: %v", templateName, err) 208 // Continue with the existing template 209 } 210 } 211 212 tmpl, exists := p.t[templateName] 213 if !exists { 214 return fmt.Errorf("template not found: %s", templateName) 215 } 216 217 if base == "" { 218 return tmpl.Execute(w, params) 219 } else { 220 return tmpl.ExecuteTemplate(w, base, params) 221 } 222} 223 224func (p *Pages) execute(name string, w io.Writer, params any) error { 225 return p.executeOrReload(name, w, "layouts/base", params) 226} 227 228func (p *Pages) executePlain(name string, w io.Writer, params any) error { 229 return p.executeOrReload(name, w, "", params) 230} 231 232func (p *Pages) executeRepo(name string, w io.Writer, params any) error { 233 return p.executeOrReload(name, w, "layouts/repobase", params) 234} 235 236type LoginParams struct { 237} 238 239func (p *Pages) Login(w io.Writer, params LoginParams) error { 240 return p.executePlain("user/login", w, params) 241} 242 243type TimelineParams struct { 244 LoggedInUser *auth.User 245 Timeline []db.TimelineEvent 246 DidHandleMap map[string]string 247} 248 249func (p *Pages) Timeline(w io.Writer, params TimelineParams) error { 250 return p.execute("timeline", w, params) 251} 252 253type SettingsParams struct { 254 LoggedInUser *auth.User 255 PubKeys []db.PublicKey 256 Emails []db.Email 257} 258 259func (p *Pages) Settings(w io.Writer, params SettingsParams) error { 260 return p.execute("settings", w, params) 261} 262 263type KnotsParams struct { 264 LoggedInUser *auth.User 265 Registrations []db.Registration 266} 267 268func (p *Pages) Knots(w io.Writer, params KnotsParams) error { 269 return p.execute("knots", w, params) 270} 271 272type KnotParams struct { 273 LoggedInUser *auth.User 274 DidHandleMap map[string]string 275 Registration *db.Registration 276 Members []string 277 IsOwner bool 278} 279 280func (p *Pages) Knot(w io.Writer, params KnotParams) error { 281 return p.execute("knot", w, params) 282} 283 284type NewRepoParams struct { 285 LoggedInUser *auth.User 286 Knots []string 287} 288 289func (p *Pages) NewRepo(w io.Writer, params NewRepoParams) error { 290 return p.execute("repo/new", w, params) 291} 292 293type ForkRepoParams struct { 294 LoggedInUser *auth.User 295 Knots []string 296 RepoInfo RepoInfo 297} 298 299func (p *Pages) ForkRepo(w io.Writer, params ForkRepoParams) error { 300 return p.execute("repo/fork", w, params) 301} 302 303type ProfilePageParams struct { 304 LoggedInUser *auth.User 305 UserDid string 306 UserHandle string 307 Repos []db.Repo 308 CollaboratingRepos []db.Repo 309 ProfileStats ProfileStats 310 FollowStatus db.FollowStatus 311 AvatarUri string 312 ProfileTimeline *db.ProfileTimeline 313 314 DidHandleMap map[string]string 315} 316 317type ProfileStats struct { 318 Followers int 319 Following int 320} 321 322func (p *Pages) ProfilePage(w io.Writer, params ProfilePageParams) error { 323 return p.execute("user/profile", w, params) 324} 325 326type FollowFragmentParams struct { 327 UserDid string 328 FollowStatus db.FollowStatus 329} 330 331func (p *Pages) FollowFragment(w io.Writer, params FollowFragmentParams) error { 332 return p.executePlain("user/fragments/follow", w, params) 333} 334 335type RepoActionsFragmentParams struct { 336 IsStarred bool 337 RepoAt syntax.ATURI 338 Stats db.RepoStats 339} 340 341func (p *Pages) RepoActionsFragment(w io.Writer, params RepoActionsFragmentParams) error { 342 return p.executePlain("repo/fragments/repoActions", w, params) 343} 344 345type RepoDescriptionParams struct { 346 RepoInfo RepoInfo 347} 348 349func (p *Pages) EditRepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error { 350 return p.executePlain("repo/fragments/editRepoDescription", w, params) 351} 352 353func (p *Pages) RepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error { 354 return p.executePlain("repo/fragments/repoDescription", w, params) 355} 356 357type RepoInfo struct { 358 Name string 359 OwnerDid string 360 OwnerHandle string 361 Description string 362 Knot string 363 RepoAt syntax.ATURI 364 IsStarred bool 365 Stats db.RepoStats 366 Roles RolesInRepo 367 Source *db.Repo 368 SourceHandle string 369 DisableFork bool 370} 371 372type RolesInRepo struct { 373 Roles []string 374} 375 376func (r RolesInRepo) SettingsAllowed() bool { 377 return slices.Contains(r.Roles, "repo:settings") 378} 379 380func (r RolesInRepo) CollaboratorInviteAllowed() bool { 381 return slices.Contains(r.Roles, "repo:invite") 382} 383 384func (r RolesInRepo) RepoDeleteAllowed() bool { 385 return slices.Contains(r.Roles, "repo:delete") 386} 387 388func (r RolesInRepo) IsOwner() bool { 389 return slices.Contains(r.Roles, "repo:owner") 390} 391 392func (r RolesInRepo) IsCollaborator() bool { 393 return slices.Contains(r.Roles, "repo:collaborator") 394} 395 396func (r RolesInRepo) IsPushAllowed() bool { 397 return slices.Contains(r.Roles, "repo:push") 398} 399 400func (r RepoInfo) OwnerWithAt() string { 401 if r.OwnerHandle != "" { 402 return fmt.Sprintf("@%s", r.OwnerHandle) 403 } else { 404 return r.OwnerDid 405 } 406} 407 408func (r RepoInfo) FullName() string { 409 return path.Join(r.OwnerWithAt(), r.Name) 410} 411 412func (r RepoInfo) OwnerWithoutAt() string { 413 if strings.HasPrefix(r.OwnerWithAt(), "@") { 414 return strings.TrimPrefix(r.OwnerWithAt(), "@") 415 } else { 416 return userutil.FlattenDid(r.OwnerDid) 417 } 418} 419 420func (r RepoInfo) FullNameWithoutAt() string { 421 return path.Join(r.OwnerWithoutAt(), r.Name) 422} 423 424func (r RepoInfo) GetTabs() [][]string { 425 tabs := [][]string{ 426 {"overview", "/", "square-chart-gantt"}, 427 {"issues", "/issues", "circle-dot"}, 428 {"pulls", "/pulls", "git-pull-request"}, 429 } 430 431 if r.Roles.SettingsAllowed() { 432 tabs = append(tabs, []string{"settings", "/settings", "cog"}) 433 } 434 435 return tabs 436} 437 438// each tab on a repo could have some metadata: 439// 440// issues -> number of open issues etc. 441// settings -> a warning icon to setup branch protection? idk 442// 443// we gather these bits of info here, because go templates 444// are difficult to program in 445func (r RepoInfo) TabMetadata() map[string]any { 446 meta := make(map[string]any) 447 448 if r.Stats.PullCount.Open > 0 { 449 meta["pulls"] = r.Stats.PullCount.Open 450 } 451 452 if r.Stats.IssueCount.Open > 0 { 453 meta["issues"] = r.Stats.IssueCount.Open 454 } 455 456 // more stuff? 457 458 return meta 459} 460 461type RepoIndexParams struct { 462 LoggedInUser *auth.User 463 RepoInfo RepoInfo 464 Active string 465 TagMap map[string][]string 466 CommitsTrunc []*object.Commit 467 TagsTrunc []*types.TagReference 468 BranchesTrunc []types.Branch 469 types.RepoIndexResponse 470 HTMLReadme template.HTML 471 Raw bool 472 EmailToDidOrHandle map[string]string 473} 474 475func (p *Pages) RepoIndexPage(w io.Writer, params RepoIndexParams) error { 476 params.Active = "overview" 477 if params.IsEmpty { 478 return p.executeRepo("repo/empty", w, params) 479 } 480 481 if params.ReadmeFileName != "" { 482 var htmlString string 483 ext := filepath.Ext(params.ReadmeFileName) 484 switch ext { 485 case ".md", ".markdown", ".mdown", ".mkdn", ".mkd": 486 htmlString = markup.RenderMarkdown(params.Readme) 487 params.Raw = false 488 params.HTMLReadme = template.HTML(bluemonday.UGCPolicy().Sanitize(htmlString)) 489 default: 490 htmlString = string(params.Readme) 491 params.Raw = true 492 params.HTMLReadme = template.HTML(bluemonday.NewPolicy().Sanitize(htmlString)) 493 } 494 } 495 496 return p.executeRepo("repo/index", w, params) 497} 498 499type RepoLogParams struct { 500 LoggedInUser *auth.User 501 RepoInfo RepoInfo 502 types.RepoLogResponse 503 Active string 504 EmailToDidOrHandle map[string]string 505} 506 507func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error { 508 params.Active = "overview" 509 return p.executeRepo("repo/log", w, params) 510} 511 512type RepoCommitParams struct { 513 LoggedInUser *auth.User 514 RepoInfo RepoInfo 515 Active string 516 EmailToDidOrHandle map[string]string 517 518 types.RepoCommitResponse 519} 520 521func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error { 522 params.Active = "overview" 523 return p.executeRepo("repo/commit", w, params) 524} 525 526type RepoTreeParams struct { 527 LoggedInUser *auth.User 528 RepoInfo RepoInfo 529 Active string 530 BreadCrumbs [][]string 531 BaseTreeLink string 532 BaseBlobLink string 533 types.RepoTreeResponse 534} 535 536type RepoTreeStats struct { 537 NumFolders uint64 538 NumFiles uint64 539} 540 541func (r RepoTreeParams) TreeStats() RepoTreeStats { 542 numFolders, numFiles := 0, 0 543 for _, f := range r.Files { 544 if !f.IsFile { 545 numFolders += 1 546 } else if f.IsFile { 547 numFiles += 1 548 } 549 } 550 551 return RepoTreeStats{ 552 NumFolders: uint64(numFolders), 553 NumFiles: uint64(numFiles), 554 } 555} 556 557func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error { 558 params.Active = "overview" 559 return p.execute("repo/tree", w, params) 560} 561 562type RepoBranchesParams struct { 563 LoggedInUser *auth.User 564 RepoInfo RepoInfo 565 Active string 566 types.RepoBranchesResponse 567} 568 569func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error { 570 params.Active = "overview" 571 return p.executeRepo("repo/branches", w, params) 572} 573 574type RepoTagsParams struct { 575 LoggedInUser *auth.User 576 RepoInfo RepoInfo 577 Active string 578 types.RepoTagsResponse 579} 580 581func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error { 582 params.Active = "overview" 583 return p.executeRepo("repo/tags", w, params) 584} 585 586type RepoBlobParams struct { 587 LoggedInUser *auth.User 588 RepoInfo RepoInfo 589 Active string 590 BreadCrumbs [][]string 591 ShowRendered bool 592 RenderToggle bool 593 RenderedContents template.HTML 594 types.RepoBlobResponse 595} 596 597func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error { 598 var style *chroma.Style = styles.Get("catpuccin-latte") 599 600 if params.ShowRendered { 601 switch markup.GetFormat(params.Path) { 602 case markup.FormatMarkdown: 603 params.RenderedContents = template.HTML(markup.RenderMarkdown(params.Contents)) 604 } 605 } 606 607 if params.Lines < 5000 { 608 c := params.Contents 609 formatter := chromahtml.New( 610 chromahtml.InlineCode(false), 611 chromahtml.WithLineNumbers(true), 612 chromahtml.WithLinkableLineNumbers(true, "L"), 613 chromahtml.Standalone(false), 614 chromahtml.WithClasses(true), 615 ) 616 617 lexer := lexers.Get(filepath.Base(params.Path)) 618 if lexer == nil { 619 lexer = lexers.Fallback 620 } 621 622 iterator, err := lexer.Tokenise(nil, c) 623 if err != nil { 624 return fmt.Errorf("chroma tokenize: %w", err) 625 } 626 627 var code bytes.Buffer 628 err = formatter.Format(&code, style, iterator) 629 if err != nil { 630 return fmt.Errorf("chroma format: %w", err) 631 } 632 633 params.Contents = code.String() 634 } 635 636 params.Active = "overview" 637 return p.executeRepo("repo/blob", w, params) 638} 639 640type Collaborator struct { 641 Did string 642 Handle string 643 Role string 644} 645 646type RepoSettingsParams struct { 647 LoggedInUser *auth.User 648 RepoInfo RepoInfo 649 Collaborators []Collaborator 650 Active string 651 Branches []string 652 DefaultBranch string 653 // TODO: use repoinfo.roles 654 IsCollaboratorInviteAllowed bool 655} 656 657func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error { 658 params.Active = "settings" 659 return p.executeRepo("repo/settings", w, params) 660} 661 662type RepoIssuesParams struct { 663 LoggedInUser *auth.User 664 RepoInfo RepoInfo 665 Active string 666 Issues []db.Issue 667 DidHandleMap map[string]string 668 Page pagination.Page 669 FilteringByOpen bool 670} 671 672func (p *Pages) RepoIssues(w io.Writer, params RepoIssuesParams) error { 673 params.Active = "issues" 674 return p.executeRepo("repo/issues/issues", w, params) 675} 676 677type RepoSingleIssueParams struct { 678 LoggedInUser *auth.User 679 RepoInfo RepoInfo 680 Active string 681 Issue db.Issue 682 Comments []db.Comment 683 IssueOwnerHandle string 684 DidHandleMap map[string]string 685 686 State string 687} 688 689func (p *Pages) RepoSingleIssue(w io.Writer, params RepoSingleIssueParams) error { 690 params.Active = "issues" 691 if params.Issue.Open { 692 params.State = "open" 693 } else { 694 params.State = "closed" 695 } 696 return p.execute("repo/issues/issue", w, params) 697} 698 699type RepoNewIssueParams struct { 700 LoggedInUser *auth.User 701 RepoInfo RepoInfo 702 Active string 703} 704 705func (p *Pages) RepoNewIssue(w io.Writer, params RepoNewIssueParams) error { 706 params.Active = "issues" 707 return p.executeRepo("repo/issues/new", w, params) 708} 709 710type EditIssueCommentParams struct { 711 LoggedInUser *auth.User 712 RepoInfo RepoInfo 713 Issue *db.Issue 714 Comment *db.Comment 715} 716 717func (p *Pages) EditIssueCommentFragment(w io.Writer, params EditIssueCommentParams) error { 718 return p.executePlain("repo/issues/fragments/editIssueComment", w, params) 719} 720 721type SingleIssueCommentParams struct { 722 LoggedInUser *auth.User 723 DidHandleMap map[string]string 724 RepoInfo RepoInfo 725 Issue *db.Issue 726 Comment *db.Comment 727} 728 729func (p *Pages) SingleIssueCommentFragment(w io.Writer, params SingleIssueCommentParams) error { 730 return p.executePlain("repo/issues/fragments/issueComment", w, params) 731} 732 733type RepoNewPullParams struct { 734 LoggedInUser *auth.User 735 RepoInfo RepoInfo 736 Branches []types.Branch 737 Active string 738} 739 740func (p *Pages) RepoNewPull(w io.Writer, params RepoNewPullParams) error { 741 params.Active = "pulls" 742 return p.executeRepo("repo/pulls/new", w, params) 743} 744 745type RepoPullsParams struct { 746 LoggedInUser *auth.User 747 RepoInfo RepoInfo 748 Pulls []*db.Pull 749 Active string 750 DidHandleMap map[string]string 751 FilteringBy db.PullState 752} 753 754func (p *Pages) RepoPulls(w io.Writer, params RepoPullsParams) error { 755 params.Active = "pulls" 756 return p.executeRepo("repo/pulls/pulls", w, params) 757} 758 759type ResubmitResult uint64 760 761const ( 762 ShouldResubmit ResubmitResult = iota 763 ShouldNotResubmit 764 Unknown 765) 766 767func (r ResubmitResult) Yes() bool { 768 return r == ShouldResubmit 769} 770func (r ResubmitResult) No() bool { 771 return r == ShouldNotResubmit 772} 773func (r ResubmitResult) Unknown() bool { 774 return r == Unknown 775} 776 777type RepoSinglePullParams struct { 778 LoggedInUser *auth.User 779 RepoInfo RepoInfo 780 Active string 781 DidHandleMap map[string]string 782 Pull *db.Pull 783 MergeCheck types.MergeCheckResponse 784 ResubmitCheck ResubmitResult 785} 786 787func (p *Pages) RepoSinglePull(w io.Writer, params RepoSinglePullParams) error { 788 params.Active = "pulls" 789 return p.executeRepo("repo/pulls/pull", w, params) 790} 791 792type RepoPullPatchParams struct { 793 LoggedInUser *auth.User 794 DidHandleMap map[string]string 795 RepoInfo RepoInfo 796 Pull *db.Pull 797 Diff *types.NiceDiff 798 Round int 799 Submission *db.PullSubmission 800} 801 802// this name is a mouthful 803func (p *Pages) RepoPullPatchPage(w io.Writer, params RepoPullPatchParams) error { 804 return p.execute("repo/pulls/patch", w, params) 805} 806 807type RepoPullInterdiffParams struct { 808 LoggedInUser *auth.User 809 DidHandleMap map[string]string 810 RepoInfo RepoInfo 811 Pull *db.Pull 812 Round int 813 Interdiff *patchutil.InterdiffResult 814} 815 816// this name is a mouthful 817func (p *Pages) RepoPullInterdiffPage(w io.Writer, params RepoPullInterdiffParams) error { 818 return p.execute("repo/pulls/interdiff", w, params) 819} 820 821type PullPatchUploadParams struct { 822 RepoInfo RepoInfo 823} 824 825func (p *Pages) PullPatchUploadFragment(w io.Writer, params PullPatchUploadParams) error { 826 return p.executePlain("repo/pulls/fragments/pullPatchUpload", w, params) 827} 828 829type PullCompareBranchesParams struct { 830 RepoInfo RepoInfo 831 Branches []types.Branch 832} 833 834func (p *Pages) PullCompareBranchesFragment(w io.Writer, params PullCompareBranchesParams) error { 835 return p.executePlain("repo/pulls/fragments/pullCompareBranches", w, params) 836} 837 838type PullCompareForkParams struct { 839 RepoInfo RepoInfo 840 Forks []db.Repo 841} 842 843func (p *Pages) PullCompareForkFragment(w io.Writer, params PullCompareForkParams) error { 844 return p.executePlain("repo/pulls/fragments/pullCompareForks", w, params) 845} 846 847type PullCompareForkBranchesParams struct { 848 RepoInfo RepoInfo 849 SourceBranches []types.Branch 850 TargetBranches []types.Branch 851} 852 853func (p *Pages) PullCompareForkBranchesFragment(w io.Writer, params PullCompareForkBranchesParams) error { 854 return p.executePlain("repo/pulls/fragments/pullCompareForksBranches", w, params) 855} 856 857type PullResubmitParams struct { 858 LoggedInUser *auth.User 859 RepoInfo RepoInfo 860 Pull *db.Pull 861 SubmissionId int 862} 863 864func (p *Pages) PullResubmitFragment(w io.Writer, params PullResubmitParams) error { 865 return p.executePlain("repo/pulls/fragments/pullResubmit", w, params) 866} 867 868type PullActionsParams struct { 869 LoggedInUser *auth.User 870 RepoInfo RepoInfo 871 Pull *db.Pull 872 RoundNumber int 873 MergeCheck types.MergeCheckResponse 874 ResubmitCheck ResubmitResult 875} 876 877func (p *Pages) PullActionsFragment(w io.Writer, params PullActionsParams) error { 878 return p.executePlain("repo/pulls/fragments/pullActions", w, params) 879} 880 881type PullNewCommentParams struct { 882 LoggedInUser *auth.User 883 RepoInfo RepoInfo 884 Pull *db.Pull 885 RoundNumber int 886} 887 888func (p *Pages) PullNewCommentFragment(w io.Writer, params PullNewCommentParams) error { 889 return p.executePlain("repo/pulls/fragments/pullNewComment", w, params) 890} 891 892func (p *Pages) Static() http.Handler { 893 if p.dev { 894 return http.StripPrefix("/static/", http.FileServer(http.Dir("appview/pages/static"))) 895 } 896 897 sub, err := fs.Sub(Files, "static") 898 if err != nil { 899 log.Fatalf("no static dir found? that's crazy: %v", err) 900 } 901 // Custom handler to apply Cache-Control headers for font files 902 return Cache(http.StripPrefix("/static/", http.FileServer(http.FS(sub)))) 903} 904 905func Cache(h http.Handler) http.Handler { 906 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 907 path := strings.Split(r.URL.Path, "?")[0] 908 909 if strings.HasSuffix(path, ".css") { 910 // on day for css files 911 w.Header().Set("Cache-Control", "public, max-age=86400") 912 } else { 913 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") 914 } 915 h.ServeHTTP(w, r) 916 }) 917} 918 919func CssContentHash() string { 920 cssFile, err := Files.Open("static/tw.css") 921 if err != nil { 922 log.Printf("Error opening CSS file: %v", err) 923 return "" 924 } 925 defer cssFile.Close() 926 927 hasher := sha256.New() 928 if _, err := io.Copy(hasher, cssFile); err != nil { 929 log.Printf("Error hashing CSS file: %v", err) 930 return "" 931 } 932 933 return hex.EncodeToString(hasher.Sum(nil))[:8] // Use first 8 chars of hash 934} 935 936func (p *Pages) Error500(w io.Writer) error { 937 return p.execute("errors/500", w, nil) 938} 939 940func (p *Pages) Error404(w io.Writer) error { 941 return p.execute("errors/404", w, nil) 942} 943 944func (p *Pages) Error503(w io.Writer) error { 945 return p.execute("errors/503", w, nil) 946}