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