2024-03-11 23:28:37 +01:00

62 lines
1.5 KiB
Go

package color
import (
"fmt"
"io"
)
// Value is a type definition for the data type of a single color component.
type Value = float64
// Color represents an RGB color.
type Color struct {
R Value
G Value
B Value
}
// RGB creates a new color with red, green and blue values in the range of 0.0 to 1.0.
func RGB(r Value, g Value, b Value) Color {
return Color{r, g, b}
}
// Fprint writes the text in the given color to the writer.
func (c Color) Fprint(writer io.Writer, args ...any) {
if !Terminal {
fmt.Fprint(writer, args...)
return
}
fmt.Fprintf(writer, "\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
}
// Print writes the text in the given color to standard output.
func (c Color) Print(args ...any) {
if !Terminal {
fmt.Print(args...)
return
}
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
}
// Printf formats according to a format specifier and writes the text in the given color to standard output.
func (c Color) Printf(format string, args ...any) {
if !Terminal {
fmt.Printf(format, args...)
return
}
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprintf(format, args...))
}
// Println writes the text in the given color to standard output and appends a newline.
func (c Color) Println(args ...any) {
if !Terminal {
fmt.Println(args...)
return
}
fmt.Printf("\x1b[38;2;%d;%d;%dm%s\n\x1b[0m", byte(c.R*255), byte(c.G*255), byte(c.B*255), fmt.Sprint(args...))
}