gitstack

grindlemire/go-tui code browser

9.2 KB Go 373 lines 2026-02-14 · 208bcf7 raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Package tui provides terminal rendering primitives for building terminal user interfaces.
package tui

import (
	"errors"
	"math"
	"strings"
)

// ColorType distinguishes between color representations.
type ColorType uint8

const (
	// ColorDefault represents the terminal's default color (no color set).
	ColorDefault ColorType = iota
	// ColorANSI represents an ANSI 256 palette color (0-255).
	ColorANSI
	// ColorRGB represents a true color (24-bit RGB).
	ColorRGB
)

// Color represents a terminal color with support for default, ANSI 256, and true color.
// Zero value represents the terminal default color.
type Color struct {
	typ ColorType
	// For ANSI: r holds the palette index (0-255)
	// For RGB: r, g, b hold the color components
	r, g, b uint8
}

// DefaultColor returns a Color representing the terminal's default color.
func DefaultColor() Color {
	return Color{typ: ColorDefault}
}

// ANSIColor returns a Color from the ANSI 256 palette.
func ANSIColor(index uint8) Color {
	return Color{typ: ColorANSI, r: index}
}

// RGBColor returns a true color (24-bit RGB) Color.
func RGBColor(r, g, b uint8) Color {
	return Color{typ: ColorRGB, r: r, g: g, b: b}
}

// HexColor parses a hex color string and returns a Color.
// Supported formats: "#RRGGBB" and "#RGB".
func HexColor(hex string) (Color, error) {
	hex = strings.TrimPrefix(hex, "#")

	switch len(hex) {
	case 6:
		// #RRGGBB
		r, err := parseHexByte(hex[0:2])
		if err != nil {
			return Color{}, err
		}
		g, err := parseHexByte(hex[2:4])
		if err != nil {
			return Color{}, err
		}
		b, err := parseHexByte(hex[4:6])
		if err != nil {
			return Color{}, err
		}
		return RGBColor(r, g, b), nil
	case 3:
		// #RGB -> expand to #RRGGBB
		r, err := parseHexNibble(hex[0])
		if err != nil {
			return Color{}, err
		}
		g, err := parseHexNibble(hex[1])
		if err != nil {
			return Color{}, err
		}
		b, err := parseHexNibble(hex[2])
		if err != nil {
			return Color{}, err
		}
		// Expand nibble to byte: 0xF -> 0xFF
		return RGBColor(r<<4|r, g<<4|g, b<<4|b), nil
	default:
		return Color{}, errors.New("invalid hex color format: expected #RGB or #RRGGBB")
	}
}

// parseHexByte parses a two-character hex string into a byte.
func parseHexByte(s string) (uint8, error) {
	if len(s) != 2 {
		return 0, errors.New("invalid hex byte")
	}
	high, err := parseHexNibble(s[0])
	if err != nil {
		return 0, err
	}
	low, err := parseHexNibble(s[1])
	if err != nil {
		return 0, err
	}
	return high<<4 | low, nil
}

// parseHexNibble parses a single hex character into a nibble (0-15).
func parseHexNibble(c byte) (uint8, error) {
	switch {
	case c >= '0' && c <= '9':
		return c - '0', nil
	case c >= 'a' && c <= 'f':
		return c - 'a' + 10, nil
	case c >= 'A' && c <= 'F':
		return c - 'A' + 10, nil
	default:
		return 0, errors.New("invalid hex character")
	}
}

// Type returns the ColorType of this color.
func (c Color) Type() ColorType {
	return c.typ
}

// IsDefault returns true if this is the terminal's default color.
func (c Color) IsDefault() bool {
	return c.typ == ColorDefault
}

// ANSI returns the ANSI palette index.
// For non-ANSI colors, it returns 0.
func (c Color) ANSI() uint8 {
	if c.typ != ColorANSI {
		return 0
	}
	return c.r
}

// RGB returns the red, green, and blue components.
// For non-RGB colors, it returns (0, 0, 0).
func (c Color) RGB() (r, g, b uint8) {
	if c.typ != ColorRGB {
		return 0, 0, 0
	}
	return c.r, c.g, c.b
}

// Equal returns true if both colors are identical.
func (c Color) Equal(other Color) bool {
	if c.typ != other.typ {
		return false
	}
	switch c.typ {
	case ColorDefault:
		return true
	case ColorANSI:
		return c.r == other.r
	case ColorRGB:
		return c.r == other.r && c.g == other.g && c.b == other.b
	}
	return false
}

// ToANSI approximates an RGB color to the nearest ANSI 256 palette entry.
// Uses the 6x6x6 color cube (indices 16-231) plus grayscale (232-255).
// Returns the color unchanged if it's already ANSI or default.
func (c Color) ToANSI() Color {
	if c.typ != ColorRGB {
		return c
	}

	r, g, b := c.r, c.g, c.b

	// Check if grayscale (or close to it)
	if r == g && g == b {
		// Grayscale ramp: 232-255 (24 shades)
		// 0 maps to 232, 255 maps to 255
		if r < 8 {
			return ANSIColor(16) // Black in the color cube is closer
		}
		if r > 248 {
			return ANSIColor(231) // White in the color cube is closer
		}
		gray := uint8(232 + (int(r)-8)*24/240)
		return ANSIColor(gray)
	}

	// 6x6x6 color cube: 16-231
	// Each component maps to 0-5
	ri := int(r) * 5 / 255
	gi := int(g) * 5 / 255
	bi := int(b) * 5 / 255

	index := uint8(16 + 36*ri + 6*gi + bi)
	return ANSIColor(index)
}

// Standard ANSI colors (basic 8 colors).
var (
	Black   = ANSIColor(0)
	Red     = ANSIColor(1)
	Green   = ANSIColor(2)
	Yellow  = ANSIColor(3)
	Blue    = ANSIColor(4)
	Magenta = ANSIColor(5)
	Cyan    = ANSIColor(6)
	White   = ANSIColor(7)
)

// Bright ANSI colors (high-intensity variants).
var (
	BrightBlack   = ANSIColor(8)
	BrightRed     = ANSIColor(9)
	BrightGreen   = ANSIColor(10)
	BrightYellow  = ANSIColor(11)
	BrightBlue    = ANSIColor(12)
	BrightMagenta = ANSIColor(13)
	BrightCyan    = ANSIColor(14)
	BrightWhite   = ANSIColor(15)
)

// ansi16RGB maps ANSI colors 0-15 to approximate RGB values.
// These are typical terminal color values; actual values vary by terminal.
var ansi16RGB = [16][3]uint8{
	{0, 0, 0},       // 0: Black
	{205, 49, 49},   // 1: Red
	{13, 188, 121},  // 2: Green
	{229, 229, 16},  // 3: Yellow
	{36, 114, 200},  // 4: Blue
	{188, 63, 188},  // 5: Magenta
	{17, 168, 205},  // 6: Cyan
	{229, 229, 229}, // 7: White
	{102, 102, 102}, // 8: Bright Black (Gray)
	{241, 76, 76},   // 9: Bright Red
	{35, 209, 139},  // 10: Bright Green
	{245, 245, 67},  // 11: Bright Yellow
	{59, 142, 234},  // 12: Bright Blue
	{214, 112, 214}, // 13: Bright Magenta
	{41, 184, 219},  // 14: Bright Cyan
	{255, 255, 255}, // 15: Bright White
}

// ToRGBValues returns the red, green, and blue components of any color.
// For ANSI colors, it approximates the RGB values.
// For default colors, it returns (0, 0, 0).
func (c Color) ToRGBValues() (r, g, b uint8) {
	switch c.typ {
	case ColorDefault:
		return 0, 0, 0
	case ColorRGB:
		return c.r, c.g, c.b
	case ColorANSI:
		idx := c.r
		if idx < 16 {
			// Standard ANSI colors 0-15
			rgb := ansi16RGB[idx]
			return rgb[0], rgb[1], rgb[2]
		} else if idx < 232 {
			// 6x6x6 color cube (indices 16-231)
			// index = 16 + 36*r + 6*g + b where r,g,b are 0-5
			idx -= 16
			ri := idx / 36
			gi := (idx % 36) / 6
			bi := idx % 6
			// Convert 0-5 to RGB: 0→0, 1→95, 2→135, 3→175, 4→215, 5→255
			cubeToRGB := func(v uint8) uint8 {
				if v == 0 {
					return 0
				}
				return 55 + v*40
			}
			return cubeToRGB(ri), cubeToRGB(gi), cubeToRGB(bi)
		} else {
			// Grayscale (indices 232-255)
			// 24 shades from dark gray to light gray
			gray := 8 + (idx-232)*10
			return gray, gray, gray
		}
	}
	return 0, 0, 0
}

// Luminance returns the relative luminance of the color (0.0-1.0).
// Uses the W3C formula for calculating relative luminance.
func (c Color) Luminance() float64 {
	if c.typ == ColorDefault {
		// Default color luminance is unknown; assume dark background
		return 0.0
	}
	r, g, b := c.ToRGBValues()

	// Convert to linear RGB (sRGB gamma correction)
	linearize := func(v uint8) float64 {
		f := float64(v) / 255.0
		if f <= 0.03928 {
			return f / 12.92
		}
		return math.Pow((f+0.055)/1.055, 2.4)
	}

	rLin := linearize(r)
	gLin := linearize(g)
	bLin := linearize(b)

	// W3C relative luminance formula
	return 0.2126*rLin + 0.7152*gLin + 0.0722*bLin
}

// IsLight returns true if the color is perceptually light.
// Uses a luminance threshold of 0.5 (middle gray).
func (c Color) IsLight() bool {
	if c.typ == ColorDefault {
		return false // Assume default is dark
	}
	return c.Luminance() > 0.5
}

// GradientDirection specifies the direction of a gradient.
type GradientDirection int

const (
	// GradientHorizontal is a left-to-right gradient.
	GradientHorizontal GradientDirection = iota
	// GradientVertical is a top-to-bottom gradient.
	GradientVertical
	// GradientDiagonalDown is a top-left to bottom-right gradient.
	GradientDiagonalDown
	// GradientDiagonalUp is a bottom-left to top-right gradient.
	GradientDiagonalUp
)

// Gradient represents a color gradient between two colors.
type Gradient struct {
	Start     Color
	End       Color
	Direction GradientDirection
}

// NewGradient creates a new horizontal gradient from start to end color.
func NewGradient(start, end Color) Gradient {
	return Gradient{
		Start:     start,
		End:       end,
		Direction: GradientHorizontal,
	}
}

// WithDirection returns a new gradient with the specified direction.
func (g Gradient) WithDirection(d GradientDirection) Gradient {
	g.Direction = d
	return g
}

// At returns the interpolated color at position t in [0, 1].
// t=0 returns the start color, t=1 returns the end color.
func (g Gradient) At(t float64) Color {
	// Clamp t to [0, 1]
	if t < 0 {
		t = 0
	}
	if t > 1 {
		t = 1
	}

	// Convert both colors to RGB for interpolation
	r1, g1, b1 := g.Start.ToRGBValues()
	r2, g2, b2 := g.End.ToRGBValues()

	// Linearly interpolate each component
	r := uint8(float64(r1) + t*float64(int(r2)-int(r1)))
	gVal := uint8(float64(g1) + t*float64(int(g2)-int(g1)))
	b := uint8(float64(b1) + t*float64(int(b2)-int(b1)))

	return RGBColor(r, gVal, b)
}