responsive.go raw

   1  package gel
   2  
   3  import (
   4  	"sort"
   5  	
   6  	l "github.com/p9c/gio/layout"
   7  )
   8  
   9  // WidgetSize is a widget with a specification of the minimum size to select it for viewing.
  10  // Note that the widgets you put in here should be wrapped in func(l.Context) l.Dimensions otherwise
  11  // any parameters retrieved from the controlling state variable will be from initialization and not
  12  // at execution of the widget in the render process
  13  type WidgetSize struct {
  14  	Size   float32
  15  	Widget l.Widget
  16  }
  17  
  18  type Widgets []WidgetSize
  19  
  20  func (w Widgets) Len() int {
  21  	return len(w)
  22  }
  23  
  24  func (w Widgets) Less(i, j int) bool {
  25  	// we want largest first so this uses greater than
  26  	return w[i].Size > w[j].Size
  27  }
  28  
  29  func (w Widgets) Swap(i, j int) {
  30  	w[i], w[j] = w[j], w[i]
  31  }
  32  
  33  type Responsive struct {
  34  	*Theme
  35  	Widgets
  36  	size int32
  37  }
  38  
  39  func (th *Theme) Responsive(size int32, widgets Widgets) *Responsive {
  40  	return &Responsive{Theme: th, size: size, Widgets: widgets}
  41  }
  42  
  43  func (r *Responsive) Fn(gtx l.Context) l.Dimensions {
  44  	out := func(l.Context) l.Dimensions {
  45  		return l.Dimensions{}
  46  	}
  47  	sort.Sort(r.Widgets)
  48  	for i := range r.Widgets {
  49  		if float32(r.size)/r.TextSize.V >= r.Widgets[i].Size {
  50  			out = r.Widgets[i].Widget
  51  			// D.Ln("selected widget for responsive with scale", r.size, "width", r.Widgets[i].Size)
  52  			break
  53  		}
  54  	}
  55  	return out(gtx)
  56  }
  57