github.com/utopiagio/gio@v0.0.8/widget/button_test.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  package widget_test
     4  
     5  import (
     6  	"image"
     7  	"testing"
     8  
     9  	"github.com/utopiagio/gio/io/input"
    10  	"github.com/utopiagio/gio/io/key"
    11  	"github.com/utopiagio/gio/layout"
    12  	"github.com/utopiagio/gio/op"
    13  	"github.com/utopiagio/gio/widget"
    14  )
    15  
    16  func TestClickable(t *testing.T) {
    17  	var (
    18  		r  input.Router
    19  		b1 widget.Clickable
    20  		b2 widget.Clickable
    21  	)
    22  	gtx := layout.Context{
    23  		Ops:    new(op.Ops),
    24  		Source: r.Source(),
    25  	}
    26  	layout := func() {
    27  		b1.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
    28  			return layout.Dimensions{Size: image.Pt(100, 100)}
    29  		})
    30  		// buttons are on top of each other but we only use focus and keyevents, so this is fine
    31  		b2.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
    32  			return layout.Dimensions{Size: image.Pt(100, 100)}
    33  		})
    34  	}
    35  	frame := func() {
    36  		gtx.Reset()
    37  		layout()
    38  		r.Frame(gtx.Ops)
    39  	}
    40  	gtx.Execute(key.FocusCmd{Tag: &b1})
    41  	frame()
    42  	if !gtx.Focused(&b1) {
    43  		t.Error("button 1 did not gain focus")
    44  	}
    45  	if gtx.Focused(&b2) {
    46  		t.Error("button 2 should not have focus")
    47  	}
    48  	r.Queue(
    49  		key.Event{
    50  			Name:  key.NameReturn,
    51  			State: key.Press,
    52  		},
    53  		key.Event{
    54  			Name:  key.NameReturn,
    55  			State: key.Release,
    56  		},
    57  	)
    58  	if !b1.Clicked(gtx) {
    59  		t.Error("button 1 did not get clicked when it got return press & release")
    60  	}
    61  	if b2.Clicked(gtx) {
    62  		t.Error("button 2 got clicked when it did not have focus")
    63  	}
    64  	r.Queue(
    65  		key.Event{
    66  			Name:  key.NameReturn,
    67  			State: key.Press,
    68  		},
    69  	)
    70  	if b1.Clicked(gtx) {
    71  		t.Error("button 1 got clicked, even if it only got return press")
    72  	}
    73  	frame()
    74  	gtx.Execute(key.FocusCmd{Tag: &b2})
    75  	frame()
    76  	if gtx.Focused(&b1) {
    77  		t.Error("button 1 should not have focus")
    78  	}
    79  	if !gtx.Focused(&b2) {
    80  		t.Error("button 2 did not gain focus")
    81  	}
    82  	r.Queue(
    83  		key.Event{
    84  			Name:  key.NameReturn,
    85  			State: key.Release,
    86  		},
    87  	)
    88  	if b1.Clicked(gtx) {
    89  		t.Error("button 1 got clicked, even if it had lost focus")
    90  	}
    91  	if b2.Clicked(gtx) {
    92  		t.Error("button 2 should not have been clicked, as it only got return release")
    93  	}
    94  }