diff --git a/go.mod b/go.mod index 144a6b9..0420c8d 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.26.7 require ( charm.land/bubbles/v2 v2.1.1 - charm.land/bubbletea/v2 v2.0.8 + charm.land/bubbletea/v2 v2.0.9 charm.land/glamour/v2 v2.0.2-0.20260914112920-7bb50a2ac56e charm.land/lipgloss/v2 v2.0.6 github.com/atotto/clipboard v0.1.4 diff --git a/go.sum b/go.sum index f7766cf..a4ca29a 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ charm.land/bubbles/v2 v2.1.1 h1:7r55WzBxpo/R3z98hGmY7KKPd3ET6vsf0Fb9sDHOV60= charm.land/bubbles/v2 v2.1.1/go.mod h1:GE6M31gaWZVXzGw73OeuTTgy4lX+OtkH0E5ymnNsHxo= -charm.land/bubbletea/v2 v2.0.8 h1:SxTJMhCAI3lbPmy4SgX5LWZ24AdINr4I6UEqzZvYJuY= -charm.land/bubbletea/v2 v2.0.8/go.mod h1:2SkdgoTXluXJHOUwAoRlRXF/28vklb1rFl6GcgV1/ss= +charm.land/bubbletea/v2 v2.0.9 h1:DpJCMWKgzQK8SJv4zbKKFHAI10ymWy/evClPFk0k0f8= +charm.land/bubbletea/v2 v2.0.9/go.mod h1:2SkdgoTXluXJHOUwAoRlRXF/28vklb1rFl6GcgV1/ss= charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ= charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q= github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= diff --git a/ui/pager.go b/ui/pager.go index 7cdb82e..2dd7e50 100644 --- a/ui/pager.go +++ b/ui/pager.go @@ -153,7 +153,7 @@ func newPagerModel(common *commonModel) pagerModel { sp := spinner.New() sp.Spinner = spinner.Line - sp.Style = common.styles.stashSpinnerStyle + sp.Style = common.styles.statusBarSpinnerStyle m := pagerModel{ common: common, @@ -317,6 +317,16 @@ func (m pagerModel) update(msg tea.Msg) (pagerModel, tea.Cmd) { } m.setContent(msg.content) + // A rendering pass failed, e.g. while fetching the document's remote + // images. Report it and stop the loading indicator, which would + // otherwise stay in the status bar forever. + case errMsg: + var wasLoading bool + wasLoading, m.remoteImagesLoading = m.remoteImagesLoading, false + if wasLoading { + cmds = append(cmds, m.showStatusMessage(pagerStatusMessage{msg.Error(), true})) + } + // Keep the loading indicator spinning while the remote images load. case spinner.TickMsg: if m.remoteImagesLoading { @@ -360,7 +370,17 @@ func (m pagerModel) update(msg tea.Msg) (pagerModel, tea.Cmd) { func (m pagerModel) View() string { var b strings.Builder - fmt.Fprint(&b, m.viewport.View()+"\n") + + // The viewport pads its content to the height it was given, but it draws + // nothing at all until it has been sized, i.e. before the first window + // size message. The status bar would then end up at the top of the screen, + // and the lines it doesn't cover would keep the previous frame on screen. + // Fill the gap so the bar always stays at the bottom. + content := m.viewport.View() + if missing := m.common.height - statusBarHeight - (strings.Count(content, "\n") + 1); m.common.height > 0 && missing > 0 { + content += strings.Repeat("\n", missing) + } + fmt.Fprint(&b, content+"\n") // Footer m.statusBarView(&b) @@ -403,28 +423,32 @@ func (m pagerModel) statusBarView(b *strings.Builder) { } // Note - var note string - switch { - case m.remoteImagesLoading: - note = m.remoteSpinner.View() + " Loading remote images..." - case showStatusMessage: - note = m.statusMessage - default: - note = m.currentDocument.Note - } - note = truncate.StringWithTail(" "+note+" ", uint(max(0, //nolint:gosec + noteWidth := max(0, m.common.width- ansi.PrintableRuneWidth(logo)- ansi.PrintableRuneWidth(scrollPercent)- ansi.PrintableRuneWidth(helpNote), - )), ellipsis) + ) // The loading indicator takes the place of the status message, so it's // styled like the file name rather than like a message. showMessage := showStatusMessage && !m.remoteImagesLoading - if showMessage { - note = styles.statusBarMessageStyle(note) - } else { - note = styles.statusBarNoteStyle(note) + var note string + switch { + case m.remoteImagesLoading: + // The spinner's own styling ends in an ANSI reset which would wipe + // the status bar background of everything after it, so the note is + // styled in segments around the spinner. + spinnerView := m.remoteSpinner.View() + textWidth := max(0, noteWidth-ansi.PrintableRuneWidth(spinnerView)-1) + note = styles.statusBarNoteStyle(" ") + spinnerView + + styles.statusBarNoteStyle(truncate.StringWithTail( //nolint:gosec + " Loading remote images... ", uint(textWidth), ellipsis)) + case showMessage: + note = styles.statusBarMessageStyle(truncate.StringWithTail( //nolint:gosec + " "+m.statusMessage+" ", uint(noteWidth), ellipsis)) + default: + note = styles.statusBarNoteStyle(truncate.StringWithTail( //nolint:gosec + " "+m.currentDocument.Note+" ", uint(noteWidth), ellipsis)) } // Empty space diff --git a/ui/stash.go b/ui/stash.go index 220982f..0657e3b 100644 --- a/ui/stash.go +++ b/ui/stash.go @@ -660,7 +660,7 @@ func (m stashModel) view() string { var s string switch m.viewState { case stashStateShowingError: - return errorView(m.common.styles, m.err, false) + return fillHeight(errorView(m.common.styles, m.err, false), m.common.height) case stashStateLoadingDocument: s += " " + m.spinner.View() + " Loading document..." case stashStateReady: @@ -733,7 +733,7 @@ func (m stashModel) view() string { help, ) } - return "\n" + indent(s, stashIndent) + return fillHeight("\n"+indent(s, stashIndent), m.common.height) } func glowLogoView(styles Styles) string { diff --git a/ui/styles.go b/ui/styles.go index 2c22e22..1b6ac14 100644 --- a/ui/styles.go +++ b/ui/styles.go @@ -42,6 +42,7 @@ type Styles struct { statusBarMessageStyle func(...string) string statusBarMessageScrollPosStyle func(...string) string statusBarMessageHelpStyle func(...string) string + statusBarSpinnerStyle lipgloss.Style helpViewStyle func(...string) string lineNumberStyle func(...string) string @@ -135,6 +136,10 @@ func newStyles(isDark bool) Styles { Background(green). Render + s.statusBarSpinnerStyle = lipgloss.NewStyle(). + Foreground(gray). + Background(statusBarBg) + s.helpViewStyle = lipgloss.NewStyle(). Foreground(statusBarNoteFg). Background(s.adaptive("#f2f2f2", "#1B1B1B")). diff --git a/ui/ui.go b/ui/ui.go index a053c5a..4891f06 100644 --- a/ui/ui.go +++ b/ui/ui.go @@ -350,7 +350,7 @@ func (m model) View() tea.View { var content string switch { case m.fatalErr != nil: - content = errorView(m.common.styles, m.fatalErr, true) + content = fillHeight(errorView(m.common.styles, m.fatalErr, true), m.common.height) case m.state == stateShowDocument: content = m.pager.View() default: @@ -465,6 +465,18 @@ func stripAbsolutePath(fullPath, cwd string) string { return strings.ReplaceAll(fp, cp+string(os.PathSeparator), "") } +// fillHeight pads a view with newlines so that it fills the given number of +// terminal lines. Views that don't cover the whole terminal leave whatever the +// previous frame drew on screen, which is visible as stale lines, e.g. the +// status bar of a document stuck at the bottom after going back to the stash. +func fillHeight(s string, height int) string { + missing := height - (strings.Count(s, "\n") + 1) + if height <= 0 || missing <= 0 { + return s + } + return s + strings.Repeat("\n", missing) +} + // Lightweight version of reflow's indent function. func indent(s string, n int) string { if n <= 0 || s == "" { diff --git a/ui/ui_test.go b/ui/ui_test.go index 6782420..50195c4 100644 --- a/ui/ui_test.go +++ b/ui/ui_test.go @@ -2,6 +2,7 @@ package ui import ( "bytes" + "errors" "image" "image/color" "image/png" @@ -10,6 +11,7 @@ import ( "os" "path/filepath" "strings" + "sync" "sync/atomic" "testing" "time" @@ -416,3 +418,140 @@ func TestPagerRemoteImagesLoading(t *testing.T) { t.Errorf("expected the loading indicator to be gone, got: %q", m.View()) } } + +// TestViewsFillScreen checks that the views shown between documents (loading, +// error) and the pager before it has been sized fill the terminal height. +// Views that don't cover the whole screen leave whatever the previous frame +// drew on it, e.g. a document's status bar stuck at the bottom after going +// back to the stash. +func TestViewsFillScreen(t *testing.T) { + const height = 24 + common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: height} + + check := func(name, view string) { + t.Helper() + if got := strings.Count(view, "\n") + 1; got != height { + t.Errorf("expected the %s view to fill the screen, got %d lines, want %d", name, got, height) + } + } + + stash := newStashModel(&common) + stash.setSize(80, height) + stash.loaded = true + check("stash", stash.view()) + + stash.viewState = stashStateLoadingDocument + check("loading", stash.view()) + + stash.viewState = stashStateShowingError + stash.err = errMsg{err: errors.New("boom")} + check("error", stash.view()) + + pager := newPagerModel(&common) + check("unsized pager", pager.View()) + pager.setSize(80, height) + check("empty pager", pager.View()) + pager.setContent("hello\nworld") + check("pager", pager.View()) +} + +// TestPagerRemoteImagesLoadError checks that a failed loading pass clears the +// loading indicator and reports the error, rather than leaving the indicator +// in the status bar forever. +func TestPagerRemoteImagesLoadError(t *testing.T) { + common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: 24} + m := newPagerModel(&common) + m.setSize(80, 24) + m.currentDocument = markdown{Note: "test.md", Body: "![](https://example.com/img.png)"} + + m, _ = m.update(contentRenderedMsg{ + content: "text without images", + body: m.currentDocument.Body, + remoteImagesPending: true, + }) + if !m.remoteImagesLoading { + t.Fatal("expected the remote images to be reported as loading") + } + + m, cmd := m.update(errMsg{err: errors.New("boom")}) + if m.remoteImagesLoading { + t.Error("expected the loading indicator to be cleared") + } + if strings.Contains(m.View(), "Loading remote images") { + t.Errorf("expected the loading indicator to be gone, got: %q", m.View()) + } + if !strings.Contains(m.View(), "boom") { + t.Errorf("expected the error to be reported, got: %q", m.View()) + } + if cmd == nil { + t.Error("expected a status message timeout") + } +} + +// staticViewModel renders a view that never changes, like the loading +// indicator between documents. +type staticViewModel struct{} + +func (staticViewModel) Init() tea.Cmd { return nil } +func (m staticViewModel) Update(tea.Msg) (tea.Model, tea.Cmd) { return m, nil } +func (staticViewModel) View() tea.View { + v := tea.NewView("static") + v.AltScreen = true + return v +} + +// syncBuffer is a buffer that can be read while the program writes to it. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// TestResizeRedrawsUnchangedView checks that a window resize redraws the +// screen even when the view doesn't change, e.g. while a document loads. The +// renderer must not skip the screen erase queued by the resize, or the +// terminal keeps whatever the previous frame drew, like a document's status +// bar left stuck at the bottom (fixed in bubbletea v2.0.9, see +// charmbracelet/bubbletea#1755). +func TestResizeRedrawsUnchangedView(t *testing.T) { + var out syncBuffer + p := tea.NewProgram(staticViewModel{}, + tea.WithOutput(&out), + tea.WithInput(strings.NewReader("")), + tea.WithWindowSize(80, 24), + ) + + done := make(chan struct{}) + go func() { + defer close(done) + + // Wait for the initial frame, then resize to the same dimensions so + // that only the resize can redraw the screen. + time.Sleep(250 * time.Millisecond) + before := strings.Count(out.String(), "static") + + p.Send(tea.WindowSizeMsg{Width: 80, Height: 24}) + time.Sleep(250 * time.Millisecond) + + if after := strings.Count(out.String(), "static"); after <= before { + t.Errorf("expected the screen to be redrawn on resize, got no redraw (frames before=%d, after=%d)", + before, after) + } + p.Send(tea.Quit()) + }() + if _, err := p.Run(); err != nil { + t.Fatal(err) + } + <-done +}