feat: expand parent colors

This commit is contained in:
Jan De Dobbeleer 2021-12-16 10:57:01 +01:00 committed by Jan De Dobbeleer
parent e8f9bb20b0
commit df78bad3b5
2 changed files with 25 additions and 8 deletions

View file

@ -24,7 +24,7 @@ type AnsiWriter struct {
ansi *ansiUtils ansi *ansiUtils
terminalBackground string terminalBackground string
Colors *Color Colors *Color
ParentColors *Color ParentColors []*Color
ansiColors AnsiColors ansiColors AnsiColors
} }
@ -80,10 +80,13 @@ func (a *AnsiWriter) setColors(background, foreground string) {
} }
func (a *AnsiWriter) setParentColors(background, foreground string) { func (a *AnsiWriter) setParentColors(background, foreground string) {
a.ParentColors = &Color{ if a.ParentColors == nil {
a.ParentColors = make([]*Color, 0)
}
a.ParentColors = append([]*Color{{
Background: background, Background: background,
Foreground: foreground, Foreground: foreground,
} }}, a.ParentColors...)
} }
func (a *AnsiWriter) clearParentColors() { func (a *AnsiWriter) clearParentColors() {
@ -183,16 +186,30 @@ func (a *AnsiWriter) isKeyword(color string) bool {
} }
func (a *AnsiWriter) expandKeyword(keyword string) string { func (a *AnsiWriter) expandKeyword(keyword string) string {
resolveParentColor := func(keyword string) string {
for _, color := range a.ParentColors {
if color == nil {
return Transparent
}
switch keyword {
case ParentBackground:
keyword = color.Background
case ParentForeground:
keyword = color.Foreground
default:
return keyword
}
}
return keyword
}
resolveKeyword := func(keyword string) string { resolveKeyword := func(keyword string) string {
switch { switch {
case keyword == Background && a.Colors != nil: case keyword == Background && a.Colors != nil:
return a.Colors.Background return a.Colors.Background
case keyword == Foreground && a.Colors != nil: case keyword == Foreground && a.Colors != nil:
return a.Colors.Foreground return a.Colors.Foreground
case keyword == ParentBackground && a.ParentColors != nil: case (keyword == ParentBackground || keyword == ParentForeground) && a.ParentColors != nil:
return a.ParentColors.Background return resolveParentColor(keyword)
case keyword == ParentForeground && a.ParentColors != nil:
return a.ParentColors.Foreground
default: default:
return Transparent return Transparent
} }

View file

@ -175,7 +175,7 @@ func TestWriteANSIColors(t *testing.T) {
ansi.init("pwsh") ansi.init("pwsh")
renderer := &AnsiWriter{ renderer := &AnsiWriter{
ansi: ansi, ansi: ansi,
ParentColors: tc.Parent, ParentColors: []*Color{tc.Parent},
Colors: tc.Colors, Colors: tc.Colors,
terminalBackground: tc.TerminalBackground, terminalBackground: tc.TerminalBackground,
ansiColors: &DefaultColors{}, ansiColors: &DefaultColors{},