From c4068c642c90bc56ea6cd89f72a04020aa1dd049 Mon Sep 17 00:00:00 2001 From: Ayman Bagabas Date: Fri, 1 Aug 2025 12:22:10 -0400 Subject: [PATCH] fix(textarea): ensure viewport content is set during update This ensures that the viewport content is set and persisted correctly. Setting the content during View won't doesn't work because it mutates a copy of the model instead without persisting the changes. Moreover, any after effects of setting the content won't be visible because the next Update will be called on the older model, not the new one. --- textarea/textarea.go | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/textarea/textarea.go b/textarea/textarea.go index 4c44935..0e9a2a6 100644 --- a/textarea/textarea.go +++ b/textarea/textarea.go @@ -1235,6 +1235,9 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { m.Err = msg } + // Make sure we set the content of the viewport before updating it. + view := m.view() + m.viewport.SetContent(view) vp, cmd := m.viewport.Update(msg) m.viewport = &vp cmds = append(cmds, cmd) @@ -1257,9 +1260,8 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { return m, tea.Batch(cmds...) } -// View renders the text area in its current state. -func (m Model) View() string { - if m.Value() == "" && m.row == 0 && m.col == 0 && m.Placeholder != "" { +func (m *Model) view() string { + if len(m.Value()) == 0 && m.row == 0 && m.col == 0 && m.Placeholder != "" { return m.placeholderView() } m.virtualCursor.TextStyle = m.activeStyle().computedCursorLine() @@ -1352,8 +1354,22 @@ func (m Model) View() string { s.WriteRune('\n') } - m.viewport.SetContent(s.String()) - return styles.Base.Render(m.viewport.View()) + return s.String() +} + +// View renders the text area in its current state. +func (m Model) View() string { + view := strings.TrimSpace(m.viewport.View()) + if view == "" { + // XXX: This is a workaround for the case where the viewport hasn't + // been initialized yet like during the initial render. In that case, + // we need to render the view again because Update hasn't been called + // yet to set the content of the viewport. + m.viewport.SetContent(m.view()) + view = m.viewport.View() + } + styles := m.activeStyle() + return styles.Base.Render(view) } // promptView renders a single line of the prompt.