Skip to content
Myr

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

7 files+672 added−0 removed

added:examples/list-default/main.go+87 added
1package main23import (4 "fmt"5 "os"67 "github.com/charmbracelet/bubbles/list"8 tea "github.com/charmbracelet/bubbletea"9 "github.com/charmbracelet/lipgloss"10)1112var docStyle = lipgloss.NewStyle().Margin(1, 2)1314type item struct {15 title, desc string16}1718func (i item) Title() string { return i.title }19func (i item) Description() string { return i.desc }20func (i item) FilterValue() string { return i.title }2122type model struct {23 list list.Model24}2526func (m model) Init() tea.Cmd {27 return nil28}2930func (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 }4041 var cmd tea.Cmd42 m.list, cmd = m.list.Update(msg)43 return m, cmd44}4546func (m model) View() string {47 return docStyle.Render(m.list.View())48}4950func 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 }7677 m := model{list: list.NewModel(items, list.NewDefaultDelegate(), 0, 0)}78 m.list.Title = "My Fave Things"7980 p := tea.NewProgram(m)81 p.EnterAltScreen()8283 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
1package main23import (4 "github.com/charmbracelet/bubbles/key"5 "github.com/charmbracelet/bubbles/list"6 tea "github.com/charmbracelet/bubbletea"7)89func newItemDelegate(keys *delegateKeyMap) 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.KeyMsg:23 switch {24 case key.Matches(msg, keys.choose):25 return m.NewStatusMessage(statusMessageStyle("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(statusMessageStyle("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}
added:examples/list-fancy/main.go+190 added
1package main23import (4 "fmt"5 "math/rand"6 "os"7 "time"89 "github.com/charmbracelet/bubbles/key"10 "github.com/charmbracelet/bubbles/list"11 tea "github.com/charmbracelet/bubbletea"12 "github.com/charmbracelet/lipgloss"13)1415var (16 appStyle = lipgloss.NewStyle().Padding(1, 2)1718 titleStyle = lipgloss.NewStyle().19 Foreground(lipgloss.Color("#FFFDF5")).20 Background(lipgloss.Color("#25A065")).21 Padding(0, 1)2223 statusMessageStyle = lipgloss.NewStyle().24 Foreground(lipgloss.AdaptiveColor{Light: "#04B575", Dark: "#04B575"}).25 Render26)2728type item struct {29 title string30 description string31}3233func (i item) Title() string { return i.title }34func (i item) Description() string { return i.description }35func (i item) FilterValue() string { return i.title }3637type listKeyMap struct {38 toggleSpinner key.Binding39 toggleTitleBar key.Binding40 toggleStatusBar key.Binding41 togglePagination key.Binding42 toggleHelpMenu key.Binding43 insertItem key.Binding44}4546func 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}7475type model struct {76 list list.Model77 itemGenerator *randomItemGenerator78 keys *listKeyMap79 delegateKeys *delegateKeyMap80}8182func newModel() model {83 var (84 itemGenerator randomItemGenerator85 delegateKeys = newDelegateKeyMap()86 listKeys = newListKeyMap()87 )8889 // 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 }9596 // 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 }111112 return model{113 list: groceryList,114 keys: listKeys,115 delegateKeys: delegateKeys,116 itemGenerator: &itemGenerator,117 }118}119120func (m model) Init() tea.Cmd {121 return tea.EnterAltScreen122}123124func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {125 var cmds []tea.Cmd126127 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)131132 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 }137138 switch {139 case key.Matches(msg, m.keys.toggleSpinner):140 cmd := m.list.ToggleSpinner()141 return m, cmd142143 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, nil149150 case key.Matches(msg, m.keys.toggleStatusBar):151 m.list.SetShowStatusBar(!m.list.ShowStatusBar())152 return m, nil153154 case key.Matches(msg, m.keys.togglePagination):155 m.list.SetShowPagination(!m.list.ShowPagination())156 return m, nil157158 case key.Matches(msg, m.keys.toggleHelpMenu):159 m.list.SetShowHelp(!m.list.ShowHelp())160 return m, nil161162 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 }170171 // This will also call our delegate's update function.172 newListModel, cmd := m.list.Update(msg)173 m.list = newListModel174 cmds = append(cmds, cmd)175176 return m, tea.Batch(cmds...)177}178179func (m model) View() string {180 return appStyle.Render(m.list.View())181}182183func main() {184 rand.Seed(time.Now().UTC().UnixNano())185186 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
1package main23import (4 "math/rand"5 "sync"6)78type randomItemGenerator struct {9 titles []string10 descs []string11 titleIndex int12 descIndex int13 mtx *sync.Mutex14 shuffle *sync.Once15}1617func (r *randomItemGenerator) reset() {18 r.mtx = &sync.Mutex{}19 r.shuffle = &sync.Once{}2021 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 }9394 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 }130131 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}139140func (r *randomItemGenerator) next() item {141 if r.mtx == nil {142 r.reset()143 }144145 r.mtx.Lock()146 defer r.mtx.Unlock()147148 i := item{149 title: r.titles[r.titleIndex],150 description: r.descs[r.descIndex],151 }152153 r.titleIndex++154 if r.titleIndex >= len(r.titles) {155 r.titleIndex = 0156 }157158 r.descIndex++159 if r.descIndex >= len(r.descs) {160 r.descIndex = 0161 }162163 return i164}
added:examples/list-simple/main.go+137 added
1package main23import (4 "fmt"5 "io"6 "os"78 "github.com/charmbracelet/bubbles/list"9 tea "github.com/charmbracelet/bubbletea"10 "github.com/charmbracelet/lipgloss"11)1213const listHeight = 141415var (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)2324type item string2526func (i item) FilterValue() string { return string(i) }2728type itemDelegate struct{}2930func (d itemDelegate) Height() int { return 1 }31func (d itemDelegate) Spacing() int { return 0 }32func (d itemDelegate) Update(msg tea.Msg, m *list.Model) tea.Cmd { return nil }33func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {34 i, ok := listItem.(item)35 if !ok {36 return37 }3839 str := fmt.Sprintf("%d. %s", index+1, i)4041 fn := itemStyle.Render42 if index == m.Index() {43 fn = func(s string) string {44 return selectedItemStyle.Render("> " + s)45 }46 }4748 fmt.Fprintf(w, fn(str))49}5051type model struct {52 list list.Model53 items []item54 choice string55 quitting bool56}5758func (m model) Init() tea.Cmd {59 return nil60}6162func (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, nil6768 case tea.KeyMsg:69 switch keypress := msg.String(); keypress {70 case "ctrl+c":71 m.quitting = true72 return m, tea.Quit7374 case "enter":75 i, ok := m.list.SelectedItem().(item)76 if ok {77 m.choice = string(i)78 }79 return m, tea.Quit8081 default:82 if !m.list.SettingFilter() && (keypress == "q" || keypress == "esc") {83 m.quitting = true84 return m, tea.Quit85 }8687 var cmd tea.Cmd88 m.list, cmd = m.list.Update(msg)89 return m, cmd90 }9192 default:93 return m, nil94 }95}9697func (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}106107func 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 }120121 const defaultWidth = 20122123 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 = helpStyle130131 m := model{list: l}132133 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 lines
28github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=29github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=30github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=31github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=32github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=33github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=34github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=35github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=36github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
26 unmodified lines
63github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=64github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=65github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=66github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=67github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=68github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=69github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=70github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=71github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
20 unmodified lines
modified:.gitignore+3 added
2 unmodified lines
34examples/fullscreen/fullscreen5examples/help/help6examples/http/http7examples/list-default/list-default8examples/list-fancy/list-fancy9examples/list-simple/list-simple10examples/mouse/mouse11examples/pager/pager12examples/simple/simple13examples/spinner/spinner
6 unmodified lines