23 Commits

Author SHA1 Message Date
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
kena
649f78e1fd fix(textarea): pre-allocation of value (#213)
The maximum slice size of m.value is the max number of rows,
which is the max height.
2022-08-15 10:25:20 -04:00
kena
e72e4a190b perf(textarea): amortize heap allocs in Value (#212) 2022-08-15 10:24:54 -04:00
kena
9b67fb8724 perf: avoid recomputing the key representation in key.Matches 2022-08-12 16:07:31 -04:00
Maas Lalani
93e3c756c4 docs: responsive images for mobile 2022-08-08 17:35:57 -04:00
Maas Lalani
e200bf8c81 feat: LineCount method for counting number of lines in textarea 2022-08-05 16:37:05 -04:00
Maas Lalani
47eee84147 fix: include new line characters for Length() 2022-08-05 16:37:05 -04:00
Maas Lalani
84eacf535a fix: CharLimit <= 0 should be ignored 2022-08-04 14:52:50 -04:00
Maas Lalani
8f65160828 fix: add ctrl+h to backspace text 2022-07-31 13:20:02 -04:00
Weslei Juan Novaes Pereira
58a9d4c7ec feat: table bubble (#173)
Add table Bubble for displaying tabular data

Co-authored-by: Maas Lalani <maas@lalani.dev>
Co-authored-by: Christian Rocha <christian@rocha.is>
2022-07-21 15:06:38 -04:00
Maas Lalani
e32dcde62a fix(viewport): Guard against negative string repetitions (#196) 2022-07-21 14:39:17 -04:00
Hironao OTSUBO
e49b5573bc fix(key): Unbound keys should be disabled
* fix condition for #188
This is a fix of https://github.com/charmbracelet/bubbles/pull/188
Unbound keys has nil keys and they are not Enabled
2022-07-11 10:45:18 -04:00
Maas Lalani
746ec595c3 fix(textarea): change placeholder color to match textinput (#192) 2022-07-07 22:34:48 -04:00
Hironao OTSUBO
d4eeb4f5be fix(key): unbound keys are not enabled 2022-07-06 17:01:28 -07:00
Jonah
b74f696cc8 feat(list): add IsFiltered method (#98) 2022-07-05 16:38:10 -04:00
9 changed files with 748 additions and 86 deletions

View File

@@ -56,7 +56,11 @@ options.
## Progress
<img src="https://stuff.charm.sh/bubbles-examples/progress.gif" width="800" alt="Progressbar Example">
<picture>
<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
[Harmonica][harmonica]. Supports solid and gradient fills. The empty and filled
@@ -83,7 +87,11 @@ logic and visualize pagination however you like.
## Viewport
<img src="https://stuff.charm.sh/bubbles-examples/viewport.gif?0" width="600" alt="Viewport Example">
<picture>
<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
pager keybindings and mouse wheel support. A high performance mode is available
@@ -99,7 +107,11 @@ indenting and text wrapping.
## List
<img src="https://stuff.charm.sh/bubbles-examples/list.gif" width="600" alt="List Example">
<picture>
<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.
Features pagination, fuzzy filtering, auto-generated help, an activity spinner,
@@ -133,7 +145,11 @@ can be customized as you see fit.
## Help
<img src="https://stuff.charm.sh/bubbles-examples/help.gif" width="500" alt="Help Example">
<picture>
<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
from your keybindings. It features single and multi-line modes, which the user

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
// enabled by default.
func (b Binding) Enabled() bool {
return !b.disabled
return !b.disabled && b.keys != nil
}
// SetEnabled enables or disables the keybinding.
@@ -130,9 +130,10 @@ type Help struct {
// Matches checks if the given KeyMsg matches the given bindings.
func Matches(k tea.KeyMsg, b ...Binding) bool {
keys := k.String()
for _, binding := range b {
for _, v := range binding.keys {
if k.String() == v && binding.Enabled() {
if keys == v && binding.Enabled() {
return true
}
}

26
key/key_test.go Normal file
View File

@@ -0,0 +1,26 @@
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

@@ -534,6 +534,15 @@ func (m Model) SettingFilter() bool {
return m.filterState == Filtering
}
// IsFiltered returns whether or not the list is currently filtered.
// It's purely a convenience method for the following:
//
// m.FilterState() == FilterApplied
//
func (m Model) IsFiltered() bool {
return m.filterState == FilterApplied
}
// Width returns the current width setting.
func (m Model) Width() int {
return m.width

393
table/table.go Normal file
View File

@@ -0,0 +1,393 @@
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()
}
// 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)
}

54
table/table_test.go Normal file
View File

@@ -0,0 +1,54 @@
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

@@ -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,10 +133,27 @@ type Model struct {
Err error
// 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
// 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 encodes the keybindings recognized by the widget.
KeyMap KeyMap
// Styling. FocusedStyle and BlurredStyle are used to style the textarea in
@@ -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
@@ -193,7 +233,7 @@ func New() Model {
Cursor: cur,
KeyMap: DefaultKeyMap,
value: make([][]rune, minHeight, maxWidth),
value: make([][]rune, minHeight, maxHeight),
focus: false,
col: 0,
row: 0,
@@ -217,7 +257,7 @@ func DefaultStyles() (Style, Style) {
CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "240"}),
EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}),
LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Text: lipgloss.NewStyle(),
}
@@ -227,7 +267,7 @@ func DefaultStyles() (Style, Style) {
CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}),
LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
Text: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "245", Dark: "7"}),
}
@@ -271,13 +311,13 @@ func (m Model) Value() string {
return ""
}
var v string
var v strings.Builder
for _, l := range m.value {
v += string(l)
v += "\n"
v.WriteString(string(l))
v.WriteByte('\n')
}
return strings.TrimSuffix(v, "\n")
return strings.TrimSuffix(v.String(), "\n")
}
// Length returns the number of characters currently in the text input.
@@ -286,7 +326,12 @@ func (m *Model) Length() int {
for _, row := range m.value {
l += rw.StringWidth(string(row))
}
return l
return l + len(m.value) - 1
}
// 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.
@@ -404,7 +449,7 @@ func (m *Model) Blur() {
// Reset sets the input to its default state with no input.
func (m *Model) Reset() {
m.value = make([][]rune, minHeight, maxWidth)
m.value = make([][]rune, minHeight, maxHeight)
m.col = 0
m.row = 0
m.viewport.GotoTop()
@@ -468,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() {
@@ -542,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)
}
}
@@ -574,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
@@ -657,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.
@@ -677,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
@@ -769,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):
@@ -784,20 +913,26 @@ 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 rw.StringWidth(m.Value()) >= m.CharLimit {
if m.CharLimit > 0 && rw.StringWidth(m.Value()) >= m.CharLimit {
break
}
@@ -843,6 +978,7 @@ func (m Model) View() string {
var newLines int
displayLine := 0
for l, line := range m.value {
wrappedLines := wrap(line, m.width)
@@ -853,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 {
@@ -902,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))))
@@ -915,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 (
@@ -923,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 {
@@ -940,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

@@ -611,7 +611,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyBackspace: // delete character before cursor
case tea.KeyBackspace, tea.KeyCtrlH: // delete character before cursor
m.Err = nil
if msg.Alt {

View File

@@ -10,7 +10,7 @@ import (
)
// New returns a new model with the given width and height as well as default
// keymappings.
// key mappings.
func New(width, height int) (m Model) {
m.Width = width
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
// numer of lines. Use Model.ViewDown to get the lines that should be rendered.
// number of lines. Use Model.ViewDown to get the lines that should be rendered.
// For example:
//
// lines := model.ViewDown(1)
@@ -344,24 +344,29 @@ func (m Model) updateAsModel(msg tea.Msg) (Model, tea.Cmd) {
func (m Model) View() string {
if m.HighPerformanceRendering {
// Just send newlines since we're going to be rendering the actual
// content seprately. We still need to send something that equals the
// content separately. We still need to send something that equals the
// height of this view so that the Bubble Tea standard renderer can
// position anything below this view properly.
return strings.Repeat("\n", m.Height-1)
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 {