src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/cli/tk/widget.go (about) 1 // Package tk is the toolkit for the cli package. 2 // 3 // This package defines three basic interfaces - Renderer, Handler and Widget - 4 // and numerous implementations of these interfaces. 5 package tk 6 7 import ( 8 "src.elv.sh/pkg/cli/term" 9 ) 10 11 // Widget is the basic component of UI; it knows how to handle events and how to 12 // render itself. 13 type Widget interface { 14 Renderer 15 MaxHeighter 16 Handler 17 } 18 19 // Renderer wraps the Render method. 20 type Renderer interface { 21 // Render renders onto a region of bound width and height. 22 Render(width, height int) *term.Buffer 23 } 24 25 // MaxHeighter wraps the MaxHeight method. 26 type MaxHeighter interface { 27 // MaxHeight returns the maximum height needed when rendering onto a region 28 // of bound width and height. The returned value may be larger than the 29 // height argument. 30 MaxHeight(width, height int) int 31 } 32 33 // Handler wraps the Handle method. 34 type Handler interface { 35 // Try to handle a terminal event and returns whether the event has been 36 // handled. 37 Handle(event term.Event) bool 38 } 39 40 // Bindings is the interface for key bindings. 41 type Bindings interface { 42 Handle(Widget, term.Event) bool 43 } 44 45 // DummyBindings is a trivial Bindings implementation. 46 type DummyBindings struct{} 47 48 // Handle always returns false. 49 func (DummyBindings) Handle(w Widget, event term.Event) bool { 50 return false 51 } 52 53 // MapBindings is a map-backed Bindings implementation. 54 type MapBindings map[term.Event]func(Widget) 55 56 // Handle handles the event by calling the function corresponding to the event 57 // in the map. If there is no corresponding function, it returns false. 58 func (m MapBindings) Handle(w Widget, event term.Event) bool { 59 fn, ok := m[event] 60 if ok { 61 fn(w) 62 } 63 return ok 64 } 65 66 // FuncBindings is a function-based Bindings implementation. 67 type FuncBindings func(Widget, term.Event) bool 68 69 // Handle handles the event by calling the function. 70 func (f FuncBindings) Handle(w Widget, event term.Event) bool { 71 return f(w, event) 72 }