github.com/jmigpin/editor@v1.6.0/util/uiutil/widget/button.go (about)

     1  package widget
     2  
     3  import (
     4  	"image"
     5  
     6  	"github.com/jmigpin/editor/util/uiutil/event"
     7  )
     8  
     9  type Button struct {
    10  	ENode
    11  	Label   *Label
    12  	Sticky  bool // stay down after click to behave like a menu button
    13  	OnClick func(*event.MouseClick)
    14  
    15  	down  bool
    16  	stuck bool
    17  }
    18  
    19  func NewButton(ctx ImageContext) *Button {
    20  	b := &Button{}
    21  	b.Label = NewLabel(ctx)
    22  	b.Append(b.Label)
    23  	return b
    24  }
    25  func (b *Button) OnInputEvent(ev0 interface{}, p image.Point) event.Handled {
    26  	// set "text_*" one level below (b.Label) to allow subclassing elements (ex: floatbutton) to set their own "text_*" values without disrupting the hover/down/sticky colors.
    27  	restoreColor := func() {
    28  		b.Label.SetThemePaletteColor("text_fg", nil)
    29  		b.Label.SetThemePaletteColor("text_bg", nil)
    30  	}
    31  	hoverShade := func() {
    32  		fg := b.TreeThemePaletteColor("button_hover_fg")
    33  		bg := b.TreeThemePaletteColor("button_hover_bg")
    34  		b.Label.SetThemePaletteColor("text_fg", fg)
    35  		b.Label.SetThemePaletteColor("text_bg", bg)
    36  	}
    37  	downShade := func() {
    38  		fg := b.TreeThemePaletteColor("button_down_fg")
    39  		bg := b.TreeThemePaletteColor("button_down_bg")
    40  		b.Label.SetThemePaletteColor("text_fg", fg)
    41  		b.Label.SetThemePaletteColor("text_bg", bg)
    42  	}
    43  	stickyShade := func() {
    44  		fg := b.TreeThemePaletteColor("button_sticky_fg")
    45  		bg := b.TreeThemePaletteColor("button_sticky_bg")
    46  		b.Label.SetThemePaletteColor("text_fg", fg)
    47  		b.Label.SetThemePaletteColor("text_bg", bg)
    48  	}
    49  
    50  	switch t := ev0.(type) {
    51  	case *event.MouseEnter:
    52  		if !b.stuck {
    53  			hoverShade()
    54  		}
    55  	case *event.MouseLeave:
    56  		if !b.stuck {
    57  			restoreColor()
    58  		}
    59  	case *event.MouseDown:
    60  		b.down = true
    61  		if !b.stuck {
    62  			downShade()
    63  		}
    64  	case *event.MouseUp:
    65  		if b.down && !b.stuck {
    66  			hoverShade()
    67  		}
    68  		b.down = false
    69  	case *event.MouseClick:
    70  		if b.Sticky {
    71  			if !b.stuck {
    72  				b.stuck = true
    73  				stickyShade()
    74  			} else {
    75  				b.stuck = false
    76  				hoverShade()
    77  			}
    78  		}
    79  		if b.OnClick != nil {
    80  			b.OnClick(t)
    81  		}
    82  	}
    83  	return false
    84  }