Files
prevara/slider.go
2025-11-30 16:45:22 +00:00

116 lines
2.8 KiB
Go

package gel
import (
"image"
"image/color"
l "github.com/p9c/p9/pkg/gel/gio/layout"
"github.com/p9c/p9/pkg/gel/gio/op"
"github.com/p9c/p9/pkg/gel/gio/op/clip"
"github.com/p9c/p9/pkg/gel/gio/op/paint"
"github.com/p9c/p9/pkg/gel/gio/unit"
"github.com/p9c/p9/pkg/gel/f32color"
)
type Slider struct {
*Window
min, max float32
color color.NRGBA
float *Float
}
// Slider is for selecting a value in a range.
func (w *Window) Slider() *Slider {
return &Slider{
Window: w,
color: w.Colors.GetNRGBAFromName("Primary"),
}
}
// Min sets the value at the left hand side
func (s *Slider) Min(min float32) *Slider {
s.min = min
return s
}
// Max sets the value at the right hand side
func (s *Slider) Max(max float32) *Slider {
s.max = max
return s
}
// Color sets the color to draw the slider in
func (s *Slider) Color(color string) *Slider {
s.color = s.Theme.Colors.GetNRGBAFromName(color)
return s
}
// Float sets the initial value
func (s *Slider) Float(f *Float) *Slider {
s.float = f
return s
}
// Fn renders the slider
func (s *Slider) Fn(gtx l.Context) l.Dimensions {
thumbRadiusInt := gtx.Dp(unit.Dp(6))
trackWidth := gtx.Dp(unit.Dp(2))
thumbRadius := thumbRadiusInt
halfWidthInt := 2 * thumbRadiusInt
halfWidth := halfWidthInt
size := gtx.Constraints.Min
// Keep a minimum length so that the track is always visible.
minLength := halfWidthInt + 3*thumbRadiusInt + halfWidthInt
if size.X < minLength {
size.X = minLength
}
size.Y = 2 * halfWidthInt
st := op.Offset(image.Pt(halfWidth, 0)).Push(gtx.Ops)
gtx.Constraints.Min = image.Pt(size.X-2*halfWidthInt, size.Y)
s.float.Fn(gtx, halfWidthInt, s.min, s.max)
thumbPos := halfWidth + int(s.float.Pos())
st.Pop()
col := s.color
if !gtx.Source.Enabled() {
col = f32color.MulAlpha(col, 150)
}
// Draw track before thumb.
trackMinY := halfWidth - trackWidth/2
trackMaxY := halfWidth + trackWidth/2
trackBeforeThumb := image.Rectangle{
Min: image.Pt(halfWidth, trackMinY),
Max: image.Pt(thumbPos, trackMaxY),
}
st1 := clip.Rect(trackBeforeThumb).Push(gtx.Ops)
paint.ColorOp{Color: col}.Add(gtx.Ops)
paint.PaintOp{}.Add(gtx.Ops)
st1.Pop()
// Draw track after thumb.
trackAfterThumb := image.Rectangle{
Min: image.Pt(thumbPos, trackMinY),
Max: image.Pt(size.X-halfWidth, trackMaxY),
}
st2 := clip.Rect(trackAfterThumb).Push(gtx.Ops)
paint.ColorOp{Color: f32color.MulAlpha(col, 96)}.Add(gtx.Ops)
paint.PaintOp{}.Add(gtx.Ops)
st2.Pop()
// Draw thumb.
thumbRect := image.Rectangle{
Min: image.Pt(thumbPos-thumbRadius, halfWidth-thumbRadius),
Max: image.Pt(thumbPos+thumbRadius, halfWidth+thumbRadius),
}
st3 := clip.UniformRRect(thumbRect, thumbRadius).Push(gtx.Ops)
paint.ColorOp{Color: col}.Add(gtx.Ops)
paint.PaintOp{}.Add(gtx.Ops)
st3.Pop()
return l.Dimensions{Size: size}
}