add hover + click behavior

This commit is contained in:
Drew Weymouth
2023-04-25 19:56:21 -07:00
parent 8f462447e2
commit 238b786a15
+52 -3
View File
@@ -1,12 +1,14 @@
package widgets
import (
"math"
"supersonic/res"
"supersonic/ui/layouts"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/driver/desktop"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
)
@@ -17,7 +19,7 @@ var (
)
const (
starRatingBetweenStarPad = 2
starRatingBetweenStarPad = 1
)
type StarRating struct {
@@ -26,7 +28,11 @@ type StarRating struct {
Rating int
StarSize float32
container *fyne.Container
OnRatingChanged func(int)
holdRating bool // don't render mouseHoverRating
mouseHoverRating int // zero if not hovered
container *fyne.Container
}
func NewStarRating() *StarRating {
@@ -52,15 +58,58 @@ func (s *StarRating) createContainer() {
}
}
var _ desktop.Hoverable = (*StarRating)(nil)
func (s *StarRating) MouseIn(e *desktop.MouseEvent) {
s.MouseMoved(e)
}
func (s *StarRating) MouseMoved(e *desktop.MouseEvent) {
hoverRating := int(math.Ceil(5 * float64(e.Position.X/s.Size().Width)))
if s.mouseHoverRating != hoverRating {
s.holdRating = false
s.mouseHoverRating = hoverRating
s.Refresh()
}
}
func (s *StarRating) MouseOut() {
s.mouseHoverRating = 0
s.holdRating = false
s.Refresh()
}
var _ fyne.Tappable = (*StarRating)(nil)
func (s *StarRating) Tapped(*fyne.PointEvent) {
if s.mouseHoverRating <= 0 {
return //shouldn't happen
}
if s.Rating == s.mouseHoverRating {
s.Rating = 0
} else {
s.Rating = s.mouseHoverRating
}
s.holdRating = true
s.Refresh()
if s.OnRatingChanged != nil {
s.OnRatingChanged(s.Rating)
}
}
func (s *StarRating) Refresh() {
// widget has not had renderer created yet
if s.container == nil {
return
}
rating := s.Rating
if !s.holdRating && s.mouseHoverRating > 0 {
rating = s.mouseHoverRating
}
for i := 0; i < 5; i++ {
im := s.container.Objects[i].(*canvas.Image)
im.SetMinSize(fyne.NewSize(s.StarSize, s.StarSize))
if s.Rating > i {
if rating > i {
im.Resource = themedResStarFilled
} else {
im.Resource = themedResStarOutline