diff --git a/ui/widgets/starrating.go b/ui/widgets/starrating.go index b67ea8e..928a649 100644 --- a/ui/widgets/starrating.go +++ b/ui/widgets/starrating.go @@ -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