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