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