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 TagMap map[string][]string
503 types.RepoLogResponse
504 Active string
505 EmailToDidOrHandle map[string]string
506}
507
508func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error {
509 params.Active = "overview"
510 return p.executeRepo("repo/log", w, params)
511}
512
513type RepoCommitParams struct {
514 LoggedInUser *auth.User
515 RepoInfo RepoInfo
516 Active string
517 EmailToDidOrHandle map[string]string
518
519 types.RepoCommitResponse
520}
521
522func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error {
523 params.Active = "overview"
524 return p.executeRepo("repo/commit", w, params)
525}
526
527type RepoTreeParams struct {
528 LoggedInUser *auth.User
529 RepoInfo RepoInfo
530 Active string
531 BreadCrumbs [][]string
532 BaseTreeLink string
533 BaseBlobLink string
534 types.RepoTreeResponse
535}
536
537type RepoTreeStats struct {
538 NumFolders uint64
539 NumFiles uint64
540}
541
542func (r RepoTreeParams) TreeStats() RepoTreeStats {
543 numFolders, numFiles := 0, 0
544 for _, f := range r.Files {
545 if !f.IsFile {
546 numFolders += 1
547 } else if f.IsFile {
548 numFiles += 1
549 }
550 }
551
552 return RepoTreeStats{
553 NumFolders: uint64(numFolders),
554 NumFiles: uint64(numFiles),
555 }
556}
557
558func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error {
559 params.Active = "overview"
560 return p.execute("repo/tree", w, params)
561}
562
563type RepoBranchesParams struct {
564 LoggedInUser *auth.User
565 RepoInfo RepoInfo
566 Active string
567 types.RepoBranchesResponse
568}
569
570func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error {
571 params.Active = "overview"
572 return p.executeRepo("repo/branches", w, params)
573}
574
575type RepoTagsParams struct {
576 LoggedInUser *auth.User
577 RepoInfo RepoInfo
578 Active string
579 types.RepoTagsResponse
580}
581
582func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error {
583 params.Active = "overview"
584 return p.executeRepo("repo/tags", w, params)
585}
586
587type RepoBlobParams struct {
588 LoggedInUser *auth.User
589 RepoInfo RepoInfo
590 Active string
591 BreadCrumbs [][]string
592 ShowRendered bool
593 RenderToggle bool
594 RenderedContents template.HTML
595 types.RepoBlobResponse
596}
597
598func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error {
599 var style *chroma.Style = styles.Get("catpuccin-latte")
600
601 if params.ShowRendered {
602 switch markup.GetFormat(params.Path) {
603 case markup.FormatMarkdown:
604 params.RenderedContents = template.HTML(markup.RenderMarkdown(params.Contents))
605 }
606 }
607
608 if params.Lines < 5000 {
609 c := params.Contents
610 formatter := chromahtml.New(
611 chromahtml.InlineCode(false),
612 chromahtml.WithLineNumbers(true),
613 chromahtml.WithLinkableLineNumbers(true, "L"),
614 chromahtml.Standalone(false),
615 chromahtml.WithClasses(true),
616 )
617
618 lexer := lexers.Get(filepath.Base(params.Path))
619 if lexer == nil {
620 lexer = lexers.Fallback
621 }
622
623 iterator, err := lexer.Tokenise(nil, c)
624 if err != nil {
625 return fmt.Errorf("chroma tokenize: %w", err)
626 }
627
628 var code bytes.Buffer
629 err = formatter.Format(&code, style, iterator)
630 if err != nil {
631 return fmt.Errorf("chroma format: %w", err)
632 }
633
634 params.Contents = code.String()
635 }
636
637 params.Active = "overview"
638 return p.executeRepo("repo/blob", w, params)
639}
640
641type Collaborator struct {
642 Did string
643 Handle string
644 Role string
645}
646
647type RepoSettingsParams struct {
648 LoggedInUser *auth.User
649 RepoInfo RepoInfo
650 Collaborators []Collaborator
651 Active string
652 Branches []string
653 DefaultBranch string
654 // TODO: use repoinfo.roles
655 IsCollaboratorInviteAllowed bool
656}
657
658func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error {
659 params.Active = "settings"
660 return p.executeRepo("repo/settings", w, params)
661}
662
663type RepoIssuesParams struct {
664 LoggedInUser *auth.User
665 RepoInfo RepoInfo
666 Active string
667 Issues []db.Issue
668 DidHandleMap map[string]string
669 Page pagination.Page
670 FilteringByOpen bool
671}
672
673func (p *Pages) RepoIssues(w io.Writer, params RepoIssuesParams) error {
674 params.Active = "issues"
675 return p.executeRepo("repo/issues/issues", w, params)
676}
677
678type RepoSingleIssueParams struct {
679 LoggedInUser *auth.User
680 RepoInfo RepoInfo
681 Active string
682 Issue db.Issue
683 Comments []db.Comment
684 IssueOwnerHandle string
685 DidHandleMap map[string]string
686
687 State string
688}
689
690func (p *Pages) RepoSingleIssue(w io.Writer, params RepoSingleIssueParams) error {
691 params.Active = "issues"
692 if params.Issue.Open {
693 params.State = "open"
694 } else {
695 params.State = "closed"
696 }
697 return p.execute("repo/issues/issue", w, params)
698}
699
700type RepoNewIssueParams struct {
701 LoggedInUser *auth.User
702 RepoInfo RepoInfo
703 Active string
704}
705
706func (p *Pages) RepoNewIssue(w io.Writer, params RepoNewIssueParams) error {
707 params.Active = "issues"
708 return p.executeRepo("repo/issues/new", w, params)
709}
710
711type EditIssueCommentParams struct {
712 LoggedInUser *auth.User
713 RepoInfo RepoInfo
714 Issue *db.Issue
715 Comment *db.Comment
716}
717
718func (p *Pages) EditIssueCommentFragment(w io.Writer, params EditIssueCommentParams) error {
719 return p.executePlain("repo/issues/fragments/editIssueComment", w, params)
720}
721
722type SingleIssueCommentParams struct {
723 LoggedInUser *auth.User
724 DidHandleMap map[string]string
725 RepoInfo RepoInfo
726 Issue *db.Issue
727 Comment *db.Comment
728}
729
730func (p *Pages) SingleIssueCommentFragment(w io.Writer, params SingleIssueCommentParams) error {
731 return p.executePlain("repo/issues/fragments/issueComment", w, params)
732}
733
734type RepoNewPullParams struct {
735 LoggedInUser *auth.User
736 RepoInfo RepoInfo
737 Branches []types.Branch
738 Active string
739}
740
741func (p *Pages) RepoNewPull(w io.Writer, params RepoNewPullParams) error {
742 params.Active = "pulls"
743 return p.executeRepo("repo/pulls/new", w, params)
744}
745
746type RepoPullsParams struct {
747 LoggedInUser *auth.User
748 RepoInfo RepoInfo
749 Pulls []*db.Pull
750 Active string
751 DidHandleMap map[string]string
752 FilteringBy db.PullState
753}
754
755func (p *Pages) RepoPulls(w io.Writer, params RepoPullsParams) error {
756 params.Active = "pulls"
757 return p.executeRepo("repo/pulls/pulls", w, params)
758}
759
760type ResubmitResult uint64
761
762const (
763 ShouldResubmit ResubmitResult = iota
764 ShouldNotResubmit
765 Unknown
766)
767
768func (r ResubmitResult) Yes() bool {
769 return r == ShouldResubmit
770}
771func (r ResubmitResult) No() bool {
772 return r == ShouldNotResubmit
773}
774func (r ResubmitResult) Unknown() bool {
775 return r == Unknown
776}
777
778type RepoSinglePullParams struct {
779 LoggedInUser *auth.User
780 RepoInfo RepoInfo
781 Active string
782 DidHandleMap map[string]string
783 Pull *db.Pull
784 MergeCheck types.MergeCheckResponse
785 ResubmitCheck ResubmitResult
786}
787
788func (p *Pages) RepoSinglePull(w io.Writer, params RepoSinglePullParams) error {
789 params.Active = "pulls"
790 return p.executeRepo("repo/pulls/pull", w, params)
791}
792
793type RepoPullPatchParams struct {
794 LoggedInUser *auth.User
795 DidHandleMap map[string]string
796 RepoInfo RepoInfo
797 Pull *db.Pull
798 Diff *types.NiceDiff
799 Round int
800 Submission *db.PullSubmission
801}
802
803// this name is a mouthful
804func (p *Pages) RepoPullPatchPage(w io.Writer, params RepoPullPatchParams) error {
805 return p.execute("repo/pulls/patch", w, params)
806}
807
808type RepoPullInterdiffParams struct {
809 LoggedInUser *auth.User
810 DidHandleMap map[string]string
811 RepoInfo RepoInfo
812 Pull *db.Pull
813 Round int
814 Interdiff *patchutil.InterdiffResult
815}
816
817// this name is a mouthful
818func (p *Pages) RepoPullInterdiffPage(w io.Writer, params RepoPullInterdiffParams) error {
819 return p.execute("repo/pulls/interdiff", w, params)
820}
821
822type PullPatchUploadParams struct {
823 RepoInfo RepoInfo
824}
825
826func (p *Pages) PullPatchUploadFragment(w io.Writer, params PullPatchUploadParams) error {
827 return p.executePlain("repo/pulls/fragments/pullPatchUpload", w, params)
828}
829
830type PullCompareBranchesParams struct {
831 RepoInfo RepoInfo
832 Branches []types.Branch
833}
834
835func (p *Pages) PullCompareBranchesFragment(w io.Writer, params PullCompareBranchesParams) error {
836 return p.executePlain("repo/pulls/fragments/pullCompareBranches", w, params)
837}
838
839type PullCompareForkParams struct {
840 RepoInfo RepoInfo
841 Forks []db.Repo
842}
843
844func (p *Pages) PullCompareForkFragment(w io.Writer, params PullCompareForkParams) error {
845 return p.executePlain("repo/pulls/fragments/pullCompareForks", w, params)
846}
847
848type PullCompareForkBranchesParams struct {
849 RepoInfo RepoInfo
850 SourceBranches []types.Branch
851 TargetBranches []types.Branch
852}
853
854func (p *Pages) PullCompareForkBranchesFragment(w io.Writer, params PullCompareForkBranchesParams) error {
855 return p.executePlain("repo/pulls/fragments/pullCompareForksBranches", w, params)
856}
857
858type PullResubmitParams struct {
859 LoggedInUser *auth.User
860 RepoInfo RepoInfo
861 Pull *db.Pull
862 SubmissionId int
863}
864
865func (p *Pages) PullResubmitFragment(w io.Writer, params PullResubmitParams) error {
866 return p.executePlain("repo/pulls/fragments/pullResubmit", w, params)
867}
868
869type PullActionsParams struct {
870 LoggedInUser *auth.User
871 RepoInfo RepoInfo
872 Pull *db.Pull
873 RoundNumber int
874 MergeCheck types.MergeCheckResponse
875 ResubmitCheck ResubmitResult
876}
877
878func (p *Pages) PullActionsFragment(w io.Writer, params PullActionsParams) error {
879 return p.executePlain("repo/pulls/fragments/pullActions", w, params)
880}
881
882type PullNewCommentParams struct {
883 LoggedInUser *auth.User
884 RepoInfo RepoInfo
885 Pull *db.Pull
886 RoundNumber int
887}
888
889func (p *Pages) PullNewCommentFragment(w io.Writer, params PullNewCommentParams) error {
890 return p.executePlain("repo/pulls/fragments/pullNewComment", w, params)
891}
892
893func (p *Pages) Static() http.Handler {
894 if p.dev {
895 return http.StripPrefix("/static/", http.FileServer(http.Dir("appview/pages/static")))
896 }
897
898 sub, err := fs.Sub(Files, "static")
899 if err != nil {
900 log.Fatalf("no static dir found? that's crazy: %v", err)
901 }
902 // Custom handler to apply Cache-Control headers for font files
903 return Cache(http.StripPrefix("/static/", http.FileServer(http.FS(sub))))
904}
905
906func Cache(h http.Handler) http.Handler {
907 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
908 path := strings.Split(r.URL.Path, "?")[0]
909
910 if strings.HasSuffix(path, ".css") {
911 // on day for css files
912 w.Header().Set("Cache-Control", "public, max-age=86400")
913 } else {
914 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
915 }
916 h.ServeHTTP(w, r)
917 })
918}
919
920func CssContentHash() string {
921 cssFile, err := Files.Open("static/tw.css")
922 if err != nil {
923 log.Printf("Error opening CSS file: %v", err)
924 return ""
925 }
926 defer cssFile.Close()
927
928 hasher := sha256.New()
929 if _, err := io.Copy(hasher, cssFile); err != nil {
930 log.Printf("Error hashing CSS file: %v", err)
931 return ""
932 }
933
934 return hex.EncodeToString(hasher.Sum(nil))[:8] // Use first 8 chars of hash
935}
936
937func (p *Pages) Error500(w io.Writer) error {
938 return p.execute("errors/500", w, nil)
939}
940
941func (p *Pages) Error404(w io.Writer) error {
942 return p.execute("errors/404", w, nil)
943}
944
945func (p *Pages) Error503(w io.Writer) error {
946 return p.execute("errors/503", w, nil)
947}