8 Commits

Author SHA1 Message Date
Christian Muehlhaeuser
2e2a7eccb7 Add vertical layout 2020-10-30 15:59:45 +01:00
Christian Rocha
9b47f26bdd Doc and logic corrections per the linter 2020-10-28 21:27:15 -04:00
Christian Rocha
9c780011ff Underpinnings for always-on and always-hidden cursor modes 2020-10-28 21:27:15 -04:00
Christian Rocha
8148e61443 Correct ^F/^B keybindings for forward/back cursor movement 2020-10-28 21:27:15 -04:00
Christian Rocha
ce7d8da084 Fix lock-up that could occur with cursor blinking
Note that to do this we've replaced the blink timer with a context.
2020-10-28 21:27:15 -04:00
Christian Rocha
d14fdf585c Textinput Update and View functions are now methods on the model 2020-10-28 21:27:15 -04:00
Christian Rocha
bf7719e6c1 Handle paste via command/message since it's IO 2020-10-28 21:27:15 -04:00
Christian Rocha
1b530b293c Reset blink timer when moving the cursor 2020-10-28 21:27:15 -04:00
2 changed files with 345 additions and 129 deletions

118
layouts/vertical.go Normal file
View File

@@ -0,0 +1,118 @@
package layouts
import (
tea "github.com/charmbracelet/bubbletea"
)
// Model is the Bubble Tea model for a vertical layout element.
type Model struct {
Index int
Items []tea.Model
// Focus indicates whether user focus should be on this component
focus bool
}
type FocusItem interface {
Focus() tea.Model
Blur() tea.Model
}
// NewModel creates a new model with default settings.
func NewModel() Model {
return Model{}
}
// Update is the Tea update loop.
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
if !m.focus {
return m, nil
}
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "shift+tab", "up":
m.Index--
if m.Index < 0 {
m.Index = len(m.Items) - 1
}
m.updateFocus()
case "tab", "down":
m.Index++
if m.Index >= len(m.Items) {
m.Index = 0
}
m.updateFocus()
}
}
cmd := m.updateItems(msg)
return m, cmd
}
// View renders the layout in its current state.
func (m Model) View() string {
var view string
for _, v := range m.Items {
if mi, ok := v.(tea.Model); ok {
view += mi.View() + "\n"
}
}
return view
}
func (m *Model) updateFocus() {
for i, v := range m.Items {
if m.Index == i {
if fi, ok := v.(FocusItem); ok {
// new focused item
m.Items[i] = fi.Focus()
}
} else {
if fi, ok := v.(FocusItem); ok {
m.Items[i] = fi.Blur()
}
}
}
}
// Pass messages and models through to text input components. Only text inputs
// with Focus() set will respond, so it's safe to simply update all of them
// here without any further logic.
func (m *Model) updateItems(msg tea.Msg) tea.Cmd {
var (
cmd tea.Cmd
cmds []tea.Cmd
)
for i, v := range m.Items {
if mi, ok := v.(tea.Model); ok {
m.Items[i], cmd = mi.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
}
}
return tea.Batch(cmds...)
}
// Focused returns the focus state on the model.
func (m Model) Focused() bool {
return m.focus
}
// Focus sets the focus state on the model.
func (m *Model) Focus() {
m.focus = true
m.updateFocus()
}
// Blur removes the focus state on the model.
func (m *Model) Blur() {
m.focus = false
}

View File

@@ -1,6 +1,7 @@
package textinput
import (
"context"
"strings"
"time"
"unicode"
@@ -13,6 +14,20 @@ import (
const defaultBlinkSpeed = time.Millisecond * 530
// color is a helper for returning colors.
var color func(s string) termenv.Color = termenv.ColorProfile().Color
// blinkMsg and blinkCanceled are used to manage cursor blinking.
type blinkMsg struct{}
type blinkCanceled struct{}
// Messages for clipboard events.
type pasteMsg string
type pasteErrMsg struct{ error }
// EchoMode sets the input behavior of the text input field.
type EchoMode int
const (
// EchoNormal displays text as is. This is the default behavior.
EchoNormal EchoMode = iota
@@ -28,29 +43,34 @@ const (
// EchoOnEdit
)
// EchoMode sets the input behavior of the text input field.
type EchoMode int
// blinkCtx manages cursor blinking.
type blinkCtx struct {
ctx context.Context
cancel context.CancelFunc
}
var (
// color is a helper for returning colors.
color func(s string) termenv.Color = termenv.ColorProfile().Color
type cursorMode int
const (
cursorBlink = iota
cursorStatic
cursorHide
)
// Model is the Bubble Tea model for this text input element.
type Model struct {
Err error
// General settings
Prompt string
Placeholder string
Cursor string
BlinkSpeed time.Duration
TextColor string
FocusedTextColor string
BackgroundColor string
PlaceholderColor string
CursorColor string
EchoMode EchoMode
EchoCharacter rune
@@ -80,6 +100,37 @@ type Model struct {
// overflowing.
offset int
offsetRight int
// Used to manage cursor blink
blinkCtx *blinkCtx
// cursorMode determines the behavior of the cursor
cursorMode cursorMode
}
// NewModel creates a new model with default settings.
func NewModel() Model {
return Model{
Prompt: "> ",
Placeholder: "",
BlinkSpeed: defaultBlinkSpeed,
TextColor: "",
FocusedTextColor: "205",
PlaceholderColor: "240",
CursorColor: "",
EchoCharacter: '*',
CharLimit: 0,
value: nil,
focus: false,
blink: true,
pos: 0,
cursorMode: cursorBlink,
blinkCtx: &blinkCtx{
ctx: context.Background(),
},
}
}
// SetValue sets the value of the text input.
@@ -103,20 +154,28 @@ func (m Model) Value() string {
// SetCursor start moves the cursor to the given position. If the position is
// out of bounds the cursor will be moved to the start or end accordingly.
func (m *Model) SetCursor(pos int) {
// Returns whether or nor the cursor timer should be reset.
func (m *Model) SetCursor(pos int) bool {
m.pos = clamp(pos, 0, len(m.value))
m.blink = false
m.handleOverflow()
// Show the cursor unless it's been explicitly hidden
m.blink = m.cursorMode == cursorHide
// Reset cursor blink if necessary
return m.cursorMode == cursorBlink
}
// CursorStart moves the cursor to the start of the field.
func (m *Model) CursorStart() {
m.SetCursor(0)
// CursorStart moves the cursor to the start of the field. Returns whether or
// not the curosr blink should be reset.
func (m *Model) CursorStart() bool {
return m.SetCursor(0)
}
// CursorEnd moves the cursor to the end of the field.
func (m *Model) CursorEnd() {
m.SetCursor(len(m.value))
// CursorEnd moves the cursor to the end of the field. Returns whether or not
// the cursor blink should be reset.
func (m *Model) CursorEnd() bool {
return m.SetCursor(len(m.value))
}
// Focused returns the focus state on the model.
@@ -125,30 +184,32 @@ func (m Model) Focused() bool {
}
// Focus sets the focus state on the model.
func (m *Model) Focus() {
func (m Model) Focus() tea.Model {
m.focus = true
m.blink = false
m.blink = m.cursorMode == cursorHide // show the cursor unless we've explicitly hidden it
return m
}
// Blur removes the focus state on the model.
func (m *Model) Blur() {
func (m Model) Blur() tea.Model {
m.focus = false
m.blink = true
return m
}
// Reset sets the input to its default state with no input.
func (m *Model) Reset() {
// Reset sets the input to its default state with no input. Returns whether
// or not the cursor blink should reset.
func (m *Model) Reset() bool {
m.value = nil
m.SetCursor(0)
return m.SetCursor(0)
}
// Paste pastes the contents of the clipboard into the text area (if supported).
func (m *Model) Paste() {
pasteString, err := clipboard.ReadAll()
if err != nil {
m.Err = err
}
paste := []rune(pasteString)
// handle a clipboard paste event, if supported. Returns whether or not the
// cursor blink should be reset.
func (m *Model) handlePaste(v string) (blink bool) {
paste := []rune(v)
var availSpace int
if m.CharLimit > 0 {
@@ -187,8 +248,8 @@ func (m *Model) Paste() {
// Put it all back together
m.value = append(head, tail...)
// Reset blink state and run overflow checks
m.SetCursor(m.pos)
// Reset blink state if necessary and run overflow checks
return m.SetCursor(m.pos)
}
// If a max width is defined, perform some logic to treat the visible area
@@ -256,26 +317,27 @@ func (m *Model) colorPlaceholder(s string) string {
String()
}
// deleteWordLeft deletes the word left to the cursor.
func (m *Model) deleteWordLeft() {
// deleteWordLeft deletes the word left to the cursor. Returns whether or not
// the cursor blink should be reset.
func (m *Model) deleteWordLeft() (blink bool) {
if m.pos == 0 || len(m.value) == 0 {
return
}
i := m.pos
m.SetCursor(m.pos - 1)
blink = m.SetCursor(m.pos - 1)
for unicode.IsSpace(m.value[m.pos]) {
// ignore series of whitespace before cursor
m.SetCursor(m.pos - 1)
blink = m.SetCursor(m.pos - 1)
}
for m.pos > 0 {
if !unicode.IsSpace(m.value[m.pos]) {
m.SetCursor(m.pos - 1)
blink = m.SetCursor(m.pos - 1)
} else {
if m.pos > 0 {
// keep the previous space
m.SetCursor(m.pos + 1)
blink = m.SetCursor(m.pos + 1)
}
break
}
@@ -286,24 +348,27 @@ func (m *Model) deleteWordLeft() {
} else {
m.value = append(m.value[:m.pos], m.value[i:]...)
}
return
}
// deleteWordRight deletes the word right to the cursor.
func (m *Model) deleteWordRight() {
// deleteWordRight deletes the word right to the cursor. Returns whether or not
// the cursor blink should be reset.
func (m *Model) deleteWordRight() (blink bool) {
if m.pos >= len(m.value) || len(m.value) == 0 {
return
}
i := m.pos
m.SetCursor(m.pos + 1)
blink = m.SetCursor(m.pos + 1)
for unicode.IsSpace(m.value[m.pos]) {
// ignore series of whitespace after cursor
m.SetCursor(m.pos + 1)
blink = m.SetCursor(m.pos + 1)
}
for m.pos < len(m.value) {
if !unicode.IsSpace(m.value[m.pos]) {
m.SetCursor(m.pos + 1)
blink = m.SetCursor(m.pos + 1)
} else {
break
}
@@ -314,10 +379,14 @@ func (m *Model) deleteWordRight() {
} else {
m.value = append(m.value[:i], m.value[m.pos:]...)
}
m.SetCursor(i)
blink = m.SetCursor(i)
return
}
func (m *Model) wordLeft() {
// wordLeft moves the cursor one word to the left. Returns whether or not the
// cursor blink should be reset.
func (m *Model) wordLeft() (blink bool) {
if m.pos == 0 || len(m.value) == 0 {
return
}
@@ -326,7 +395,7 @@ func (m *Model) wordLeft() {
for i >= 0 {
if unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos - 1)
blink = m.SetCursor(m.pos - 1)
i--
} else {
break
@@ -335,15 +404,19 @@ func (m *Model) wordLeft() {
for i >= 0 {
if !unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos - 1)
blink = m.SetCursor(m.pos - 1)
i--
} else {
break
}
}
return
}
func (m *Model) wordRight() {
// wordRight moves the cursor one word to the right. Returns whether or not the
// cursor blink should be reset.
func (m *Model) wordRight() (blink bool) {
if m.pos >= len(m.value) || len(m.value) == 0 {
return
}
@@ -352,7 +425,7 @@ func (m *Model) wordRight() {
for i < len(m.value) {
if unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos + 1)
blink = m.SetCursor(m.pos + 1)
i++
} else {
break
@@ -361,12 +434,14 @@ func (m *Model) wordRight() {
for i < len(m.value) {
if !unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos + 1)
blink = m.SetCursor(m.pos + 1)
i++
} else {
break
}
}
return
}
func (m Model) echoTransform(v string) string {
@@ -381,104 +456,80 @@ func (m Model) echoTransform(v string) string {
}
}
// BlinkMsg is sent when the cursor should alternate it's blinking state.
type BlinkMsg struct{}
// NewModel creates a new model with default settings.
func NewModel() Model {
return Model{
Prompt: "> ",
Placeholder: "",
BlinkSpeed: defaultBlinkSpeed,
TextColor: "",
PlaceholderColor: "240",
CursorColor: "",
EchoCharacter: '*',
CharLimit: 0,
value: nil,
focus: false,
blink: true,
pos: 0,
}
func (m Model) Init() tea.Cmd {
return Blink
}
// Update is the Tea update loop.
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
// Update is the Bubble Tea update loop.
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if !m.focus {
m.blink = true
return m, nil
}
var resetBlink bool
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyBackspace: // delete character before cursor
if msg.Alt {
m.deleteWordLeft()
resetBlink = m.deleteWordLeft()
} else {
if len(m.value) > 0 {
m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
if m.pos > 0 {
m.SetCursor(m.pos - 1)
resetBlink = m.SetCursor(m.pos - 1)
}
}
}
case tea.KeyLeft:
case tea.KeyLeft, tea.KeyCtrlB:
if msg.Alt { // alt+left arrow, back one word
m.wordLeft()
resetBlink = m.wordLeft()
break
}
if m.pos > 0 {
m.SetCursor(m.pos - 1)
if m.pos > 0 { // left arrow, ^F, back one character
resetBlink = m.SetCursor(m.pos - 1)
}
case tea.KeyRight:
case tea.KeyRight, tea.KeyCtrlF:
if msg.Alt { // alt+right arrow, forward one word
m.wordRight()
resetBlink = m.wordRight()
break
}
if m.pos < len(m.value) {
m.SetCursor(m.pos + 1)
if m.pos < len(m.value) { // right arrow, ^F, forward one word
resetBlink = m.SetCursor(m.pos + 1)
}
case tea.KeyCtrlW: // ^W, delete word left of cursor
m.deleteWordLeft()
case tea.KeyCtrlF: // ^F, forward one character
fallthrough
case tea.KeyCtrlB: // ^B, back one charcter
fallthrough
resetBlink = m.deleteWordLeft()
case tea.KeyHome, tea.KeyCtrlA: // ^A, go to beginning
m.CursorStart()
resetBlink = m.CursorStart()
case tea.KeyDelete, tea.KeyCtrlD: // ^D, delete char under cursor
if len(m.value) > 0 && m.pos < len(m.value) {
m.value = append(m.value[:m.pos], m.value[m.pos+1:]...)
}
case tea.KeyCtrlE, tea.KeyEnd: // ^E, go to end
m.CursorEnd()
resetBlink = m.CursorEnd()
case tea.KeyCtrlK: // ^K, kill text after cursor
m.value = m.value[:m.pos]
m.SetCursor(len(m.value))
resetBlink = m.SetCursor(len(m.value))
case tea.KeyCtrlU: // ^U, kill text before cursor
m.value = m.value[m.pos:]
m.SetCursor(0)
resetBlink = m.SetCursor(0)
m.offset = 0
case tea.KeyCtrlV: // ^V paste
m.Paste()
return m, Paste
case tea.KeyRune: // input a regular character
if msg.Alt {
if msg.Rune == 'd' { // alt+d, delete word right of cursor
m.deleteWordRight()
resetBlink = m.deleteWordRight()
break
}
if msg.Rune == 'b' { // alt+b, back one word
m.wordLeft()
resetBlink = m.wordLeft()
break
}
if msg.Rune == 'f' { // alt+f, forward one word
m.wordRight()
resetBlink = m.wordRight()
break
}
}
@@ -486,25 +537,47 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
// Input a regular character
if m.CharLimit <= 0 || len(m.value) < m.CharLimit {
m.value = append(m.value[:m.pos], append([]rune{msg.Rune}, m.value[m.pos:]...)...)
m.SetCursor(m.pos + 1)
resetBlink = m.SetCursor(m.pos + 1)
}
}
case BlinkMsg:
case blinkMsg:
var cmd tea.Cmd
if m.cursorMode == cursorBlink {
m.blink = !m.blink
return m, Blink(m)
cmd = m.blinkCmd()
}
return m, cmd
case blinkCanceled: // no-op
return m, nil
case pasteMsg:
resetBlink = m.handlePaste(string(msg))
case pasteErrMsg:
m.Err = msg
}
var cmd tea.Cmd
if resetBlink {
cmd = m.blinkCmd()
}
m.handleOverflow()
return m, nil
return m, cmd
}
// View renders the textinput in its current state.
func View(m Model) string {
func (m Model) View() string {
prompt := termenv.String(m.Prompt)
if m.focus {
prompt = prompt.Foreground(color(m.FocusedTextColor))
}
// Placeholder text
if len(m.value) == 0 && m.Placeholder != "" {
return placeholderView(m)
return prompt.String() + m.placeholderView()
}
value := m.value[m.offset:m.offsetRight]
@@ -512,10 +585,10 @@ func View(m Model) string {
v := m.colorText(m.echoTransform(string(value[:pos])))
if pos < len(value) {
v += cursorView(m.echoTransform(string(value[pos])), m) // cursor and text under it
v += m.cursorView(m.echoTransform(string(value[pos]))) // cursor and text under it
v += m.colorText(m.echoTransform(string(value[pos+1:]))) // text after cursor
} else {
v += cursorView(" ", m)
v += m.cursorView(" ")
}
// If a max width and background color were set fill the empty spaces with
@@ -532,11 +605,11 @@ func View(m Model) string {
)
}
return m.Prompt + v
return prompt.String() + v
}
// placeholderView.
func placeholderView(m Model) string {
// placeholderView returns the prompt and placeholder view, if any.
func (m Model) placeholderView() string {
var (
v string
p = m.Placeholder
@@ -544,41 +617,66 @@ func placeholderView(m Model) string {
// Cursor
if m.blink && m.PlaceholderColor != "" {
v += cursorView(m.colorPlaceholder(p[:1]), m)
v += m.cursorView(m.colorPlaceholder(p[:1]))
} else {
v += cursorView(p[:1], m)
v += m.cursorView(p[:1])
}
// The rest of the placeholder text
v += m.colorPlaceholder(p[1:])
return m.Prompt + v
return v
}
// cursorView styles the cursor.
func cursorView(s string, m Model) string {
func (m Model) cursorView(v string) string {
if m.blink {
if m.TextColor != "" || m.BackgroundColor != "" {
return termenv.String(s).
return termenv.String(v).
Foreground(color(m.TextColor)).
Background(color(m.BackgroundColor)).
String()
}
return s
return v
}
return termenv.String(s).
return termenv.String(v).
Foreground(color(m.CursorColor)).
Background(color(m.BackgroundColor)).
Reverse().
String()
}
// Blink is a command used to time the cursor blinking.
func Blink(model Model) tea.Cmd {
return func() tea.Msg {
time.Sleep(model.BlinkSpeed)
return BlinkMsg{}
// blinkCmd is an internal command used to manage cursor blinking.
func (m Model) blinkCmd() tea.Cmd {
if m.blinkCtx != nil && m.blinkCtx.cancel != nil {
m.blinkCtx.cancel()
}
ctx, cancel := context.WithTimeout(m.blinkCtx.ctx, m.BlinkSpeed)
m.blinkCtx.cancel = cancel
return func() tea.Msg {
defer cancel()
<-ctx.Done()
if ctx.Err() == context.DeadlineExceeded {
return blinkMsg{}
}
return blinkCanceled{}
}
}
// Blink is a command used to initialize cursor blinking.
func Blink() tea.Msg {
return blinkMsg{}
}
// Paste is a command for pasting from the clipboard into the text input.
func Paste() tea.Msg {
str, err := clipboard.ReadAll()
if err != nil {
return pasteErrMsg{err}
}
return pasteMsg(str)
}
func clamp(v, low, high int) int {