tui/layouts/utils.go

91 lines
1.5 KiB
Go
Raw Normal View History

2023-04-24 11:41:38 +02:00
package layouts
import (
"math"
"git.tordarus.net/Tordarus/tui"
)
func min(x, y int) int {
if x < y {
return x
}
return y
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func limit(v, minv, maxv int) int {
return min(max(v, minv), maxv)
}
func iff[T any](condition bool, trueValue, falseValue T) T {
if condition {
return trueValue
}
return falseValue
}
type LayoutResult struct {
Sizes map[tui.View]tui.Size
Sum tui.Size
Min tui.Size
Max tui.Size
Pref tui.Size
Count int
VerticalNegativeCount int
HorizontalNegativeCount int
}
func CalculateLayoutResult(views []tui.View) *LayoutResult {
result := &LayoutResult{
Sizes: map[tui.View]tui.Size{},
Sum: tui.Size{Width: 0, Height: 0},
Min: tui.Size{Width: math.MaxInt, Height: math.MaxInt},
Max: tui.Size{Width: -1, Height: -1},
Count: 0,
VerticalNegativeCount: 0,
HorizontalNegativeCount: 0,
}
for _, view := range views {
if view == nil {
continue
}
result.Count++
width, height := view.Layout()
result.Sizes[view] = tui.Size{Width: width, Height: height}
if width > 0 {
result.Sum.Width += width
result.Min.Width = min(result.Min.Width, width)
result.Max.Width = max(result.Max.Width, width)
} else if width < 0 {
result.HorizontalNegativeCount++
}
if height > 0 {
result.Sum.Height += height
result.Min.Height = min(result.Min.Height, height)
result.Max.Height = max(result.Max.Height, height)
} else if height < 0 {
result.VerticalNegativeCount++
}
}
return result
}