Skip to content

Commit

Permalink
add optional subtext to menu widget
Browse files Browse the repository at this point in the history
  • Loading branch information
bcicen committed Jan 11, 2018
1 parent 0e75bbd commit 734d4bf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
16 changes: 9 additions & 7 deletions menus.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ func Confirm(txt string, fn func()) {
m := menu.NewMenu()
m.Selectable = true
m.BorderLabel = "Confirm"
m.SubText = txt

items := []menu.Item{
menu.Item{Val: "cancel", Label: "[c]ancel"},
Expand All @@ -210,27 +211,28 @@ func Confirm(txt string, fn func()) {
m.AddItems(items...)
ui.Render(m)

yes := func(ui.Event) {
yes := func() {
response = true
ui.StopLoop()
}

no := func(ui.Event) {
no := func() {
response = false
ui.StopLoop()
}

HandleKeys("up", m.Up)
HandleKeys("down", m.Down)
ui.Handle("/sys/kbd/c", no)
ui.Handle("/sys/kbd/y", yes)
HandleKeys("exit", no)
ui.Handle("/sys/kbd/c", func(ui.Event) { no() })
ui.Handle("/sys/kbd/y", func(ui.Event) { yes() })

ui.Handle("/sys/kbd/<enter>", func(e ui.Event) {
ui.Handle("/sys/kbd/<enter>", func(ui.Event) {
switch m.SelectedItem().Val {
case "cancel":
no(e)
no()
case "yes":
yes(e)
yes()
}
})

Expand Down
27 changes: 23 additions & 4 deletions widgets/menu/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ type Padding [2]int // x,y padding

type Menu struct {
ui.Block
SortItems bool // enable automatic sorting of menu items
SortItems bool // enable automatic sorting of menu items
SubText string // optional text to display before items
TextFgColor ui.Attribute
TextBgColor ui.Attribute
Selectable bool
Expand Down Expand Up @@ -82,9 +83,19 @@ func (m *Menu) Buffer() ui.Buffer {
var cell ui.Cell
buf := m.Block.Buffer()

y := m.Y + m.padding[1]

if m.SubText != "" {
x := m.X + m.padding[0]
for i, ch := range m.SubText {
cell = ui.Cell{Ch: ch, Fg: m.TextFgColor, Bg: m.TextBgColor}
buf.Set(x+i, y, cell)
}
y += 2
}

for n, item := range m.items {
x := m.X + m.padding[0]
y := m.Y + m.padding[1]
for _, ch := range item.Text() {
// invert bg/fg colors on currently selected row
if m.Selectable && n == m.cursorPos {
Expand Down Expand Up @@ -118,14 +129,22 @@ func (m *Menu) Down() {
func (m *Menu) calcSize() {
m.Width = 7 // minimum width

items := m.items
var height int
for _, i := range m.items {
s := i.Text()
if len(s) > m.Width {
m.Width = len(s)
}
height++
}

if m.SubText != "" {
if len(m.SubText) > m.Width {
m.Width = len(m.SubText)
}
height += 2
}

m.Width += (m.padding[0] * 2)
m.Height = len(items) + (m.padding[1] * 2)
m.Height = height + (m.padding[1] * 2)
}

0 comments on commit 734d4bf

Please sign in to comment.