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