From 4eef7220b41707b2b406ec9b0549a2af8e9f8bdb Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Thu, 22 Feb 2024 09:56:55 -0300 Subject: [PATCH] feat: copy address to the clipboard (#275) closes #274 --- wishlist.go | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/wishlist.go b/wishlist.go index cbfd311..bd4f479 100644 --- a/wishlist.go +++ b/wishlist.go @@ -2,15 +2,22 @@ package wishlist import ( "errors" + "fmt" + "net" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/list" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/log" + "github.com/muesli/termenv" ) var ( + copyIPAddr = key.NewBinding( + key.WithKeys("y"), + key.WithHelp("y", "copy address"), + ) enter = key.NewBinding( key.WithKeys("enter", "o"), key.WithHelp("enter/o", "connect"), @@ -22,6 +29,9 @@ var ( func NewListing(endpoints []*Endpoint, client SSHClient, r *lipgloss.Renderer) *ListModel { l := list.New(nil, list.NewDefaultDelegate(), 0, 0) l.Title = "Directory Listing" + l.AdditionalFullHelpKeys = func() []key.Binding { + return []key.Binding{copyIPAddr} + } l.AdditionalShortHelpKeys = func() []key.Binding { return []key.Binding{enter} } @@ -126,17 +136,21 @@ func (m *ListModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if key.Matches(msg, list.DefaultKeyMap().Quit) && !m.list.SettingFilter() && m.list.FilterState() != list.FilterApplied { m.quitting = true } + if key.Matches(msg, copyIPAddr) && !m.list.SettingFilter() { + if w := m.selected(); w != nil { + host, _, _ := net.SplitHostPort(w.endpoint.Address) + termenv.Copy(host) + return m, m.list.NewStatusMessage(fmt.Sprintf("copied %q to the clipboard", host)) + } + + return m, nil + } if key.Matches(msg, enter) { if m.list.SettingFilter() { break } - selectedItem := m.list.SelectedItem() - if selectedItem == nil { - return m, nil - } - w, ok := selectedItem.(ItemWrapper) - if !ok { - // this should never happen + w := m.selected() + if w == nil { return m, nil } cmd := m.client.For(w.endpoint) @@ -168,6 +182,19 @@ func (m *ListModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, cmd } +func (m *ListModel) selected() *ItemWrapper { + selectedItem := m.list.SelectedItem() + if selectedItem == nil { + return nil + } + w, ok := selectedItem.(ItemWrapper) + if !ok { + // this should never happen + return nil + } + return &w +} + // View comply with tea.Model interface. func (m *ListModel) View() string { if m.quitting {