Skip to content

Instantly share code, notes, and snippets.

@bashbunni
Created September 7, 2022 17:55
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bashbunni/0ab98bc9641223f611139382485b1ad3 to your computer and use it in GitHub Desktop.
Recolor Selected Items in List Bubble
package main
import (
"fmt"
"os"
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
const listHeight = 14
var (
titleStyle = lipgloss.NewStyle().MarginLeft(2)
paginationStyle = list.DefaultStyles().PaginationStyle.PaddingLeft(4)
helpStyle = list.DefaultStyles().HelpStyle.PaddingLeft(4).PaddingBottom(1)
quitTextStyle = lipgloss.NewStyle().Margin(1, 0, 2, 4)
)
type item struct {
title string
description string
}
func (i item) Title() string {
return i.title
}
func (i item) Description() string {
return i.description
}
func (i item) FilterValue() string {
return i.Title()
}
type model struct {
list list.Model
choice string
quitting bool
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.list.SetWidth(msg.Width)
return m, nil
case tea.KeyMsg:
switch keypress := msg.String(); keypress {
case "ctrl+c":
m.quitting = true
return m, tea.Quit
case "enter":
i, ok := m.list.SelectedItem().(item)
if ok {
m.choice = i.Title()
}
return m, tea.Quit
}
}
var cmd tea.Cmd
m.list, cmd = m.list.Update(msg)
return m, cmd
}
func (m model) View() string {
if m.choice != "" {
return quitTextStyle.Render(fmt.Sprintf("%s? Sounds good to me.", m.choice))
}
if m.quitting {
return quitTextStyle.Render("Not hungry? That’s cool.")
}
return "\n" + m.list.View()
}
func newDefaultItem(title string) item {
return item{title: title}
}
func main() {
items := []list.Item{
newDefaultItem("Ramen"),
newDefaultItem("Tomato Soup"),
newDefaultItem("Hamburgers"),
newDefaultItem("Cheeseburgers"),
newDefaultItem("Currywurst"),
newDefaultItem("Okonomiyaki"),
newDefaultItem("Pasta"),
newDefaultItem("Fillet Mignon"),
newDefaultItem("Caviar"),
newDefaultItem("Just Wine"),
}
const defaultWidth = 20
d := list.NewDefaultDelegate()
d.Styles.SelectedTitle.BorderForeground(lipgloss.Color("196"))
// d.Styles.SelectedDesc.BorderForeground(lipgloss.Color("196")) if you want to change the description color too
d.Styles.SelectedTitle.Foreground(lipgloss.Color("196"))
d.ShowDescription = false
l := list.New(items, d, defaultWidth, listHeight)
l.Title = "What do you want for dinner?"
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.Styles.Title = titleStyle
l.Styles.PaginationStyle = paginationStyle
l.Styles.HelpStyle = helpStyle
m := model{list: l}
if err := tea.NewProgram(m).Start(); err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment