copy.go

 1package copy
 2
 3import (
 4	"github.com/aymanbagabas/go-osc52"
 5	tea "github.com/charmbracelet/bubbletea"
 6	"github.com/charmbracelet/lipgloss"
 7)
 8
 9// CopyMsg is a message that is sent when the user copies text.
10type CopyMsg string
11
12// CopyCmd is a command that copies text to the clipboard using OSC52.
13func CopyCmd(output *osc52.Output, str string) tea.Cmd {
14	return func() tea.Msg {
15		output.Copy(str)
16		return CopyMsg(str)
17	}
18}
19
20type Copy struct {
21	output      *osc52.Output
22	text        string
23	copied      bool
24	CopiedStyle lipgloss.Style
25	TextStyle   lipgloss.Style
26}
27
28func New(output *osc52.Output, text string) *Copy {
29	copy := &Copy{
30		output: output,
31		text:   text,
32	}
33	return copy
34}
35
36func (c *Copy) SetText(text string) {
37	c.text = text
38}
39
40func (c *Copy) Init() tea.Cmd {
41	c.copied = false
42	return nil
43}
44
45func (c *Copy) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
46	switch msg.(type) {
47	case CopyMsg:
48		c.copied = true
49	default:
50		c.copied = false
51	}
52	return c, nil
53}
54
55func (c *Copy) View() string {
56	if c.copied {
57		return c.CopiedStyle.String()
58	}
59	return c.TextStyle.Render(c.text)
60}
61
62func (c *Copy) CopyCmd() tea.Cmd {
63	return CopyCmd(c.output, c.text)
64}