package menu import ( "fmt" "math" "reflect" "strconv" "strings" "github.com/sirupsen/logrus" ) type Menu struct { Items []Item // Current selected position. Position int // Parent menu for this submenu. Parent *Menu // Editing indicates edit mode for an item. Editing bool // Number of items visible per page. pageSize int } // New builds a menu over the exported fields of a struct pointer. It returns an // error for non-struct or unaddressable data, unsupported fields, or invalid tags. // Values remain owned by the caller; menu edits and reads must be serialized. func New(data any, pageSize int, parent *Menu) (*Menu, error) { ref := reflect.ValueOf(data) // if its a pointer, resolve its value if ref.Kind() == reflect.Ptr { ref = reflect.Indirect(ref) } if ref.Kind() == reflect.Interface { ref = ref.Elem() } if ref.Kind() != reflect.Struct { return nil, fmt.Errorf("menu: %T is not a struct", data) } if !ref.CanAddr() { return nil, fmt.Errorf("menu: %T must be a pointer to a struct", data) } menu := &Menu{ Parent: parent, pageSize: pageSize, Items: []Item{{ Label: "Go back", Icon: "md_history", Value: Back, }}, } menu.SetPageSize(pageSize) typ := ref.Type() for i, n := 0, ref.NumField(); i < n; i++ { field := typ.Field(i) if field.Tag.Get("menu") == "-" || !field.IsExported() { continue } var ( fieldRef = ref.Field(i) value = ref.Field(i).Addr().Interface() icon = field.Tag.Get("icon") label = field.Tag.Get("menu") options []string step = 1 min, max int err error ) if len(label) == 0 { label = field.Name } if tag := field.Tag.Get("options"); tag != "" { options = strings.Split(tag, ",") } if stepTag := field.Tag.Get("step"); stepTag != "" { if step, err = strconv.Atoi(stepTag); err != nil { return nil, fmt.Errorf("menu: invalid `step` setting on field %s: %w", field.Name, err) } } if minTag := field.Tag.Get("min"); minTag != "" { if min, err = strconv.Atoi(minTag); err != nil { return nil, fmt.Errorf("menu: invalid `min` setting on field %s: %w", field.Name, err) } } if maxTag := field.Tag.Get("max"); maxTag != "" { if max, err = strconv.Atoi(maxTag); err != nil { return nil, fmt.Errorf("menu: invalid `max` setting on field %s: %w", field.Name, err) } } if !fieldRef.CanAddr() { return nil, fmt.Errorf("menu: field %s is not addressable", field.Name) } if !fieldRef.CanSet() { return nil, fmt.Errorf("menu: field %s is not settable", field.Name) } switch field.Type.Kind() { case reflect.Struct: subMenu, err := New(value, pageSize, menu) if err != nil { return nil, err } menu.Items = append(menu.Items, Item{ Label: label, Value: nil, Field: fieldRef, Icon: icon, SubMenu: subMenu, }) case reflect.Bool, reflect.String: menu.Items = append(menu.Items, Item{ Label: label, Value: value, Field: fieldRef, Icon: icon, Options: options, }) case reflect.Uint8: if min < 0 || min > math.MaxUint8 || max < 0 || max > math.MaxUint8 { return nil, fmt.Errorf("menu: min/max %d/%d on field %s.%s is out of range for uint8", min, max, typ.Name(), field.Name) } if max == 0 { max = math.MaxUint8 } menu.Items = append(menu.Items, Item{ Label: label, Value: value, Field: fieldRef, Icon: icon, Min: min, Max: max, Step: step, }) case reflect.Int8: if min < math.MinInt8 || min > math.MaxInt8 || max < math.MinInt8 || max > math.MaxInt8 { return nil, fmt.Errorf("menu: min/max %d/%d on field %s.%s is out of range for int8", min, max, typ.Name(), field.Name) } if min == 0 && max == 0 { min, max = math.MinInt8, math.MaxInt8 } if min == max { return nil, fmt.Errorf("menu: no min/max range specified on field %s.%s", typ.Name(), field.Name) } menu.Items = append(menu.Items, Item{ Label: label, Value: value, Field: fieldRef, Icon: icon, Min: min, Max: max, Step: step, }) case reflect.Int: if min == max { return nil, fmt.Errorf("menu: no min/max range specified for field %s.%s", typ.Name(), field.Name) } menu.Items = append(menu.Items, Item{ Label: label, Value: value, Field: fieldRef, Icon: icon, Min: min, Max: max, Step: step, }) default: return nil, fmt.Errorf("menu: can't render field %s.%s with type %s", typ.Name(), field.Name, field.Type.Kind()) } } return menu, nil } // Change is used for editing and navigating, delta is either positive or negative input. func (m *Menu) Change(delta int) { if m.Editing { m.edit(delta) } else { m.move(delta) } } func (m *Menu) edit(delta int) { item := &m.Items[m.Position] logrus.WithFields(logrus.Fields{ "action": "edit", "delta": delta, "type": fmt.Sprintf("%T", item.Value), }).Debug("menu change") // Adjust the value if editing switch v := item.Value.(type) { case *uint8: newValue := int(*v) + delta*item.Step if newValue >= item.Min && newValue <= item.Max { *v = uint8(newValue) } case *int: newValue := *v + (delta * item.Step) if newValue >= item.Min && newValue <= item.Max { *v = newValue } case *bool: if delta != 0 { *v = delta > 0 } case *string: if len(item.Options) > 0 { currentIndex := indexOf(*v, item.Options) if currentIndex != -1 { newIndex := (currentIndex + delta%len(item.Options) + len(item.Options)) % len(item.Options) *v = item.Options[newIndex] } } } } func (m *Menu) move(delta int) { logrus.WithFields(logrus.Fields{ "action": "move", "delta": delta, "position": m.Position, }).Debug("menu change") // Move the cursor if not editing m.Position += delta if m.Position < 0 { m.Position = 0 } else if m.Position >= len(m.Items) { m.Position = len(m.Items) - 1 } logrus.WithFields(logrus.Fields{ "action": "move", "delta": delta, "position": m.Position, }).Debug("menu change done") } // ActiveItem is the current item that is active. func (m *Menu) ActiveItem() Item { return m.Items[m.Position] } // PageSize returns the current page size. func (m *Menu) PageSize() int { return m.pageSize } // SetPageSize updates this menu and its submenus, with a minimum of one item. func (m *Menu) SetPageSize(pageSize int) { if pageSize < 1 { pageSize = 1 } m.pageSize = pageSize for _, item := range m.Items { if item.SubMenu != nil { item.SubMenu.SetPageSize(pageSize) } } } // IsEditing checks if we're in editing mode. func (m *Menu) IsEditing() bool { return m.Editing } // ToggleEdit exits editing or starts editing an editable item. Informational // items, submenu entries and Back remain in navigation mode. func (m *Menu) ToggleEdit() { if m.Editing { m.Editing = false } else if m.ActiveItem().IsEditable() { m.Editing = true } } func (m *Menu) IsSubMenu() bool { return m.Position < len(m.Items) && m.Items[m.Position].SubMenu != nil } // EnterSubmenu enters the selected sub menu. func (m *Menu) EnterSubMenu() *Menu { if m.Position < len(m.Items) && m.Items[m.Position].SubMenu != nil { logrus.WithFields(logrus.Fields{ "action": "enter subment", "item": m.Items[m.Position].Label, }).Debug("menu enter sub menu") return m.Items[m.Position].SubMenu } logrus.Debug("menu enter sub menu failed; no sub menu item") return nil } // ExitSubmenu returns to the parent menu. func (m *Menu) ExitSubMenu() *Menu { if m.Parent != nil { logrus.Debug("menu exit sub menu") return m.Parent } logrus.Debug("menu exit sub menu failed; no parent") return nil // If no parent, return nil. } type Item struct { // Label on the menu. Label string // Icon on the menu. Icon string // Value is the original value. Value interface{} // Field is the original struct field. Field reflect.Value // SubMenu is the submenu item. SubMenu *Menu // Min, Max and Step provides the bounds for integers. Min, Max, Step int // Options for string values. Options []string } // IsEditable reports whether the item accepts rotary input. Strings without // enumerated options are informational and remain read-only. func (item Item) IsEditable() bool { switch item.Value.(type) { case *bool, *uint8, *int: return true case *string: return len(item.Options) > 0 default: return false } } // indexOf returns the index of a value in a slice, or -1 if not found func indexOf(needle string, haystack []string) int { for i, opt := range haystack { if opt == needle { return i } } return -1 } // Magic actions. type menuAction struct{} // Actions. var ( Back menuAction SubMenu menuAction )