Add list examples
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Christian Muehlhaeuser · committed by Christian Muehlhaeuser · parent 1b8495e · Browse files · 7 files·+672 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+672 added−0 removed
- other:+672 added−0 removed
Provenance
- Commit
27ba7e7- Tree
900bbdf- Author
Christian Muehlhaeuser <muesli@gmail.com>- Committer
Christian Muehlhaeuser <muesli@gmail.com>- Parent
1b8495e
7 files changed+672 added−0 removed
added:examples/list-default/main.go+87 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ "github.com/charmbracelet/bubbles/list"8+ tea "github.com/charmbracelet/bubbletea"9+ "github.com/charmbracelet/lipgloss"10+)11+12+var docStyle = lipgloss.NewStyle().Margin(1, 2)13+14+type item struct {15+ title, desc string16+}17+18+func (i item) Title() string { return i.title }19+func (i item) Description() string { return i.desc }20+func (i item) FilterValue() string { return i.title }21+22+type model struct {23+ list list.Model24+}25+26+func (m model) Init() tea.Cmd {27+ return nil28+}29+30+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {31+ switch msg := msg.(type) {32+ case tea.KeyMsg:33+ if msg.String() == "ctrl+c" {34+ return m, nil35+ }36+ case tea.WindowSizeMsg:37+ top, right, bottom, left := docStyle.GetMargin()38+ m.list.SetSize(msg.Width-left-right, msg.Height-top-bottom)39+ }40+41+ var cmd tea.Cmd42+ m.list, cmd = m.list.Update(msg)43+ return m, cmd44+}45+46+func (m model) View() string {47+ return docStyle.Render(m.list.View())48+}49+50+func main() {51+ items := []list.Item{52+ item{title: "Raspberry Pi’s", desc: "I have ’em all over my house"},53+ item{title: "Nutella", desc: "It's good on toast"},54+ item{title: "Bitter melon", desc: "It cools you down"},55+ item{title: "Nice socks", desc: "And by that I mean socks without holes"},56+ item{title: "Eight hours of sleep", desc: "I had this once"},57+ item{title: "Cats", desc: "Usually"},58+ item{title: "Plantasia, the album", desc: "My plants love it too"},59+ item{title: "Pour over coffee", desc: "It takes forever to make though"},60+ item{title: "VR", desc: "Virtual reality...what is there to say?"},61+ item{title: "Noguchi Lamps", desc: "Such pleasing organic forms"},62+ item{title: "Linux", desc: "Pretty much the best OS"},63+ item{title: "Business school", desc: "Just kidding"},64+ item{title: "Pottery", desc: "Wet clay is a great feeling"},65+ item{title: "Shampoo", desc: "Nothing like clean hair"},66+ item{title: "Table tennis", desc: "It’s surprisingly exhausting"},67+ item{title: "Milk crates", desc: "Great for packing in your extra stuff"},68+ item{title: "Afternoon tea", desc: "Especially the tea sandwich part"},69+ item{title: "Stickers", desc: "The thicker the vinyl the better"},70+ item{title: "20° Weather", desc: "Celsius, not Fahrenheit"},71+ item{title: "Warm light", desc: "Like around 2700 Kelvin"},72+ item{title: "The vernal equinox", desc: "The autumnal equinox is pretty good too"},73+ item{title: "Gaffer’s tape", desc: "Basically sticky fabric"},74+ item{title: "Terrycloth", desc: "In other words, towel fabric"},75+ }76+77+ m := model{list: list.NewModel(items, list.NewDefaultDelegate(), 0, 0)}78+ m.list.Title = "My Fave Things"79+80+ p := tea.NewProgram(m)81+ p.EnterAltScreen()82+83+ if err := p.Start(); err != nil {84+ fmt.Println("Error running program:", err)85+ os.Exit(1)86+ }87+}added:examples/list-fancy/delegate.go+89 added
1+package main2+3+import (4+ "github.com/charmbracelet/bubbles/key"5+ "github.com/charmbracelet/bubbles/list"6+ tea "github.com/charmbracelet/bubbletea"7+)8+9+func newItemDelegate(keys *delegateKeyMap) list.DefaultDelegate {10+ d := list.NewDefaultDelegate()11+12+ d.UpdateFunc = func(msg tea.Msg, m *list.Model) tea.Cmd {13+ var title string14+15+ if i, ok := m.SelectedItem().(item); ok {16+ title = i.Title()17+ } else {18+ return nil19+ }20+21+ switch msg := msg.(type) {22+ case tea.KeyMsg:23+ switch {24+ case key.Matches(msg, keys.choose):25+ return m.NewStatusMessage(statusMessageStyle("You chose " + title))26+27+ 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(statusMessageStyle("Deleted " + title))34+ }35+ }36+37+ return nil38+ }39+40+ help := []key.Binding{keys.choose, keys.remove}41+42+ d.ShortHelpFunc = func() []key.Binding {43+ return help44+ }45+46+ d.FullHelpFunc = func() [][]key.Binding {47+ return [][]key.Binding{help}48+ }49+50+ return d51+}52+53+type delegateKeyMap struct {54+ choose key.Binding55+ remove key.Binding56+}57+58+// Additional short help entries. This satisfies the help.KeyMap interface and59+// is entirely optional.60+func (d delegateKeyMap) ShortHelp() []key.Binding {61+ return []key.Binding{62+ d.choose,63+ d.remove,64+ }65+}66+67+// Additional full help entries. This satisfies the help.KeyMap interface and68+// is entirely optional.69+func (d delegateKeyMap) FullHelp() [][]key.Binding {70+ return [][]key.Binding{71+ {72+ d.choose,73+ d.remove,74+ },75+ }76+}77+78+func 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+}added:examples/list-fancy/main.go+190 added
1+package main2+3+import (4+ "fmt"5+ "math/rand"6+ "os"7+ "time"8+9+ "github.com/charmbracelet/bubbles/key"10+ "github.com/charmbracelet/bubbles/list"11+ tea "github.com/charmbracelet/bubbletea"12+ "github.com/charmbracelet/lipgloss"13+)14+15+var (16+ appStyle = lipgloss.NewStyle().Padding(1, 2)17+18+ titleStyle = lipgloss.NewStyle().19+ Foreground(lipgloss.Color("#FFFDF5")).20+ Background(lipgloss.Color("#25A065")).21+ Padding(0, 1)22+23+ statusMessageStyle = lipgloss.NewStyle().24+ Foreground(lipgloss.AdaptiveColor{Light: "#04B575", Dark: "#04B575"}).25+ Render26+)27+28+type item struct {29+ title string30+ description string31+}32+33+func (i item) Title() string { return i.title }34+func (i item) Description() string { return i.description }35+func (i item) FilterValue() string { return i.title }36+37+type listKeyMap struct {38+ toggleSpinner key.Binding39+ toggleTitleBar key.Binding40+ toggleStatusBar key.Binding41+ togglePagination key.Binding42+ toggleHelpMenu key.Binding43+ insertItem key.Binding44+}45+46+func newListKeyMap() *listKeyMap {47+ return &listKeyMap{48+ insertItem: key.NewBinding(49+ key.WithKeys("a"),50+ key.WithHelp("a", "add item"),51+ ),52+ toggleSpinner: key.NewBinding(53+ key.WithKeys("s"),54+ key.WithHelp("s", "toggle spinner"),55+ ),56+ toggleTitleBar: key.NewBinding(57+ key.WithKeys("T"),58+ key.WithHelp("T", "toggle title"),59+ ),60+ toggleStatusBar: key.NewBinding(61+ key.WithKeys("S"),62+ key.WithHelp("S", "toggle status"),63+ ),64+ togglePagination: key.NewBinding(65+ key.WithKeys("P"),66+ key.WithHelp("P", "toggle pagination"),67+ ),68+ toggleHelpMenu: key.NewBinding(69+ key.WithKeys("H"),70+ key.WithHelp("H", "toggle help"),71+ ),72+ }73+}74+75+type model struct {76+ list list.Model77+ itemGenerator *randomItemGenerator78+ keys *listKeyMap79+ delegateKeys *delegateKeyMap80+}81+82+func newModel() model {83+ var (84+ itemGenerator randomItemGenerator85+ delegateKeys = newDelegateKeyMap()86+ listKeys = newListKeyMap()87+ )88+89+ // Make initial list of items90+ const numItems = 2491+ items := make([]list.Item, numItems)92+ for i := 0; i < numItems; i++ {93+ items[i] = itemGenerator.next()94+ }95+96+ // Setup list97+ delegate := newItemDelegate(delegateKeys)98+ groceryList := list.NewModel(items, delegate, 0, 0)99+ groceryList.Title = "Groceries"100+ groceryList.Styles.Title = titleStyle101+ groceryList.AdditionalFullHelpKeys = func() []key.Binding {102+ return []key.Binding{103+ listKeys.toggleSpinner,104+ listKeys.insertItem,105+ listKeys.toggleTitleBar,106+ listKeys.toggleStatusBar,107+ listKeys.togglePagination,108+ listKeys.toggleHelpMenu,109+ }110+ }111+112+ return model{113+ list: groceryList,114+ keys: listKeys,115+ delegateKeys: delegateKeys,116+ itemGenerator: &itemGenerator,117+ }118+}119+120+func (m model) Init() tea.Cmd {121+ return tea.EnterAltScreen122+}123+124+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {125+ var cmds []tea.Cmd126+127+ switch msg := msg.(type) {128+ case tea.WindowSizeMsg:129+ topGap, rightGap, bottomGap, leftGap := appStyle.GetPadding()130+ m.list.SetSize(msg.Width-leftGap-rightGap, msg.Height-topGap-bottomGap)131+132+ case tea.KeyMsg:133+ // Don't match any of the keys below if we're actively filtering.134+ if m.list.FilterState() == list.Filtering {135+ break136+ }137+138+ switch {139+ case key.Matches(msg, m.keys.toggleSpinner):140+ cmd := m.list.ToggleSpinner()141+ return m, cmd142+143+ case key.Matches(msg, m.keys.toggleTitleBar):144+ v := !m.list.ShowTitle()145+ m.list.SetShowTitle(v)146+ m.list.SetShowFilter(v)147+ m.list.SetFilteringEnabled(v)148+ return m, nil149+150+ case key.Matches(msg, m.keys.toggleStatusBar):151+ m.list.SetShowStatusBar(!m.list.ShowStatusBar())152+ return m, nil153+154+ case key.Matches(msg, m.keys.togglePagination):155+ m.list.SetShowPagination(!m.list.ShowPagination())156+ return m, nil157+158+ case key.Matches(msg, m.keys.toggleHelpMenu):159+ m.list.SetShowHelp(!m.list.ShowHelp())160+ return m, nil161+162+ case key.Matches(msg, m.keys.insertItem):163+ m.delegateKeys.remove.SetEnabled(true)164+ newItem := m.itemGenerator.next()165+ insCmd := m.list.InsertItem(0, newItem)166+ statusCmd := m.list.NewStatusMessage(statusMessageStyle("Added " + newItem.Title()))167+ return m, tea.Batch(insCmd, statusCmd)168+ }169+ }170+171+ // This will also call our delegate's update function.172+ newListModel, cmd := m.list.Update(msg)173+ m.list = newListModel174+ cmds = append(cmds, cmd)175+176+ return m, tea.Batch(cmds...)177+}178+179+func (m model) View() string {180+ return appStyle.Render(m.list.View())181+}182+183+func main() {184+ rand.Seed(time.Now().UTC().UnixNano())185+186+ if err := tea.NewProgram(newModel()).Start(); err != nil {187+ fmt.Println("Error running program:", err)188+ os.Exit(1)189+ }190+}added:examples/list-fancy/randomitems.go+164 added
1+package main2+3+import (4+ "math/rand"5+ "sync"6+)7+8+type randomItemGenerator struct {9+ titles []string10+ descs []string11+ titleIndex int12+ descIndex int13+ mtx *sync.Mutex14+ shuffle *sync.Once15+}16+17+func (r *randomItemGenerator) reset() {18+ r.mtx = &sync.Mutex{}19+ r.shuffle = &sync.Once{}20+21+ r.titles = []string{22+ "Artichoke",23+ "Baking Flour",24+ "Bananas",25+ "Barley",26+ "Bean Sprouts",27+ "Bitter Melon",28+ "Black Cod",29+ "Blood Orange",30+ "Brown Sugar",31+ "Cashew Apple",32+ "Cashews",33+ "Cat Food",34+ "Coconut Milk",35+ "Cucumber",36+ "Curry Paste",37+ "Currywurst",38+ "Dill",39+ "Dragonfruit",40+ "Dried Shrimp",41+ "Eggs",42+ "Fish Cake",43+ "Furikake",44+ "Garlic",45+ "Gherkin",46+ "Ginger",47+ "Granulated Sugar",48+ "Grapefruit",49+ "Green Onion",50+ "Hazelnuts",51+ "Heavy whipping cream",52+ "Honey Dew",53+ "Horseradish",54+ "Jicama",55+ "Kohlrabi",56+ "Leeks",57+ "Lentils",58+ "Licorice Root",59+ "Meyer Lemons",60+ "Milk",61+ "Molasses",62+ "Muesli",63+ "Nectarine",64+ "Niagamo Root",65+ "Nopal",66+ "Nutella",67+ "Oat Milk",68+ "Oatmeal",69+ "Olives",70+ "Papaya",71+ "Party Gherkin",72+ "Peppers",73+ "Persian Lemons",74+ "Pickle",75+ "Pineapple",76+ "Plantains",77+ "Pocky",78+ "Powdered Sugar",79+ "Quince",80+ "Radish",81+ "Ramps",82+ "Star Anise",83+ "Sweet Potato",84+ "Tamarind",85+ "Unsalted Butter",86+ "Watermelon",87+ "Weißwurst",88+ "Yams",89+ "Yeast",90+ "Yuzu",91+ "Snow Peas",92+ }93+94+ r.descs = []string{95+ "A little weird",96+ "Bold flavor",97+ "Can’t get enough",98+ "Delectable",99+ "Expensive",100+ "Expired",101+ "Exquisite",102+ "Fresh",103+ "Gimme",104+ "In season",105+ "Kind of spicy",106+ "Looks fresh",107+ "Looks good to me",108+ "Maybe not",109+ "My favorite",110+ "Oh my",111+ "On sale",112+ "Organic",113+ "Questionable",114+ "Really fresh",115+ "Refreshing",116+ "Salty",117+ "Scrumptious",118+ "Delectable",119+ "Slightly sweet",120+ "Smells great",121+ "Tasty",122+ "Too ripe",123+ "At last",124+ "What?",125+ "Wow",126+ "Yum",127+ "Maybe",128+ "Sure, why not?",129+ }130+131+ r.shuffle.Do(func() {132+ shuf := func(x []string) {133+ rand.Shuffle(len(x), func(i, j int) { x[i], x[j] = x[j], x[i] })134+ }135+ shuf(r.titles)136+ shuf(r.descs)137+ })138+}139+140+func (r *randomItemGenerator) next() item {141+ if r.mtx == nil {142+ r.reset()143+ }144+145+ r.mtx.Lock()146+ defer r.mtx.Unlock()147+148+ i := item{149+ title: r.titles[r.titleIndex],150+ description: r.descs[r.descIndex],151+ }152+153+ r.titleIndex++154+ if r.titleIndex >= len(r.titles) {155+ r.titleIndex = 0156+ }157+158+ r.descIndex++159+ if r.descIndex >= len(r.descs) {160+ r.descIndex = 0161+ }162+163+ return i164+}added:examples/list-simple/main.go+137 added
1+package main2+3+import (4+ "fmt"5+ "io"6+ "os"7+8+ "github.com/charmbracelet/bubbles/list"9+ tea "github.com/charmbracelet/bubbletea"10+ "github.com/charmbracelet/lipgloss"11+)12+13+const listHeight = 1414+15+var (16+ titleStyle = lipgloss.NewStyle().MarginLeft(2)17+ itemStyle = lipgloss.NewStyle().PaddingLeft(4)18+ selectedItemStyle = lipgloss.NewStyle().PaddingLeft(2).Foreground(lipgloss.Color("170"))19+ paginationStyle = list.DefaultStyles().PaginationStyle.PaddingLeft(4)20+ helpStyle = list.DefaultStyles().HelpStyle.PaddingLeft(4).PaddingBottom(1)21+ quitTextStyle = lipgloss.NewStyle().Margin(1, 0, 2, 4)22+)23+24+type item string25+26+func (i item) FilterValue() string { return string(i) }27+28+type itemDelegate struct{}29+30+func (d itemDelegate) Height() int { return 1 }31+func (d itemDelegate) Spacing() int { return 0 }32+func (d itemDelegate) Update(msg tea.Msg, m *list.Model) tea.Cmd { return nil }33+func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {34+ i, ok := listItem.(item)35+ if !ok {36+ return37+ }38+39+ str := fmt.Sprintf("%d. %s", index+1, i)40+41+ fn := itemStyle.Render42+ if index == m.Index() {43+ fn = func(s string) string {44+ return selectedItemStyle.Render("> " + s)45+ }46+ }47+48+ fmt.Fprintf(w, fn(str))49+}50+51+type model struct {52+ list list.Model53+ items []item54+ choice string55+ quitting bool56+}57+58+func (m model) Init() tea.Cmd {59+ return nil60+}61+62+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {63+ switch msg := msg.(type) {64+ case tea.WindowSizeMsg:65+ m.list.SetWidth(msg.Width)66+ return m, nil67+68+ case tea.KeyMsg:69+ switch keypress := msg.String(); keypress {70+ case "ctrl+c":71+ m.quitting = true72+ return m, tea.Quit73+74+ case "enter":75+ i, ok := m.list.SelectedItem().(item)76+ if ok {77+ m.choice = string(i)78+ }79+ return m, tea.Quit80+81+ default:82+ if !m.list.SettingFilter() && (keypress == "q" || keypress == "esc") {83+ m.quitting = true84+ return m, tea.Quit85+ }86+87+ var cmd tea.Cmd88+ m.list, cmd = m.list.Update(msg)89+ return m, cmd90+ }91+92+ default:93+ return m, nil94+ }95+}96+97+func (m model) View() string {98+ if m.choice != "" {99+ return quitTextStyle.Render(fmt.Sprintf("%s? Sounds good to me.", m.choice))100+ }101+ if m.quitting {102+ return quitTextStyle.Render("Not hungry? That’s cool.")103+ }104+ return "\n" + m.list.View()105+}106+107+func main() {108+ items := []list.Item{109+ item("Ramen"),110+ item("Tomato Soup"),111+ item("Hamburgers"),112+ item("Cheeseburgers"),113+ item("Currywurst"),114+ item("Okonomiyaki"),115+ item("Pasta"),116+ item("Fillet Mignon"),117+ item("Caviar"),118+ item("Just Wine"),119+ }120+121+ const defaultWidth = 20122+123+ l := list.NewModel(items, itemDelegate{}, defaultWidth, listHeight)124+ l.Title = "What do you want for dinner?"125+ l.SetShowStatusBar(false)126+ l.SetFilteringEnabled(false)127+ l.Styles.Title = titleStyle128+ l.Styles.PaginationStyle = paginationStyle129+ l.Styles.HelpStyle = helpStyle130+131+ m := model{list: l}132+133+ if err := tea.NewProgram(m).Start(); err != nil {134+ fmt.Println("Error running program:", err)135+ os.Exit(1)136+ }137+}modified:examples/go.sum+2 added
27 unmodified lines28 github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=29 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=30 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=31 github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=32+github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=33 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=34 github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=35 github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=36 github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=26 unmodified lines63 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=64 github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=65 github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=66 github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=67+github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=68 github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=69 github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=70 github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=71 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=20 unmodified linesmodified:.gitignore+3 added
2 unmodified lines3 4 examples/fullscreen/fullscreen5 examples/help/help6 examples/http/http7+examples/list-default/list-default8+examples/list-fancy/list-fancy9+examples/list-simple/list-simple10 examples/mouse/mouse11 examples/pager/pager12 examples/simple/simple13 examples/spinner/spinner6 unmodified lines