github.com/wtfutil/wtf@v0.43.0/view/multisource_widget.go (about) 1 package view 2 3 import ( 4 "github.com/wtfutil/wtf/cfg" 5 "github.com/wtfutil/wtf/utils" 6 ) 7 8 // MultiSourceWidget is a widget that supports displaying data from multiple sources 9 type MultiSourceWidget struct { 10 moduleConfig *cfg.Common 11 singular string 12 plural string 13 14 DisplayFunction func() 15 Idx int 16 Sources []string 17 } 18 19 // NewMultiSourceWidget creates and returns an instance of MultiSourceWidget 20 func NewMultiSourceWidget(moduleConfig *cfg.Common, singular, plural string) MultiSourceWidget { 21 widget := MultiSourceWidget{ 22 moduleConfig: moduleConfig, 23 singular: singular, 24 plural: plural, 25 } 26 27 widget.loadSources() 28 29 return widget 30 } 31 32 /* -------------------- Exported Functions -------------------- */ 33 34 // CurrentSource returns the string representations of the currently-displayed source 35 func (widget *MultiSourceWidget) CurrentSource() string { 36 if widget.Idx >= len(widget.Sources) { 37 return "" 38 } 39 40 return widget.Sources[widget.Idx] 41 } 42 43 // NextSource displays the next source in the source list. If the current source is the last 44 // source it wraps around to the first source 45 func (widget *MultiSourceWidget) NextSource() { 46 widget.Idx++ 47 if widget.Idx == len(widget.Sources) { 48 widget.Idx = 0 49 } 50 51 if widget.DisplayFunction != nil { 52 widget.DisplayFunction() 53 } 54 } 55 56 // PrevSource displays the previous source in the source list. If the current source is the first 57 // source, it wraps around to the last source 58 func (widget *MultiSourceWidget) PrevSource() { 59 widget.Idx-- 60 if widget.Idx < 0 { 61 widget.Idx = len(widget.Sources) - 1 62 } 63 64 if widget.DisplayFunction != nil { 65 widget.DisplayFunction() 66 } 67 } 68 69 // SetDisplayFunction stores the function that should be called when the source is 70 // changed. This is typically called from within the initializer for the struct that 71 // embeds MultiSourceWidget 72 // 73 // Example: 74 // 75 // widget := Widget{ 76 // MultiSourceWidget: wtf.NewMultiSourceWidget(settings.common, "person", "people") 77 // } 78 // 79 // widget.SetDisplayFunction(widget.display) 80 func (widget *MultiSourceWidget) SetDisplayFunction(displayFunc func()) { 81 widget.DisplayFunction = displayFunc 82 } 83 84 /* -------------------- Unexported Functions -------------------- */ 85 86 func (widget *MultiSourceWidget) loadSources() { 87 var empty []interface{} 88 89 single := widget.moduleConfig.Config.UString(widget.singular, "") 90 multiple := widget.moduleConfig.Config.UList(widget.plural, empty) 91 92 asStrs := utils.ToStrs(multiple) 93 94 if single != "" { 95 asStrs = append(asStrs, single) 96 } 97 98 widget.Sources = asStrs 99 }