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