tui/views/view_constrain.go

38 lines
852 B
Go
Raw Permalink Normal View History

2022-04-02 13:01:41 +02:00
package views
import (
2023-04-24 11:55:04 +02:00
"git.milar.in/milarin/gmath"
"git.milar.in/milarin/tui"
2022-04-02 13:01:41 +02:00
)
// 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{}
2022-04-02 13:01:41 +02:00
2022-05-04 11:13:18 +02:00
func NewConstrainView(view tui.View, maxWidth, maxHeight int) *ConstrainView {
2022-04-02 13:01:41 +02:00
v := new(ConstrainView)
v.SetView(view)
2022-05-04 11:13:18 +02:00
v.Constrain(maxWidth, maxHeight)
2022-04-02 13:01:41 +02:00
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
}
2022-05-04 11:13:18 +02:00
vw, vh := v.View().Layout()
2023-04-24 11:55:04 +02:00
prefWidth = iff(vw >= 0, gmath.Min(vw, v.MaxWidth), v.MaxWidth)
prefHeight = iff(vh >= 0, gmath.Min(vh, v.MaxHeight), v.MaxHeight)
return
2022-04-02 13:01:41 +02:00
}