Skip to content
Myr

delegate.go

This file

Path

examples/list-fancy/delegate.go

89 lines · 1.8 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

1package main23import (4	"charm.land/bubbles/v2/key"5	"charm.land/bubbles/v2/list"6	tea "charm.land/bubbletea/v2"7)89func newItemDelegate(keys *delegateKeyMap, styles *styles) list.DefaultDelegate {10	d := list.NewDefaultDelegate()1112	d.UpdateFunc = func(msg tea.Msg, m *list.Model) tea.Cmd {13		var title string1415		if i, ok := m.SelectedItem().(item); ok {16			title = i.Title()17		} else {18			return nil19		}2021		switch msg := msg.(type) {22		case tea.KeyPressMsg:23			switch {24			case key.Matches(msg, keys.choose):25				return m.NewStatusMessage(styles.statusMessage.Render("You chose " + title))2627			case key.Matches(msg, keys.remove):28				index := m.Index()29				m.RemoveItem(index)30				if len(m.Items()) == 0 {31					keys.remove.SetEnabled(false)32				}33				return m.NewStatusMessage(styles.statusMessage.Render("Deleted " + title))34			}35		}3637		return nil38	}3940	help := []key.Binding{keys.choose, keys.remove}4142	d.ShortHelpFunc = func() []key.Binding {43		return help44	}4546	d.FullHelpFunc = func() [][]key.Binding {47		return [][]key.Binding{help}48	}4950	return d51}5253type delegateKeyMap struct {54	choose key.Binding55	remove key.Binding56}5758// Additional short help entries. This satisfies the help.KeyMap interface and59// is entirely optional.60func (d delegateKeyMap) ShortHelp() []key.Binding {61	return []key.Binding{62		d.choose,63		d.remove,64	}65}6667// Additional full help entries. This satisfies the help.KeyMap interface and68// is entirely optional.69func (d delegateKeyMap) FullHelp() [][]key.Binding {70	return [][]key.Binding{71		{72			d.choose,73			d.remove,74		},75	}76}7778func newDelegateKeyMap() *delegateKeyMap {79	return &delegateKeyMap{80		choose: key.NewBinding(81			key.WithKeys("enter"),82			key.WithHelp("enter", "choose"),83		),84		remove: key.NewBinding(85			key.WithKeys("x", "backspace"),86			key.WithHelp("x", "delete"),87		),88	}89}