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