github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/dos/ui/record.go (about)

     1  package ui
     2  
     3  import "reflect"
     4  
     5  func ReflectLoadWidgets(record Record) []Widget {
     6  	if record, ok := record.(interface {
     7  		Widgets() []Widget
     8  	}); ok {
     9  		return record.Widgets()
    10  	}
    11  
    12  	widgets := []Widget{}
    13  
    14  	v := reflect.ValueOf(record)
    15  	if v.Kind() == reflect.Ptr {
    16  		v = v.Elem()
    17  	}
    18  
    19  	for i := 0; i < v.NumField(); i++ {
    20  		field := v.Field(i)
    21  
    22  		// get address if not one
    23  		if field.Kind() != reflect.Ptr {
    24  			field = field.Addr()
    25  		}
    26  
    27  		if widget, ok := field.Interface().(Widget); ok {
    28  			widgets = append(widgets, widget)
    29  		}
    30  	}
    31  
    32  	return widgets
    33  }