goncdu/tui/utils.go
2025-02-10 16:26:13 +08:00

57 lines
1.4 KiB
Go

package tui
import (
"fmt"
"math"
)
// TruncateStr 截断字符串以适应给定宽度
func TruncateStr(inStr string, maxWidth int) string {
if len(inStr) <= maxWidth {
return inStr
}
headLen := (maxWidth - 3) / 2
tailLen := maxWidth - headLen - 3
return fmt.Sprintf("%s...%s", inStr[:headLen], inStr[len(inStr)-tailLen:])
}
// FormatProgressBar generates a progress bar string.
func FormatProgressBar(size, maxSize int64, width int, blockChars []string) string {
if blockChars == nil || len(blockChars) < 2 {
blockChars = []string{" ", "#"}
}
if maxSize == 0 {
return "[" + repeatString(blockChars[0], width) + "]"
}
ratio := float64(size) / float64(maxSize)
filledLength := int(ratio * float64(width))
remainingLength := width - filledLength
// Calculate the fractional part
fractionalPart := math.Mod(ratio*float64(width), 1.0)
// Create the progress bar string
progressBar := repeatString(blockChars[len(blockChars)-1], filledLength)
if fractionalPart > 0 && filledLength < width {
// Calculate the index for the fractional part
fractionalIndex := int(fractionalPart*float64(len(blockChars)-2)) + 1
progressBar += blockChars[fractionalIndex]
remainingLength--
}
progressBar += repeatString(blockChars[0], remainingLength)
return "[" + progressBar + "]"
}
// repeatString repeats a string n times.
func repeatString(s string, n int) string {
result := ""
for i := 0; i < n; i++ {
result += s
}
return result
}