Skip to content

Commit

Permalink
fix: cache color profile and background
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed Jul 31, 2023
1 parent 98e7511 commit b228c58
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@ var renderer = &Renderer{
// Renderer is a lipgloss terminal renderer.
type Renderer struct {
output *termenv.Output
hasDarkBackground *bool
mtx sync.RWMutex
colorProfile termenv.Profile
hasDarkBackground bool

getColorProfile sync.Once
explicitColorProfile bool

getBackgroundColor sync.Once
explicitBackgroundColor bool

mtx sync.RWMutex
}

// RendererOption is a function that can be used to configure a [Renderer].
Expand Down Expand Up @@ -59,7 +67,16 @@ func (r *Renderer) SetOutput(o *termenv.Output) {

// ColorProfile returns the detected termenv color profile.
func (r *Renderer) ColorProfile() termenv.Profile {
return r.output.Profile
r.mtx.RLock()
defer r.mtx.RUnlock()

if !r.explicitColorProfile {
r.getColorProfile.Do(func() {
r.colorProfile = r.output.EnvColorProfile()
})
}

return r.colorProfile
}

// ColorProfile returns the detected termenv color profile.
Expand All @@ -86,7 +103,9 @@ func ColorProfile() termenv.Profile {
func (r *Renderer) SetColorProfile(p termenv.Profile) {
r.mtx.Lock()
defer r.mtx.Unlock()
r.output.Profile = p

r.colorProfile = p
r.explicitColorProfile = true
}

// SetColorProfile sets the color profile on the default renderer. This
Expand Down Expand Up @@ -120,10 +139,14 @@ func HasDarkBackground() bool {
func (r *Renderer) HasDarkBackground() bool {
r.mtx.RLock()
defer r.mtx.RUnlock()
if r.hasDarkBackground != nil {
return *r.hasDarkBackground

if !r.explicitBackgroundColor {
r.getBackgroundColor.Do(func() {
r.hasDarkBackground = r.output.HasDarkBackground()
})
}
return r.output.HasDarkBackground()

return r.hasDarkBackground
}

// SetHasDarkBackground sets the background color detection value for the
Expand Down Expand Up @@ -151,5 +174,7 @@ func SetHasDarkBackground(b bool) {
func (r *Renderer) SetHasDarkBackground(b bool) {
r.mtx.Lock()
defer r.mtx.Unlock()
r.hasDarkBackground = &b

r.hasDarkBackground = b
r.explicitBackgroundColor = true
}

0 comments on commit b228c58

Please sign in to comment.