forked from
tangled.org/core
Monorepo for Tangled — https://tangled.org
1package pages
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "embed"
7 "encoding/hex"
8 "fmt"
9 "html/template"
10 "io"
11 "io/fs"
12 "log"
13 "net/http"
14 "os"
15 "path/filepath"
16 "strings"
17
18 "tangled.sh/tangled.sh/core/appview"
19 "tangled.sh/tangled.sh/core/appview/auth"
20 "tangled.sh/tangled.sh/core/appview/db"
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.Dev,
52 CamoUrl: config.CamoHost,
53 CamoSecret: config.CamoSharedSecret,
54 }
55
56 p := &Pages{
57 t: make(map[string]*template.Template),
58 dev: config.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 *auth.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 *auth.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 *auth.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 *auth.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 *auth.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 *auth.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 *auth.User
314 UserDid string
315 UserHandle string
316 Repos []db.Repo
317 CollaboratingRepos []db.Repo
318 ProfileStats ProfileStats
319 FollowStatus db.FollowStatus
320 AvatarUri string
321 ProfileTimeline *db.ProfileTimeline
322
323 DidHandleMap map[string]string
324}
325
326type ProfileStats struct {
327 Followers int
328 Following int
329}
330
331func (p *Pages) ProfilePage(w io.Writer, params ProfilePageParams) error {
332 return p.execute("user/profile", w, params)
333}
334
335type FollowFragmentParams struct {
336 UserDid string
337 FollowStatus db.FollowStatus
338}
339
340func (p *Pages) FollowFragment(w io.Writer, params FollowFragmentParams) error {
341 return p.executePlain("user/fragments/follow", w, params)
342}
343
344type RepoActionsFragmentParams struct {
345 IsStarred bool
346 RepoAt syntax.ATURI
347 Stats db.RepoStats
348}
349
350func (p *Pages) RepoActionsFragment(w io.Writer, params RepoActionsFragmentParams) error {
351 return p.executePlain("repo/fragments/repoActions", w, params)
352}
353
354type RepoDescriptionParams struct {
355 RepoInfo repoinfo.RepoInfo
356}
357
358func (p *Pages) EditRepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
359 return p.executePlain("repo/fragments/editRepoDescription", w, params)
360}
361
362func (p *Pages) RepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
363 return p.executePlain("repo/fragments/repoDescription", w, params)
364}
365
366type RepoIndexParams struct {
367 LoggedInUser *auth.User
368 RepoInfo repoinfo.RepoInfo
369 Active string
370 TagMap map[string][]string
371 CommitsTrunc []*object.Commit
372 TagsTrunc []*types.TagReference
373 BranchesTrunc []types.Branch
374 types.RepoIndexResponse
375 HTMLReadme template.HTML
376 Raw bool
377 EmailToDidOrHandle map[string]string
378}
379
380func (p *Pages) RepoIndexPage(w io.Writer, params RepoIndexParams) error {
381 params.Active = "overview"
382 if params.IsEmpty {
383 return p.executeRepo("repo/empty", w, params)
384 }
385
386 p.rctx.RepoInfo = params.RepoInfo
387 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
388
389 if params.ReadmeFileName != "" {
390 var htmlString string
391 ext := filepath.Ext(params.ReadmeFileName)
392 switch ext {
393 case ".md", ".markdown", ".mdown", ".mkdn", ".mkd":
394 htmlString = p.rctx.RenderMarkdown(params.Readme)
395 params.Raw = false
396 params.HTMLReadme = template.HTML(bluemonday.UGCPolicy().Sanitize(htmlString))
397 default:
398 htmlString = string(params.Readme)
399 params.Raw = true
400 params.HTMLReadme = template.HTML(bluemonday.NewPolicy().Sanitize(htmlString))
401 }
402 }
403
404 return p.executeRepo("repo/index", w, params)
405}
406
407type RepoLogParams struct {
408 LoggedInUser *auth.User
409 RepoInfo repoinfo.RepoInfo
410 TagMap map[string][]string
411 types.RepoLogResponse
412 Active string
413 EmailToDidOrHandle map[string]string
414}
415
416func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error {
417 params.Active = "overview"
418 return p.executeRepo("repo/log", w, params)
419}
420
421type RepoCommitParams struct {
422 LoggedInUser *auth.User
423 RepoInfo repoinfo.RepoInfo
424 Active string
425 EmailToDidOrHandle map[string]string
426
427 types.RepoCommitResponse
428}
429
430func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error {
431 params.Active = "overview"
432 return p.executeRepo("repo/commit", w, params)
433}
434
435type RepoTreeParams struct {
436 LoggedInUser *auth.User
437 RepoInfo repoinfo.RepoInfo
438 Active string
439 BreadCrumbs [][]string
440 BaseTreeLink string
441 BaseBlobLink string
442 types.RepoTreeResponse
443}
444
445type RepoTreeStats struct {
446 NumFolders uint64
447 NumFiles uint64
448}
449
450func (r RepoTreeParams) TreeStats() RepoTreeStats {
451 numFolders, numFiles := 0, 0
452 for _, f := range r.Files {
453 if !f.IsFile {
454 numFolders += 1
455 } else if f.IsFile {
456 numFiles += 1
457 }
458 }
459
460 return RepoTreeStats{
461 NumFolders: uint64(numFolders),
462 NumFiles: uint64(numFiles),
463 }
464}
465
466func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error {
467 params.Active = "overview"
468 return p.execute("repo/tree", w, params)
469}
470
471type RepoBranchesParams struct {
472 LoggedInUser *auth.User
473 RepoInfo repoinfo.RepoInfo
474 Active string
475 types.RepoBranchesResponse
476}
477
478func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error {
479 params.Active = "overview"
480 return p.executeRepo("repo/branches", w, params)
481}
482
483type RepoTagsParams struct {
484 LoggedInUser *auth.User
485 RepoInfo repoinfo.RepoInfo
486 Active string
487 types.RepoTagsResponse
488 ArtifactMap map[plumbing.Hash][]db.Artifact
489 DanglingArtifacts []db.Artifact
490}
491
492func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error {
493 params.Active = "overview"
494 return p.executeRepo("repo/tags", w, params)
495}
496
497type RepoArtifactParams struct {
498 LoggedInUser *auth.User
499 RepoInfo repoinfo.RepoInfo
500 Artifact db.Artifact
501}
502
503func (p *Pages) RepoArtifactFragment(w io.Writer, params RepoArtifactParams) error {
504 return p.executePlain("repo/fragments/artifact", w, params)
505}
506
507type RepoBlobParams struct {
508 LoggedInUser *auth.User
509 RepoInfo repoinfo.RepoInfo
510 Active string
511 BreadCrumbs [][]string
512 ShowRendered bool
513 RenderToggle bool
514 RenderedContents template.HTML
515 types.RepoBlobResponse
516}
517
518func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error {
519 var style *chroma.Style = styles.Get("catpuccin-latte")
520
521 if params.ShowRendered {
522 switch markup.GetFormat(params.Path) {
523 case markup.FormatMarkdown:
524 p.rctx.RepoInfo = params.RepoInfo
525 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
526 params.RenderedContents = template.HTML(p.rctx.RenderMarkdown(params.Contents))
527 }
528 }
529
530 if params.Lines < 5000 {
531 c := params.Contents
532 formatter := chromahtml.New(
533 chromahtml.InlineCode(false),
534 chromahtml.WithLineNumbers(true),
535 chromahtml.WithLinkableLineNumbers(true, "L"),
536 chromahtml.Standalone(false),
537 chromahtml.WithClasses(true),
538 )
539
540 lexer := lexers.Get(filepath.Base(params.Path))
541 if lexer == nil {
542 lexer = lexers.Fallback
543 }
544
545 iterator, err := lexer.Tokenise(nil, c)
546 if err != nil {
547 return fmt.Errorf("chroma tokenize: %w", err)
548 }
549
550 var code bytes.Buffer
551 err = formatter.Format(&code, style, iterator)
552 if err != nil {
553 return fmt.Errorf("chroma format: %w", err)
554 }
555
556 params.Contents = code.String()
557 }
558
559 params.Active = "overview"
560 return p.executeRepo("repo/blob", w, params)
561}
562
563type Collaborator struct {
564 Did string
565 Handle string
566 Role string
567}
568
569type RepoSettingsParams struct {
570 LoggedInUser *auth.User
571 RepoInfo repoinfo.RepoInfo
572 Collaborators []Collaborator
573 Active string
574 Branches []string
575 DefaultBranch string
576 // TODO: use repoinfo.roles
577 IsCollaboratorInviteAllowed bool
578}
579
580func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error {
581 params.Active = "settings"
582 return p.executeRepo("repo/settings", w, params)
583}
584
585type RepoIssuesParams struct {
586 LoggedInUser *auth.User
587 RepoInfo repoinfo.RepoInfo
588 Active string
589 Issues []db.Issue
590 DidHandleMap map[string]string
591 Page pagination.Page
592 FilteringByOpen bool
593}
594
595func (p *Pages) RepoIssues(w io.Writer, params RepoIssuesParams) error {
596 params.Active = "issues"
597 return p.executeRepo("repo/issues/issues", w, params)
598}
599
600type RepoSingleIssueParams struct {
601 LoggedInUser *auth.User
602 RepoInfo repoinfo.RepoInfo
603 Active string
604 Issue db.Issue
605 Comments []db.Comment
606 IssueOwnerHandle string
607 DidHandleMap map[string]string
608
609 State string
610}
611
612func (p *Pages) RepoSingleIssue(w io.Writer, params RepoSingleIssueParams) error {
613 params.Active = "issues"
614 if params.Issue.Open {
615 params.State = "open"
616 } else {
617 params.State = "closed"
618 }
619 return p.execute("repo/issues/issue", w, params)
620}
621
622type RepoNewIssueParams struct {
623 LoggedInUser *auth.User
624 RepoInfo repoinfo.RepoInfo
625 Active string
626}
627
628func (p *Pages) RepoNewIssue(w io.Writer, params RepoNewIssueParams) error {
629 params.Active = "issues"
630 return p.executeRepo("repo/issues/new", w, params)
631}
632
633type EditIssueCommentParams struct {
634 LoggedInUser *auth.User
635 RepoInfo repoinfo.RepoInfo
636 Issue *db.Issue
637 Comment *db.Comment
638}
639
640func (p *Pages) EditIssueCommentFragment(w io.Writer, params EditIssueCommentParams) error {
641 return p.executePlain("repo/issues/fragments/editIssueComment", w, params)
642}
643
644type SingleIssueCommentParams struct {
645 LoggedInUser *auth.User
646 DidHandleMap map[string]string
647 RepoInfo repoinfo.RepoInfo
648 Issue *db.Issue
649 Comment *db.Comment
650}
651
652func (p *Pages) SingleIssueCommentFragment(w io.Writer, params SingleIssueCommentParams) error {
653 return p.executePlain("repo/issues/fragments/issueComment", w, params)
654}
655
656type RepoNewPullParams struct {
657 LoggedInUser *auth.User
658 RepoInfo repoinfo.RepoInfo
659 Branches []types.Branch
660 Active string
661}
662
663func (p *Pages) RepoNewPull(w io.Writer, params RepoNewPullParams) error {
664 params.Active = "pulls"
665 return p.executeRepo("repo/pulls/new", w, params)
666}
667
668type RepoPullsParams struct {
669 LoggedInUser *auth.User
670 RepoInfo repoinfo.RepoInfo
671 Pulls []*db.Pull
672 Active string
673 DidHandleMap map[string]string
674 FilteringBy db.PullState
675}
676
677func (p *Pages) RepoPulls(w io.Writer, params RepoPullsParams) error {
678 params.Active = "pulls"
679 return p.executeRepo("repo/pulls/pulls", w, params)
680}
681
682type ResubmitResult uint64
683
684const (
685 ShouldResubmit ResubmitResult = iota
686 ShouldNotResubmit
687 Unknown
688)
689
690func (r ResubmitResult) Yes() bool {
691 return r == ShouldResubmit
692}
693func (r ResubmitResult) No() bool {
694 return r == ShouldNotResubmit
695}
696func (r ResubmitResult) Unknown() bool {
697 return r == Unknown
698}
699
700type RepoSinglePullParams struct {
701 LoggedInUser *auth.User
702 RepoInfo repoinfo.RepoInfo
703 Active string
704 DidHandleMap map[string]string
705 Pull *db.Pull
706 MergeCheck types.MergeCheckResponse
707 ResubmitCheck ResubmitResult
708}
709
710func (p *Pages) RepoSinglePull(w io.Writer, params RepoSinglePullParams) error {
711 params.Active = "pulls"
712 return p.executeRepo("repo/pulls/pull", w, params)
713}
714
715type RepoPullPatchParams struct {
716 LoggedInUser *auth.User
717 DidHandleMap map[string]string
718 RepoInfo repoinfo.RepoInfo
719 Pull *db.Pull
720 Diff *types.NiceDiff
721 Round int
722 Submission *db.PullSubmission
723}
724
725// this name is a mouthful
726func (p *Pages) RepoPullPatchPage(w io.Writer, params RepoPullPatchParams) error {
727 return p.execute("repo/pulls/patch", w, params)
728}
729
730type RepoPullInterdiffParams struct {
731 LoggedInUser *auth.User
732 DidHandleMap map[string]string
733 RepoInfo repoinfo.RepoInfo
734 Pull *db.Pull
735 Round int
736 Interdiff *patchutil.InterdiffResult
737}
738
739// this name is a mouthful
740func (p *Pages) RepoPullInterdiffPage(w io.Writer, params RepoPullInterdiffParams) error {
741 return p.execute("repo/pulls/interdiff", w, params)
742}
743
744type PullPatchUploadParams struct {
745 RepoInfo repoinfo.RepoInfo
746}
747
748func (p *Pages) PullPatchUploadFragment(w io.Writer, params PullPatchUploadParams) error {
749 return p.executePlain("repo/pulls/fragments/pullPatchUpload", w, params)
750}
751
752type PullCompareBranchesParams struct {
753 RepoInfo repoinfo.RepoInfo
754 Branches []types.Branch
755}
756
757func (p *Pages) PullCompareBranchesFragment(w io.Writer, params PullCompareBranchesParams) error {
758 return p.executePlain("repo/pulls/fragments/pullCompareBranches", w, params)
759}
760
761type PullCompareForkParams struct {
762 RepoInfo repoinfo.RepoInfo
763 Forks []db.Repo
764}
765
766func (p *Pages) PullCompareForkFragment(w io.Writer, params PullCompareForkParams) error {
767 return p.executePlain("repo/pulls/fragments/pullCompareForks", w, params)
768}
769
770type PullCompareForkBranchesParams struct {
771 RepoInfo repoinfo.RepoInfo
772 SourceBranches []types.Branch
773 TargetBranches []types.Branch
774}
775
776func (p *Pages) PullCompareForkBranchesFragment(w io.Writer, params PullCompareForkBranchesParams) error {
777 return p.executePlain("repo/pulls/fragments/pullCompareForksBranches", w, params)
778}
779
780type PullResubmitParams struct {
781 LoggedInUser *auth.User
782 RepoInfo repoinfo.RepoInfo
783 Pull *db.Pull
784 SubmissionId int
785}
786
787func (p *Pages) PullResubmitFragment(w io.Writer, params PullResubmitParams) error {
788 return p.executePlain("repo/pulls/fragments/pullResubmit", w, params)
789}
790
791type PullActionsParams struct {
792 LoggedInUser *auth.User
793 RepoInfo repoinfo.RepoInfo
794 Pull *db.Pull
795 RoundNumber int
796 MergeCheck types.MergeCheckResponse
797 ResubmitCheck ResubmitResult
798}
799
800func (p *Pages) PullActionsFragment(w io.Writer, params PullActionsParams) error {
801 return p.executePlain("repo/pulls/fragments/pullActions", w, params)
802}
803
804type PullNewCommentParams struct {
805 LoggedInUser *auth.User
806 RepoInfo repoinfo.RepoInfo
807 Pull *db.Pull
808 RoundNumber int
809}
810
811func (p *Pages) PullNewCommentFragment(w io.Writer, params PullNewCommentParams) error {
812 return p.executePlain("repo/pulls/fragments/pullNewComment", w, params)
813}
814
815func (p *Pages) Static() http.Handler {
816 if p.dev {
817 return http.StripPrefix("/static/", http.FileServer(http.Dir("appview/pages/static")))
818 }
819
820 sub, err := fs.Sub(Files, "static")
821 if err != nil {
822 log.Fatalf("no static dir found? that's crazy: %v", err)
823 }
824 // Custom handler to apply Cache-Control headers for font files
825 return Cache(http.StripPrefix("/static/", http.FileServer(http.FS(sub))))
826}
827
828func Cache(h http.Handler) http.Handler {
829 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
830 path := strings.Split(r.URL.Path, "?")[0]
831
832 if strings.HasSuffix(path, ".css") {
833 // on day for css files
834 w.Header().Set("Cache-Control", "public, max-age=86400")
835 } else {
836 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
837 }
838 h.ServeHTTP(w, r)
839 })
840}
841
842func CssContentHash() string {
843 cssFile, err := Files.Open("static/tw.css")
844 if err != nil {
845 log.Printf("Error opening CSS file: %v", err)
846 return ""
847 }
848 defer cssFile.Close()
849
850 hasher := sha256.New()
851 if _, err := io.Copy(hasher, cssFile); err != nil {
852 log.Printf("Error hashing CSS file: %v", err)
853 return ""
854 }
855
856 return hex.EncodeToString(hasher.Sum(nil))[:8] // Use first 8 chars of hash
857}
858
859func (p *Pages) Error500(w io.Writer) error {
860 return p.execute("errors/500", w, nil)
861}
862
863func (p *Pages) Error404(w io.Writer) error {
864 return p.execute("errors/404", w, nil)
865}
866
867func (p *Pages) Error503(w io.Writer) error {
868 return p.execute("errors/503", w, nil)
869}