1 Commits

Author SHA1 Message Date
Maas Lalani
8d709dc384 chore: bump go from 1.13 to 1.18 2022-07-07 10:56:47 -04:00
11 changed files with 441 additions and 929 deletions

View File

@@ -26,8 +26,8 @@ applications. These components are used in production in [Glow][glow],
A spinner, useful for indicating that some kind an operation is happening. A spinner, useful for indicating that some kind an operation is happening.
There are a couple default ones, but you can also pass your own ”frames.” There are a couple default ones, but you can also pass your own ”frames.”
* [Example code, basic spinner](https://github.com/charmbracelet/bubbletea/tree/master/examples/spinner/main.go) * [Example code, basic spinner](https://github.com/charmbracelet/tea/tree/master/examples/spinner/main.go)
* [Example code, various spinners](https://github.com/charmbracelet/bubbletea/tree/master/examples/spinners/main.go) * [Example code, various spinners](https://github.com/charmbracelet/tea/tree/master/examples/spinners/main.go)
## Text Input ## Text Input
@@ -38,8 +38,8 @@ A text input field, akin to an `<input type="text">` in HTML. Supports unicode,
pasting, in-place scrolling when the value exceeds the width of the element and pasting, in-place scrolling when the value exceeds the width of the element and
the common, and many customization options. the common, and many customization options.
* [Example code, one field](https://github.com/charmbracelet/bubbletea/tree/master/examples/textinput/main.go) * [Example code, one field](https://github.com/charmbracelet/tea/tree/master/examples/textinput/main.go)
* [Example code, many fields](https://github.com/charmbracelet/bubbletea/tree/master/examples/textinputs/main.go) * [Example code, many fields](https://github.com/charmbracelet/tea/tree/master/examples/textinputs/main.go)
## Text Area ## Text Area
@@ -50,25 +50,13 @@ spans multiple lines. Supports unicode, pasting, vertical scrolling when the
value exceeds the width and height of the element, and many customization value exceeds the width and height of the element, and many customization
options. options.
* [Example code, chat input](https://github.com/charmbracelet/bubbletea/tree/master/examples/chat/main.go) * [Example code, chat input](https://github.com/charmbracelet/tea/tree/master/examples/chat/main.go)
* [Example code, story time input](https://github.com/charmbracelet/bubbletea/tree/master/examples/textarea/main.go) * [Example code, story time input](https://github.com/charmbracelet/tea/tree/master/examples/textarea/main.go)
## Table
<img src="https://stuff.charm.sh/bubbles-examples/table.gif" width="400" alt="Table Example">
A component for displaying and navigating tabular data (columns and rows).
Supports vertical scrolling and many customization options.
* [Example code, countries and populations](https://github.com/charmbracelet/bubbletea/tree/master/examples/table/main.go)
## Progress ## Progress
<picture> <img src="https://stuff.charm.sh/bubbles-examples/progress.gif" width="800" alt="Progressbar Example">
<source media="(max-width: 800px)" srcset="https://stuff.charm.sh/bubbles-examples/progress.gif">
<source media="(min-width: 800px)" width="800" srcset="https://stuff.charm.sh/bubbles-examples/progress.gif">
<img src="https://stuff.charm.sh/bubbles-examples/progress.gif" alt="Progressbar Example">
</picture>
A simple, customizable progress meter, with optional animation via A simple, customizable progress meter, with optional animation via
[Harmonica][harmonica]. Supports solid and gradient fills. The empty and filled [Harmonica][harmonica]. Supports solid and gradient fills. The empty and filled
@@ -95,17 +83,13 @@ logic and visualize pagination however you like.
## Viewport ## Viewport
<picture> <img src="https://stuff.charm.sh/bubbles-examples/viewport.gif?0" width="600" alt="Viewport Example">
<source media="(max-width: 600px)" srcset="https://stuff.charm.sh/bubbles-examples/viewport.gif?0">
<source media="(min-width: 600px)" width="600" srcset="https://stuff.charm.sh/bubbles-examples/viewport.gif?0">
<img src="https://stuff.charm.sh/bubbles-examples/viewport.gif?0" alt="Viewport Example">
</picture>
A viewport for vertically scrolling content. Optionally includes standard A viewport for vertically scrolling content. Optionally includes standard
pager keybindings and mouse wheel support. A high performance mode is available pager keybindings and mouse wheel support. A high performance mode is available
for applications which make use of the alternate screen buffer. for applications which make use of the alternate screen buffer.
* [Example code](https://github.com/charmbracelet/bubbletea/tree/master/examples/pager/main.go) * [Example code](https://github.com/charmbracelet/tea/tree/master/examples/pager/main.go)
This component is well complemented with [Reflow][reflow] for ANSI-aware This component is well complemented with [Reflow][reflow] for ANSI-aware
indenting and text wrapping. indenting and text wrapping.
@@ -115,20 +99,16 @@ indenting and text wrapping.
## List ## List
<picture> <img src="https://stuff.charm.sh/bubbles-examples/list.gif" width="600" alt="List Example">
<source media="(max-width: 600px)" srcset="https://stuff.charm.sh/bubbles-examples/list.gif">
<source media="(min-width: 600px)" width="600" srcset="https://stuff.charm.sh/bubbles-examples/list.gif">
<img src="https://stuff.charm.sh/bubbles-examples/list.gif" alt="List Example">
</picture>
A customizable, batteries-included component for browsing a set of items. A customizable, batteries-included component for browsing a set of items.
Features pagination, fuzzy filtering, auto-generated help, an activity spinner, Features pagination, fuzzy filtering, auto-generated help, an activity spinner,
and status messages, all of which can be enabled and disabled as needed. and status messages, all of which can be enabled and disabled as needed.
Extrapolated from [Glow][glow]. Extrapolated from [Glow][glow].
* [Example code, default list](https://github.com/charmbracelet/bubbletea/tree/master/examples/list-default/main.go) * [Example code, default list](https://github.com/charmbracelet/tea/tree/master/examples/list-default/main.go)
* [Example code, simple list](https://github.com/charmbracelet/bubbletea/tree/master/examples/list-simple/main.go) * [Example code, simple list](https://github.com/charmbracelet/tea/tree/master/examples/list-simple/main.go)
* [Example code, all features](https://github.com/charmbracelet/bubbletea/tree/master/examples/list-fancy/main.go) * [Example code, all features](https://github.com/charmbracelet/tea/tree/master/examples/list-fancy/main.go)
## Timer ## Timer
@@ -153,11 +133,7 @@ can be customized as you see fit.
## Help ## Help
<picture> <img src="https://stuff.charm.sh/bubbles-examples/help.gif" width="500" alt="Help Example">
<source media="(max-width: 500px)" srcset="https://stuff.charm.sh/bubbles-examples/help.gif">
<source media="(min-width: 500px)" width="500" srcset="https://stuff.charm.sh/bubbles-examples/help.gif">
<img src="https://stuff.charm.sh/bubbles-examples/help.gif" alt="Help Example">
</picture>
A customizable horizontal mini help view that automatically generates itself A customizable horizontal mini help view that automatically generates itself
from your keybindings. It features single and multi-line modes, which the user from your keybindings. It features single and multi-line modes, which the user
@@ -236,7 +212,7 @@ If youve built a Bubble you think should be listed here,
## License ## License
[MIT](https://github.com/charmbracelet/bubbletea/raw/master/LICENSE) [MIT](https://github.com/charmbracelet/teaparty/raw/master/LICENSE)
*** ***

View File

@@ -70,8 +70,8 @@ type Model struct {
blinkCtx *blinkCtx blinkCtx *blinkCtx
// The ID of the blink message we're expecting to receive. // The ID of the blink message we're expecting to receive.
blinkTag int blinkTag int
// mode determines the behavior of the cursor // cursorMode determines the behavior of the cursor
mode Mode cursorMode Mode
} }
// New creates a new model with default settings. // New creates a new model with default settings.
@@ -80,7 +80,7 @@ func New() Model {
BlinkSpeed: defaultBlinkSpeed, BlinkSpeed: defaultBlinkSpeed,
Blink: true, Blink: true,
mode: CursorBlink, cursorMode: CursorBlink,
blinkCtx: &blinkCtx{ blinkCtx: &blinkCtx{
ctx: context.Background(), ctx: context.Background(),
@@ -94,7 +94,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
case initialBlinkMsg: case initialBlinkMsg:
// We accept all initialBlinkMsgs generated by the Blink command. // We accept all initialBlinkMsgs generated by the Blink command.
if m.mode != CursorBlink || !m.focus { if m.cursorMode != CursorBlink || !m.focus {
return m, nil return m, nil
} }
@@ -106,7 +106,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
// only exactly when it should. // only exactly when it should.
// Is this model blink-able? // Is this model blink-able?
if m.mode != CursorBlink || !m.focus { if m.cursorMode != CursorBlink || !m.focus {
return m, nil return m, nil
} }
@@ -116,7 +116,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
} }
var cmd tea.Cmd var cmd tea.Cmd
if m.mode == CursorBlink { if m.cursorMode == CursorBlink {
m.Blink = !m.Blink m.Blink = !m.Blink
cmd = m.BlinkCmd() cmd = m.BlinkCmd()
} }
@@ -128,18 +128,18 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
return m, nil return m, nil
} }
// Mode returns the model's cursor mode. For available cursor modes, see // CursorMode returns the model's cursor mode. For available cursor modes, see
// type Mode. // type CursorMode.
func (m Model) Mode() Mode { func (m Model) CursorMode() Mode {
return m.mode return m.cursorMode
} }
// SetMode sets the model's cursor mode. This method returns a command. // SetCursorMode sets the model's cursor mode. This method returns a command.
// //
// For available cursor modes, see type CursorMode. // For available cursor modes, see type CursorMode.
func (m *Model) SetMode(mode Mode) tea.Cmd { func (m *Model) SetCursorMode(mode Mode) tea.Cmd {
m.mode = mode m.cursorMode = mode
m.Blink = m.mode == CursorHide || !m.focus m.Blink = m.cursorMode == CursorHide || !m.focus
if mode == CursorBlink { if mode == CursorBlink {
return Blink return Blink
} }
@@ -148,7 +148,7 @@ func (m *Model) SetMode(mode Mode) tea.Cmd {
// BlinkCmd is an command used to manage cursor blinking. // BlinkCmd is an command used to manage cursor blinking.
func (m *Model) BlinkCmd() tea.Cmd { func (m *Model) BlinkCmd() tea.Cmd {
if m.mode != CursorBlink { if m.cursorMode != CursorBlink {
return nil return nil
} }
@@ -179,9 +179,9 @@ func Blink() tea.Msg {
// Focus focuses the cursor to allow it to blink if desired. // Focus focuses the cursor to allow it to blink if desired.
func (m *Model) Focus() tea.Cmd { func (m *Model) Focus() tea.Cmd {
m.focus = true m.focus = true
m.Blink = m.mode == CursorHide // show the cursor unless we've explicitly hidden it m.Blink = m.cursorMode == CursorHide // show the cursor unless we've explicitly hidden it
if m.mode == CursorBlink && m.focus { if m.cursorMode == CursorBlink && m.focus {
return m.BlinkCmd() return m.BlinkCmd()
} }
return nil return nil
@@ -201,7 +201,7 @@ func (m *Model) SetChar(char string) {
// View displays the cursor. // View displays the cursor.
func (m Model) View() string { func (m Model) View() string {
if m.Blink { if m.Blink {
return m.TextStyle.Inline(true).Render(m.char) return m.TextStyle.Render(m.char)
} }
return m.Style.Inline(true).Reverse(true).Render(m.char) return m.Style.Inline(true).Reverse(true).Render(m.char)
} }

18
go.mod
View File

@@ -1,16 +1,26 @@
module github.com/charmbracelet/bubbles module github.com/charmbracelet/bubbles
go 1.13 go 1.18
require ( require (
github.com/atotto/clipboard v0.1.4 github.com/atotto/clipboard v0.1.4
github.com/charmbracelet/bubbletea v0.21.0 github.com/charmbracelet/bubbletea v0.22.0
github.com/charmbracelet/harmonica v0.2.0 github.com/charmbracelet/harmonica v0.2.0
github.com/charmbracelet/lipgloss v0.5.0 github.com/charmbracelet/lipgloss v0.5.0
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 github.com/lucasb-eyer/go-colorful v1.2.0
github.com/mattn/go-runewidth v0.0.13 github.com/mattn/go-runewidth v0.0.13
github.com/muesli/reflow v0.3.0 github.com/muesli/reflow v0.3.0
github.com/muesli/termenv v0.11.1-0.20220212125758-44cd13922739 github.com/muesli/termenv v0.12.0
github.com/sahilm/fuzzy v0.1.0 github.com/sahilm/fuzzy v0.1.0
) )
require (
github.com/containerd/console v1.0.3 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect
github.com/muesli/cancelreader v0.2.1 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
)

14
go.sum
View File

@@ -1,7 +1,7 @@
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/charmbracelet/bubbletea v0.21.0 h1:f3y+kanzgev5PA916qxmDybSHU3N804uOnKnhRPXTcI= github.com/charmbracelet/bubbletea v0.22.0 h1:E1BTNSE3iIrq0G0X6TjGAmrQ32cGCbFDPcIuImikrUc=
github.com/charmbracelet/bubbletea v0.21.0/go.mod h1:GgmJMec61d08zXsOhqRC/AiOx4K4pmz+VIcRIm1FKr4= github.com/charmbracelet/bubbletea v0.22.0/go.mod h1:aoVIwlNlr5wbCB26KhxfrqAn0bMp4YpJcoOelbxApjs=
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ= github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
github.com/charmbracelet/lipgloss v0.5.0 h1:lulQHuVeodSgDez+3rGiuxlPVXSnhth442DATR2/8t8= github.com/charmbracelet/lipgloss v0.5.0 h1:lulQHuVeodSgDez+3rGiuxlPVXSnhth442DATR2/8t8=
@@ -20,19 +20,17 @@ github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34= github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho= github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=
github.com/muesli/cancelreader v0.2.0 h1:SOpr+CfyVNce341kKqvbhhzQhBPyJRXQaCtn03Pae1Q= github.com/muesli/cancelreader v0.2.1 h1:Xzd1B4U5bWQOuSKuN398MyynIGTNT89dxzpEDsalXZs=
github.com/muesli/cancelreader v0.2.0/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/cancelreader v0.2.1/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ= github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ=
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs= github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs=
github.com/muesli/termenv v0.11.1-0.20220212125758-44cd13922739 h1:QANkGiGr39l1EESqrE0gZw0/AJNYzIvoGLhIoVYtluI=
github.com/muesli/termenv v0.11.1-0.20220212125758-44cd13922739/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs= github.com/muesli/termenv v0.11.1-0.20220212125758-44cd13922739/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/muesli/termenv v0.12.0 h1:KuQRUE3PgxRFWhq4gHvZtPSLCGDqM5q/cYr1pZ39ytc=
github.com/muesli/termenv v0.12.0/go.mod h1:WCCv32tusQ/EEZ5S8oUIIrC/nIuBcxCVqlN4Xfkv+7A=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI= github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=
github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=

View File

@@ -106,7 +106,7 @@ func (b Binding) Help() Help {
// keybindings won't be activated and won't show up in help. Keybindings are // keybindings won't be activated and won't show up in help. Keybindings are
// enabled by default. // enabled by default.
func (b Binding) Enabled() bool { func (b Binding) Enabled() bool {
return !b.disabled && b.keys != nil return !b.disabled || b.keys == nil
} }
// SetEnabled enables or disables the keybinding. // SetEnabled enables or disables the keybinding.
@@ -130,10 +130,9 @@ type Help struct {
// Matches checks if the given KeyMsg matches the given bindings. // Matches checks if the given KeyMsg matches the given bindings.
func Matches(k tea.KeyMsg, b ...Binding) bool { func Matches(k tea.KeyMsg, b ...Binding) bool {
keys := k.String()
for _, binding := range b { for _, binding := range b {
for _, v := range binding.keys { for _, v := range binding.keys {
if keys == v && binding.Enabled() { if k.String() == v && binding.Enabled() {
return true return true
} }
} }

View File

@@ -1,26 +0,0 @@
package key
import (
"testing"
)
func TestBinding_Enabled(t *testing.T) {
binding := NewBinding(
WithKeys("k", "up"),
WithHelp("↑/k", "move up"),
)
if !binding.Enabled() {
t.Errorf("expected key to be Enabled")
}
binding.SetEnabled(false)
if binding.Enabled() {
t.Errorf("expected key not to be Enabled")
}
binding.SetEnabled(true)
binding.Unbind()
if binding.Enabled() {
t.Errorf("expected key not to be Enabled")
}
}

View File

@@ -1,399 +0,0 @@
package table
import (
"strings"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/mattn/go-runewidth"
)
// Model defines a state for the table widget.
type Model struct {
KeyMap KeyMap
cols []Column
rows []Row
cursor int
focus bool
styles Styles
viewport viewport.Model
}
// Row represents one line in the table.
type Row []string
// Column defines the table structure.
type Column struct {
Title string
Width int
}
// KeyMap defines keybindings. It satisfies to the help.KeyMap interface, which
// is used to render the menu menu.
type KeyMap struct {
LineUp key.Binding
LineDown key.Binding
PageUp key.Binding
PageDown key.Binding
HalfPageUp key.Binding
HalfPageDown key.Binding
GotoTop key.Binding
GotoBottom key.Binding
}
// DefaultKeyMap returns a default set of keybindings.
func DefaultKeyMap() KeyMap {
const spacebar = " "
return KeyMap{
LineUp: key.NewBinding(
key.WithKeys("up", "k"),
key.WithHelp("↑/k", "up"),
),
LineDown: key.NewBinding(
key.WithKeys("down", "j"),
key.WithHelp("↓/j", "down"),
),
PageUp: key.NewBinding(
key.WithKeys("b", "pgup"),
key.WithHelp("b/pgup", "page up"),
),
PageDown: key.NewBinding(
key.WithKeys("f", "pgdown", spacebar),
key.WithHelp("f/pgdn", "page down"),
),
HalfPageUp: key.NewBinding(
key.WithKeys("u", "ctrl+u"),
key.WithHelp("u", "½ page up"),
),
HalfPageDown: key.NewBinding(
key.WithKeys("d", "ctrl+d"),
key.WithHelp("d", "½ page down"),
),
GotoTop: key.NewBinding(
key.WithKeys("home", "g"),
key.WithHelp("g/home", "go to start"),
),
GotoBottom: key.NewBinding(
key.WithKeys("end", "G"),
key.WithHelp("G/end", "go to end"),
),
}
}
// Styles contains style definitions for this list component. By default, these
// values are generated by DefaultStyles.
type Styles struct {
Header lipgloss.Style
Cell lipgloss.Style
Selected lipgloss.Style
}
// DefaultStyles returns a set of default style definitions for this table.
func DefaultStyles() Styles {
return Styles{
Selected: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("212")),
Header: lipgloss.NewStyle().Bold(true).Padding(0, 1),
Cell: lipgloss.NewStyle().Padding(0, 1),
}
}
// SetStyles sets the table styles.
func (m *Model) SetStyles(s Styles) {
m.styles = s
m.UpdateViewport()
}
// Option is used to set options in New. For example:
//
// table := New(WithColumns([]Column{{Title: "ID", Width: 10}}))
//
type Option func(*Model)
// New creates a new model for the table widget.
func New(opts ...Option) Model {
m := Model{
cursor: 0,
viewport: viewport.New(0, 20),
KeyMap: DefaultKeyMap(),
styles: DefaultStyles(),
}
for _, opt := range opts {
opt(&m)
}
m.UpdateViewport()
return m
}
// WithColumns sets the table columns (headers).
func WithColumns(cols []Column) Option {
return func(m *Model) {
m.cols = cols
}
}
// WithRows sets the table rows (data).
func WithRows(rows []Row) Option {
return func(m *Model) {
m.rows = rows
}
}
// WithHeight sets the height of the table.
func WithHeight(h int) Option {
return func(m *Model) {
m.viewport.Height = h
}
}
// WithWidth sets the width of the table.
func WithWidth(w int) Option {
return func(m *Model) {
m.viewport.Width = w
}
}
// WithFocused sets the focus state of the table.
func WithFocused(f bool) Option {
return func(m *Model) {
m.focus = f
}
}
// WithStyles sets the table styles.
func WithStyles(s Styles) Option {
return func(m *Model) {
m.styles = s
}
}
// WithKeyMap sets the key map.
func WithKeyMap(km KeyMap) Option {
return func(m *Model) {
m.KeyMap = km
}
}
// Update is the Bubble Tea update loop.
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
if !m.focus {
return m, nil
}
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case key.Matches(msg, m.KeyMap.LineUp):
m.MoveUp(1)
case key.Matches(msg, m.KeyMap.LineDown):
m.MoveDown(1)
case key.Matches(msg, m.KeyMap.PageUp):
m.MoveUp(m.viewport.Height)
case key.Matches(msg, m.KeyMap.PageDown):
m.MoveDown(m.viewport.Height)
case key.Matches(msg, m.KeyMap.HalfPageUp):
m.MoveUp(m.viewport.Height / 2)
case key.Matches(msg, m.KeyMap.HalfPageDown):
m.MoveDown(m.viewport.Height / 2)
case key.Matches(msg, m.KeyMap.LineDown):
m.MoveDown(1)
case key.Matches(msg, m.KeyMap.GotoTop):
m.GotoTop()
case key.Matches(msg, m.KeyMap.GotoBottom):
m.GotoBottom()
}
}
return m, tea.Batch(cmds...)
}
// Focused returns the focus state of the table.
func (m Model) Focused() bool {
return m.focus
}
// Focus focusses the table, allowing the user to move around the rows and
// interact.
func (m *Model) Focus() {
m.focus = true
m.UpdateViewport()
}
// Blur blurs the table, preventing selection or movement.
func (m *Model) Blur() {
m.focus = false
m.UpdateViewport()
}
// View renders the component.
func (m Model) View() string {
return m.headersView() + "\n" + m.viewport.View()
}
// UpdateViewport updates the list content based on the previously defined
// columns and rows.
func (m *Model) UpdateViewport() {
renderedRows := make([]string, 0, len(m.rows))
for i := range m.rows {
renderedRows = append(renderedRows, m.renderRow(i))
}
m.viewport.SetContent(
lipgloss.JoinVertical(lipgloss.Left, renderedRows...),
)
}
// SelectedRow returns the selected row.
// You can cast it to your own implementation.
func (m Model) SelectedRow() Row {
return m.rows[m.cursor]
}
// SetRows set a new rows state.
func (m *Model) SetRows(r []Row) {
m.rows = r
m.UpdateViewport()
}
// SetColumns set a new columns state.
func (m *Model) SetColumns(c []Column) {
m.cols = c
m.UpdateViewport()
}
// SetWidth sets the width of the viewport of the table.
func (m *Model) SetWidth(w int) {
m.viewport.Width = w
m.UpdateViewport()
}
// SetHeight sets the height of the viewport of the table.
func (m *Model) SetHeight(h int) {
m.viewport.Height = h
m.UpdateViewport()
}
// Height returns the viewport height of the table.
func (m Model) Height() int {
return m.viewport.Height
}
// Width returns the viewport width of the table.
func (m Model) Width() int {
return m.viewport.Width
}
// Cursor returns the index of the selected row.
func (m Model) Cursor() int {
return m.cursor
}
// SetCursor sets the cursor position in the table.
func (m *Model) SetCursor(n int) {
m.cursor = clamp(n, 0, len(m.rows)-1)
m.UpdateViewport()
}
// MoveUp moves the selection up by any number of row.
// It can not go above the first row.
func (m *Model) MoveUp(n int) {
m.cursor = clamp(m.cursor-n, 0, len(m.rows)-1)
m.UpdateViewport()
if m.cursor < m.viewport.YOffset {
m.viewport.SetYOffset(m.cursor)
}
}
// MoveDown moves the selection down by any number of row.
// It can not go below the last row.
func (m *Model) MoveDown(n int) {
m.cursor = clamp(m.cursor+n, 0, len(m.rows)-1)
m.UpdateViewport()
if m.cursor > (m.viewport.YOffset + (m.viewport.Height - 1)) {
m.viewport.SetYOffset(m.cursor - (m.viewport.Height - 1))
}
}
// GotoTop moves the selection to the first row.
func (m *Model) GotoTop() {
m.MoveUp(m.cursor)
}
// GotoBottom moves the selection to the last row.
func (m *Model) GotoBottom() {
m.MoveDown(len(m.rows))
}
// FromValues create the table rows from a simple string. It uses `\n` by
// default for getting all the rows and the given separator for the fields on
// each row.
func (m *Model) FromValues(value, separator string) {
rows := []Row{}
for _, line := range strings.Split(value, "\n") {
r := Row{}
for _, field := range strings.Split(line, separator) {
r = append(r, field)
}
rows = append(rows, r)
}
m.SetRows(rows)
}
func (m Model) headersView() string {
var s = make([]string, 0, len(m.cols))
for _, col := range m.cols {
style := lipgloss.NewStyle().Width(col.Width).MaxWidth(col.Width).Inline(true)
renderedCell := style.Render(runewidth.Truncate(col.Title, col.Width, "…"))
s = append(s, m.styles.Header.Render(renderedCell))
}
return lipgloss.JoinHorizontal(lipgloss.Left, s...)
}
func (m *Model) renderRow(rowID int) string {
var s = make([]string, 0, len(m.cols))
for i, value := range m.rows[rowID] {
style := lipgloss.NewStyle().Width(m.cols[i].Width).MaxWidth(m.cols[i].Width).Inline(true)
renderedCell := m.styles.Cell.Render(style.Render(runewidth.Truncate(value, m.cols[i].Width, "…")))
s = append(s, renderedCell)
}
row := lipgloss.JoinHorizontal(lipgloss.Left, s...)
if rowID == m.cursor {
return m.styles.Selected.Render(row)
}
return row
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func clamp(v, low, high int) int {
return min(max(v, low), high)
}

View File

@@ -1,54 +0,0 @@
package table
import "testing"
func TestFromValues(t *testing.T) {
input := "foo1,bar1\nfoo2,bar2\nfoo3,bar3"
table := New(WithColumns([]Column{{Title: "Foo"}, {Title: "Bar"}}))
table.FromValues(input, ",")
if len(table.rows) != 3 {
t.Fatalf("expect table to have 3 rows but it has %d", len(table.rows))
}
expect := []Row{
{"foo1", "bar1"},
{"foo2", "bar2"},
{"foo3", "bar3"},
}
if !deepEqual(table.rows, expect) {
t.Fatal("table rows is not equals to the input")
}
}
func TestFromValuesWithTabSeparator(t *testing.T) {
input := "foo1.\tbar1\nfoo,bar,baz\tbar,2"
table := New(WithColumns([]Column{{Title: "Foo"}, {Title: "Bar"}}))
table.FromValues(input, "\t")
if len(table.rows) != 2 {
t.Fatalf("expect table to have 2 rows but it has %d", len(table.rows))
}
expect := []Row{
{"foo1.", "bar1"},
{"foo,bar,baz", "bar,2"},
}
if !deepEqual(table.rows, expect) {
t.Fatal("table rows is not equals to the input")
}
}
func deepEqual(a, b []Row) bool {
if len(a) != len(b) {
return false
}
for i, r := range a {
for j, f := range r {
if f != b[i][j] {
return false
}
}
}
return true
}

View File

@@ -6,7 +6,7 @@ import (
"unicode" "unicode"
"github.com/atotto/clipboard" "github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/internal/cursor" "github.com/charmbracelet/bubbles/cursor"
"github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/viewport" "github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
@@ -46,14 +46,6 @@ type KeyMap struct {
Paste key.Binding Paste key.Binding
WordBackward key.Binding WordBackward key.Binding
WordForward key.Binding WordForward key.Binding
InputBegin key.Binding
InputEnd key.Binding
UppercaseWordForward key.Binding
LowercaseWordForward key.Binding
CapitalizeWordForward key.Binding
TransposeCharacterBackward key.Binding
} }
// DefaultKeyMap is the default set of key bindings for navigating and acting // DefaultKeyMap is the default set of key bindings for navigating and acting
@@ -75,14 +67,6 @@ var DefaultKeyMap = KeyMap{
LineStart: key.NewBinding(key.WithKeys("home", "ctrl+a")), LineStart: key.NewBinding(key.WithKeys("home", "ctrl+a")),
LineEnd: key.NewBinding(key.WithKeys("end", "ctrl+e")), LineEnd: key.NewBinding(key.WithKeys("end", "ctrl+e")),
Paste: key.NewBinding(key.WithKeys("ctrl+v")), Paste: key.NewBinding(key.WithKeys("ctrl+v")),
InputBegin: key.NewBinding(key.WithKeys("alt+<", "ctrl+home")),
InputEnd: key.NewBinding(key.WithKeys("alt+>", "ctrl+end")),
CapitalizeWordForward: key.NewBinding(key.WithKeys("alt+c")),
LowercaseWordForward: key.NewBinding(key.WithKeys("alt+l")),
UppercaseWordForward: key.NewBinding(key.WithKeys("alt+u")),
TransposeCharacterBackward: key.NewBinding(key.WithKeys("ctrl+t")),
} }
// LineInfo is a helper for keeping track of line information regarding // LineInfo is a helper for keeping track of line information regarding
@@ -133,27 +117,10 @@ type Model struct {
Err error Err error
// General settings. // General settings.
// Prompt is printed at the beginning of each line.
//
// When changing the value of Prompt after the model has been
// initialized, ensure that SetWidth() gets called afterwards.
//
// See also SetPromptFunc().
Prompt string Prompt string
// Placeholder is the text displayed when the user
// hasn't entered anything yet.
Placeholder string Placeholder string
// ShowLineNumbers, if enabled, causes line numbers to be printed
// after the prompt.
ShowLineNumbers bool ShowLineNumbers bool
// EndOfBufferCharacter is displayed at the end of the input.
EndOfBufferCharacter rune EndOfBufferCharacter rune
// KeyMap encodes the keybindings recognized by the widget.
KeyMap KeyMap KeyMap KeyMap
// Styling. FocusedStyle and BlurredStyle are used to style the textarea in // Styling. FocusedStyle and BlurredStyle are used to style the textarea in
@@ -173,13 +140,6 @@ type Model struct {
// accept. If 0 or less, there's no limit. // accept. If 0 or less, there's no limit.
CharLimit int CharLimit int
// If promptFunc is set, it replaces Prompt as a generator for
// prompt strings at the beginning of each line.
promptFunc func(line int) string
// promptWidth is the width of the prompt.
promptWidth int
// width is the maximum number of characters that can be displayed at once. // width is the maximum number of characters that can be displayed at once.
// If 0 or less this setting is ignored. // If 0 or less this setting is ignored.
width int width int
@@ -233,7 +193,7 @@ func New() Model {
Cursor: cur, Cursor: cur,
KeyMap: DefaultKeyMap, KeyMap: DefaultKeyMap,
value: make([][]rune, minHeight, maxHeight), value: make([][]rune, minHeight, maxWidth),
focus: false, focus: false,
col: 0, col: 0,
row: 0, row: 0,
@@ -257,7 +217,7 @@ func DefaultStyles() (Style, Style) {
CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "240"}), CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "240"}),
EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}), EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}),
LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}), LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("240")), Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")), Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Text: lipgloss.NewStyle(), Text: lipgloss.NewStyle(),
} }
@@ -267,7 +227,7 @@ func DefaultStyles() (Style, Style) {
CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}), CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}), EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}),
LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}), LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("240")), Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")), Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Text: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "245", Dark: "7"}), Text: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "245", Dark: "7"}),
} }
@@ -311,13 +271,13 @@ func (m Model) Value() string {
return "" return ""
} }
var v strings.Builder var v string
for _, l := range m.value { for _, l := range m.value {
v.WriteString(string(l)) v += string(l)
v.WriteByte('\n') v += "\n"
} }
return strings.TrimSuffix(v.String(), "\n") return strings.TrimSuffix(v, "\n")
} }
// Length returns the number of characters currently in the text input. // Length returns the number of characters currently in the text input.
@@ -326,12 +286,7 @@ func (m *Model) Length() int {
for _, row := range m.value { for _, row := range m.value {
l += rw.StringWidth(string(row)) l += rw.StringWidth(string(row))
} }
return l + len(m.value) - 1 return l
}
// LineCount returns the number of lines that are currently in the text input.
func (m *Model) LineCount() int {
return len(m.value)
} }
// Line returns the line position. // Line returns the line position.
@@ -449,7 +404,7 @@ func (m *Model) Blur() {
// Reset sets the input to its default state with no input. // Reset sets the input to its default state with no input.
func (m *Model) Reset() { func (m *Model) Reset() {
m.value = make([][]rune, minHeight, maxHeight) m.value = make([][]rune, minHeight, maxWidth)
m.col = 0 m.col = 0
m.row = 0 m.row = 0
m.viewport.GotoTop() m.viewport.GotoTop()
@@ -513,24 +468,6 @@ func (m *Model) deleteAfterCursor() {
m.SetCursor(len(m.value[m.row])) m.SetCursor(len(m.value[m.row]))
} }
// transposeLeft exchanges the runes at the cursor and immediately
// before. No-op if the cursor is at the beginning of the line. If
// the cursor is not at the end of the line yet, moves the cursor to
// the right.
func (m *Model) transposeLeft() {
if m.col == 0 || len(m.value[m.row]) < 2 {
return
}
if m.col >= len(m.value[m.row]) {
m.SetCursor(m.col - 1)
}
m.value[m.row][m.col-1], m.value[m.row][m.col] =
m.value[m.row][m.col], m.value[m.row][m.col-1]
if m.col < len(m.value[m.row]) {
m.SetCursor(m.col + 1)
}
}
// deleteWordLeft deletes the word left to the cursor. Returns whether or not // deleteWordLeft deletes the word left to the cursor. Returns whether or not
// the cursor blink should be reset. // the cursor blink should be reset.
func (m *Model) deleteWordLeft() { func (m *Model) deleteWordLeft() {
@@ -605,50 +542,31 @@ func (m *Model) deleteWordRight() {
m.SetCursor(oldCol) m.SetCursor(oldCol)
} }
// characterRight moves the cursor one character to the right.
func (m *Model) characterRight() {
if m.col < len(m.value[m.row]) {
m.SetCursor(m.col + 1)
} else {
if m.row < len(m.value)-1 {
m.row++
m.CursorStart()
}
}
}
// characterLeft moves the cursor one character to the left.
// If insideLine is set, the cursor is moved to the last
// character in the previous line, instead of one past that.
func (m *Model) characterLeft(insideLine bool) {
if m.col == 0 && m.row != 0 {
m.row--
m.CursorEnd()
if !insideLine {
return
}
}
if m.col > 0 {
m.SetCursor(m.col - 1)
}
}
// wordLeft moves the cursor one word to the left. Returns whether or not the // wordLeft moves the cursor one word to the left. Returns whether or not the
// cursor blink should be reset. If input is masked, move input to the start // cursor blink should be reset. If input is masked, move input to the start
// so as not to reveal word breaks in the masked input. // so as not to reveal word breaks in the masked input.
func (m *Model) wordLeft() { func (m *Model) wordLeft() {
for { if m.col == 0 || len(m.value[m.row]) == 0 {
m.characterLeft(true /* insideLine */) return
if m.col < len(m.value[m.row]) && !unicode.IsSpace(m.value[m.row][m.col]) { }
i := m.col - 1
for i >= 0 {
if unicode.IsSpace(m.value[m.row][min(i, len(m.value[m.row])-1)]) {
m.SetCursor(m.col - 1)
i--
} else {
break break
} }
} }
for m.col > 0 { for i >= 0 {
if unicode.IsSpace(m.value[m.row][m.col-1]) { if !unicode.IsSpace(m.value[m.row][min(i, len(m.value[m.row])-1)]) {
m.SetCursor(m.col - 1)
i--
} else {
break break
} }
m.SetCursor(m.col - 1)
} }
} }
@@ -656,54 +574,28 @@ func (m *Model) wordLeft() {
// cursor blink should be reset. If the input is masked, move input to the end // cursor blink should be reset. If the input is masked, move input to the end
// so as not to reveal word breaks in the masked input. // so as not to reveal word breaks in the masked input.
func (m *Model) wordRight() { func (m *Model) wordRight() {
m.doWordRight(func(int, int) { /* nothing */ }) if m.col >= len(m.value[m.row]) || len(m.value[m.row]) == 0 {
} return
func (m *Model) doWordRight(fn func(charIdx int, pos int)) {
// Skip spaces forward.
for {
if m.col < len(m.value[m.row]) && !unicode.IsSpace(m.value[m.row][m.col]) {
break
}
if m.row == len(m.value)-1 && m.col == len(m.value[m.row]) {
// End of text.
break
}
m.characterRight()
} }
charIdx := 0 i := m.col
for m.col < len(m.value[m.row]) { for i < len(m.value[m.row]) {
if unicode.IsSpace(m.value[m.row][m.col]) { if unicode.IsSpace(m.value[m.row][i]) {
break
}
fn(charIdx, m.col)
m.SetCursor(m.col + 1) m.SetCursor(m.col + 1)
charIdx++ i++
} else {
break
}
}
for i < len(m.value[m.row]) {
if !unicode.IsSpace(m.value[m.row][i]) {
m.SetCursor(m.col + 1)
i++
} else {
break
} }
}
// uppercaseRight changes the word to the right to uppercase.
func (m *Model) uppercaseRight() {
m.doWordRight(func(_ int, i int) {
m.value[m.row][i] = unicode.ToUpper(m.value[m.row][i])
})
}
// lowercaseRight changes the word to the right to lowercase.
func (m *Model) lowercaseRight() {
m.doWordRight(func(_ int, i int) {
m.value[m.row][i] = unicode.ToLower(m.value[m.row][i])
})
}
// capitalizeRight changes the word to the right to title case.
func (m *Model) capitalizeRight() {
m.doWordRight(func(charIdx int, i int) {
if charIdx == 0 {
m.value[m.row][i] = unicode.ToTitle(m.value[m.row][i])
} }
})
} }
// LineInfo returns the number of characters from the start of the // LineInfo returns the number of characters from the start of the
@@ -765,18 +657,6 @@ func (m Model) Width() int {
return m.width return m.width
} }
// moveToBegin moves the cursor to the beginning of the input.
func (m *Model) moveToBegin() {
m.row = 0
m.SetCursor(0)
}
// moveToEnd moves the cursor to the end of the input.
func (m *Model) moveToEnd() {
m.row = len(m.value) - 1
m.SetCursor(len(m.value[m.row]))
}
// SetWidth sets the width of the textarea to fit exactly within the given width. // SetWidth sets the width of the textarea to fit exactly within the given width.
// This means that the textarea will account for the width of the prompt and // This means that the textarea will account for the width of the prompt and
// whether or not line numbers are being shown. // whether or not line numbers are being shown.
@@ -797,26 +677,10 @@ func (m *Model) SetWidth(w int) {
// Account for base style borders and padding. // Account for base style borders and padding.
inputWidth -= m.style.Base.GetHorizontalFrameSize() inputWidth -= m.style.Base.GetHorizontalFrameSize()
if m.promptFunc == nil { inputWidth -= rw.StringWidth(m.Prompt)
m.promptWidth = rw.StringWidth(m.Prompt)
}
inputWidth -= m.promptWidth
m.width = clamp(inputWidth, minWidth, maxWidth) m.width = clamp(inputWidth, minWidth, maxWidth)
} }
// SetPromptFunc supersedes the Prompt field and sets a dynamic prompt
// instead.
// If the function returns a prompt that is shorter than the
// specified promptWidth, it will be padded to the left.
// If it returns a prompt that is longer, display artifacts
// may occur; the caller is responsible for computing an adequate
// promptWidth.
func (m *Model) SetPromptFunc(promptWidth int, fn func(lineIdx int) string) {
m.promptFunc = fn
m.promptWidth = promptWidth
}
// Height returns the current height of the textarea. // Height returns the current height of the textarea.
func (m Model) Height() int { func (m Model) Height() int {
return m.height return m.height
@@ -905,7 +769,14 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
case key.Matches(msg, m.KeyMap.LineStart): case key.Matches(msg, m.KeyMap.LineStart):
m.CursorStart() m.CursorStart()
case key.Matches(msg, m.KeyMap.CharacterForward): case key.Matches(msg, m.KeyMap.CharacterForward):
m.characterRight() if m.col < len(m.value[m.row]) {
m.SetCursor(m.col + 1)
} else {
if m.row < len(m.value)-1 {
m.row++
m.CursorStart()
}
}
case key.Matches(msg, m.KeyMap.LineNext): case key.Matches(msg, m.KeyMap.LineNext):
m.CursorDown() m.CursorDown()
case key.Matches(msg, m.KeyMap.WordForward): case key.Matches(msg, m.KeyMap.WordForward):
@@ -913,26 +784,20 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
case key.Matches(msg, m.KeyMap.Paste): case key.Matches(msg, m.KeyMap.Paste):
return m, Paste return m, Paste
case key.Matches(msg, m.KeyMap.CharacterBackward): case key.Matches(msg, m.KeyMap.CharacterBackward):
m.characterLeft(false /* insideLine */) if m.col == 0 && m.row != 0 {
m.row--
m.CursorEnd()
break
}
if m.col > 0 {
m.SetCursor(m.col - 1)
}
case key.Matches(msg, m.KeyMap.LinePrevious): case key.Matches(msg, m.KeyMap.LinePrevious):
m.CursorUp() m.CursorUp()
case key.Matches(msg, m.KeyMap.WordBackward): case key.Matches(msg, m.KeyMap.WordBackward):
m.wordLeft() m.wordLeft()
case key.Matches(msg, m.KeyMap.InputBegin):
m.moveToBegin()
case key.Matches(msg, m.KeyMap.InputEnd):
m.moveToEnd()
case key.Matches(msg, m.KeyMap.LowercaseWordForward):
m.lowercaseRight()
case key.Matches(msg, m.KeyMap.UppercaseWordForward):
m.uppercaseRight()
case key.Matches(msg, m.KeyMap.CapitalizeWordForward):
m.capitalizeRight()
case key.Matches(msg, m.KeyMap.TransposeCharacterBackward):
m.transposeLeft()
default: default:
if m.CharLimit > 0 && rw.StringWidth(m.Value()) >= m.CharLimit { if rw.StringWidth(m.Value()) >= m.CharLimit {
break break
} }
@@ -978,7 +843,6 @@ func (m Model) View() string {
var newLines int var newLines int
displayLine := 0
for l, line := range m.value { for l, line := range m.value {
wrappedLines := wrap(line, m.width) wrappedLines := wrap(line, m.width)
@@ -989,10 +853,7 @@ func (m Model) View() string {
} }
for wl, wrappedLine := range wrappedLines { for wl, wrappedLine := range wrappedLines {
prompt := m.getPromptString(displayLine) s.WriteString(style.Render(m.style.Prompt.Render(m.Prompt)))
prompt = m.style.Prompt.Render(prompt)
s.WriteString(style.Render(prompt))
displayLine++
if m.ShowLineNumbers { if m.ShowLineNumbers {
if wl == 0 { if wl == 0 {
@@ -1041,10 +902,7 @@ func (m Model) View() string {
// Always show at least `m.Height` lines at all times. // Always show at least `m.Height` lines at all times.
// To do this we can simply pad out a few extra new lines in the view. // To do this we can simply pad out a few extra new lines in the view.
for i := 0; i < m.height; i++ { for i := 0; i < m.height; i++ {
prompt := m.getPromptString(displayLine) s.WriteString(m.style.Prompt.Render(m.Prompt))
prompt = m.style.Prompt.Render(prompt)
s.WriteString(prompt)
displayLine++
if m.ShowLineNumbers { if m.ShowLineNumbers {
lineNumber := m.style.EndOfBuffer.Render((fmt.Sprintf(m.lineNumberFormat, string(m.EndOfBufferCharacter)))) lineNumber := m.style.EndOfBuffer.Render((fmt.Sprintf(m.lineNumberFormat, string(m.EndOfBufferCharacter))))
@@ -1057,19 +915,6 @@ func (m Model) View() string {
return m.style.Base.Render(m.viewport.View()) return m.style.Base.Render(m.viewport.View())
} }
func (m Model) getPromptString(displayLine int) (prompt string) {
prompt = m.Prompt
if m.promptFunc == nil {
return prompt
}
prompt = m.promptFunc(displayLine)
pl := rw.StringWidth(prompt)
if pl < m.promptWidth {
prompt = fmt.Sprintf("%*s%s", m.promptWidth-pl, "", prompt)
}
return prompt
}
// placeholderView returns the prompt and placeholder view, if any. // placeholderView returns the prompt and placeholder view, if any.
func (m Model) placeholderView() string { func (m Model) placeholderView() string {
var ( var (
@@ -1078,8 +923,7 @@ func (m Model) placeholderView() string {
style = m.style.Placeholder.Inline(true) style = m.style.Placeholder.Inline(true)
) )
prompt := m.getPromptString(0) prompt := m.style.Prompt.Render(m.Prompt)
prompt = m.style.Prompt.Render(prompt)
s.WriteString(m.style.CursorLine.Render(prompt)) s.WriteString(m.style.CursorLine.Render(prompt))
if m.ShowLineNumbers { if m.ShowLineNumbers {
@@ -1096,8 +940,6 @@ func (m Model) placeholderView() string {
// The rest of the new lines // The rest of the new lines
for i := 1; i < m.height; i++ { for i := 1; i < m.height; i++ {
s.WriteRune('\n') s.WriteRune('\n')
prompt := m.getPromptString(i)
prompt = m.style.Prompt.Render(prompt)
s.WriteString(prompt) s.WriteString(prompt)
if m.ShowLineNumbers { if m.ShowLineNumbers {

View File

@@ -1,17 +1,48 @@
package textinput package textinput
import ( import (
"context"
"strings" "strings"
"sync"
"time" "time"
"unicode" "unicode"
"github.com/atotto/clipboard" "github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/internal/cursor"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss" "github.com/charmbracelet/lipgloss"
rw "github.com/mattn/go-runewidth" rw "github.com/mattn/go-runewidth"
) )
const defaultBlinkSpeed = time.Millisecond * 530
// Internal ID management for text inputs. Necessary for blink integrity when
// multiple text inputs are involved.
var (
lastID int
idMtx sync.Mutex
)
// Return the next ID we should use on the Model.
func nextID() int {
idMtx.Lock()
defer idMtx.Unlock()
lastID++
return lastID
}
// initialBlinkMsg initializes cursor blinking.
type initialBlinkMsg struct{}
// blinkMsg signals that the cursor should blink. It contains metadata that
// allows us to tell if the blink message is the one we're expecting.
type blinkMsg struct {
id int
tag int
}
// blinkCanceled is sent when a blink operation is canceled.
type blinkCanceled struct{}
// Internal messages for clipboard operations. // Internal messages for clipboard operations.
type pasteMsg string type pasteMsg string
type pasteErrMsg struct{ error } type pasteErrMsg struct{ error }
@@ -34,6 +65,32 @@ const (
// EchoOnEdit. // EchoOnEdit.
) )
// blinkCtx manages cursor blinking.
type blinkCtx struct {
ctx context.Context
cancel context.CancelFunc
}
// CursorMode describes the behavior of the cursor.
type CursorMode int
// Available cursor modes.
const (
CursorBlink CursorMode = iota
CursorStatic
CursorHide
)
// String returns a the cursor mode in a human-readable format. This method is
// provisional and for informational purposes only.
func (c CursorMode) String() string {
return [...]string{
"blink",
"static",
"hidden",
}[c]
}
// ValidateFunc is a function that returns an error if the input is invalid. // ValidateFunc is a function that returns an error if the input is invalid.
type ValidateFunc func(string) error type ValidateFunc func(string) error
@@ -44,13 +101,9 @@ type Model struct {
// General settings. // General settings.
Prompt string Prompt string
Placeholder string Placeholder string
BlinkSpeed time.Duration
EchoMode EchoMode EchoMode EchoMode
EchoCharacter rune EchoCharacter rune
Cursor cursor.Model
// Deprecated: use cursor.BlinkSpeed instead.
// This is unused and will be removed in the future.
BlinkSpeed time.Duration
// Styles. These will be applied as inline styles. // Styles. These will be applied as inline styles.
// //
@@ -71,6 +124,12 @@ type Model struct {
// viewport. If 0 or less this setting is ignored. // viewport. If 0 or less this setting is ignored.
Width int Width int
// The ID of this Model as it relates to other textinput Models.
id int
// The ID of the blink message we're expecting to receive.
blinkTag int
// Underlying text value. // Underlying text value.
value []rune value []rune
@@ -78,6 +137,9 @@ type Model struct {
// component. When false, ignore keyboard input and hide the cursor. // component. When false, ignore keyboard input and hide the cursor.
focus bool focus bool
// Cursor blink state.
blink bool
// Cursor position. // Cursor position.
pos int pos int
@@ -86,6 +148,12 @@ type Model struct {
offset int offset int
offsetRight int offsetRight int
// Used to manage cursor blink
blinkCtx *blinkCtx
// cursorMode determines the behavior of the cursor
cursorMode CursorMode
// Validate is a function that checks whether or not the text within the // Validate is a function that checks whether or not the text within the
// input is valid. If it is not valid, the `Err` field will be set to the // input is valid. If it is not valid, the `Err` field will be set to the
// error returned by the function. If the function is not defined, all // error returned by the function. If the function is not defined, all
@@ -97,14 +165,21 @@ type Model struct {
func New() Model { func New() Model {
return Model{ return Model{
Prompt: "> ", Prompt: "> ",
BlinkSpeed: defaultBlinkSpeed,
EchoCharacter: '*', EchoCharacter: '*',
CharLimit: 0, CharLimit: 0,
PlaceholderStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("240")), PlaceholderStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
Cursor: cursor.New(),
id: nextID(),
value: nil, value: nil,
focus: false, focus: false,
blink: true,
pos: 0, pos: 0,
cursorMode: CursorBlink,
blinkCtx: &blinkCtx{
ctx: context.Background(),
},
} }
} }
@@ -130,8 +205,8 @@ func (m *Model) SetValue(s string) {
} else { } else {
m.value = runes m.value = runes
} }
if m.pos > len(m.value) { if m.pos == 0 || m.pos > len(m.value) {
m.SetCursor(len(m.value)) m.setCursor(len(m.value))
} }
m.handleOverflow() m.handleOverflow()
} }
@@ -141,26 +216,74 @@ func (m Model) Value() string {
return string(m.value) return string(m.value)
} }
// Position returns the cursor position. // Cursor returns the cursor position.
func (m Model) Position() int { func (m Model) Cursor() int {
return m.pos return m.pos
} }
// Blink returns whether or not to draw the cursor.
func (m Model) Blink() bool {
return m.blink
}
// SetCursor moves the cursor to the given position. If the position is // SetCursor 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. // out of bounds the cursor will be moved to the start or end accordingly.
func (m *Model) SetCursor(pos int) { func (m *Model) SetCursor(pos int) {
m.setCursor(pos)
}
// setCursor moves the cursor to the given position and returns whether or not
// the cursor blink should be reset. If the position is out of bounds the
// cursor will be moved to the start or end accordingly.
func (m *Model) setCursor(pos int) bool {
m.pos = clamp(pos, 0, len(m.value)) m.pos = clamp(pos, 0, len(m.value))
m.handleOverflow() 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 input field. // CursorStart moves the cursor to the start of the input field.
func (m *Model) CursorStart() { func (m *Model) CursorStart() {
m.SetCursor(0) m.cursorStart()
}
// cursorStart moves the cursor to the start of the input field and 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 input field. // CursorEnd moves the cursor to the end of the input field.
func (m *Model) CursorEnd() { func (m *Model) CursorEnd() {
m.SetCursor(len(m.value)) m.cursorEnd()
}
// CursorMode returns the model's cursor mode. For available cursor modes, see
// type CursorMode.
func (m Model) CursorMode() CursorMode {
return m.cursorMode
}
// SetCursorMode sets the model's cursor mode. This method returns a command.
//
// For available cursor modes, see type CursorMode.
func (m *Model) SetCursorMode(mode CursorMode) tea.Cmd {
m.cursorMode = mode
m.blink = m.cursorMode == CursorHide || !m.focus
if mode == CursorBlink {
return Blink
}
return nil
}
// cursorEnd moves the cursor to the end of the input field and returns whether
// the cursor should blink should reset.
func (m *Model) cursorEnd() bool {
return m.setCursor(len(m.value))
} }
// Focused returns the focus state on the model. // Focused returns the focus state on the model.
@@ -172,24 +295,31 @@ func (m Model) Focused() bool {
// receive keyboard input and the cursor will be hidden. // receive keyboard input and the cursor will be hidden.
func (m *Model) Focus() tea.Cmd { func (m *Model) Focus() tea.Cmd {
m.focus = true m.focus = true
return m.Cursor.Focus() m.blink = m.cursorMode == CursorHide // show the cursor unless we've explicitly hidden it
if m.cursorMode == CursorBlink && m.focus {
return m.blinkCmd()
}
return nil
} }
// Blur removes the focus state on the model. When the model is blurred it can // Blur removes the focus state on the model. When the model is blurred it can
// not receive keyboard input and the cursor will be hidden. // not receive keyboard input and the cursor will be hidden.
func (m *Model) Blur() { func (m *Model) Blur() {
m.focus = false m.focus = false
m.Cursor.Blur() m.blink = true
} }
// Reset sets the input to its default state with no input. // Reset sets the input to its default state with no input. Returns whether
func (m *Model) Reset() { // or not the cursor blink should reset.
func (m *Model) Reset() bool {
m.value = nil m.value = nil
m.SetCursor(0) return m.setCursor(0)
} }
// handle a clipboard paste event, if supported. // handle a clipboard paste event, if supported. Returns whether or not the
func (m *Model) handlePaste(v string) { // cursor blink should reset.
func (m *Model) handlePaste(v string) bool {
paste := []rune(v) paste := []rune(v)
var availSpace int var availSpace int
@@ -199,7 +329,7 @@ func (m *Model) handlePaste(v string) {
// If the char limit's been reached cancel // If the char limit's been reached cancel
if m.CharLimit > 0 && availSpace <= 0 { if m.CharLimit > 0 && availSpace <= 0 {
return return false
} }
// If there's not enough space to paste the whole thing cut the pasted // If there's not enough space to paste the whole thing cut the pasted
@@ -236,7 +366,8 @@ func (m *Model) handlePaste(v string) {
m.pos = oldPos m.pos = oldPos
} }
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 // If a max width is defined, perform some logic to treat the visible area
@@ -284,30 +415,31 @@ func (m *Model) handleOverflow() {
} }
} }
// deleteBeforeCursor deletes all text before the cursor. // deleteBeforeCursor deletes all text before the cursor. Returns whether or
func (m *Model) deleteBeforeCursor() { // not the cursor blink should be reset.
func (m *Model) deleteBeforeCursor() bool {
m.value = m.value[m.pos:] m.value = m.value[m.pos:]
m.offset = 0 m.offset = 0
m.SetCursor(0) return m.setCursor(0)
} }
// deleteAfterCursor deletes all text after the cursor. If input is masked // deleteAfterCursor deletes all text after the cursor. Returns whether or not
// delete everything after the cursor so as not to reveal word breaks in the // the cursor blink should be reset. If input is masked delete everything after
// masked input. // the cursor so as not to reveal word breaks in the masked input.
func (m *Model) deleteAfterCursor() { func (m *Model) deleteAfterCursor() bool {
m.value = m.value[:m.pos] m.value = m.value[:m.pos]
m.SetCursor(len(m.value)) return m.setCursor(len(m.value))
} }
// deleteWordLeft deletes the word left to the cursor. // deleteWordLeft deletes the word left to the cursor. Returns whether or not
func (m *Model) deleteWordLeft() { // the cursor blink should be reset.
func (m *Model) deleteWordLeft() bool {
if m.pos == 0 || len(m.value) == 0 { if m.pos == 0 || len(m.value) == 0 {
return return false
} }
if m.EchoMode != EchoNormal { if m.EchoMode != EchoNormal {
m.deleteBeforeCursor() return m.deleteBeforeCursor()
return
} }
// Linter note: it's critical that we acquire the initial cursor position // Linter note: it's critical that we acquire the initial cursor position
@@ -315,22 +447,22 @@ func (m *Model) deleteWordLeft() {
// call into the corresponding if clause does not apply here. // call into the corresponding if clause does not apply here.
oldPos := m.pos //nolint:ifshort oldPos := m.pos //nolint:ifshort
m.SetCursor(m.pos - 1) blink := m.setCursor(m.pos - 1)
for unicode.IsSpace(m.value[m.pos]) { for unicode.IsSpace(m.value[m.pos]) {
if m.pos <= 0 { if m.pos <= 0 {
break break
} }
// ignore series of whitespace before cursor // ignore series of whitespace before cursor
m.SetCursor(m.pos - 1) blink = m.setCursor(m.pos - 1)
} }
for m.pos > 0 { for m.pos > 0 {
if !unicode.IsSpace(m.value[m.pos]) { if !unicode.IsSpace(m.value[m.pos]) {
m.SetCursor(m.pos - 1) blink = m.setCursor(m.pos - 1)
} else { } else {
if m.pos > 0 { if m.pos > 0 {
// keep the previous space // keep the previous space
m.SetCursor(m.pos + 1) blink = m.setCursor(m.pos + 1)
} }
break break
} }
@@ -341,26 +473,27 @@ func (m *Model) deleteWordLeft() {
} else { } else {
m.value = append(m.value[:m.pos], m.value[oldPos:]...) m.value = append(m.value[:m.pos], m.value[oldPos:]...)
} }
return blink
} }
// deleteWordRight deletes the word right to the cursor If input is masked // deleteWordRight deletes the word right to the cursor. Returns whether or not
// delete everything after the cursor so as not to reveal word breaks in the // the cursor blink should be reset. If input is masked delete everything after
// masked input. // the cursor so as not to reveal word breaks in the masked input.
func (m *Model) deleteWordRight() { func (m *Model) deleteWordRight() bool {
if m.pos >= len(m.value) || len(m.value) == 0 { if m.pos >= len(m.value) || len(m.value) == 0 {
return return false
} }
if m.EchoMode != EchoNormal { if m.EchoMode != EchoNormal {
m.deleteAfterCursor() return m.deleteAfterCursor()
return
} }
oldPos := m.pos oldPos := m.pos
m.SetCursor(m.pos + 1) m.setCursor(m.pos + 1)
for unicode.IsSpace(m.value[m.pos]) { for unicode.IsSpace(m.value[m.pos]) {
// ignore series of whitespace after cursor // ignore series of whitespace after cursor
m.SetCursor(m.pos + 1) m.setCursor(m.pos + 1)
if m.pos >= len(m.value) { if m.pos >= len(m.value) {
break break
@@ -369,7 +502,7 @@ func (m *Model) deleteWordRight() {
for m.pos < len(m.value) { for m.pos < len(m.value) {
if !unicode.IsSpace(m.value[m.pos]) { if !unicode.IsSpace(m.value[m.pos]) {
m.SetCursor(m.pos + 1) m.setCursor(m.pos + 1)
} else { } else {
break break
} }
@@ -381,25 +514,26 @@ func (m *Model) deleteWordRight() {
m.value = append(m.value[:oldPos], m.value[m.pos:]...) m.value = append(m.value[:oldPos], m.value[m.pos:]...)
} }
m.SetCursor(oldPos) return m.setCursor(oldPos)
} }
// wordLeft moves the cursor one word to the left. If input is masked, move // wordLeft moves the cursor one word to the left. Returns whether or not the
// input to the start so as not to reveal word breaks in the masked input. // cursor blink should be reset. If input is masked, move input to the start
func (m *Model) wordLeft() { // so as not to reveal word breaks in the masked input.
func (m *Model) wordLeft() bool {
if m.pos == 0 || len(m.value) == 0 { if m.pos == 0 || len(m.value) == 0 {
return return false
} }
if m.EchoMode != EchoNormal { if m.EchoMode != EchoNormal {
m.CursorStart() return m.cursorStart()
return
} }
blink := false
i := m.pos - 1 i := m.pos - 1
for i >= 0 { for i >= 0 {
if unicode.IsSpace(m.value[i]) { if unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos - 1) blink = m.setCursor(m.pos - 1)
i-- i--
} else { } else {
break break
@@ -408,30 +542,33 @@ func (m *Model) wordLeft() {
for i >= 0 { for i >= 0 {
if !unicode.IsSpace(m.value[i]) { if !unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos - 1) blink = m.setCursor(m.pos - 1)
i-- i--
} else { } else {
break break
} }
} }
return blink
} }
// wordRight moves the cursor one word to the right. If the input is masked, // wordRight moves the cursor one word to the right. Returns whether or not the
// move input to the end so as not to reveal word breaks in the masked input. // cursor blink should be reset. If the input is masked, move input to the end
func (m *Model) wordRight() { // so as not to reveal word breaks in the masked input.
func (m *Model) wordRight() bool {
if m.pos >= len(m.value) || len(m.value) == 0 { if m.pos >= len(m.value) || len(m.value) == 0 {
return return false
} }
if m.EchoMode != EchoNormal { if m.EchoMode != EchoNormal {
m.CursorEnd() return m.cursorEnd()
return
} }
blink := false
i := m.pos i := m.pos
for i < len(m.value) { for i < len(m.value) {
if unicode.IsSpace(m.value[i]) { if unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos + 1) blink = m.setCursor(m.pos + 1)
i++ i++
} else { } else {
break break
@@ -440,12 +577,14 @@ func (m *Model) wordRight() {
for i < len(m.value) { for i < len(m.value) {
if !unicode.IsSpace(m.value[i]) { if !unicode.IsSpace(m.value[i]) {
m.SetCursor(m.pos + 1) blink = m.setCursor(m.pos + 1)
i++ i++
} else { } else {
break break
} }
} }
return blink
} }
func (m Model) echoTransform(v string) string { func (m Model) echoTransform(v string) string {
@@ -463,73 +602,72 @@ func (m Model) echoTransform(v string) string {
// Update is the Bubble Tea update loop. // Update is the Bubble Tea update loop.
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
if !m.focus { if !m.focus {
m.blink = true
return m, nil return m, nil
} }
// Let's remember where the position of the cursor currently is so that if var resetBlink bool
// the cursor position changes, we can reset the blink.
oldPos := m.pos //nolint
switch msg := msg.(type) { switch msg := msg.(type) {
case tea.KeyMsg: case tea.KeyMsg:
switch msg.Type { switch msg.Type {
case tea.KeyBackspace, tea.KeyCtrlH: // delete character before cursor case tea.KeyBackspace: // delete character before cursor
m.Err = nil m.Err = nil
if msg.Alt { if msg.Alt {
m.deleteWordLeft() resetBlink = m.deleteWordLeft()
} else { } else {
if len(m.value) > 0 { if len(m.value) > 0 {
m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...) m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
if m.pos > 0 { if m.pos > 0 {
m.SetCursor(m.pos - 1) resetBlink = m.setCursor(m.pos - 1)
} }
} }
} }
case tea.KeyLeft, tea.KeyCtrlB: case tea.KeyLeft, tea.KeyCtrlB:
if msg.Alt { // alt+left arrow, back one word if msg.Alt { // alt+left arrow, back one word
m.wordLeft() resetBlink = m.wordLeft()
break break
} }
if m.pos > 0 { // left arrow, ^F, back one character if m.pos > 0 { // left arrow, ^F, back one character
m.SetCursor(m.pos - 1) resetBlink = m.setCursor(m.pos - 1)
} }
case tea.KeyRight, tea.KeyCtrlF: case tea.KeyRight, tea.KeyCtrlF:
if msg.Alt { // alt+right arrow, forward one word if msg.Alt { // alt+right arrow, forward one word
m.wordRight() resetBlink = m.wordRight()
break break
} }
if m.pos < len(m.value) { // right arrow, ^F, forward one character if m.pos < len(m.value) { // right arrow, ^F, forward one character
m.SetCursor(m.pos + 1) resetBlink = m.setCursor(m.pos + 1)
} }
case tea.KeyCtrlW: // ^W, delete word left of cursor case tea.KeyCtrlW: // ^W, delete word left of cursor
m.deleteWordLeft() resetBlink = m.deleteWordLeft()
case tea.KeyHome, tea.KeyCtrlA: // ^A, go to beginning case tea.KeyHome, tea.KeyCtrlA: // ^A, go to beginning
m.CursorStart() resetBlink = m.cursorStart()
case tea.KeyDelete, tea.KeyCtrlD: // ^D, delete char under cursor case tea.KeyDelete, tea.KeyCtrlD: // ^D, delete char under cursor
if len(m.value) > 0 && m.pos < len(m.value) { if len(m.value) > 0 && m.pos < len(m.value) {
m.value = append(m.value[:m.pos], m.value[m.pos+1:]...) m.value = append(m.value[:m.pos], m.value[m.pos+1:]...)
} }
case tea.KeyCtrlE, tea.KeyEnd: // ^E, go to end case tea.KeyCtrlE, tea.KeyEnd: // ^E, go to end
m.CursorEnd() resetBlink = m.cursorEnd()
case tea.KeyCtrlK: // ^K, kill text after cursor case tea.KeyCtrlK: // ^K, kill text after cursor
m.deleteAfterCursor() resetBlink = m.deleteAfterCursor()
case tea.KeyCtrlU: // ^U, kill text before cursor case tea.KeyCtrlU: // ^U, kill text before cursor
m.deleteBeforeCursor() resetBlink = m.deleteBeforeCursor()
case tea.KeyCtrlV: // ^V paste case tea.KeyCtrlV: // ^V paste
return m, Paste return m, Paste
case tea.KeyRunes, tea.KeySpace: // input regular characters case tea.KeyRunes, tea.KeySpace: // input regular characters
if msg.Alt && len(msg.Runes) == 1 { if msg.Alt && len(msg.Runes) == 1 {
if msg.Runes[0] == 'd' { // alt+d, delete word right of cursor if msg.Runes[0] == 'd' { // alt+d, delete word right of cursor
m.deleteWordRight() resetBlink = m.deleteWordRight()
break break
} }
if msg.Runes[0] == 'b' { // alt+b, back one word if msg.Runes[0] == 'b' { // alt+b, back one word
m.wordLeft() resetBlink = m.wordLeft()
break break
} }
if msg.Runes[0] == 'f' { // alt+f, forward one word if msg.Runes[0] == 'f' { // alt+f, forward one word
m.wordRight() resetBlink = m.wordRight()
break break
} }
} }
@@ -543,31 +681,59 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
value = append(value[:m.pos], append(runes, value[m.pos:]...)...) value = append(value[:m.pos], append(runes, value[m.pos:]...)...)
m.SetValue(string(value)) m.SetValue(string(value))
if m.Err == nil { if m.Err == nil {
m.SetCursor(m.pos + len(runes)) resetBlink = m.setCursor(m.pos + len(runes))
} }
} }
} }
case initialBlinkMsg:
// We accept all initialBlinkMsgs genrated by the Blink command.
if m.cursorMode != CursorBlink || !m.focus {
return m, nil
}
cmd := m.blinkCmd()
return m, cmd
case blinkMsg:
// We're choosy about whether to accept blinkMsgs so that our cursor
// only exactly when it should.
// Is this model blinkable?
if m.cursorMode != CursorBlink || !m.focus {
return m, nil
}
// Were we expecting this blink message?
if msg.id != m.id || msg.tag != m.blinkTag {
return m, nil
}
var cmd tea.Cmd
if m.cursorMode == CursorBlink {
m.blink = !m.blink
cmd = m.blinkCmd()
}
return m, cmd
case blinkCanceled: // no-op
return m, nil
case pasteMsg: case pasteMsg:
m.handlePaste(string(msg)) resetBlink = m.handlePaste(string(msg))
case pasteErrMsg: case pasteErrMsg:
m.Err = msg m.Err = msg
} }
var cmds []tea.Cmd
var cmd tea.Cmd var cmd tea.Cmd
if resetBlink {
m.Cursor, cmd = m.Cursor.Update(msg) cmd = m.blinkCmd()
cmds = append(cmds, cmd)
if oldPos != m.pos {
m.Cursor.Blink = false
cmds = append(cmds, m.Cursor.BlinkCmd())
} }
m.handleOverflow() m.handleOverflow()
return m, tea.Batch(cmds...) return m, cmd
} }
// View renders the textinput in its current state. // View renders the textinput in its current state.
@@ -584,13 +750,10 @@ func (m Model) View() string {
v := styleText(m.echoTransform(string(value[:pos]))) v := styleText(m.echoTransform(string(value[:pos])))
if pos < len(value) { if pos < len(value) {
char := m.echoTransform(string(value[pos])) v += m.cursorView(m.echoTransform(string(value[pos]))) // cursor and text under it
m.Cursor.SetChar(char)
v += m.Cursor.View() // cursor and text under it
v += styleText(m.echoTransform(string(value[pos+1:]))) // text after cursor v += styleText(m.echoTransform(string(value[pos+1:]))) // text after cursor
} else { } else {
m.Cursor.SetChar(" ") v += m.cursorView(" ")
v += m.Cursor.View()
} }
// If a max width and background color were set fill the empty spaces with // If a max width and background color were set fill the empty spaces with
@@ -615,9 +778,12 @@ func (m Model) placeholderView() string {
style = m.PlaceholderStyle.Inline(true).Render style = m.PlaceholderStyle.Inline(true).Render
) )
m.Cursor.TextStyle = m.PlaceholderStyle // Cursor
m.Cursor.SetChar(p[:1]) if m.blink {
v += m.Cursor.View() v += m.cursorView(style(p[:1]))
} else {
v += m.cursorView(p[:1])
}
// The rest of the placeholder text // The rest of the placeholder text
v += style(p[1:]) v += style(p[1:])
@@ -625,9 +791,42 @@ func (m Model) placeholderView() string {
return m.PromptStyle.Render(m.Prompt) + v return m.PromptStyle.Render(m.Prompt) + v
} }
// cursorView styles the cursor.
func (m Model) cursorView(v string) string {
if m.blink {
return m.TextStyle.Render(v)
}
return m.CursorStyle.Inline(true).Reverse(true).Render(v)
}
// blinkCmd is an internal command used to manage cursor blinking.
func (m *Model) blinkCmd() tea.Cmd {
if m.cursorMode != CursorBlink {
return nil
}
if m.blinkCtx != nil && m.blinkCtx.cancel != nil {
m.blinkCtx.cancel()
}
ctx, cancel := context.WithTimeout(m.blinkCtx.ctx, m.BlinkSpeed)
m.blinkCtx.cancel = cancel
m.blinkTag++
return func() tea.Msg {
defer cancel()
<-ctx.Done()
if ctx.Err() == context.DeadlineExceeded {
return blinkMsg{id: m.id, tag: m.blinkTag}
}
return blinkCanceled{}
}
}
// Blink is a command used to initialize cursor blinking. // Blink is a command used to initialize cursor blinking.
func Blink() tea.Msg { func Blink() tea.Msg {
return cursor.Blink() return initialBlinkMsg{}
} }
// Paste is a command for pasting from the clipboard into the text input. // Paste is a command for pasting from the clipboard into the text input.
@@ -659,31 +858,3 @@ func max(a, b int) int {
} }
return b return b
} }
// Deprecated.
// Deprecated: use cursor.Mode.
type CursorMode int
const (
// Deprecated: use cursor.CursorBlink.
CursorBlink = CursorMode(cursor.CursorBlink)
// Deprecated: use cursor.CursorStatic.
CursorStatic = CursorMode(cursor.CursorStatic)
// Deprecated: use cursor.CursorHide.
CursorHide = CursorMode(cursor.CursorHide)
)
func (c CursorMode) String() string {
return cursor.Mode(c).String()
}
// Deprecated: use cursor.Mode().
func (m Model) CursorMode() CursorMode {
return CursorMode(m.Cursor.Mode())
}
// Deprecated: use cursor.SetMode().
func (m *Model) SetCursorMode(mode CursorMode) tea.Cmd {
return m.Cursor.SetMode(cursor.Mode(mode))
}

View File

@@ -10,7 +10,7 @@ import (
) )
// New returns a new model with the given width and height as well as default // New returns a new model with the given width and height as well as default
// key mappings. // keymappings.
func New(width, height int) (m Model) { func New(width, height int) (m Model) {
m.Width = width m.Width = width
m.Height = height m.Height = height
@@ -237,7 +237,7 @@ func Sync(m Model) tea.Cmd {
} }
// ViewDown is a high performance command that moves the viewport up by a given // ViewDown is a high performance command that moves the viewport up by a given
// number of lines. Use Model.ViewDown to get the lines that should be rendered. // numer of lines. Use Model.ViewDown to get the lines that should be rendered.
// For example: // For example:
// //
// lines := model.ViewDown(1) // lines := model.ViewDown(1)
@@ -344,29 +344,24 @@ func (m Model) updateAsModel(msg tea.Msg) (Model, tea.Cmd) {
func (m Model) View() string { func (m Model) View() string {
if m.HighPerformanceRendering { if m.HighPerformanceRendering {
// Just send newlines since we're going to be rendering the actual // Just send newlines since we're going to be rendering the actual
// content separately. We still need to send something that equals the // content seprately. We still need to send something that equals the
// height of this view so that the Bubble Tea standard renderer can // height of this view so that the Bubble Tea standard renderer can
// position anything below this view properly. // position anything below this view properly.
return strings.Repeat("\n", max(0, m.Height-1)) return strings.Repeat("\n", m.Height-1)
} }
w, h := m.Width, m.Height lines := m.visibleLines()
if sw := m.Style.GetWidth(); sw != 0 {
w = min(w, sw) // Fill empty space with newlines
extraLines := ""
if len(lines) < m.Height {
extraLines = strings.Repeat("\n", max(0, m.Height-len(lines)))
} }
if sh := m.Style.GetHeight(); sh != 0 {
h = min(h, sh)
}
contentWidth := w - m.Style.GetHorizontalFrameSize()
contentHeight := h - m.Style.GetVerticalFrameSize()
contents := lipgloss.NewStyle().
Height(contentHeight). // pad to height.
MaxHeight(contentHeight). // truncate height if taller.
MaxWidth(contentWidth). // truncate width.
Render(strings.Join(m.visibleLines(), "\n"))
return m.Style.Copy(). return m.Style.Copy().
UnsetWidth().UnsetHeight(). // Style size already applied in contents. UnsetWidth().
Render(contents) UnsetHeight().
Render(strings.Join(lines, "\n") + extraLines)
} }
func clamp(v, low, high int) int { func clamp(v, low, high int) int {