From d179958048588a70a2a29d4e18b2fd050ff30dcb Mon Sep 17 00:00:00 2001 From: Ayman Bagabas Date: Thu, 31 Oct 2024 15:46:44 -0400 Subject: [PATCH] feat: complete color support This commit adds a new function `Complete` that replaces the old `CompleteColor` type. It returns a `CompleteFunc` which takes three colors and returns the appropriate one based on the given color profile. --- color.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/color.go b/color.go index cacd2539..50a43f6f 100644 --- a/color.go +++ b/color.go @@ -5,6 +5,7 @@ import ( "image/color" "strconv" + "github.com/charmbracelet/colorprofile" "github.com/charmbracelet/x/ansi" "github.com/lucasb-eyer/go-colorful" ) @@ -179,3 +180,47 @@ func isDarkColor(c color.Color) bool { _, _, l := col.Hsl() return l < 0.5 //nolint:mnd } + +// CompleteFunc is a function that returns the appropriate color based on the +// given color profile. +// +// Example usage: +// +// p := colorprofile.Detect(os.Stderr, os.Environ()) +// complete := lipgloss.Complete(p) +// color := complete( +// lipgloss.Color(1), // ANSI +// lipgloss.Color(124), // ANSI256 +// lipgloss.Color("#ff34ac"), // TrueColor +// ) +// fmt.Println("Ooh, pretty color: ", color) +// +// For more info see [Complete]. +type CompleteFunc func(ansi, ansi256, truecolor color.Color) color.Color + +// Complete returns a function that will return the appropriate color based on +// the given color profile. +// +// Example usage: +// +// p := colorprofile.Detect(os.Stderr, os.Environ()) +// complete := lipgloss.Complete(p) +// color := complete( +// lipgloss.Color(1), // ANSI +// lipgloss.Color(124), // ANSI256 +// lipgloss.Color("#ff34ac"), // TrueColor +// ) +// fmt.Println("Ooh, pretty color: ", color) +func Complete(p colorprofile.Profile) CompleteFunc { + return func(ansi, ansi256, truecolor color.Color) color.Color { + switch p { + case colorprofile.ANSI: + return ansi + case colorprofile.ANSI256: + return ansi256 + case colorprofile.TrueColor: + return truecolor + } + return noColor + } +}