tui: add uiCache

Clean up/fix how we calculate the height of the content viewport
This commit is contained in:
Matt Low 2024-03-23 02:52:56 +00:00
parent c51644e78e
commit ef929da68c
1 changed files with 35 additions and 22 deletions

View File

@ -39,6 +39,14 @@ const (
selectedMessage
)
type uiCache struct {
header string
content string
error string
input string
footer string
}
type model struct {
width int
height int
@ -69,6 +77,8 @@ type model struct {
content viewport.Model
input textarea.Model
spinner spinner.Model
cache *uiCache
}
type message struct {
@ -181,7 +191,6 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.width = msg.Width
m.height = msg.Height
m.content.Width = msg.Width
m.content.Height = msg.Height - m.getFixedComponentHeight()
m.input.SetWidth(msg.Width - 1)
m.updateContent()
case msgConversationLoaded:
@ -284,9 +293,26 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
if m.width > 0 {
m.cache.header = m.headerView()
m.cache.footer = m.footerView()
m.cache.error = m.errorView()
m.cache.input = m.inputView()
fixedHeight := height(m.cache.header) + height(m.cache.error) + height(m.cache.input) + height(m.cache.footer)
m.content.Height = m.height - fixedHeight
m.cache.content = m.contentView()
}
return m, tea.Batch(cmds...)
}
func height(str string) int {
if str == "" {
return 0
}
return strings.Count(str, "\n") + 1
}
func (m model) View() string {
if m.width == 0 {
// this is the case upon initial startup, but it's also a safe bet that
@ -296,14 +322,13 @@ func (m model) View() string {
}
sections := make([]string, 0, 6)
sections = append(sections, m.headerView())
sections = append(sections, m.contentView())
error := m.errorView()
if error != "" {
sections = append(sections, error)
sections = append(sections, m.cache.header)
sections = append(sections, m.cache.content)
if m.cache.error != "" {
sections = append(sections, m.cache.error)
}
sections = append(sections, m.inputView())
sections = append(sections, m.footerView())
sections = append(sections, m.cache.input)
sections = append(sections, m.cache.footer)
return lipgloss.JoinVertical(
lipgloss.Left,
@ -311,20 +336,6 @@ func (m model) View() string {
)
}
// returns the total height of "fixed" components, which are those which don't
// change height dependent on window size.
func (m *model) getFixedComponentHeight() int {
h := 0
h += m.input.Height()
h += lipgloss.Height(m.headerView())
h += lipgloss.Height(m.footerView())
errorView := m.errorView()
if errorView != "" {
h += lipgloss.Height(errorView)
}
return h
}
func (m *model) headerView() string {
titleStyle := lipgloss.NewStyle().
PaddingLeft(1).
@ -420,6 +431,8 @@ func initialModel(ctx *lmcli.Context, convShortname string) model {
wrap: true,
selectedMessage: -1,
cache: &uiCache{},
}
m.content = viewport.New(0, 0)