tui/views/view_constrain.go
2023-04-24 11:55:04 +02:00

38 lines
852 B
Go

package views
import (
"git.milar.in/milarin/gmath"
"git.milar.in/milarin/tui"
)
// ConstrainView is a tui.Wrapper which constrains the dimensions of its View
type ConstrainView struct {
tui.WrapperTmpl
MaxWidth int
MaxHeight int
}
var _ tui.Wrapper = &ConstrainView{}
func NewConstrainView(view tui.View, maxWidth, maxHeight int) *ConstrainView {
v := new(ConstrainView)
v.SetView(view)
v.Constrain(maxWidth, maxHeight)
return v
}
func (v *ConstrainView) Constrain(maxWidth, maxHeight int) {
v.MaxWidth, v.MaxHeight = maxWidth, maxHeight
}
func (v *ConstrainView) Layout() (prefWidth, prefHeight int) {
if v.View() == nil {
return v.MaxWidth, v.MaxHeight
}
vw, vh := v.View().Layout()
prefWidth = iff(vw >= 0, gmath.Min(vw, v.MaxWidth), v.MaxWidth)
prefHeight = iff(vh >= 0, gmath.Min(vh, v.MaxHeight), v.MaxHeight)
return
}