15 Commits

Author SHA1 Message Date
Maas Lalani
1e920595f2 feat(table): add SetColumns method to set columns 2022-09-27 13:11:34 -04:00
Maas Lalani
a4ed54327f chore: move cursor bubble to internal 2022-09-14 15:45:51 -04:00
Maas Lalani
a99b55cda1 Delegate Cursor Logic to cursor bubble (#181)
* refactor: remove cursor logic from textinput
* chore: Add Deprecated Fields to avoid breaking changes
* fix: Ctrl+A and typing moves to end bug
2022-09-14 10:44:10 -04:00
Raphael 'kena' Poss
062b257e8c fix(cursor): apply TextStyle inline (#230)
Co-authored-by: Maas Lalani <maas@lalani.dev>
2022-09-07 16:05:25 -04:00
Maas Lalani
8b3bfee06d docs: add table bubble to README 2022-09-06 13:28:31 -04:00
Maas Lalani
ff77858511 docs: change tea{,party} to bubbletea 2022-09-06 13:28:31 -04:00
Bastian Winkler
13f52d678d fix(table): append headers/columns to zero sized string slice 2022-09-02 16:30:15 -04:00
Raphael 'kena' Poss
278edd1c2b fix(viewport): properly truncate to size (#228)
There are many "interesting" cases:

- logical content is wider than display width (long lines).
  In this case, we truncate.
- logical content is smaller than display height (fewer lines
  than visible).
  In this case, we pad with empty lines up to the specified height.
- logical content is higher than display height (more lines than
  visible).
  In this case, we truncate.

- style specifies a width wider than the display width.
  In this case, we ignore the style width and
  fit in the display width.
- style specifies a height higher than the display height.
  Same as width, we ignore the style and fit in the display height.
- style specifies a narrower width or smaller height than the display.
  In this case we obey the style.
2022-09-02 12:50:33 -07:00
Raphael 'kena' Poss
09e1f00349 textarea: support dynamic prompts
The dynamic prompt can be different on every line.
See for example:
[![asciicast](https://asciinema.org/a/iFBPBwoDZOzcoRJOgfmPk8ObH.svg)](https://asciinema.org/a/iFBPBwoDZOzcoRJOgfmPk8ObH)
2022-09-02 14:31:26 -04:00
Raphael 'kena' Poss
c099d31570 textarea: add some comments 2022-09-02 14:31:26 -04:00
Raphael 'kena' Poss
db2a8b4e16 textarea: new bindings for "go to begin" / "go to end" 2022-09-02 13:44:52 -04:00
Nicolas Karolak
afd6f58c18 feat(table): add function to set cursor position (#219) 2022-08-30 20:54:25 -04:00
Christian Rocha
d44e242f37 fix(viewport): honor width and height settings 2022-08-29 21:05:16 -07:00
buz
776062e30c fix(table): correct keybinding for page down (#220)
Co-authored-by: Bastian Winkler <buz@serious.im>
2022-08-21 09:56:58 -04:00
kena
1c26128786 textarea: add uppercase/lowercase/capitalize word right (#210)
* Extract char navigation in separate function.

* Make wordLeft/wordRight find words on the prev/next line

... if there's no word on the current line to find any more.

* Support uppercase/lowercase/capitalize commands.

* Add transpose
2022-08-19 11:17:36 -04:00
6 changed files with 413 additions and 406 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.
There are a couple default ones, but you can also pass your own ”frames.”
* [Example code, basic spinner](https://github.com/charmbracelet/tea/tree/master/examples/spinner/main.go)
* [Example code, various spinners](https://github.com/charmbracelet/tea/tree/master/examples/spinners/main.go)
* [Example code, basic spinner](https://github.com/charmbracelet/bubbletea/tree/master/examples/spinner/main.go)
* [Example code, various spinners](https://github.com/charmbracelet/bubbletea/tree/master/examples/spinners/main.go)
## 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
the common, and many customization options.
* [Example code, one field](https://github.com/charmbracelet/tea/tree/master/examples/textinput/main.go)
* [Example code, many fields](https://github.com/charmbracelet/tea/tree/master/examples/textinputs/main.go)
* [Example code, one field](https://github.com/charmbracelet/bubbletea/tree/master/examples/textinput/main.go)
* [Example code, many fields](https://github.com/charmbracelet/bubbletea/tree/master/examples/textinputs/main.go)
## Text Area
@@ -50,9 +50,17 @@ spans multiple lines. Supports unicode, pasting, vertical scrolling when the
value exceeds the width and height of the element, and many customization
options.
* [Example code, chat input](https://github.com/charmbracelet/tea/tree/master/examples/chat/main.go)
* [Example code, story time input](https://github.com/charmbracelet/tea/tree/master/examples/textarea/main.go)
* [Example code, chat input](https://github.com/charmbracelet/bubbletea/tree/master/examples/chat/main.go)
* [Example code, story time input](https://github.com/charmbracelet/bubbletea/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
@@ -97,7 +105,7 @@ A viewport for vertically scrolling content. Optionally includes standard
pager keybindings and mouse wheel support. A high performance mode is available
for applications which make use of the alternate screen buffer.
* [Example code](https://github.com/charmbracelet/tea/tree/master/examples/pager/main.go)
* [Example code](https://github.com/charmbracelet/bubbletea/tree/master/examples/pager/main.go)
This component is well complemented with [Reflow][reflow] for ANSI-aware
indenting and text wrapping.
@@ -118,9 +126,9 @@ Features pagination, fuzzy filtering, auto-generated help, an activity spinner,
and status messages, all of which can be enabled and disabled as needed.
Extrapolated from [Glow][glow].
* [Example code, default list](https://github.com/charmbracelet/tea/tree/master/examples/list-default/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/tea/tree/master/examples/list-fancy/main.go)
* [Example code, default list](https://github.com/charmbracelet/bubbletea/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, all features](https://github.com/charmbracelet/bubbletea/tree/master/examples/list-fancy/main.go)
## Timer
@@ -228,7 +236,7 @@ If youve built a Bubble you think should be listed here,
## License
[MIT](https://github.com/charmbracelet/teaparty/raw/master/LICENSE)
[MIT](https://github.com/charmbracelet/bubbletea/raw/master/LICENSE)
***

View File

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

View File

@@ -59,11 +59,11 @@ func DefaultKeyMap() KeyMap {
),
PageUp: key.NewBinding(
key.WithKeys("b", "pgup"),
key.WithHelp("b", "page up"),
key.WithHelp("b/pgup", "page up"),
),
PageDown: key.NewBinding(
key.WithKeys("f", "pgup", spacebar),
key.WithHelp("f", "page down"),
key.WithKeys("f", "pgdown", spacebar),
key.WithHelp("f/pgdn", "page down"),
),
HalfPageUp: key.NewBinding(
key.WithKeys("u", "ctrl+u"),
@@ -264,6 +264,12 @@ func (m *Model) SetRows(r []Row) {
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
@@ -291,6 +297,12 @@ 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) {
@@ -340,7 +352,7 @@ func (m *Model) FromValues(value, separator string) {
}
func (m Model) headersView() string {
var s = make([]string, len(m.cols))
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, "…"))
@@ -350,7 +362,7 @@ func (m Model) headersView() string {
}
func (m *Model) renderRow(rowID int) string {
var s = make([]string, len(m.cols))
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, "…")))

View File

@@ -6,7 +6,7 @@ import (
"unicode"
"github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/cursor"
"github.com/charmbracelet/bubbles/internal/cursor"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
@@ -46,6 +46,14 @@ type KeyMap struct {
Paste key.Binding
WordBackward 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
@@ -67,6 +75,14 @@ var DefaultKeyMap = KeyMap{
LineStart: key.NewBinding(key.WithKeys("home", "ctrl+a")),
LineEnd: key.NewBinding(key.WithKeys("end", "ctrl+e")),
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
@@ -117,11 +133,28 @@ type Model struct {
Err error
// General settings.
Prompt string
Placeholder string
ShowLineNumbers bool
// 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
// Placeholder is the text displayed when the user
// hasn't entered anything yet.
Placeholder string
// ShowLineNumbers, if enabled, causes line numbers to be printed
// after the prompt.
ShowLineNumbers bool
// EndOfBufferCharacter is displayed at the end of the input.
EndOfBufferCharacter rune
KeyMap KeyMap
// KeyMap encodes the keybindings recognized by the widget.
KeyMap KeyMap
// Styling. FocusedStyle and BlurredStyle are used to style the textarea in
// focused and blurred states.
@@ -140,6 +173,13 @@ type Model struct {
// accept. If 0 or less, there's no limit.
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.
// If 0 or less this setting is ignored.
width int
@@ -473,6 +513,24 @@ func (m *Model) deleteAfterCursor() {
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
// the cursor blink should be reset.
func (m *Model) deleteWordLeft() {
@@ -547,31 +605,50 @@ func (m *Model) deleteWordRight() {
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
// 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.
func (m *Model) wordLeft() {
if m.col == 0 || len(m.value[m.row]) == 0 {
return
}
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 {
for {
m.characterLeft(true /* insideLine */)
if m.col < len(m.value[m.row]) && !unicode.IsSpace(m.value[m.row][m.col]) {
break
}
}
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 {
for m.col > 0 {
if unicode.IsSpace(m.value[m.row][m.col-1]) {
break
}
m.SetCursor(m.col - 1)
}
}
@@ -579,28 +656,54 @@ func (m *Model) wordLeft() {
// 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.
func (m *Model) wordRight() {
if m.col >= len(m.value[m.row]) || len(m.value[m.row]) == 0 {
return
}
m.doWordRight(func(int, int) { /* nothing */ })
}
i := m.col
for i < len(m.value[m.row]) {
if unicode.IsSpace(m.value[m.row][i]) {
m.SetCursor(m.col + 1)
i++
} else {
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
}
}
for i < len(m.value[m.row]) {
if !unicode.IsSpace(m.value[m.row][i]) {
m.SetCursor(m.col + 1)
i++
} else {
if m.row == len(m.value)-1 && m.col == len(m.value[m.row]) {
// End of text.
break
}
m.characterRight()
}
charIdx := 0
for m.col < len(m.value[m.row]) {
if unicode.IsSpace(m.value[m.row][m.col]) {
break
}
fn(charIdx, m.col)
m.SetCursor(m.col + 1)
charIdx++
}
}
// 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
@@ -662,6 +765,18 @@ func (m Model) Width() int {
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.
// This means that the textarea will account for the width of the prompt and
// whether or not line numbers are being shown.
@@ -682,10 +797,26 @@ func (m *Model) SetWidth(w int) {
// Account for base style borders and padding.
inputWidth -= m.style.Base.GetHorizontalFrameSize()
inputWidth -= rw.StringWidth(m.Prompt)
if m.promptFunc == nil {
m.promptWidth = rw.StringWidth(m.Prompt)
}
inputWidth -= m.promptWidth
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.
func (m Model) Height() int {
return m.height
@@ -774,14 +905,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
case key.Matches(msg, m.KeyMap.LineStart):
m.CursorStart()
case key.Matches(msg, m.KeyMap.CharacterForward):
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()
}
}
m.characterRight()
case key.Matches(msg, m.KeyMap.LineNext):
m.CursorDown()
case key.Matches(msg, m.KeyMap.WordForward):
@@ -789,18 +913,24 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
case key.Matches(msg, m.KeyMap.Paste):
return m, Paste
case key.Matches(msg, m.KeyMap.CharacterBackward):
if m.col == 0 && m.row != 0 {
m.row--
m.CursorEnd()
break
}
if m.col > 0 {
m.SetCursor(m.col - 1)
}
m.characterLeft(false /* insideLine */)
case key.Matches(msg, m.KeyMap.LinePrevious):
m.CursorUp()
case key.Matches(msg, m.KeyMap.WordBackward):
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:
if m.CharLimit > 0 && rw.StringWidth(m.Value()) >= m.CharLimit {
break
@@ -848,6 +978,7 @@ func (m Model) View() string {
var newLines int
displayLine := 0
for l, line := range m.value {
wrappedLines := wrap(line, m.width)
@@ -858,7 +989,10 @@ func (m Model) View() string {
}
for wl, wrappedLine := range wrappedLines {
s.WriteString(style.Render(m.style.Prompt.Render(m.Prompt)))
prompt := m.getPromptString(displayLine)
prompt = m.style.Prompt.Render(prompt)
s.WriteString(style.Render(prompt))
displayLine++
if m.ShowLineNumbers {
if wl == 0 {
@@ -907,7 +1041,10 @@ func (m Model) View() string {
// 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.
for i := 0; i < m.height; i++ {
s.WriteString(m.style.Prompt.Render(m.Prompt))
prompt := m.getPromptString(displayLine)
prompt = m.style.Prompt.Render(prompt)
s.WriteString(prompt)
displayLine++
if m.ShowLineNumbers {
lineNumber := m.style.EndOfBuffer.Render((fmt.Sprintf(m.lineNumberFormat, string(m.EndOfBufferCharacter))))
@@ -920,6 +1057,19 @@ func (m Model) View() string {
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.
func (m Model) placeholderView() string {
var (
@@ -928,7 +1078,8 @@ func (m Model) placeholderView() string {
style = m.style.Placeholder.Inline(true)
)
prompt := m.style.Prompt.Render(m.Prompt)
prompt := m.getPromptString(0)
prompt = m.style.Prompt.Render(prompt)
s.WriteString(m.style.CursorLine.Render(prompt))
if m.ShowLineNumbers {
@@ -945,6 +1096,8 @@ func (m Model) placeholderView() string {
// The rest of the new lines
for i := 1; i < m.height; i++ {
s.WriteRune('\n')
prompt := m.getPromptString(i)
prompt = m.style.Prompt.Render(prompt)
s.WriteString(prompt)
if m.ShowLineNumbers {

View File

@@ -1,48 +1,17 @@
package textinput
import (
"context"
"strings"
"sync"
"time"
"unicode"
"github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/internal/cursor"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
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.
type pasteMsg string
type pasteErrMsg struct{ error }
@@ -65,32 +34,6 @@ const (
// 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.
type ValidateFunc func(string) error
@@ -101,9 +44,13 @@ type Model struct {
// General settings.
Prompt string
Placeholder string
BlinkSpeed time.Duration
EchoMode EchoMode
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.
//
@@ -124,12 +71,6 @@ type Model struct {
// viewport. If 0 or less this setting is ignored.
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.
value []rune
@@ -137,9 +78,6 @@ type Model struct {
// component. When false, ignore keyboard input and hide the cursor.
focus bool
// Cursor blink state.
blink bool
// Cursor position.
pos int
@@ -148,12 +86,6 @@ type Model struct {
offset 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
// 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
@@ -165,21 +97,14 @@ type Model struct {
func New() Model {
return Model{
Prompt: "> ",
BlinkSpeed: defaultBlinkSpeed,
EchoCharacter: '*',
CharLimit: 0,
PlaceholderStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
Cursor: cursor.New(),
id: nextID(),
value: nil,
focus: false,
blink: true,
pos: 0,
cursorMode: CursorBlink,
blinkCtx: &blinkCtx{
ctx: context.Background(),
},
value: nil,
focus: false,
pos: 0,
}
}
@@ -205,8 +130,8 @@ func (m *Model) SetValue(s string) {
} else {
m.value = runes
}
if m.pos == 0 || m.pos > len(m.value) {
m.setCursor(len(m.value))
if m.pos > len(m.value) {
m.SetCursor(len(m.value))
}
m.handleOverflow()
}
@@ -216,74 +141,26 @@ func (m Model) Value() string {
return string(m.value)
}
// Cursor returns the cursor position.
func (m Model) Cursor() int {
// Position returns the cursor position.
func (m Model) Position() int {
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
// out of bounds the cursor will be moved to the start or end accordingly.
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.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.
func (m *Model) CursorStart() {
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)
m.SetCursor(0)
}
// CursorEnd moves the cursor to the end of the input field.
func (m *Model) CursorEnd() {
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))
m.SetCursor(len(m.value))
}
// Focused returns the focus state on the model.
@@ -295,31 +172,24 @@ func (m Model) Focused() bool {
// receive keyboard input and the cursor will be hidden.
func (m *Model) Focus() tea.Cmd {
m.focus = true
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
return m.Cursor.Focus()
}
// 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.
func (m *Model) Blur() {
m.focus = false
m.blink = true
m.Cursor.Blur()
}
// 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 {
// Reset sets the input to its default state with no input.
func (m *Model) Reset() {
m.value = nil
return m.setCursor(0)
m.SetCursor(0)
}
// handle a clipboard paste event, if supported. Returns whether or not the
// cursor blink should reset.
func (m *Model) handlePaste(v string) bool {
// handle a clipboard paste event, if supported.
func (m *Model) handlePaste(v string) {
paste := []rune(v)
var availSpace int
@@ -329,7 +199,7 @@ func (m *Model) handlePaste(v string) bool {
// If the char limit's been reached cancel
if m.CharLimit > 0 && availSpace <= 0 {
return false
return
}
// If there's not enough space to paste the whole thing cut the pasted
@@ -366,8 +236,7 @@ func (m *Model) handlePaste(v string) bool {
m.pos = oldPos
}
// Reset blink state if necessary and run overflow checks
return m.setCursor(m.pos)
m.SetCursor(m.pos)
}
// If a max width is defined, perform some logic to treat the visible area
@@ -415,31 +284,30 @@ func (m *Model) handleOverflow() {
}
}
// deleteBeforeCursor deletes all text before the cursor. Returns whether or
// not the cursor blink should be reset.
func (m *Model) deleteBeforeCursor() bool {
// deleteBeforeCursor deletes all text before the cursor.
func (m *Model) deleteBeforeCursor() {
m.value = m.value[m.pos:]
m.offset = 0
return m.setCursor(0)
m.SetCursor(0)
}
// deleteAfterCursor deletes all text after the cursor. Returns whether or not
// the cursor blink should be reset. If input is masked delete everything after
// the cursor so as not to reveal word breaks in the masked input.
func (m *Model) deleteAfterCursor() bool {
// deleteAfterCursor deletes all text after the cursor. If input is masked
// delete everything after the cursor so as not to reveal word breaks in the
// masked input.
func (m *Model) deleteAfterCursor() {
m.value = m.value[:m.pos]
return m.setCursor(len(m.value))
m.SetCursor(len(m.value))
}
// deleteWordLeft deletes the word left to the cursor. Returns whether or not
// the cursor blink should be reset.
func (m *Model) deleteWordLeft() bool {
// deleteWordLeft deletes the word left to the cursor.
func (m *Model) deleteWordLeft() {
if m.pos == 0 || len(m.value) == 0 {
return false
return
}
if m.EchoMode != EchoNormal {
return m.deleteBeforeCursor()
m.deleteBeforeCursor()
return
}
// Linter note: it's critical that we acquire the initial cursor position
@@ -447,22 +315,22 @@ func (m *Model) deleteWordLeft() bool {
// call into the corresponding if clause does not apply here.
oldPos := m.pos //nolint:ifshort
blink := m.setCursor(m.pos - 1)
m.SetCursor(m.pos - 1)
for unicode.IsSpace(m.value[m.pos]) {
if m.pos <= 0 {
break
}
// ignore series of whitespace before cursor
blink = m.setCursor(m.pos - 1)
m.SetCursor(m.pos - 1)
}
for m.pos > 0 {
if !unicode.IsSpace(m.value[m.pos]) {
blink = m.setCursor(m.pos - 1)
m.SetCursor(m.pos - 1)
} else {
if m.pos > 0 {
// keep the previous space
blink = m.setCursor(m.pos + 1)
m.SetCursor(m.pos + 1)
}
break
}
@@ -473,27 +341,26 @@ func (m *Model) deleteWordLeft() bool {
} else {
m.value = append(m.value[:m.pos], m.value[oldPos:]...)
}
return blink
}
// deleteWordRight deletes the word right to the cursor. Returns whether or not
// the cursor blink should be reset. If input is masked delete everything after
// the cursor so as not to reveal word breaks in the masked input.
func (m *Model) deleteWordRight() bool {
// deleteWordRight deletes the word right to the cursor If input is masked
// delete everything after the cursor so as not to reveal word breaks in the
// masked input.
func (m *Model) deleteWordRight() {
if m.pos >= len(m.value) || len(m.value) == 0 {
return false
return
}
if m.EchoMode != EchoNormal {
return m.deleteAfterCursor()
m.deleteAfterCursor()
return
}
oldPos := m.pos
m.setCursor(m.pos + 1)
m.SetCursor(m.pos + 1)
for unicode.IsSpace(m.value[m.pos]) {
// ignore series of whitespace after cursor
m.setCursor(m.pos + 1)
m.SetCursor(m.pos + 1)
if m.pos >= len(m.value) {
break
@@ -502,7 +369,7 @@ func (m *Model) deleteWordRight() bool {
for m.pos < len(m.value) {
if !unicode.IsSpace(m.value[m.pos]) {
m.setCursor(m.pos + 1)
m.SetCursor(m.pos + 1)
} else {
break
}
@@ -514,26 +381,25 @@ func (m *Model) deleteWordRight() bool {
m.value = append(m.value[:oldPos], m.value[m.pos:]...)
}
return m.setCursor(oldPos)
m.SetCursor(oldPos)
}
// 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
// so as not to reveal word breaks in the masked input.
func (m *Model) wordLeft() bool {
// wordLeft moves the cursor one word to the left. If input is masked, move
// input to the start so as not to reveal word breaks in the masked input.
func (m *Model) wordLeft() {
if m.pos == 0 || len(m.value) == 0 {
return false
return
}
if m.EchoMode != EchoNormal {
return m.cursorStart()
m.CursorStart()
return
}
blink := false
i := m.pos - 1
for i >= 0 {
if unicode.IsSpace(m.value[i]) {
blink = m.setCursor(m.pos - 1)
m.SetCursor(m.pos - 1)
i--
} else {
break
@@ -542,33 +408,30 @@ func (m *Model) wordLeft() bool {
for i >= 0 {
if !unicode.IsSpace(m.value[i]) {
blink = m.setCursor(m.pos - 1)
m.SetCursor(m.pos - 1)
i--
} else {
break
}
}
return blink
}
// wordRight moves the cursor one word to the right. Returns whether or not the
// 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.
func (m *Model) wordRight() bool {
// wordRight moves the cursor one word to the right. If the input is masked,
// move input to the end so as not to reveal word breaks in the masked input.
func (m *Model) wordRight() {
if m.pos >= len(m.value) || len(m.value) == 0 {
return false
return
}
if m.EchoMode != EchoNormal {
return m.cursorEnd()
m.CursorEnd()
return
}
blink := false
i := m.pos
for i < len(m.value) {
if unicode.IsSpace(m.value[i]) {
blink = m.setCursor(m.pos + 1)
m.SetCursor(m.pos + 1)
i++
} else {
break
@@ -577,14 +440,12 @@ func (m *Model) wordRight() bool {
for i < len(m.value) {
if !unicode.IsSpace(m.value[i]) {
blink = m.setCursor(m.pos + 1)
m.SetCursor(m.pos + 1)
i++
} else {
break
}
}
return blink
}
func (m Model) echoTransform(v string) string {
@@ -602,11 +463,12 @@ func (m Model) echoTransform(v string) string {
// Update is the Bubble Tea update loop.
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
if !m.focus {
m.blink = true
return m, nil
}
var resetBlink bool
// Let's remember where the position of the cursor currently is so that if
// the cursor position changes, we can reset the blink.
oldPos := m.pos //nolint
switch msg := msg.(type) {
case tea.KeyMsg:
@@ -615,59 +477,59 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
m.Err = nil
if msg.Alt {
resetBlink = m.deleteWordLeft()
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 {
resetBlink = m.setCursor(m.pos - 1)
m.SetCursor(m.pos - 1)
}
}
}
case tea.KeyLeft, tea.KeyCtrlB:
if msg.Alt { // alt+left arrow, back one word
resetBlink = m.wordLeft()
m.wordLeft()
break
}
if m.pos > 0 { // left arrow, ^F, back one character
resetBlink = m.setCursor(m.pos - 1)
m.SetCursor(m.pos - 1)
}
case tea.KeyRight, tea.KeyCtrlF:
if msg.Alt { // alt+right arrow, forward one word
resetBlink = m.wordRight()
m.wordRight()
break
}
if m.pos < len(m.value) { // right arrow, ^F, forward one character
resetBlink = m.setCursor(m.pos + 1)
m.SetCursor(m.pos + 1)
}
case tea.KeyCtrlW: // ^W, delete word left of cursor
resetBlink = m.deleteWordLeft()
m.deleteWordLeft()
case tea.KeyHome, tea.KeyCtrlA: // ^A, go to beginning
resetBlink = m.cursorStart()
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
resetBlink = m.cursorEnd()
m.CursorEnd()
case tea.KeyCtrlK: // ^K, kill text after cursor
resetBlink = m.deleteAfterCursor()
m.deleteAfterCursor()
case tea.KeyCtrlU: // ^U, kill text before cursor
resetBlink = m.deleteBeforeCursor()
m.deleteBeforeCursor()
case tea.KeyCtrlV: // ^V paste
return m, Paste
case tea.KeyRunes, tea.KeySpace: // input regular characters
if msg.Alt && len(msg.Runes) == 1 {
if msg.Runes[0] == 'd' { // alt+d, delete word right of cursor
resetBlink = m.deleteWordRight()
m.deleteWordRight()
break
}
if msg.Runes[0] == 'b' { // alt+b, back one word
resetBlink = m.wordLeft()
m.wordLeft()
break
}
if msg.Runes[0] == 'f' { // alt+f, forward one word
resetBlink = m.wordRight()
m.wordRight()
break
}
}
@@ -681,59 +543,31 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
value = append(value[:m.pos], append(runes, value[m.pos:]...)...)
m.SetValue(string(value))
if m.Err == nil {
resetBlink = m.setCursor(m.pos + len(runes))
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:
resetBlink = m.handlePaste(string(msg))
m.handlePaste(string(msg))
case pasteErrMsg:
m.Err = msg
}
var cmds []tea.Cmd
var cmd tea.Cmd
if resetBlink {
cmd = m.blinkCmd()
m.Cursor, cmd = m.Cursor.Update(msg)
cmds = append(cmds, cmd)
if oldPos != m.pos {
m.Cursor.Blink = false
cmds = append(cmds, m.Cursor.BlinkCmd())
}
m.handleOverflow()
return m, cmd
return m, tea.Batch(cmds...)
}
// View renders the textinput in its current state.
@@ -750,10 +584,13 @@ func (m Model) View() string {
v := styleText(m.echoTransform(string(value[:pos])))
if pos < len(value) {
v += m.cursorView(m.echoTransform(string(value[pos]))) // cursor and text under it
char := m.echoTransform(string(value[pos]))
m.Cursor.SetChar(char)
v += m.Cursor.View() // cursor and text under it
v += styleText(m.echoTransform(string(value[pos+1:]))) // text after cursor
} else {
v += m.cursorView(" ")
m.Cursor.SetChar(" ")
v += m.Cursor.View()
}
// If a max width and background color were set fill the empty spaces with
@@ -778,12 +615,9 @@ func (m Model) placeholderView() string {
style = m.PlaceholderStyle.Inline(true).Render
)
// Cursor
if m.blink {
v += m.cursorView(style(p[:1]))
} else {
v += m.cursorView(p[:1])
}
m.Cursor.TextStyle = m.PlaceholderStyle
m.Cursor.SetChar(p[:1])
v += m.Cursor.View()
// The rest of the placeholder text
v += style(p[1:])
@@ -791,42 +625,9 @@ func (m Model) placeholderView() string {
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.
func Blink() tea.Msg {
return initialBlinkMsg{}
return cursor.Blink()
}
// Paste is a command for pasting from the clipboard into the text input.
@@ -858,3 +659,31 @@ func max(a, b int) int {
}
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

@@ -350,18 +350,23 @@ func (m Model) View() string {
return strings.Repeat("\n", max(0, m.Height-1))
}
lines := m.visibleLines()
// Fill empty space with newlines
extraLines := ""
if len(lines) < m.Height {
extraLines = strings.Repeat("\n", max(0, m.Height-len(lines)))
w, h := m.Width, m.Height
if sw := m.Style.GetWidth(); sw != 0 {
w = min(w, sw)
}
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().
UnsetWidth().
UnsetHeight().
Render(strings.Join(lines, "\n") + extraLines)
UnsetWidth().UnsetHeight(). // Style size already applied in contents.
Render(contents)
}
func clamp(v, low, high int) int {