Skip to content

Commit

Permalink
feat: add context.SetValue
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed May 14, 2024
1 parent 80a1017 commit 43ffb64
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package tea
import (
"context"
"image/color"
"sync"

"github.com/charmbracelet/lipgloss"
)
Expand All @@ -13,6 +14,11 @@ import (
type Context interface {
context.Context

// SetValue sets a value on the context. This is useful for storing values
// that needs to be accessed across multiple functions.
// You can access the value later using Value.
SetValue(key, value interface{})

// BackgroundColor returns the current background color of the terminal.
// It returns nil if the terminal's doesn't support querying the background
// color.
Expand Down Expand Up @@ -46,12 +52,16 @@ type teaContext struct {
kittyFlags int
backgroundColor color.Color
hasLightBg bool // cached value

values map[interface{}]interface{}
mtx sync.Mutex
}

func newContext(ctx context.Context) *teaContext {
c := new(teaContext)
c.Context = ctx
c.kittyFlags = -1
c.values = make(map[interface{}]interface{})
return c
}

Expand All @@ -74,3 +84,18 @@ func (c *teaContext) NewStyle() lipgloss.Style {
func (c *teaContext) ColorProfile() lipgloss.Profile {
return c.profile
}

func (ctx *teaContext) Value(key interface{}) interface{} {

Check failure on line 88 in context.go

View workflow job for this annotation

GitHub Actions / lint

receiver-naming: receiver name ctx should be consistent with previous receiver name c for teaContext (revive)
ctx.mtx.Lock()
defer ctx.mtx.Unlock()
if v, ok := ctx.values[key]; ok {
return v
}
return ctx.Context.Value(key)
}

func (ctx *teaContext) SetValue(key, value interface{}) {

Check failure on line 97 in context.go

View workflow job for this annotation

GitHub Actions / lint

receiver-naming: receiver name ctx should be consistent with previous receiver name c for teaContext (revive)
ctx.mtx.Lock()
defer ctx.mtx.Unlock()
ctx.values[key] = value
}

0 comments on commit 43ffb64

Please sign in to comment.