github.com/wolfi-dev/wolfictl@v0.16.11/pkg/cli/components/list/list.go (about)

     1  package list
     2  
     3  import (
     4  	"strings"
     5  
     6  	tea "github.com/charmbracelet/bubbletea"
     7  	"github.com/charmbracelet/lipgloss"
     8  )
     9  
    10  type Model struct {
    11  	focused       bool
    12  	prompt        string
    13  	items         []string
    14  	selectedIndex int
    15  
    16  	SelectedStyle   lipgloss.Style
    17  	UnselectedStyle lipgloss.Style
    18  }
    19  
    20  func New(prompt string, items []string) Model {
    21  	return Model{
    22  		prompt:        prompt,
    23  		items:         items,
    24  		selectedIndex: 0,
    25  	}
    26  }
    27  
    28  func (m Model) Init() tea.Cmd {
    29  	return nil
    30  }
    31  
    32  func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
    33  	if msg, ok := msg.(tea.KeyMsg); ok {
    34  		switch msg.String() {
    35  		case "up", "k":
    36  			if m.selectedIndex > 0 {
    37  				m.selectedIndex--
    38  			}
    39  
    40  		case "down", "j":
    41  			if m.selectedIndex < len(m.items)-1 {
    42  				m.selectedIndex++
    43  			}
    44  		}
    45  	}
    46  
    47  	return m, nil
    48  }
    49  
    50  func (m Model) View() string {
    51  	var lines []string
    52  
    53  	lines = append(lines, m.prompt)
    54  
    55  	for i, item := range m.items {
    56  		var itemLine string
    57  
    58  		if i == m.selectedIndex {
    59  			itemLine = m.SelectedStyle.Render("> " + item)
    60  		} else {
    61  			itemLine = m.UnselectedStyle.Render("  " + item)
    62  		}
    63  
    64  		lines = append(lines, itemLine)
    65  	}
    66  
    67  	return strings.Join(lines, "\n")
    68  }
    69  
    70  func (m Model) SelectedItem() string {
    71  	return m.items[m.selectedIndex]
    72  }
    73  
    74  func (m Model) Focus() Model {
    75  	m.focused = true
    76  	return m
    77  }
    78  
    79  func (m Model) Focused() bool {
    80  	return m.focused
    81  }
    82  
    83  func (m Model) Blur() Model {
    84  	m.focused = false
    85  	return m
    86  }