src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/cli/tk/widget_test.go (about)

     1  package tk
     2  
     3  import (
     4  	"testing"
     5  
     6  	"src.elv.sh/pkg/cli/term"
     7  	"src.elv.sh/pkg/ui"
     8  )
     9  
    10  type testWidget struct {
    11  	// Text to render.
    12  	text ui.Text
    13  	// Which events to accept.
    14  	accepted []term.Event
    15  	// A record of events that have been handled.
    16  	handled []term.Event
    17  }
    18  
    19  func (w *testWidget) Render(width, height int) *term.Buffer {
    20  	buf := term.NewBufferBuilder(width).WriteStyled(w.text).Buffer()
    21  	buf.TrimToLines(0, height)
    22  	return buf
    23  }
    24  
    25  func (w *testWidget) Handle(e term.Event) bool {
    26  	for _, accept := range w.accepted {
    27  		if e == accept {
    28  			w.handled = append(w.handled, e)
    29  			return true
    30  		}
    31  	}
    32  	return false
    33  }
    34  
    35  func TestDummyBindings(t *testing.T) {
    36  	w := Empty{}
    37  	b := DummyBindings{}
    38  	for _, event := range []term.Event{term.K('a'), term.PasteSetting(true)} {
    39  		if b.Handle(w, event) {
    40  			t.Errorf("should not handle")
    41  		}
    42  	}
    43  }
    44  
    45  func TestMapBindings(t *testing.T) {
    46  	widgetCh := make(chan Widget, 1)
    47  	w := Empty{}
    48  	b := MapBindings{term.K('a'): func(w Widget) { widgetCh <- w }}
    49  	handled := b.Handle(w, term.K('a'))
    50  	if !handled {
    51  		t.Errorf("should handle")
    52  	}
    53  	if gotWidget := <-widgetCh; gotWidget != w {
    54  		t.Errorf("function called with widget %v, want %v", gotWidget, w)
    55  	}
    56  	handled = b.Handle(w, term.K('b'))
    57  	if handled {
    58  		t.Errorf("should not handle")
    59  	}
    60  }
    61  
    62  func TestFuncBindings(t *testing.T) {
    63  	widgetCh := make(chan Widget, 1)
    64  	eventCh := make(chan term.Event, 1)
    65  
    66  	h := FuncBindings(func(w Widget, event term.Event) bool {
    67  		widgetCh <- w
    68  		eventCh <- event
    69  		return event == term.K('a')
    70  	})
    71  
    72  	w := Empty{}
    73  	event := term.K('a')
    74  	handled := h.Handle(w, event)
    75  	if !handled {
    76  		t.Errorf("should handle")
    77  	}
    78  	if gotWidget := <-widgetCh; gotWidget != w {
    79  		t.Errorf("function called with widget %v, want %v", gotWidget, w)
    80  	}
    81  	if gotEvent := <-eventCh; gotEvent != event {
    82  		t.Errorf("function called with event %v, want %v", gotEvent, event)
    83  	}
    84  
    85  	event = term.K('b')
    86  	handled = h.Handle(w, event)
    87  	if handled {
    88  		t.Errorf("should not handle")
    89  	}
    90  	if gotEvent := <-eventCh; gotEvent != event {
    91  		t.Errorf("function called with event %v, want %v", gotEvent, event)
    92  	}
    93  }