Created
January 22, 2025 23:55
-
-
Save bashbunni/9e2c472f0fdd3181d06ce7fea97c09bd to your computer and use it in GitHub Desktop.
textinput bubble with bash history (bubbles#631)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os/exec" | |
"strings" | |
"github.com/charmbracelet/bubbles/help" | |
"github.com/charmbracelet/bubbles/textinput" | |
tea "github.com/charmbracelet/bubbletea" | |
"github.com/charmbracelet/lipgloss" | |
) | |
type gotHistorySuccessMsg []string | |
func main() { | |
p := tea.NewProgram(initialModel()) | |
if _, err := p.Run(); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func getHistory() tea.Msg { | |
cmd := exec.Command("bash", "-c", "history -r ~/.bash_history; history | cut -c 8-") | |
stdout, err := cmd.Output() | |
if err != nil { | |
fmt.Println(err.Error()) | |
return []string{"no results"} | |
} | |
return gotHistorySuccessMsg(strings.Split(fmt.Sprintf("%s", stdout), "\n")) | |
} | |
type model struct { | |
textInput textinput.Model | |
help help.Model | |
} | |
func initialModel() model { | |
ti := textinput.New() | |
ti.Placeholder = "history" | |
ti.Prompt = "$ " | |
ti.PromptStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63")) | |
ti.Cursor.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("63")) | |
ti.Focus() | |
ti.CharLimit = 50 | |
ti.Width = 20 | |
ti.ShowSuggestions = true | |
h := help.New() | |
return model{textInput: ti, help: h} | |
} | |
func (m model) Init() tea.Cmd { | |
return tea.Batch(getHistory, textinput.Blink) | |
} | |
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { | |
switch msg := msg.(type) { | |
case tea.KeyMsg: | |
switch msg.Type { | |
case tea.KeyEnter, tea.KeyCtrlC, tea.KeyEsc: | |
return m, tea.Quit | |
} | |
case gotHistorySuccessMsg: | |
m.textInput.SetSuggestions(msg) | |
} | |
var cmd tea.Cmd | |
m.textInput, cmd = m.textInput.Update(msg) | |
return m, cmd | |
} | |
func (m model) View() string { | |
return m.textInput.View() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment