-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathutil.go
More file actions
executable file
·362 lines (313 loc) · 9.83 KB
/
util.go
File metadata and controls
executable file
·362 lines (313 loc) · 9.83 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
package box
import (
"fmt"
"image/color"
"strings"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
"github.com/huandu/xstrings"
"github.com/mattn/go-runewidth"
)
// isTTY points to the function used to determine if a file descriptor is a terminal.
// It is defined as a variable to allow mocking in tests.
var isTTY = term.IsTerminal
// expandedLine stores a tab-expanded line, and its visible length.
type expandedLine struct {
line string // tab-expanded line
len int // line's visible length
}
// addVertPadding adds vertical padding lines using the given inner width.
//
// innerWidth represents the visible width between the vertical borders.
func (b *Box) addVertPadding(innerWidth int) ([]string, error) {
if innerWidth < 0 {
innerWidth = 0
}
padding := strings.Repeat(" ", innerWidth)
vertical, err := applyColor(b.vertical, b.color)
if err != nil {
return nil, err
}
texts := make([]string, b.py)
for i := range texts {
texts[i] = vertical + padding + vertical
}
return texts, nil
}
// longestLine expands tabs in lines and determines longest visible
// return longest length and array of expanded lines
func longestLine(lines []string) (int, []expandedLine) {
longest := 0
expandedLines := make([]expandedLine, 0, len(lines))
var tmpLine strings.Builder
var lineLen int
for _, line := range lines {
tmpLine.Reset()
for _, c := range line {
lineLen = runewidth.StringWidth(tmpLine.String())
if c == '\t' {
tmpLine.WriteString(strings.Repeat(" ", 8-(lineLen&7)))
} else {
tmpLine.WriteRune(c)
}
}
lineLen = runewidth.StringWidth(tmpLine.String())
expandedLines = append(expandedLines, expandedLine{tmpLine.String(), lineLen})
// Check if each line has ANSI Color Code then decrease the length accordingly
if runewidth.StringWidth(ansi.Strip(tmpLine.String())) < runewidth.StringWidth(tmpLine.String()) {
lineLen = runewidth.StringWidth(ansi.Strip(tmpLine.String()))
}
if lineLen > longest {
longest = lineLen
}
}
return longest, expandedLines
}
// charWidth returns the visible width of a string, treating zero-width
// results as width 1 so that box calculations always make progress.
func charWidth(s string) int {
w := runewidth.StringWidth(ansi.Strip(s))
if w == 0 {
w = 1
}
return w
}
// buildSegment builds a horizontal segment with the given visual width using
// the provided fill glyph, padding with spaces if needed to match width.
func buildSegment(fill string, width, horizontalWidth int) string {
if width <= 0 {
return ""
}
fillCount := width / horizontalWidth
seg := strings.Repeat(fill, fillCount)
padWidth := width - fillCount*horizontalWidth
if padWidth > 0 {
seg += strings.Repeat(" ", padWidth)
}
return seg
}
// buildPlainBar builds a horizontal bar (without title) that matches the
// specified visual line width.
func buildPlainBar(left, fill, right string, leftW, rightW, lineWidth, horizontalWidth int) string {
inner := max(lineWidth-leftW-rightW, 0)
bar := buildSegment(fill, inner, horizontalWidth)
return left + bar + right
}
// buildTitledBar builds a top or bottom bar containing a title. It left-aligns
// the title segment and fills the remaining space on the right with the
// horizontal glyph. Any leftover width that is not divisible by the glyph's
// width is emitted as spaces before the emoji sequence so that the last
// character before the corner is the glyph, not a space.
func buildTitledBar(left, fill, right string, leftW, rightW, lineWidth, horizontalWidth int, title string) string {
if title == "" {
return buildPlainBar(left, fill, right, leftW, rightW, lineWidth, horizontalWidth)
}
plainTitle := title
if strings.Contains(plainTitle, "\t") {
plainTitle = xstrings.ExpandTabs(plainTitle, 4)
}
titleWidth := runewidth.StringWidth(ansi.Strip(plainTitle))
titleSegWidth := titleWidth + 2 // one space padding on each side
inner := max(lineWidth-leftW-rightW, titleSegWidth)
remaining := inner - titleSegWidth
gapWidth := 0
fillWidth := remaining
if horizontalWidth > 1 {
gapWidth = remaining % horizontalWidth
fillWidth = remaining - gapWidth
}
leftSeg := ""
rightSeg := buildSegment(fill, fillWidth, horizontalWidth)
gap := ""
if gapWidth > 0 {
gap = strings.Repeat(" ", gapWidth)
}
return left + leftSeg + " " + plainTitle + " " + gap + rightSeg + right
}
// formatLine formats the line according to the information passed.
func (b *Box) formatLine(lines2 []expandedLine, longestLine, titleLen int, sideMargin, title string, texts []string) ([]string, error) {
for i, line := range lines2 {
length := line.len
// Use later
var space, oddSpace string
// compute stripped width once
strippedWidth := runewidth.StringWidth(ansi.Strip(line.line))
if strippedWidth < runewidth.StringWidth(line.line) {
length = strippedWidth
}
// If current text is shorter than the longest one
// center the text, so it looks better
if length < longestLine {
// Difference between longest and current one
diff := longestLine - length
// the spaces to add on each side
toAdd := diff / 2
space = strings.Repeat(" ", toAdd)
// If difference between the longest and current one
// is odd, we have to add one additional space before the last vertical separator
if diff%2 != 0 {
oddSpace = " "
}
}
spacing := space + sideMargin
var format AlignType
switch {
case i < titleLen && title != "" && b.titlePos == Inside:
format = centerAlign
default:
align, err := b.findAlign()
if err != nil {
return nil, err
}
format = AlignType(align)
}
sep, err := applyColor(b.vertical, b.color)
if err != nil {
return nil, err
}
formatted := fmt.Sprintf(string(format), sep, spacing, line.line, oddSpace, space, sideMargin)
texts = append(texts, formatted)
}
return texts, nil
}
func (b *Box) findAlign() (string, error) {
switch b.contentAlign {
case Center:
return centerAlign, nil
case Right:
return rightAlign, nil
case Left, "":
// If ContentAlign isn't provided then by default Alignment is Left
return leftAlign, nil
default:
return "", fmt.Errorf("invalid Content Alignment %s", b.contentAlign)
}
}
func getConvertedColor(colorStr string) (color.Color, error) {
cv, err := parseColorString(colorStr)
if err != nil {
return nil, err
}
// If profile conversion results in nil, fall back to the
// parsed color so we always emit color.
converted := profile.Convert(cv)
if converted == nil {
return cv, nil
}
return converted, nil
}
func applyColor(str string, colorStr string) (string, error) {
// Empty color string means: do not apply any styling.
if colorStr == "" {
return str, nil
}
convertedColor, err := getConvertedColor(colorStr)
if err != nil {
return str, err
}
return applyConvertedColor(str, convertedColor), nil
}
func stringColorToHex(color string) string {
if hex, exists := colorToHex[color]; exists {
return hex
}
// Return empty string for unknown colors to let ansi.XParseColor handle it
return ""
}
// addStylePreservingOriginalFormat allows to add style around the original formating
func addStylePreservingOriginalFormat(s string, f func(a string) string) string {
const reset = "\033[0m"
if !strings.Contains(s, reset) {
return f(s)
}
var sb strings.Builder
start := 0
for {
idx := strings.Index(s[start:], reset)
if idx == -1 {
sb.WriteString(f(s[start:]))
break
}
sb.WriteString(f(s[start : start+idx]))
// skip the reset sequence (preserve original behavior of removing it)
start += idx + len(reset)
}
return sb.String()
}
// parseColorString converts a color string to color.Color using stringColorToHex and ansi.XParseColor
func parseColorString(colorStr string) (color.Color, error) {
hexColor := stringColorToHex(colorStr)
if hexColor == "" {
hexColor = colorStr
}
colorValue := ansi.XParseColor(hexColor)
if colorValue == nil {
return nil, fmt.Errorf("unable to parse color: %s", colorStr)
}
return colorValue, nil
}
func applyConvertedColor(str string, c color.Color) string {
if c == nil {
return str
}
style := ansi.Style{}.ForegroundColor(c)
styled := style.Styled
// Fast path: no newlines
if !strings.Contains(str, "\n") {
return addStylePreservingOriginalFormat(str, styled)
}
var sb strings.Builder
start := 0
for {
idx := strings.IndexByte(str[start:], '\n')
if idx == -1 {
sb.WriteString(addStylePreservingOriginalFormat(str[start:], styled))
break
}
sb.WriteString(addStylePreservingOriginalFormat(str[start:start+idx], styled))
sb.WriteByte('\n')
start += idx + 1
}
return sb.String()
}
func (b *Box) applyColorBar(topBar, bottomBar, title string) (string, string, error) {
if b.titleColor == "" || title == "" {
return topBar, bottomBar, nil
}
if strings.TrimSpace(b.color) == "" {
return topBar, bottomBar, nil
}
converted, err := getConvertedColor(b.color)
if err != nil {
return "", "", err
}
if b.titlePos == Top {
strippedBar := ansi.Strip(topBar)
strippedTitle := ansi.Strip(title)
if idx := strings.Index(strippedBar, strippedTitle); idx != -1 {
// split around first occurrence to preserve any other repeats
b0 := applyConvertedColor(strippedBar[:idx], converted)
b1 := applyConvertedColor(strippedBar[idx+len(strippedTitle):], converted)
coloredTitle, err := applyColor(title, b.titleColor)
if err != nil {
return "", "", err
}
topBar = b0 + coloredTitle + b1
}
}
if b.titlePos == Bottom {
strippedBar := ansi.Strip(bottomBar)
strippedTitle := ansi.Strip(title)
if idx := strings.Index(strippedBar, strippedTitle); idx != -1 {
// split around first occurrence to preserve any other repeats
b0 := applyConvertedColor(strippedBar[:idx], converted)
b1 := applyConvertedColor(strippedBar[idx+len(strippedTitle):], converted)
coloredTitle, err := applyColor(title, b.titleColor)
if err != nil {
return "", "", err
}
bottomBar = b0 + coloredTitle + b1
}
}
return topBar, bottomBar, nil
}