yankable.go

 1package yankable
 2
 3import (
 4	"fmt"
 5	"log"
 6	"strings"
 7
 8	"github.com/aymanbagabas/go-osc52"
 9	tea "github.com/charmbracelet/bubbletea"
10	"github.com/charmbracelet/lipgloss"
11	"github.com/gliderlabs/ssh"
12)
13
14type Yankable struct {
15	yankStyle lipgloss.Style
16	style     lipgloss.Style
17	text      string
18	clicked   bool
19	osc52     *osc52.Output
20}
21
22func New(s ssh.Session, style, yankStyle lipgloss.Style, text string) *Yankable {
23	environ := s.Environ()
24	termExists := false
25	for _, env := range environ {
26		if strings.HasPrefix(env, "TERM=") {
27			termExists = true
28			break
29		}
30	}
31	if !termExists {
32		pty, _, _ := s.Pty()
33		environ = append(environ, fmt.Sprintf("TERM=%s", pty.Term))
34	}
35	log.Print(environ)
36	return &Yankable{
37		yankStyle: yankStyle,
38		style:     style,
39		text:      text,
40		clicked:   false,
41		osc52:     osc52.NewOutput(s, environ),
42	}
43}
44
45func (y *Yankable) SetText(text string) {
46	y.text = text
47}
48
49func (y *Yankable) Init() tea.Cmd {
50	return nil
51}
52
53func (y *Yankable) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
54	switch msg := msg.(type) {
55	case tea.MouseMsg:
56		switch msg.Type {
57		case tea.MouseRight:
58			y.clicked = true
59			return y, y.copy()
60		}
61	default:
62		y.clicked = false
63	}
64	return y, nil
65}
66
67func (y *Yankable) View() string {
68	if y.clicked {
69		return y.yankStyle.String()
70	}
71	return y.style.Render(y.text)
72}
73
74func (y *Yankable) copy() tea.Cmd {
75	y.osc52.Copy(y.text)
76	return nil
77}