-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgradient.go
More file actions
561 lines (453 loc) · 11 KB
/
gradient.go
File metadata and controls
561 lines (453 loc) · 11 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package gradient
import (
"fmt"
"os"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/lucasb-eyer/go-colorful"
"github.com/muesli/termenv"
)
type Mode string
const (
Dark Mode = "dark"
Light Mode = "light"
)
// ConsoleFormatter provides text formatting with gradient backgrounds
type ConsoleFormatter struct {
mode Mode
}
// catppuccinBase defines the base color for text in Catppuccin theme
const catppuccinBase = "#11111b"
type Gradient struct {
startColor colorful.Color
endColor colorful.Color
mode Mode
}
type GradientOption func(*Gradient)
func WithMode(mode Mode) GradientOption {
return func(g *Gradient) {
g.mode = mode
}
}
func detectTerminalTheme() Mode {
if os.Getenv("TERM") == "dumb" || os.Getenv("NO_COLOR") != "" {
return Dark
}
output := termenv.NewOutput(os.Stdout)
if output.HasDarkBackground() {
return Dark
}
return Light
}
func New(color1, color2 string, opts ...GradientOption) (*Gradient, error) {
start, err := colorful.Hex(color1)
if err != nil {
return nil, fmt.Errorf("invalid start color %s: %w", color1, err)
}
end, err := colorful.Hex(color2)
if err != nil {
return nil, fmt.Errorf("invalid end color %s: %w", color2, err)
}
g := &Gradient{
startColor: start,
endColor: end,
mode: detectTerminalTheme(),
}
for _, opt := range opts {
opt(g)
}
return g, nil
}
func NewWithMode(color1, color2 string, mode Mode) (*Gradient, error) {
return New(color1, color2, WithMode(mode))
}
func (g *Gradient) SetMode(mode Mode) {
g.mode = mode
}
func (g *Gradient) ColorAt(position float64) string {
if position < 0 {
position = 0
}
if position > 1 {
position = 1
}
color := g.startColor.BlendLuv(g.endColor, position)
return color.Hex()
}
func (g *Gradient) ApplyToText(text string) string {
if len(text) == 0 {
return ""
}
runes := []rune(text)
visibleCount := 0
for _, r := range runes {
if r != ' ' && r != '\t' && r != '\n' {
visibleCount++
}
}
if visibleCount == 0 {
return text
}
var result strings.Builder
visibleIndex := 0
for _, r := range runes {
if r == ' ' || r == '\t' || r == '\n' {
result.WriteRune(r)
continue
}
position := float64(visibleIndex) / float64(visibleCount-1)
if visibleCount == 1 {
position = 0.5
}
color := g.ColorAt(position)
style := lipgloss.NewStyle().Foreground(lipgloss.Color(color))
result.WriteString(style.Render(string(r)))
visibleIndex++
}
return result.String()
}
type LineOption func(*lineConfig)
type lineConfig struct {
mode string
contentStart int
contentEnd int
}
func WithContentBounds(start, end int) LineOption {
return func(c *lineConfig) {
c.mode = "manual"
c.contentStart = start
c.contentEnd = end
}
}
func WithPerLineGradient() LineOption {
return func(c *lineConfig) {
c.mode = "perline"
}
}
func WithVisualCenter() LineOption {
return func(c *lineConfig) {
c.mode = "visual"
}
}
func WithAutoDetect() LineOption {
return func(c *lineConfig) {
c.mode = "auto"
}
}
func (g *Gradient) ApplyToLines(lines []string, opts ...LineOption) []string {
if len(lines) == 0 {
return lines
}
config := &lineConfig{mode: "auto"}
for _, opt := range opts {
opt(config)
}
switch config.mode {
case "manual":
return g.applyWithManualBounds(lines, config.contentStart, config.contentEnd)
case "perline":
return g.applyPerLine(lines)
case "visual":
return g.applyWithVisualCenter(lines)
default:
return g.applyWithAutoDetect(lines)
}
}
func (g *Gradient) applyWithAutoDetect(lines []string) []string {
leftMost := -1
rightMost := 0
for _, line := range lines {
if line == "" {
continue
}
firstVisible := -1
lastVisible := -1
for i, r := range line {
if r != ' ' && r != '\t' {
if firstVisible == -1 {
firstVisible = i
}
lastVisible = i
}
}
if firstVisible != -1 {
if leftMost == -1 || firstVisible < leftMost {
leftMost = firstVisible
}
if lastVisible > rightMost {
rightMost = lastVisible
}
}
}
if leftMost == -1 {
return lines
}
contentWidth := rightMost - leftMost
if contentWidth <= 0 {
contentWidth = 1
}
result := make([]string, len(lines))
for i, line := range lines {
result[i] = g.applyToLine(line, leftMost, contentWidth)
}
return result
}
func (g *Gradient) applyWithManualBounds(lines []string, start, end int) []string {
contentWidth := end - start
if contentWidth <= 0 {
contentWidth = 1
}
result := make([]string, len(lines))
for i, line := range lines {
result[i] = g.applyToLine(line, start, contentWidth)
}
return result
}
func (g *Gradient) applyPerLine(lines []string) []string {
result := make([]string, len(lines))
for i, line := range lines {
if len(line) == 0 {
result[i] = ""
continue
}
firstVisible := -1
lastVisible := -1
for j, r := range line {
if r != ' ' && r != '\t' {
if firstVisible == -1 {
firstVisible = j
}
lastVisible = j
}
}
if firstVisible == -1 {
result[i] = line
continue
}
lineWidth := lastVisible - firstVisible
if lineWidth <= 0 {
lineWidth = 1
}
result[i] = g.applyToLine(line, firstVisible, lineWidth)
}
return result
}
func (g *Gradient) applyWithVisualCenter(lines []string) []string {
totalChars := 0
weightedCenter := 0.0
for _, line := range lines {
lineChars := 0
lineSum := 0
for i, r := range line {
if r != ' ' && r != '\t' {
lineChars++
lineSum += i
}
}
if lineChars > 0 {
totalChars += lineChars
weightedCenter += float64(lineSum)
}
}
if totalChars == 0 {
return lines
}
center := int(weightedCenter / float64(totalChars))
maxDistance := 0
for _, line := range lines {
for i, r := range line {
if r != ' ' && r != '\t' {
distance := center - i
if distance < 0 {
distance = -distance
}
if distance > maxDistance {
maxDistance = distance
}
}
}
}
leftBound := center - maxDistance
rightBound := center + maxDistance
contentWidth := rightBound - leftBound
if contentWidth <= 0 {
contentWidth = 1
}
result := make([]string, len(lines))
for i, line := range lines {
result[i] = g.applyToLine(line, leftBound, contentWidth)
}
return result
}
func (g *Gradient) applyToLine(line string, globalLeft int, contentWidth int) string {
if len(line) == 0 {
return ""
}
var result strings.Builder
runes := []rune(line)
for i, r := range runes {
if r == ' ' {
result.WriteRune(' ')
continue
}
relativePos := max(0, i-globalLeft)
position := float64(relativePos) / float64(contentWidth)
if position > 1.0 {
position = 1.0
}
color := g.ColorAt(position)
style := lipgloss.NewStyle().Foreground(lipgloss.Color(color))
result.WriteString(style.Render(string(r)))
}
return result.String()
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
type MultiGradient struct {
colors []colorful.Color
mode Mode
}
type MultiGradientOption func(*MultiGradient)
func WithMultiMode(mode Mode) MultiGradientOption {
return func(g *MultiGradient) {
g.mode = mode
}
}
func NewMulti(colors []string, opts ...MultiGradientOption) (*MultiGradient, error) {
if len(colors) < 2 {
return nil, fmt.Errorf("need at least 2 colors for gradient")
}
parsedColors := make([]colorful.Color, 0, len(colors))
for _, c := range colors {
color, err := colorful.Hex(c)
if err != nil {
return nil, fmt.Errorf("invalid color %s: %w", c, err)
}
parsedColors = append(parsedColors, color)
}
g := &MultiGradient{
colors: parsedColors,
mode: detectTerminalTheme(),
}
for _, opt := range opts {
opt(g)
}
return g, nil
}
func NewMultiWithMode(colors []string, mode Mode) (*MultiGradient, error) {
return NewMulti(colors, WithMultiMode(mode))
}
func (g *MultiGradient) SetMode(mode Mode) {
g.mode = mode
}
func (g *MultiGradient) ColorAt(position float64) string {
if position < 0 {
position = 0
}
if position > 1 {
position = 1
}
if len(g.colors) == 2 {
color := g.colors[0].BlendLuv(g.colors[1], position)
return color.Hex()
}
segment := position * float64(len(g.colors)-1)
colorIndex := int(segment)
if colorIndex >= len(g.colors)-1 {
return g.colors[len(g.colors)-1].Hex()
}
localPos := segment - float64(colorIndex)
color := g.colors[colorIndex].BlendLuv(g.colors[colorIndex+1], localPos)
return color.Hex()
}
func (g *MultiGradient) ApplyToText(text string) string {
if len(text) == 0 {
return ""
}
runes := []rune(text)
visibleCount := 0
for _, r := range runes {
if r != ' ' && r != '\t' && r != '\n' {
visibleCount++
}
}
if visibleCount == 0 {
return text
}
var result strings.Builder
visibleIndex := 0
for _, r := range runes {
if r == ' ' || r == '\t' || r == '\n' {
result.WriteRune(r)
continue
}
position := float64(visibleIndex) / float64(visibleCount-1)
if visibleCount == 1 {
position = 0.5
}
color := g.ColorAt(position)
style := lipgloss.NewStyle().Foreground(lipgloss.Color(color))
result.WriteString(style.Render(string(r)))
visibleIndex++
}
return result.String()
}
// NewConsoleFormatter creates a new ConsoleFormatter with the given mode
func NewConsoleFormatter(mode Mode) *ConsoleFormatter {
return &ConsoleFormatter{mode: mode}
}
// NewConsoleFormatterAuto creates a new ConsoleFormatter with auto-detected mode
func NewConsoleFormatterAuto() *ConsoleFormatter {
return &ConsoleFormatter{mode: detectTerminalTheme()}
}
// createGradientBackground creates a text with gradient background colors
func (f *ConsoleFormatter) createGradientBackground(text, startColor, endColor string) string {
// Handle empty text case
if text == "" {
return ""
}
// Parse hex colors to RGB
startR, startG, startB := HexToRGB(startColor)
endR, endG, endB := HexToRGB(endColor)
textWithPadding := " " + text + " "
length := len(textWithPadding)
var result strings.Builder
// For each character, calculate its position in the gradient and apply background color
for i, char := range textWithPadding {
// Calculate gradient position (0.0 to 1.0)
var t float64
if length > 1 {
t = float64(i) / float64(length-1)
} else {
t = 0.0
}
// Interpolate RGB values
r := int(float64(startR) + t*float64(endR-startR))
g := int(float64(startG) + t*float64(endG-startG))
b := int(float64(startB) + t*float64(endB-startB))
// Create style with this background color
charStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinBase)).
Background(lipgloss.Color(fmt.Sprintf("#%02x%02x%02x", r, g, b))).
Bold(true)
result.WriteString(charStyle.Render(string(char)))
}
return result.String()
}
// HexToRGB converts a hex color string to RGB values
func HexToRGB(hex string) (int, int, int) {
// Remove # if present
hex = strings.TrimPrefix(hex, "#")
// Parse hex string
var r, g, b int
fmt.Sscanf(hex, "%02x%02x%02x", &r, &g, &b)
return r, g, b
}
// CreateGradientBackground creates a text with gradient background colors (public method)
func (f *ConsoleFormatter) CreateGradientBackground(text, startColor, endColor string) string {
return f.createGradientBackground(text, startColor, endColor)
}