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 "sync"
18
19 "tangled.sh/tangled.sh/core/api/tangled"
20 "tangled.sh/tangled.sh/core/appview/commitverify"
21 "tangled.sh/tangled.sh/core/appview/config"
22 "tangled.sh/tangled.sh/core/appview/db"
23 "tangled.sh/tangled.sh/core/appview/oauth"
24 "tangled.sh/tangled.sh/core/appview/pages/markup"
25 "tangled.sh/tangled.sh/core/appview/pages/repoinfo"
26 "tangled.sh/tangled.sh/core/appview/pagination"
27 "tangled.sh/tangled.sh/core/idresolver"
28 "tangled.sh/tangled.sh/core/patchutil"
29 "tangled.sh/tangled.sh/core/types"
30
31 "github.com/alecthomas/chroma/v2"
32 chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
33 "github.com/alecthomas/chroma/v2/lexers"
34 "github.com/alecthomas/chroma/v2/styles"
35 "github.com/bluesky-social/indigo/atproto/identity"
36 "github.com/bluesky-social/indigo/atproto/syntax"
37 "github.com/go-git/go-git/v5/plumbing"
38 "github.com/go-git/go-git/v5/plumbing/object"
39)
40
41//go:embed templates/* static
42var Files embed.FS
43
44type Pages struct {
45 mu sync.RWMutex
46 t map[string]*template.Template
47
48 avatar config.AvatarConfig
49 resolver *idresolver.Resolver
50 dev bool
51 embedFS embed.FS
52 templateDir string // Path to templates on disk for dev mode
53 rctx *markup.RenderContext
54}
55
56func NewPages(config *config.Config, res *idresolver.Resolver) *Pages {
57 // initialized with safe defaults, can be overriden per use
58 rctx := &markup.RenderContext{
59 IsDev: config.Core.Dev,
60 CamoUrl: config.Camo.Host,
61 CamoSecret: config.Camo.SharedSecret,
62 Sanitizer: markup.NewSanitizer(),
63 }
64
65 p := &Pages{
66 mu: sync.RWMutex{},
67 t: make(map[string]*template.Template),
68 dev: config.Core.Dev,
69 avatar: config.Avatar,
70 embedFS: Files,
71 rctx: rctx,
72 resolver: res,
73 templateDir: "appview/pages",
74 }
75
76 // Initial load of all templates
77 p.loadAllTemplates()
78
79 return p
80}
81
82func (p *Pages) loadAllTemplates() {
83 templates := make(map[string]*template.Template)
84 var fragmentPaths []string
85
86 // Use embedded FS for initial loading
87 // First, collect all fragment paths
88 err := fs.WalkDir(p.embedFS, "templates", func(path string, d fs.DirEntry, err error) error {
89 if err != nil {
90 return err
91 }
92 if d.IsDir() {
93 return nil
94 }
95 if !strings.HasSuffix(path, ".html") {
96 return nil
97 }
98 if !strings.Contains(path, "fragments/") {
99 return nil
100 }
101 name := strings.TrimPrefix(path, "templates/")
102 name = strings.TrimSuffix(name, ".html")
103 tmpl, err := template.New(name).
104 Funcs(p.funcMap()).
105 ParseFS(p.embedFS, path)
106 if err != nil {
107 log.Fatalf("setting up fragment: %v", err)
108 }
109 templates[name] = tmpl
110 fragmentPaths = append(fragmentPaths, path)
111 log.Printf("loaded fragment: %s", name)
112 return nil
113 })
114 if err != nil {
115 log.Fatalf("walking template dir for fragments: %v", err)
116 }
117
118 // Then walk through and setup the rest of the templates
119 err = fs.WalkDir(p.embedFS, "templates", func(path string, d fs.DirEntry, err error) error {
120 if err != nil {
121 return err
122 }
123 if d.IsDir() {
124 return nil
125 }
126 if !strings.HasSuffix(path, "html") {
127 return nil
128 }
129 // Skip fragments as they've already been loaded
130 if strings.Contains(path, "fragments/") {
131 return nil
132 }
133 // Skip layouts
134 if strings.Contains(path, "layouts/") {
135 return nil
136 }
137 name := strings.TrimPrefix(path, "templates/")
138 name = strings.TrimSuffix(name, ".html")
139 // Add the page template on top of the base
140 allPaths := []string{}
141 allPaths = append(allPaths, "templates/layouts/*.html")
142 allPaths = append(allPaths, fragmentPaths...)
143 allPaths = append(allPaths, path)
144 tmpl, err := template.New(name).
145 Funcs(p.funcMap()).
146 ParseFS(p.embedFS, allPaths...)
147 if err != nil {
148 return fmt.Errorf("setting up template: %w", err)
149 }
150 templates[name] = tmpl
151 log.Printf("loaded template: %s", name)
152 return nil
153 })
154 if err != nil {
155 log.Fatalf("walking template dir: %v", err)
156 }
157
158 log.Printf("total templates loaded: %d", len(templates))
159 p.mu.Lock()
160 defer p.mu.Unlock()
161 p.t = templates
162}
163
164// loadTemplateFromDisk loads a template from the filesystem in dev mode
165func (p *Pages) loadTemplateFromDisk(name string) error {
166 if !p.dev {
167 return nil
168 }
169
170 log.Printf("reloading template from disk: %s", name)
171
172 // Find all fragments first
173 var fragmentPaths []string
174 err := filepath.WalkDir(filepath.Join(p.templateDir, "templates"), func(path string, d fs.DirEntry, err error) error {
175 if err != nil {
176 return err
177 }
178 if d.IsDir() {
179 return nil
180 }
181 if !strings.HasSuffix(path, ".html") {
182 return nil
183 }
184 if !strings.Contains(path, "fragments/") {
185 return nil
186 }
187 fragmentPaths = append(fragmentPaths, path)
188 return nil
189 })
190 if err != nil {
191 return fmt.Errorf("walking disk template dir for fragments: %w", err)
192 }
193
194 // Find the template path on disk
195 templatePath := filepath.Join(p.templateDir, "templates", name+".html")
196 if _, err := os.Stat(templatePath); os.IsNotExist(err) {
197 return fmt.Errorf("template not found on disk: %s", name)
198 }
199
200 // Create a new template
201 tmpl := template.New(name).Funcs(p.funcMap())
202
203 // Parse layouts
204 layoutGlob := filepath.Join(p.templateDir, "templates", "layouts", "*.html")
205 layouts, err := filepath.Glob(layoutGlob)
206 if err != nil {
207 return fmt.Errorf("finding layout templates: %w", err)
208 }
209
210 // Create paths for parsing
211 allFiles := append(layouts, fragmentPaths...)
212 allFiles = append(allFiles, templatePath)
213
214 // Parse all templates
215 tmpl, err = tmpl.ParseFiles(allFiles...)
216 if err != nil {
217 return fmt.Errorf("parsing template files: %w", err)
218 }
219
220 // Update the template in the map
221 p.mu.Lock()
222 defer p.mu.Unlock()
223 p.t[name] = tmpl
224 log.Printf("template reloaded from disk: %s", name)
225 return nil
226}
227
228func (p *Pages) executeOrReload(templateName string, w io.Writer, base string, params any) error {
229 // In dev mode, reload the template from disk before executing
230 if p.dev {
231 if err := p.loadTemplateFromDisk(templateName); err != nil {
232 log.Printf("warning: failed to reload template %s from disk: %v", templateName, err)
233 // Continue with the existing template
234 }
235 }
236
237 p.mu.RLock()
238 defer p.mu.RUnlock()
239 tmpl, exists := p.t[templateName]
240 if !exists {
241 return fmt.Errorf("template not found: %s", templateName)
242 }
243
244 if base == "" {
245 return tmpl.Execute(w, params)
246 } else {
247 return tmpl.ExecuteTemplate(w, base, params)
248 }
249}
250
251func (p *Pages) execute(name string, w io.Writer, params any) error {
252 return p.executeOrReload(name, w, "layouts/base", params)
253}
254
255func (p *Pages) executePlain(name string, w io.Writer, params any) error {
256 return p.executeOrReload(name, w, "", params)
257}
258
259func (p *Pages) executeRepo(name string, w io.Writer, params any) error {
260 return p.executeOrReload(name, w, "layouts/repobase", params)
261}
262
263func (p *Pages) Favicon(w io.Writer) error {
264 return p.executePlain("favicon", w, nil)
265}
266
267type LoginParams struct {
268 ReturnUrl string
269}
270
271func (p *Pages) Login(w io.Writer, params LoginParams) error {
272 return p.executePlain("user/login", w, params)
273}
274
275func (p *Pages) Signup(w io.Writer) error {
276 return p.executePlain("user/signup", w, nil)
277}
278
279func (p *Pages) CompleteSignup(w io.Writer) error {
280 return p.executePlain("user/completeSignup", w, nil)
281}
282
283type TermsOfServiceParams struct {
284 LoggedInUser *oauth.User
285}
286
287func (p *Pages) TermsOfService(w io.Writer, params TermsOfServiceParams) error {
288 return p.execute("legal/terms", w, params)
289}
290
291type PrivacyPolicyParams struct {
292 LoggedInUser *oauth.User
293}
294
295func (p *Pages) PrivacyPolicy(w io.Writer, params PrivacyPolicyParams) error {
296 return p.execute("legal/privacy", w, params)
297}
298
299type TimelineParams struct {
300 LoggedInUser *oauth.User
301 Timeline []db.TimelineEvent
302}
303
304func (p *Pages) Timeline(w io.Writer, params TimelineParams) error {
305 return p.execute("timeline/timeline", w, params)
306}
307
308type TopStarredReposLastWeekParams struct {
309 LoggedInUser *oauth.User
310 Repos []db.Repo
311}
312
313func (p *Pages) TopStarredReposLastWeek(w io.Writer, params TopStarredReposLastWeekParams) error {
314 return p.executePlain("timeline/fragments/topStarredRepos", w, params)
315}
316
317type SettingsParams struct {
318 LoggedInUser *oauth.User
319 PubKeys []db.PublicKey
320 Emails []db.Email
321}
322
323func (p *Pages) Settings(w io.Writer, params SettingsParams) error {
324 return p.execute("settings", w, params)
325}
326
327type KnotsParams struct {
328 LoggedInUser *oauth.User
329 Registrations []db.Registration
330}
331
332func (p *Pages) Knots(w io.Writer, params KnotsParams) error {
333 return p.execute("knots/index", w, params)
334}
335
336type KnotParams struct {
337 LoggedInUser *oauth.User
338 Registration *db.Registration
339 Members []string
340 Repos map[string][]db.Repo
341 IsOwner bool
342}
343
344func (p *Pages) Knot(w io.Writer, params KnotParams) error {
345 return p.execute("knots/dashboard", w, params)
346}
347
348type KnotListingParams struct {
349 db.Registration
350}
351
352func (p *Pages) KnotListing(w io.Writer, params KnotListingParams) error {
353 return p.executePlain("knots/fragments/knotListing", w, params)
354}
355
356type KnotListingFullParams struct {
357 Registrations []db.Registration
358}
359
360func (p *Pages) KnotListingFull(w io.Writer, params KnotListingFullParams) error {
361 return p.executePlain("knots/fragments/knotListingFull", w, params)
362}
363
364type KnotSecretParams struct {
365 Secret string
366}
367
368func (p *Pages) KnotSecret(w io.Writer, params KnotSecretParams) error {
369 return p.executePlain("knots/fragments/secret", w, params)
370}
371
372type SpindlesParams struct {
373 LoggedInUser *oauth.User
374 Spindles []db.Spindle
375}
376
377func (p *Pages) Spindles(w io.Writer, params SpindlesParams) error {
378 return p.execute("spindles/index", w, params)
379}
380
381type SpindleListingParams struct {
382 db.Spindle
383}
384
385func (p *Pages) SpindleListing(w io.Writer, params SpindleListingParams) error {
386 return p.executePlain("spindles/fragments/spindleListing", w, params)
387}
388
389type SpindleDashboardParams struct {
390 LoggedInUser *oauth.User
391 Spindle db.Spindle
392 Members []string
393 Repos map[string][]db.Repo
394}
395
396func (p *Pages) SpindleDashboard(w io.Writer, params SpindleDashboardParams) error {
397 return p.execute("spindles/dashboard", w, params)
398}
399
400type NewRepoParams struct {
401 LoggedInUser *oauth.User
402 Knots []string
403}
404
405func (p *Pages) NewRepo(w io.Writer, params NewRepoParams) error {
406 return p.execute("repo/new", w, params)
407}
408
409type ForkRepoParams struct {
410 LoggedInUser *oauth.User
411 Knots []string
412 RepoInfo repoinfo.RepoInfo
413}
414
415func (p *Pages) ForkRepo(w io.Writer, params ForkRepoParams) error {
416 return p.execute("repo/fork", w, params)
417}
418
419type ProfilePageParams struct {
420 LoggedInUser *oauth.User
421 Repos []db.Repo
422 CollaboratingRepos []db.Repo
423 ProfileTimeline *db.ProfileTimeline
424 Card ProfileCard
425 Punchcard db.Punchcard
426}
427
428type ProfileCard struct {
429 UserDid string
430 UserHandle string
431 FollowStatus db.FollowStatus
432 Followers int
433 Following int
434
435 Profile *db.Profile
436}
437
438func (p *Pages) ProfilePage(w io.Writer, params ProfilePageParams) error {
439 return p.execute("user/profile", w, params)
440}
441
442type ReposPageParams struct {
443 LoggedInUser *oauth.User
444 Repos []db.Repo
445 Card ProfileCard
446}
447
448func (p *Pages) ReposPage(w io.Writer, params ReposPageParams) error {
449 return p.execute("user/repos", w, params)
450}
451
452type FollowFragmentParams struct {
453 UserDid string
454 FollowStatus db.FollowStatus
455}
456
457func (p *Pages) FollowFragment(w io.Writer, params FollowFragmentParams) error {
458 return p.executePlain("user/fragments/follow", w, params)
459}
460
461type EditBioParams struct {
462 LoggedInUser *oauth.User
463 Profile *db.Profile
464}
465
466func (p *Pages) EditBioFragment(w io.Writer, params EditBioParams) error {
467 return p.executePlain("user/fragments/editBio", w, params)
468}
469
470type EditPinsParams struct {
471 LoggedInUser *oauth.User
472 Profile *db.Profile
473 AllRepos []PinnedRepo
474}
475
476type PinnedRepo struct {
477 IsPinned bool
478 db.Repo
479}
480
481func (p *Pages) EditPinsFragment(w io.Writer, params EditPinsParams) error {
482 return p.executePlain("user/fragments/editPins", w, params)
483}
484
485type RepoStarFragmentParams struct {
486 IsStarred bool
487 RepoAt syntax.ATURI
488 Stats db.RepoStats
489}
490
491func (p *Pages) RepoStarFragment(w io.Writer, params RepoStarFragmentParams) error {
492 return p.executePlain("repo/fragments/repoStar", w, params)
493}
494
495type RepoDescriptionParams struct {
496 RepoInfo repoinfo.RepoInfo
497}
498
499func (p *Pages) EditRepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
500 return p.executePlain("repo/fragments/editRepoDescription", w, params)
501}
502
503func (p *Pages) RepoDescriptionFragment(w io.Writer, params RepoDescriptionParams) error {
504 return p.executePlain("repo/fragments/repoDescription", w, params)
505}
506
507type RepoIndexParams struct {
508 LoggedInUser *oauth.User
509 RepoInfo repoinfo.RepoInfo
510 Active string
511 TagMap map[string][]string
512 CommitsTrunc []*object.Commit
513 TagsTrunc []*types.TagReference
514 BranchesTrunc []types.Branch
515 ForkInfo *types.ForkInfo
516 HTMLReadme template.HTML
517 Raw bool
518 EmailToDidOrHandle map[string]string
519 VerifiedCommits commitverify.VerifiedCommits
520 Languages []types.RepoLanguageDetails
521 Pipelines map[string]db.Pipeline
522 types.RepoIndexResponse
523}
524
525func (p *Pages) RepoIndexPage(w io.Writer, params RepoIndexParams) error {
526 params.Active = "overview"
527 if params.IsEmpty {
528 return p.executeRepo("repo/empty", w, params)
529 }
530
531 p.rctx.RepoInfo = params.RepoInfo
532 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
533
534 if params.ReadmeFileName != "" {
535 ext := filepath.Ext(params.ReadmeFileName)
536 switch ext {
537 case ".md", ".markdown", ".mdown", ".mkdn", ".mkd":
538 params.Raw = false
539 htmlString := p.rctx.RenderMarkdown(params.Readme)
540 sanitized := p.rctx.SanitizeDefault(htmlString)
541 params.HTMLReadme = template.HTML(sanitized)
542 default:
543 params.Raw = true
544 }
545 }
546
547 return p.executeRepo("repo/index", w, params)
548}
549
550type RepoLogParams struct {
551 LoggedInUser *oauth.User
552 RepoInfo repoinfo.RepoInfo
553 TagMap map[string][]string
554 types.RepoLogResponse
555 Active string
556 EmailToDidOrHandle map[string]string
557 VerifiedCommits commitverify.VerifiedCommits
558 Pipelines map[string]db.Pipeline
559}
560
561func (p *Pages) RepoLog(w io.Writer, params RepoLogParams) error {
562 params.Active = "overview"
563 return p.executeRepo("repo/log", w, params)
564}
565
566type RepoCommitParams struct {
567 LoggedInUser *oauth.User
568 RepoInfo repoinfo.RepoInfo
569 Active string
570 EmailToDidOrHandle map[string]string
571 Pipeline *db.Pipeline
572 DiffOpts types.DiffOpts
573
574 // singular because it's always going to be just one
575 VerifiedCommit commitverify.VerifiedCommits
576
577 types.RepoCommitResponse
578}
579
580func (p *Pages) RepoCommit(w io.Writer, params RepoCommitParams) error {
581 params.Active = "overview"
582 return p.executeRepo("repo/commit", w, params)
583}
584
585type RepoTreeParams struct {
586 LoggedInUser *oauth.User
587 RepoInfo repoinfo.RepoInfo
588 Active string
589 BreadCrumbs [][]string
590 TreePath string
591 types.RepoTreeResponse
592}
593
594type RepoTreeStats struct {
595 NumFolders uint64
596 NumFiles uint64
597}
598
599func (r RepoTreeParams) TreeStats() RepoTreeStats {
600 numFolders, numFiles := 0, 0
601 for _, f := range r.Files {
602 if !f.IsFile {
603 numFolders += 1
604 } else if f.IsFile {
605 numFiles += 1
606 }
607 }
608
609 return RepoTreeStats{
610 NumFolders: uint64(numFolders),
611 NumFiles: uint64(numFiles),
612 }
613}
614
615func (p *Pages) RepoTree(w io.Writer, params RepoTreeParams) error {
616 params.Active = "overview"
617 return p.execute("repo/tree", w, params)
618}
619
620type RepoBranchesParams struct {
621 LoggedInUser *oauth.User
622 RepoInfo repoinfo.RepoInfo
623 Active string
624 types.RepoBranchesResponse
625}
626
627func (p *Pages) RepoBranches(w io.Writer, params RepoBranchesParams) error {
628 params.Active = "overview"
629 return p.executeRepo("repo/branches", w, params)
630}
631
632type RepoTagsParams struct {
633 LoggedInUser *oauth.User
634 RepoInfo repoinfo.RepoInfo
635 Active string
636 types.RepoTagsResponse
637 ArtifactMap map[plumbing.Hash][]db.Artifact
638 DanglingArtifacts []db.Artifact
639}
640
641func (p *Pages) RepoTags(w io.Writer, params RepoTagsParams) error {
642 params.Active = "overview"
643 return p.executeRepo("repo/tags", w, params)
644}
645
646type RepoArtifactParams struct {
647 LoggedInUser *oauth.User
648 RepoInfo repoinfo.RepoInfo
649 Artifact db.Artifact
650}
651
652func (p *Pages) RepoArtifactFragment(w io.Writer, params RepoArtifactParams) error {
653 return p.executePlain("repo/fragments/artifact", w, params)
654}
655
656type RepoBlobParams struct {
657 LoggedInUser *oauth.User
658 RepoInfo repoinfo.RepoInfo
659 Active string
660 Unsupported bool
661 IsImage bool
662 IsVideo bool
663 ContentSrc string
664 BreadCrumbs [][]string
665 ShowRendered bool
666 RenderToggle bool
667 RenderedContents template.HTML
668 types.RepoBlobResponse
669}
670
671func (p *Pages) RepoBlob(w io.Writer, params RepoBlobParams) error {
672 var style *chroma.Style = styles.Get("catpuccin-latte")
673
674 if params.ShowRendered {
675 switch markup.GetFormat(params.Path) {
676 case markup.FormatMarkdown:
677 p.rctx.RepoInfo = params.RepoInfo
678 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
679 htmlString := p.rctx.RenderMarkdown(params.Contents)
680 sanitized := p.rctx.SanitizeDefault(htmlString)
681 params.RenderedContents = template.HTML(sanitized)
682 }
683 }
684
685 if params.Lines < 5000 {
686 c := params.Contents
687 formatter := chromahtml.New(
688 chromahtml.InlineCode(false),
689 chromahtml.WithLineNumbers(true),
690 chromahtml.WithLinkableLineNumbers(true, "L"),
691 chromahtml.Standalone(false),
692 chromahtml.WithClasses(true),
693 )
694
695 lexer := lexers.Get(filepath.Base(params.Path))
696 if lexer == nil {
697 lexer = lexers.Fallback
698 }
699
700 iterator, err := lexer.Tokenise(nil, c)
701 if err != nil {
702 return fmt.Errorf("chroma tokenize: %w", err)
703 }
704
705 var code bytes.Buffer
706 err = formatter.Format(&code, style, iterator)
707 if err != nil {
708 return fmt.Errorf("chroma format: %w", err)
709 }
710
711 params.Contents = code.String()
712 }
713
714 params.Active = "overview"
715 return p.executeRepo("repo/blob", w, params)
716}
717
718type Collaborator struct {
719 Did string
720 Handle string
721 Role string
722}
723
724type RepoSettingsParams struct {
725 LoggedInUser *oauth.User
726 RepoInfo repoinfo.RepoInfo
727 Collaborators []Collaborator
728 Active string
729 Branches []types.Branch
730 Spindles []string
731 CurrentSpindle string
732 Secrets []*tangled.RepoListSecrets_Secret
733
734 // TODO: use repoinfo.roles
735 IsCollaboratorInviteAllowed bool
736}
737
738func (p *Pages) RepoSettings(w io.Writer, params RepoSettingsParams) error {
739 params.Active = "settings"
740 return p.executeRepo("repo/settings", w, params)
741}
742
743type RepoGeneralSettingsParams struct {
744 LoggedInUser *oauth.User
745 RepoInfo repoinfo.RepoInfo
746 Active string
747 Tabs []map[string]any
748 Tab string
749 Branches []types.Branch
750}
751
752func (p *Pages) RepoGeneralSettings(w io.Writer, params RepoGeneralSettingsParams) error {
753 params.Active = "settings"
754 return p.executeRepo("repo/settings/general", w, params)
755}
756
757type RepoAccessSettingsParams struct {
758 LoggedInUser *oauth.User
759 RepoInfo repoinfo.RepoInfo
760 Active string
761 Tabs []map[string]any
762 Tab string
763 Collaborators []Collaborator
764}
765
766func (p *Pages) RepoAccessSettings(w io.Writer, params RepoAccessSettingsParams) error {
767 params.Active = "settings"
768 return p.executeRepo("repo/settings/access", w, params)
769}
770
771type RepoPipelineSettingsParams struct {
772 LoggedInUser *oauth.User
773 RepoInfo repoinfo.RepoInfo
774 Active string
775 Tabs []map[string]any
776 Tab string
777 Spindles []string
778 CurrentSpindle string
779 Secrets []map[string]any
780}
781
782func (p *Pages) RepoPipelineSettings(w io.Writer, params RepoPipelineSettingsParams) error {
783 params.Active = "settings"
784 return p.executeRepo("repo/settings/pipelines", w, params)
785}
786
787type RepoIssuesParams struct {
788 LoggedInUser *oauth.User
789 RepoInfo repoinfo.RepoInfo
790 Active string
791 Issues []db.Issue
792 Page pagination.Page
793 FilteringByOpen bool
794}
795
796func (p *Pages) RepoIssues(w io.Writer, params RepoIssuesParams) error {
797 params.Active = "issues"
798 return p.executeRepo("repo/issues/issues", w, params)
799}
800
801type RepoSingleIssueParams struct {
802 LoggedInUser *oauth.User
803 RepoInfo repoinfo.RepoInfo
804 Active string
805 Issue *db.Issue
806 Comments []db.Comment
807 IssueOwnerHandle string
808
809 OrderedReactionKinds []db.ReactionKind
810 Reactions map[db.ReactionKind]int
811 UserReacted map[db.ReactionKind]bool
812
813 State string
814}
815
816type ThreadReactionFragmentParams struct {
817 ThreadAt syntax.ATURI
818 Kind db.ReactionKind
819 Count int
820 IsReacted bool
821}
822
823func (p *Pages) ThreadReactionFragment(w io.Writer, params ThreadReactionFragmentParams) error {
824 return p.executePlain("repo/fragments/reaction", w, params)
825}
826
827func (p *Pages) RepoSingleIssue(w io.Writer, params RepoSingleIssueParams) error {
828 params.Active = "issues"
829 if params.Issue.Open {
830 params.State = "open"
831 } else {
832 params.State = "closed"
833 }
834 return p.execute("repo/issues/issue", w, params)
835}
836
837type RepoNewIssueParams struct {
838 LoggedInUser *oauth.User
839 RepoInfo repoinfo.RepoInfo
840 Active string
841}
842
843func (p *Pages) RepoNewIssue(w io.Writer, params RepoNewIssueParams) error {
844 params.Active = "issues"
845 return p.executeRepo("repo/issues/new", w, params)
846}
847
848type EditIssueCommentParams struct {
849 LoggedInUser *oauth.User
850 RepoInfo repoinfo.RepoInfo
851 Issue *db.Issue
852 Comment *db.Comment
853}
854
855func (p *Pages) EditIssueCommentFragment(w io.Writer, params EditIssueCommentParams) error {
856 return p.executePlain("repo/issues/fragments/editIssueComment", w, params)
857}
858
859type SingleIssueCommentParams struct {
860 LoggedInUser *oauth.User
861 RepoInfo repoinfo.RepoInfo
862 Issue *db.Issue
863 Comment *db.Comment
864}
865
866func (p *Pages) SingleIssueCommentFragment(w io.Writer, params SingleIssueCommentParams) error {
867 return p.executePlain("repo/issues/fragments/issueComment", w, params)
868}
869
870type RepoNewPullParams struct {
871 LoggedInUser *oauth.User
872 RepoInfo repoinfo.RepoInfo
873 Branches []types.Branch
874 Strategy string
875 SourceBranch string
876 TargetBranch string
877 Title string
878 Body string
879 Active string
880}
881
882func (p *Pages) RepoNewPull(w io.Writer, params RepoNewPullParams) error {
883 params.Active = "pulls"
884 return p.executeRepo("repo/pulls/new", w, params)
885}
886
887type RepoPullsParams struct {
888 LoggedInUser *oauth.User
889 RepoInfo repoinfo.RepoInfo
890 Pulls []*db.Pull
891 Active string
892 FilteringBy db.PullState
893 Stacks map[string]db.Stack
894 Pipelines map[string]db.Pipeline
895}
896
897func (p *Pages) RepoPulls(w io.Writer, params RepoPullsParams) error {
898 params.Active = "pulls"
899 return p.executeRepo("repo/pulls/pulls", w, params)
900}
901
902type ResubmitResult uint64
903
904const (
905 ShouldResubmit ResubmitResult = iota
906 ShouldNotResubmit
907 Unknown
908)
909
910func (r ResubmitResult) Yes() bool {
911 return r == ShouldResubmit
912}
913func (r ResubmitResult) No() bool {
914 return r == ShouldNotResubmit
915}
916func (r ResubmitResult) Unknown() bool {
917 return r == Unknown
918}
919
920type RepoSinglePullParams struct {
921 LoggedInUser *oauth.User
922 RepoInfo repoinfo.RepoInfo
923 Active string
924 Pull *db.Pull
925 Stack db.Stack
926 AbandonedPulls []*db.Pull
927 MergeCheck types.MergeCheckResponse
928 ResubmitCheck ResubmitResult
929 Pipelines map[string]db.Pipeline
930
931 OrderedReactionKinds []db.ReactionKind
932 Reactions map[db.ReactionKind]int
933 UserReacted map[db.ReactionKind]bool
934}
935
936func (p *Pages) RepoSinglePull(w io.Writer, params RepoSinglePullParams) error {
937 params.Active = "pulls"
938 return p.executeRepo("repo/pulls/pull", w, params)
939}
940
941type RepoPullPatchParams struct {
942 LoggedInUser *oauth.User
943 RepoInfo repoinfo.RepoInfo
944 Pull *db.Pull
945 Stack db.Stack
946 Diff *types.NiceDiff
947 Round int
948 Submission *db.PullSubmission
949 OrderedReactionKinds []db.ReactionKind
950 DiffOpts types.DiffOpts
951}
952
953// this name is a mouthful
954func (p *Pages) RepoPullPatchPage(w io.Writer, params RepoPullPatchParams) error {
955 return p.execute("repo/pulls/patch", w, params)
956}
957
958type RepoPullInterdiffParams struct {
959 LoggedInUser *oauth.User
960 RepoInfo repoinfo.RepoInfo
961 Pull *db.Pull
962 Round int
963 Interdiff *patchutil.InterdiffResult
964 OrderedReactionKinds []db.ReactionKind
965 DiffOpts types.DiffOpts
966}
967
968// this name is a mouthful
969func (p *Pages) RepoPullInterdiffPage(w io.Writer, params RepoPullInterdiffParams) error {
970 return p.execute("repo/pulls/interdiff", w, params)
971}
972
973type PullPatchUploadParams struct {
974 RepoInfo repoinfo.RepoInfo
975}
976
977func (p *Pages) PullPatchUploadFragment(w io.Writer, params PullPatchUploadParams) error {
978 return p.executePlain("repo/pulls/fragments/pullPatchUpload", w, params)
979}
980
981type PullCompareBranchesParams struct {
982 RepoInfo repoinfo.RepoInfo
983 Branches []types.Branch
984 SourceBranch string
985}
986
987func (p *Pages) PullCompareBranchesFragment(w io.Writer, params PullCompareBranchesParams) error {
988 return p.executePlain("repo/pulls/fragments/pullCompareBranches", w, params)
989}
990
991type PullCompareForkParams struct {
992 RepoInfo repoinfo.RepoInfo
993 Forks []db.Repo
994 Selected string
995}
996
997func (p *Pages) PullCompareForkFragment(w io.Writer, params PullCompareForkParams) error {
998 return p.executePlain("repo/pulls/fragments/pullCompareForks", w, params)
999}
1000
1001type PullCompareForkBranchesParams struct {
1002 RepoInfo repoinfo.RepoInfo
1003 SourceBranches []types.Branch
1004 TargetBranches []types.Branch
1005}
1006
1007func (p *Pages) PullCompareForkBranchesFragment(w io.Writer, params PullCompareForkBranchesParams) error {
1008 return p.executePlain("repo/pulls/fragments/pullCompareForksBranches", w, params)
1009}
1010
1011type PullResubmitParams struct {
1012 LoggedInUser *oauth.User
1013 RepoInfo repoinfo.RepoInfo
1014 Pull *db.Pull
1015 SubmissionId int
1016}
1017
1018func (p *Pages) PullResubmitFragment(w io.Writer, params PullResubmitParams) error {
1019 return p.executePlain("repo/pulls/fragments/pullResubmit", w, params)
1020}
1021
1022type PullActionsParams struct {
1023 LoggedInUser *oauth.User
1024 RepoInfo repoinfo.RepoInfo
1025 Pull *db.Pull
1026 RoundNumber int
1027 MergeCheck types.MergeCheckResponse
1028 ResubmitCheck ResubmitResult
1029 Stack db.Stack
1030}
1031
1032func (p *Pages) PullActionsFragment(w io.Writer, params PullActionsParams) error {
1033 return p.executePlain("repo/pulls/fragments/pullActions", w, params)
1034}
1035
1036type PullNewCommentParams struct {
1037 LoggedInUser *oauth.User
1038 RepoInfo repoinfo.RepoInfo
1039 Pull *db.Pull
1040 RoundNumber int
1041}
1042
1043func (p *Pages) PullNewCommentFragment(w io.Writer, params PullNewCommentParams) error {
1044 return p.executePlain("repo/pulls/fragments/pullNewComment", w, params)
1045}
1046
1047type RepoCompareParams struct {
1048 LoggedInUser *oauth.User
1049 RepoInfo repoinfo.RepoInfo
1050 Forks []db.Repo
1051 Branches []types.Branch
1052 Tags []*types.TagReference
1053 Base string
1054 Head string
1055 Diff *types.NiceDiff
1056 DiffOpts types.DiffOpts
1057
1058 Active string
1059}
1060
1061func (p *Pages) RepoCompare(w io.Writer, params RepoCompareParams) error {
1062 params.Active = "overview"
1063 return p.executeRepo("repo/compare/compare", w, params)
1064}
1065
1066type RepoCompareNewParams struct {
1067 LoggedInUser *oauth.User
1068 RepoInfo repoinfo.RepoInfo
1069 Forks []db.Repo
1070 Branches []types.Branch
1071 Tags []*types.TagReference
1072 Base string
1073 Head string
1074
1075 Active string
1076}
1077
1078func (p *Pages) RepoCompareNew(w io.Writer, params RepoCompareNewParams) error {
1079 params.Active = "overview"
1080 return p.executeRepo("repo/compare/new", w, params)
1081}
1082
1083type RepoCompareAllowPullParams struct {
1084 LoggedInUser *oauth.User
1085 RepoInfo repoinfo.RepoInfo
1086 Base string
1087 Head string
1088}
1089
1090func (p *Pages) RepoCompareAllowPullFragment(w io.Writer, params RepoCompareAllowPullParams) error {
1091 return p.executePlain("repo/fragments/compareAllowPull", w, params)
1092}
1093
1094type RepoCompareDiffParams struct {
1095 LoggedInUser *oauth.User
1096 RepoInfo repoinfo.RepoInfo
1097 Diff types.NiceDiff
1098}
1099
1100func (p *Pages) RepoCompareDiff(w io.Writer, params RepoCompareDiffParams) error {
1101 return p.executePlain("repo/fragments/diff", w, []any{params.RepoInfo.FullName, ¶ms.Diff})
1102}
1103
1104type PipelinesParams struct {
1105 LoggedInUser *oauth.User
1106 RepoInfo repoinfo.RepoInfo
1107 Pipelines []db.Pipeline
1108 Active string
1109}
1110
1111func (p *Pages) Pipelines(w io.Writer, params PipelinesParams) error {
1112 params.Active = "pipelines"
1113 return p.executeRepo("repo/pipelines/pipelines", w, params)
1114}
1115
1116type LogBlockParams struct {
1117 Id int
1118 Name string
1119 Command string
1120 Collapsed bool
1121}
1122
1123func (p *Pages) LogBlock(w io.Writer, params LogBlockParams) error {
1124 return p.executePlain("repo/pipelines/fragments/logBlock", w, params)
1125}
1126
1127type LogLineParams struct {
1128 Id int
1129 Content string
1130}
1131
1132func (p *Pages) LogLine(w io.Writer, params LogLineParams) error {
1133 return p.executePlain("repo/pipelines/fragments/logLine", w, params)
1134}
1135
1136type WorkflowParams struct {
1137 LoggedInUser *oauth.User
1138 RepoInfo repoinfo.RepoInfo
1139 Pipeline db.Pipeline
1140 Workflow string
1141 LogUrl string
1142 Active string
1143}
1144
1145func (p *Pages) Workflow(w io.Writer, params WorkflowParams) error {
1146 params.Active = "pipelines"
1147 return p.executeRepo("repo/pipelines/workflow", w, params)
1148}
1149
1150type PutStringParams struct {
1151 LoggedInUser *oauth.User
1152 Action string
1153
1154 // this is supplied in the case of editing an existing string
1155 String db.String
1156}
1157
1158func (p *Pages) PutString(w io.Writer, params PutStringParams) error {
1159 return p.execute("strings/put", w, params)
1160}
1161
1162type StringsDashboardParams struct {
1163 LoggedInUser *oauth.User
1164 Card ProfileCard
1165 Strings []db.String
1166}
1167
1168func (p *Pages) StringsDashboard(w io.Writer, params StringsDashboardParams) error {
1169 return p.execute("strings/dashboard", w, params)
1170}
1171
1172type SingleStringParams struct {
1173 LoggedInUser *oauth.User
1174 ShowRendered bool
1175 RenderToggle bool
1176 RenderedContents template.HTML
1177 String db.String
1178 Stats db.StringStats
1179 Owner identity.Identity
1180}
1181
1182func (p *Pages) SingleString(w io.Writer, params SingleStringParams) error {
1183 var style *chroma.Style = styles.Get("catpuccin-latte")
1184
1185 if params.ShowRendered {
1186 switch markup.GetFormat(params.String.Filename) {
1187 case markup.FormatMarkdown:
1188 p.rctx.RendererType = markup.RendererTypeRepoMarkdown
1189 htmlString := p.rctx.RenderMarkdown(params.String.Contents)
1190 sanitized := p.rctx.SanitizeDefault(htmlString)
1191 params.RenderedContents = template.HTML(sanitized)
1192 }
1193 }
1194
1195 c := params.String.Contents
1196 formatter := chromahtml.New(
1197 chromahtml.InlineCode(false),
1198 chromahtml.WithLineNumbers(true),
1199 chromahtml.WithLinkableLineNumbers(true, "L"),
1200 chromahtml.Standalone(false),
1201 chromahtml.WithClasses(true),
1202 )
1203
1204 lexer := lexers.Get(filepath.Base(params.String.Filename))
1205 if lexer == nil {
1206 lexer = lexers.Fallback
1207 }
1208
1209 iterator, err := lexer.Tokenise(nil, c)
1210 if err != nil {
1211 return fmt.Errorf("chroma tokenize: %w", err)
1212 }
1213
1214 var code bytes.Buffer
1215 err = formatter.Format(&code, style, iterator)
1216 if err != nil {
1217 return fmt.Errorf("chroma format: %w", err)
1218 }
1219
1220 params.String.Contents = code.String()
1221 return p.execute("strings/string", w, params)
1222}
1223
1224func (p *Pages) Static() http.Handler {
1225 if p.dev {
1226 return http.StripPrefix("/static/", http.FileServer(http.Dir("appview/pages/static")))
1227 }
1228
1229 sub, err := fs.Sub(Files, "static")
1230 if err != nil {
1231 log.Fatalf("no static dir found? that's crazy: %v", err)
1232 }
1233 // Custom handler to apply Cache-Control headers for font files
1234 return Cache(http.StripPrefix("/static/", http.FileServer(http.FS(sub))))
1235}
1236
1237func Cache(h http.Handler) http.Handler {
1238 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1239 path := strings.Split(r.URL.Path, "?")[0]
1240
1241 if strings.HasSuffix(path, ".css") {
1242 // on day for css files
1243 w.Header().Set("Cache-Control", "public, max-age=86400")
1244 } else {
1245 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
1246 }
1247 h.ServeHTTP(w, r)
1248 })
1249}
1250
1251func CssContentHash() string {
1252 cssFile, err := Files.Open("static/tw.css")
1253 if err != nil {
1254 log.Printf("Error opening CSS file: %v", err)
1255 return ""
1256 }
1257 defer cssFile.Close()
1258
1259 hasher := sha256.New()
1260 if _, err := io.Copy(hasher, cssFile); err != nil {
1261 log.Printf("Error hashing CSS file: %v", err)
1262 return ""
1263 }
1264
1265 return hex.EncodeToString(hasher.Sum(nil))[:8] // Use first 8 chars of hash
1266}
1267
1268func (p *Pages) Error500(w io.Writer) error {
1269 return p.execute("errors/500", w, nil)
1270}
1271
1272func (p *Pages) Error404(w io.Writer) error {
1273 return p.execute("errors/404", w, nil)
1274}
1275
1276func (p *Pages) Error503(w io.Writer) error {
1277 return p.execute("errors/503", w, nil)
1278}