Skip to content

Commit

Permalink
Ensure slider values are within range even on initial display
Browse files Browse the repository at this point in the history
This was previously applied only on drag.
Fixed fyne-io#1128
  • Loading branch information
andydotxyz committed Jun 25, 2020
1 parent 3d6571a commit 67fbf83
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
29 changes: 20 additions & 9 deletions widget/slider.go
Expand Up @@ -97,19 +97,29 @@ func (s *Slider) getRatio(e *fyne.PointEvent) float64 {
return 0.0
}

func (s *Slider) updateValue(ratio float64) {
v := s.Min + ratio*(s.Max-s.Min)
func (s *Slider) clampValueToRange() {
if s.Value >= s.Max {
s.Value = s.Max
return
} else if s.Value <= s.Min {
s.Value = s.Min
return
}

if s.Step == 0 { // extended Slider may not have this set - assume value is not adjusted
return
}

i := -(math.Log10(s.Step))
p := math.Pow(10, i)

if v >= s.Max {
s.Value = s.Max
} else if v <= s.Min {
s.Value = s.Min
} else {
s.Value = float64(int(v*p)) / p
}
s.Value = float64(int(s.Value*p)) / p
}

func (s *Slider) updateValue(ratio float64) {
s.Value = s.Min + ratio*(s.Max-s.Min)

s.clampValueToRange()
}

// MinSize returns the size that this widget should not shrink below
Expand Down Expand Up @@ -153,6 +163,7 @@ func (s *sliderRenderer) Refresh() {
s.thumb.FillColor = theme.TextColor()
s.active.FillColor = theme.TextColor()

s.slider.clampValueToRange()
s.Layout(s.slider.Size())
canvas.Refresh(s.slider.super())
}
Expand Down
7 changes: 7 additions & 0 deletions widget/slider_test.go
Expand Up @@ -28,6 +28,13 @@ func TestSlider_HorizontalLayout(t *testing.T) {
assert.Equal(t, theme.Padding(), aSize.Height)
}

func TestSlider_OutOfRange(t *testing.T) {
slider := NewSlider(2, 5)
slider.Resize(fyne.NewSize(100, 10))

assert.Equal(t, float64(2), slider.Value)
}

func TestSlider_VerticalLayout(t *testing.T) {
slider := NewSlider(0, 1)
slider.Orientation = Vertical
Expand Down

0 comments on commit 67fbf83

Please sign in to comment.