Handle paste via command/message since it's IO

This commit is contained in:
Christian Rocha 2020-10-24 20:20:45 -04:00
parent 1b530b293c
commit bf7719e6c1
No known key found for this signature in database
GPG Key ID: D6CC7A16E5878018

View File

@ -37,6 +37,10 @@ var color func(s string) termenv.Color = termenv.ColorProfile().Color
// blinkMsg is used to blink the cursor. // blinkMsg is used to blink the cursor.
type blinkMsg struct{} type blinkMsg struct{}
// Messages for clipboard events
type pasteMsg string
type pasteErrMsg struct{ error }
// Model is the Bubble Tea model for this text input element. // Model is the Bubble Tea model for this text input element.
type Model struct { type Model struct {
Err error Err error
@ -152,13 +156,9 @@ func (m *Model) Reset() {
m.SetCursor(0) m.SetCursor(0)
} }
// Paste pastes the contents of the clipboard into the text area (if supported). // handle a clipboard paste event, if supported.
func (m *Model) Paste() { func (m *Model) handlePaste(v string) {
pasteString, err := clipboard.ReadAll() paste := []rune(v)
if err != nil {
m.Err = err
}
paste := []rune(pasteString)
var availSpace int var availSpace int
if m.CharLimit > 0 { if m.CharLimit > 0 {
@ -469,7 +469,7 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
m.SetCursor(0) m.SetCursor(0)
m.offset = 0 m.offset = 0
case tea.KeyCtrlV: // ^V paste case tea.KeyCtrlV: // ^V paste
m.Paste() return m, Paste
case tea.KeyRune: // input a regular character case tea.KeyRune: // input a regular character
if msg.Alt { if msg.Alt {
if msg.Rune == 'd' { // alt+d, delete word right of cursor if msg.Rune == 'd' { // alt+d, delete word right of cursor
@ -498,10 +498,15 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
t, cmd := m.blinkCmd() t, cmd := m.blinkCmd()
m.blinkTimer = t m.blinkTimer = t
return m, cmd return m, cmd
case pasteMsg:
m.handlePaste(string(msg))
case pasteErrMsg:
m.Err = msg
} }
m.handleOverflow() m.handleOverflow()
return m, nil return m, nil
} }
@ -583,6 +588,14 @@ func Blink() tea.Msg {
return blinkMsg{} return blinkMsg{}
} }
func Paste() tea.Msg {
str, err := clipboard.ReadAll()
if err != nil {
return pasteErrMsg{err}
}
return pasteMsg(str)
}
// blinkCmd is an internal command used to manage cursor blinking // blinkCmd is an internal command used to manage cursor blinking
func (m Model) blinkCmd() (*time.Timer, tea.Cmd) { func (m Model) blinkCmd() (*time.Timer, tea.Cmd) {
t := time.NewTimer(m.BlinkSpeed) t := time.NewTimer(m.BlinkSpeed)