Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content/guides/03-styling.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ el.SetClass("border-double text-red")

`SetClass` replaces the previous class string. Every property the old string set is restored to the value it had before that string was applied, then the new string is applied. So `SetClass("")` after `"font-bold p-1"` removes both, `SetClass("text-green")` after `"font-bold"` is green and not bold, and a border set through the `border` attribute comes back once the class string stops mentioning borders, whichever attribute came first. Within one class string the last class wins, so `"text-red text-green"` renders green.

On `<input>`, `<textarea>`, `<markdown>`, and `<modal>` the `class` attribute is applied to the component's root element after the component's own attributes, so `<input class="border-rounded w-30" />` gets the border, grows to fit it, and takes the class width over the default. Only a fixed width class (`w-N`) sizes the input's viewport and the textarea's wrapping; percentage, fraction, and auto widths size the box only.
On `<input>`, `<textarea>`, `<markdown>`, and `<modal>` the `class` attribute is applied to the component's root element after the component's own attributes, so `<input class="border-rounded w-30" />` gets the border, grows to fit it, and takes the class width over the default. The input's viewport and the textarea's wrapping follow the width the layout gives the root, so `w-full`, `w-1/2`, and `flex-1` size the text along with the box. With `w-auto` the configured width becomes a minimum: the box fills a stretched column slot and otherwise stays at that width. To fill the remaining space in a row, use `flex-1` without `w-auto`; an auto width in a flex-grown row slot takes its flex basis from the text of the previous frame, so the box grows over a few frames and takes more of the row than the classes describe.

## Programmatic Styling

Expand Down
12 changes: 6 additions & 6 deletions docs/content/reference/built-in-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Creates a new `Input` with the given options. Default values:

| Setting | Default | Description |
|-------------|--------------|------------------------------------------|
| Width | 20 | Characters visible before scrolling |
| Width | 20 | Characters visible before scrolling, unless the layout assigns another width |
| Border | `BorderNone` | No border |
| TextStyle | `Style{}` | Default terminal style |
| Placeholder | `""` | No placeholder text |
Expand Down Expand Up @@ -156,7 +156,7 @@ inp.InsertText("> ") // prefix the line, cursor ends after the prefix

| Function | Description |
|----------|-------------|
| `WithInputWidth(int)` | Width in characters (default 20) |
| `WithInputWidth(int)` | Width in characters (default 20). The viewport follows the width the layout assigns once the root has been laid out |
| `WithInputBorder(BorderStyle)` | Border style |
| `WithInputTextStyle(Style)` | Text style |
| `WithInputPlaceholder(string)` | Placeholder text |
Expand All @@ -165,7 +165,7 @@ inp.InsertText("> ") // prefix the line, cursor ends after the prefix
| `WithInputValue(*State[string])` | Reactive two-way text binding |
| `WithInputFocusColor(Color)` | Border color when focused (default Cyan) |
| `WithInputBorderGradient(Gradient)` | Border gradient when unfocused |
| `WithInputElementOptions(opts ...Option)` | Element options for the root element, applied after the input's own options (used by generated code for `class`). A fixed width or a border set this way also sizes the text viewport |
| `WithInputElementOptions(opts ...Option)` | Element options for the root element, applied after the input's own options (used by generated code for `class`). A width or a border set this way also sizes the text viewport, which follows the laid-out width for percentage and flex widths |
| `WithInputFocusGradient(Gradient)` | Border gradient when focused |
| `WithInputOnSubmit(func(string))` | Enter key callback |
| `WithInputOnChange(func(string))` | Text change callback |
Expand Down Expand Up @@ -201,7 +201,7 @@ Creates a new `TextArea` with the given options. Default values:

| Setting | Default | Description |
|-------------|--------------|------------------------------------------|
| Width | 40 | Characters per line before wrapping |
| Width | 40 | Characters per line before wrapping, unless the layout assigns another width |
| MaxHeight | 0 (no limit) | Maximum rows of text visible |
| Border | `BorderNone` | No border |
| TextStyle | `Style{}` | Default terminal style |
Expand Down Expand Up @@ -377,7 +377,7 @@ Options follow the functional options pattern. Each returns a `TextAreaOption` (
func WithTextAreaWidth(cells int) TextAreaOption
```

Sets the width in characters. Text wraps at this boundary. Default: 40.
Sets the width in characters. Text wraps at this boundary. Default: 40. When element options give the root a percentage, flex, or auto width instead, the text wraps at the width the layout assigns and the height follows the wrapped rows.

```go
ta := tui.NewTextArea(tui.WithTextAreaWidth(80))
Expand Down Expand Up @@ -454,7 +454,7 @@ ta := tui.NewTextArea(
func WithTextAreaElementOptions(opts ...Option) TextAreaOption
```

Applies standard element options to the textarea's root element after its own options; generated code uses it for the `class` attribute. A fixed width or a border set this way also sizes the wrapping and reported height.
Applies standard element options to the textarea's root element after its own options; generated code uses it for the `class` attribute. A width or a border set this way also sizes the wrapping and reported height; a percentage, flex, or auto width wraps at the width the layout assigns.

```go
ta := tui.NewTextArea(tui.WithTextAreaElementOptions(tui.WithClass("border-rounded w-60")))
Expand Down
8 changes: 8 additions & 0 deletions element.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,14 @@ type Element struct {
// Pre-render hook for custom update logic (polling, animations, etc.)
onUpdate func()

// measure, when set, gives HeightForWidth the content height for a content
// width, for components whose height depends on the width layout assigns.
measure func(contentWidth int) int

// onLayout runs once per frame from the render walk with the element's
// final box, after any scroll-container re-layout.
onLayout func(*Element)

// Watchers attached to this element (timers, channel watchers, etc.)
watchers []Watcher

Expand Down
34 changes: 34 additions & 0 deletions element_layout.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,27 @@ func (e *Element) SetLayout(l LayoutResult) {
e.layout = l
}

// setOnLayout installs a callback the render walk runs once per frame with
// this element's final computed box.
func (e *Element) setOnLayout(fn func(*Element)) {
e.onLayout = fn
}

// reportLayout runs the onLayout hook with this frame's final box. The render
// walk calls it after every layout pass, including a scrollable parent's
// scrollbar re-layout, so the hook sees each element once per frame.
func (e *Element) reportLayout() {
if e.onLayout != nil {
e.onLayout(e)
}
}

// setMeasure installs the content measurer HeightForWidth consults instead of
// the children: fn receives the content width and returns the content height.
func (e *Element) setMeasure(fn func(contentWidth int) int) {
e.measure = fn
}

// GetLayout returns the last computed layout.
func (e *Element) GetLayout() LayoutResult {
return e.layout
Expand Down Expand Up @@ -219,6 +240,19 @@ func (e *Element) HeightForWidth(width int) int {
return h
}

// Components that wrap their own content measure it at the assigned width.
if e.measure != nil {
contentWidth := width - e.style.Padding.Horizontal()
if e.border != BorderNone {
contentWidth -= 2
}
h := e.measure(max(contentWidth, 0)) + e.style.Padding.Vertical()
if e.border != BorderNone {
h += 2
}
return h
}

// Tables: resolve column widths (with shrinking) and measure rows at
// those widths, rather than falling into the flex row branch below.
if e.tag == "table" {
Expand Down
4 changes: 4 additions & 0 deletions element_render.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ func renderElement(buf *Buffer, e *Element, inherited inheritedStyle) {
e.onUpdate()
}

e.reportLayout()

rect := e.Rect()

// Skip if outside buffer bounds
Expand Down Expand Up @@ -211,6 +213,8 @@ func renderClippedElement(buf *Buffer, e *Element, clipRect Rect, scrollX, scrol
return
}

e.reportLayout()

childRect := e.Rect()

// Translate from content space to screen space
Expand Down
49 changes: 45 additions & 4 deletions input.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ type Input struct {
onChange func(string)
elementOpts []Option

// Content width the layout engine last gave the root, valid once laidOut.
// Zero is a real width (a fully shrunk flex item), so it cannot mean unset.
layoutWidth int
laidOut bool

// Reactive state
text *State[string]
cursorPos *State[int]
Expand Down Expand Up @@ -172,12 +177,15 @@ func (inp *Input) insertString(s string) {

// --- Component Interface ---

// visibleWidth returns the number of characters visible inside the input.
// Accounts for border taking 1 char on each side.
// visibleWidth returns the number of characters visible inside the input: the
// laid-out content width once the root has been laid out, and before that the
// configured width minus the border, which takes 1 char on each side.
func (inp *Input) visibleWidth() int {
if inp.laidOut {
return inp.layoutWidth
}
Comment thread
grindlemire marked this conversation as resolved.
Resolved
w := inp.width
if inp.border != BorderNone {
// Border chars are drawn inside the element width, reducing text space
return w - 2
}
return w
Expand All @@ -189,12 +197,13 @@ func (inp *Input) visibleWidth() int {
func (inp *Input) ensureCursorVisible() {
text := inp.text.Get()
cursorCol := runeIndexToDisplayCol(text, inp.clampCursorPos())
scroll := inp.scrollPos.Get()
visible := inp.visibleWidth()
if visible <= 0 {
inp.scrollPos.Set(0)
return
}
inp.clampScroll(visible)
scroll := inp.scrollPos.Get()

// Cursor is left of the visible window: scroll back so cursor is at col 0.
if cursorCol < scroll {
Expand All @@ -213,6 +222,19 @@ func (inp *Input) ensureCursorVisible() {
}
}

// clampScroll pulls scrollPos back when it would hide text on the left while
// leaving more than the cursor's column empty on the right, as after the
// viewport grows or the text shrinks. Unlike ensureCursorVisible it also runs
// on the unfocused path, so a blurred input reclaims slack without jumping to
// the cursor.
func (inp *Input) clampScroll(visible int) {
_, total := textToClusters(inp.text.Get())
maxScroll := max(0, total+1-visible)
if inp.scrollPos.Get() > maxScroll {
inp.scrollPos.Set(maxScroll)
}
}

// Render returns the element tree for the input.
func (inp *Input) Render(app *App) *Element {
opts := []Option{
Expand All @@ -228,6 +250,22 @@ func (inp *Input) Render(app *App) *Element {
}
root := New(opts...)
root.Apply(inp.elementOpts...)
// An auto-width root would otherwise size to the viewport text and pin the
// viewport there; the configured width acts as its floor instead.
style := root.LayoutStyle()
if style.Width.IsAuto() && style.MinWidth.IsAuto() && inp.width > 0 {
root.Apply(WithMinWidth(inp.width))
}
// The viewport was sliced for this width; a frame laid out at another
// width re-renders so the text fills the box the engine gave it.
rendered := inp.visibleWidth()
root.setOnLayout(func(e *Element) {
inp.layoutWidth = e.ContentRect().Width
inp.laidOut = true
if inp.layoutWidth != rendered {
e.MarkDirty()
}
})

// Focus styling and the default height follow the final border, which
// element options (a class border) may have set.
Expand Down Expand Up @@ -541,6 +579,9 @@ func (inp *Input) displayText() string {
// In the unfocused path, scroll adjustment preserves the previously-set
// scroll position. ensureCursorVisible is only called in the focused path
// so that manually-scrolled text doesn't jump when the user blurs.
if visible > 0 {
inp.clampScroll(visible)
}
return inp.viewportText(allClusters, visible)
}

Expand Down
Loading
Loading