1package common
2
3import (
4 "context"
5
6 "github.com/charmbracelet/lipgloss"
7 "github.com/charmbracelet/log"
8 "github.com/charmbracelet/soft-serve/git"
9 "github.com/charmbracelet/soft-serve/server/auth"
10 "github.com/charmbracelet/soft-serve/server/backend"
11 "github.com/charmbracelet/soft-serve/server/config"
12 "github.com/charmbracelet/soft-serve/server/ui/keymap"
13 "github.com/charmbracelet/soft-serve/server/ui/styles"
14 "github.com/charmbracelet/ssh"
15 zone "github.com/lrstanley/bubblezone"
16 "github.com/muesli/termenv"
17)
18
19type contextKey struct {
20 name string
21}
22
23// Keys to use for context.Context.
24var (
25 ConfigKey = &contextKey{"config"}
26 RepoKey = &contextKey{"repo"}
27)
28
29// Common is a struct all components should embed.
30type Common struct {
31 ctx context.Context
32 Width, Height int
33 Styles *styles.Styles
34 KeyMap *keymap.KeyMap
35 Zone *zone.Manager
36 Renderer *lipgloss.Renderer
37 Logger *log.Logger
38}
39
40// NewCommon returns a new Common struct.
41func NewCommon(ctx context.Context, re *lipgloss.Renderer, width, height int) Common {
42 if ctx == nil {
43 ctx = context.TODO()
44 }
45 return Common{
46 ctx: ctx,
47 Width: width,
48 Height: height,
49 Styles: styles.DefaultStyles(re),
50 KeyMap: keymap.DefaultKeyMap(),
51 Zone: zone.New(),
52 Logger: log.FromContext(ctx).WithPrefix("ui"),
53 Renderer: re,
54 }
55}
56
57// Output returns the termenv output.
58func (c *Common) Output() *termenv.Output {
59 return c.Renderer.Output()
60}
61
62// SetValue sets a value in the context.
63func (c *Common) SetValue(key, value interface{}) {
64 c.ctx = context.WithValue(c.ctx, key, value)
65}
66
67// SetSize sets the width and height of the common struct.
68func (c *Common) SetSize(width, height int) {
69 c.Width = width
70 c.Height = height
71}
72
73// Config returns the server config.
74func (c *Common) Config() *config.Config {
75 return config.FromContext(c.ctx)
76}
77
78func (c *Common) Context() context.Context {
79 return c.ctx
80}
81
82// Repo returns the repository.
83func (c *Common) Repo() *git.Repository {
84 v := c.ctx.Value(RepoKey)
85 if r, ok := v.(*git.Repository); ok {
86 return r
87 }
88 return nil
89}
90
91// PublicKey returns the public key.
92func (c *Common) PublicKey() ssh.PublicKey {
93 v := c.ctx.Value(ssh.ContextKeyPublicKey)
94 if p, ok := v.(ssh.PublicKey); ok {
95 return p
96 }
97 return nil
98}
99
100// Backend returns the server backend.
101func (c *Common) Backend() *backend.Backend {
102 return backend.FromContext(c.ctx)
103}
104
105// User returns the current user from context.
106func (c *Common) User() auth.User {
107 return auth.UserFromContext(c.ctx)
108}