Skip to content

Commit

Permalink
Add character limit option and tests for input model
Browse files Browse the repository at this point in the history
  • Loading branch information
philipesteiff authored and cqroot committed Sep 21, 2024
1 parent 81774e7 commit 32cc872
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
6 changes: 6 additions & 0 deletions input/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,9 @@ func WithWidth(width int) Option {
m.textInput.Width = width
}
}

func WithCharLimit(limit int) Option {
return func(m *Model) {
m.textInput.CharLimit = limit
}
}
49 changes: 49 additions & 0 deletions input/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"reflect"
"strings"
"testing"

tea "github.com/charmbracelet/bubbletea"
Expand Down Expand Up @@ -77,3 +78,51 @@ func TestDefaultValueWithValidateFunc(t *testing.T) {

require.Nil(t, m.Error())
}

func TestWithCharLimit(t *testing.T) {
// Initialize input and output buffers
var in bytes.Buffer
var out bytes.Buffer

inputString := []byte(strings.Repeat("a", 400) + "\r\n")

in.Write(inputString)

// Create a new model with a custom char limit using WithCharLimit
model := input.New(
"test",
input.WithCharLimit(400),
)

// Run the model using tea program
tm, err := tea.NewProgram(model, tea.WithInput(&in), tea.WithOutput(&out)).Run()
require.Nil(t, err)

// Retrieve the final model after running the tea program
m, ok := tm.(input.Model)
require.True(t, ok)

// Check if the CharLimit is correctly set
require.Equal(t, 400, len(m.Data()))
}

func TestWithSmallCharLimitError(t *testing.T) {
var in bytes.Buffer
var out bytes.Buffer

inputString := []byte(strings.Repeat("a", 50) + "\r\n")
in.Write(inputString)

model := input.New(
"test",
input.WithCharLimit(10),
)

tm, err := tea.NewProgram(model, tea.WithInput(&in), tea.WithOutput(&out)).Run()
require.Nil(t, err)

m, ok := tm.(input.Model)
require.True(t, ok)

require.Equal(t, 10, len(m.Data()))
}

0 comments on commit 32cc872

Please sign in to comment.