diff --git a/docs/tui.md b/docs/tui.md index 22045222..f8de8dd4 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -82,6 +82,14 @@ Sending a reply or a forward from a thread closes the thread and returns you to While reading a thread, the From header shows the actual send-as address when HEY records one separately from the account user. +Move (`v`), labels (`b`), and collection membership (`n`) open compact menus over +the current mail screen. The thread subject wraps above the choices when there +is room; an excerpt is used only when the subject is absent. Use the arrow keys and Enter to choose an action, or Escape +to dismiss it. In labels and collections, type to filter names, Backspace to edit +the filter, and Ctrl+U to clear it. Current memberships have an `[x]` mark. Long +lists scroll within the menu. Creating a label opens a name field in the same +menu; Escape returns to the choices. + While reading a thread, links can be selected without a mouse. Tab selects the next link in document order and Shift+Tab selects the previous one; both wrap at the ends. A fixed row above the shortcut bar shows the selected destination without moving the thread. A destination too long for one row wraps onto as many rows as it needs, so you always see all of it. Press Enter to open it; opening stays unavailable until the terminal is tall enough to show the whole destination. Press Escape once to clear the selection, and Escape again to leave the thread. A thread with no selectable links keeps the normal global Tab focus behavior. Existing OSC 8 mouse links remain available. Most of those keep working while you are reading a thread, the way the web app's topic diff --git a/internal/tui/action_picker.go b/internal/tui/action_picker.go new file mode 100644 index 00000000..b35cf2a4 --- /dev/null +++ b/internal/tui/action_picker.go @@ -0,0 +1,74 @@ +package tui + +import ( + "strings" + "unicode/utf8" + + tea "charm.land/bubbletea/v2" + + "github.com/basecamp/hey-cli/internal/mail" + "github.com/basecamp/hey-cli/internal/terminal" +) + +// Keep short choices compact, but let a small terminal use all the space it has. +func actionPickerFrame(title, subject, filter, hint string, names []string, cursor, width, height int) string { + width = min(width, 64) + rows := modalContentRows(min(height, 18)) + contentWidth := modalContentWidth(width) + var before, after []string + if filter != "" && rows >= 2 { + before = append(before, truncateToWidth("Filter: "+terminal.SanitizeLine(filter), contentWidth)) + } + if hint != "" && rows >= 5 { + after = append(after, truncateToWidth(hint, contentWidth)) + } + // Keep the complete subject when it fits; on a tiny terminal the choices take + // priority over a fragment that cannot identify the thread. + if subject != "" && rows >= 5 { + lines := wrapText(terminal.SanitizeLine(subject), contentWidth) + if len(lines) <= rows-len(before)-len(after)-1 { + before = append(lines, before...) + } + } + visible := min(8, max(rows-len(before)-len(after), 1)) + list := modalListRows(names, cursor, contentWidth, visible) + if len(names) == 0 { + list = []string{truncateToWidth("No matches", contentWidth)} + } + body := append(before, list...) + body = append(body, after...) + return modalFrame(title, strings.Join(body, "\n"), width) +} + +// HEY's Name is the thread subject; Summary is only a message excerpt. +func pickerThreadSubject(posting mail.Posting) string { + subject := strings.TrimSpace(terminal.SanitizeLine(posting.Name)) + if subject == "" { + return terminal.SanitizeLine(posting.Summary) + } + return subject +} + +func pickerNameMatches(name, filter string) bool { + return strings.Contains(strings.ToLower(terminal.SanitizeLine(name)), strings.ToLower(filter)) +} + +// These lists only need an append-and-backspace filter; label creation keeps its +// existing text input with cursor movement and editing. +func editPickerFilter(filter *string, msg tea.KeyPressMsg) bool { + previous := *filter + switch { + case msg.Key().Code == tea.KeyBackspace: + if len(*filter) > 0 { + _, size := utf8.DecodeLastRuneInString(*filter) + *filter = (*filter)[:len(*filter)-size] + } + case msg.String() == "ctrl+u": + *filter = "" + case msg.Key().Text != "" && msg.Key().Mod&(tea.ModCtrl|tea.ModAlt|tea.ModSuper) == 0: + text := terminal.SanitizeLine(msg.Key().Text) + runes := []rune(*filter + text) + *filter = string(runes[:min(len(runes), 80)]) + } + return previous != *filter +} diff --git a/internal/tui/action_picker_test.go b/internal/tui/action_picker_test.go new file mode 100644 index 00000000..f5af95cf --- /dev/null +++ b/internal/tui/action_picker_test.go @@ -0,0 +1,277 @@ +package tui + +import ( + "fmt" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + + "github.com/basecamp/hey-cli/internal/mail" +) + +func TestActionPickersPreserveTheScreenBehindThem(t *testing.T) { + for _, key := range []string{"v", "b", "n"} { + for _, screen := range []string{"inbox", "thread", "search", "bundle", "seen"} { + t.Run(key+"/"+screen, func(t *testing.T) { + v := modalViewWithPostings(t) + v.Resize(100, 30) + v.postingList.toggleSelected() + switch screen { + case "thread": + v.inThread = true + v.threadPosting = v.postingList.postings[0] + v.topicViewport.SetContent(strings.Repeat("Hotel newsletter body\n", 80)) + v.topicViewport.SetYOffset(10) + case "search": + v.searchActive = true + v.searchList.setPostings([]mail.Posting{{ID: 201, TopicID: 301, Summary: "Search result"}}) + case "bundle": + v.bundleActive = true + v.bundleList.setPostings([]mail.Posting{{ID: 201, TopicID: 301, Summary: "Bundle thread"}}) + case "seen": + v.seenActive = true + v.seenList.setPostings([]mail.Posting{{ID: 201, TopicID: 301, Summary: "Seen thread"}}) + } + // Bulk-selection policy is separate from these single-thread presentations. + // Open the picker directly to exercise the same rendering from every screen. + before := v.View() + offset := v.topicViewport.YOffset() + switch key { + case "v": + v.startMove() + case "b": + v.startFolderPicker() + case "n": + v.startCollectionPicker() + } + if v.modal == nil { + t.Fatal("picker did not open") + } + rendered := stripANSI(v.View()) + if !strings.Contains(rendered, "╭") { + t.Fatal("picker did not draw a frame") + } + if screen == "thread" && !strings.Contains(rendered, "Hotel newsletter body") { + t.Fatal("thread disappeared behind picker") + } + if key == "v" { + p := moveModal(v) + frame := p.view(v.vc.styles, v.vc.width) + if lipgloss.Width(frame) >= v.vc.width || lipgloss.Height(frame) >= v.vc.height { + t.Fatal("short picker consumed the screen") + } + } + v.HandleContentKey(keyPress("esc")) + if v.modal != nil || v.View() != before || v.topicViewport.YOffset() != offset || len(v.postingList.selectedIDs()) != 1 { + t.Fatal("dismissal changed the underlying screen, scroll, or selection") + } + }) + } + } +} + +func TestActionPickerFilteringKeepsTheCorrectTarget(t *testing.T) { + v, recorded := mailWithTestServer(t, 200) + v.boxes = append(v.boxes, + mail.Source{ID: 12, Kind: mail.KindFolder, Name: "Hotel receipts"}, + mail.Source{ID: 13, Kind: mail.KindFolder, Name: "Travel plans"}, + mail.Source{ID: 24, Kind: mail.KindCollection, Name: "Hotel receipts"}, + mail.Source{ID: 25, Kind: mail.KindCollection, Name: "Travel plans"}) + v.postingList.postings[0].TopicID = 501 + v.postingList.postings[0].Folders = []mail.Folder{{ID: 13, Name: "Travel plans"}} + v.HandleContentKey(keyPress("b")) + v.HandleContentKey(keyPress("down")) + v.HandleContentKey(keyPress("HOTEL")) + p := folderModal(v) + if p.cursor != 0 || p.selected().folder.ID != 12 { + t.Fatal("filter kept a stale cursor or wrong label") + } + if screen := stripANSI(v.View()); strings.Contains(screen, "[x] Travel plans") || !strings.Contains(screen, "Filter: HOTEL") { + t.Fatal("filter did not update label choices") + } + cmd := v.HandleContentKey(keyPress("enter")) + done := cmd() + v.Update(done) + if recorded.path != "/postings/filings.json" || recorded.body.FolderID == nil || *recorded.body.FolderID != 12 { + t.Fatalf("wrong label operation: %s", recorded.path) + } + v.HandleContentKey(keyPress("n")) + v.HandleContentKey(keyPress("Travel")) + c := collectionModal(v) + if c.selected() == nil || c.selected().ID != 25 { + t.Fatal("collection filter used an unfiltered index") + } + v.HandleContentKey(keyPress("zzzz")) + if c.selected() != nil || !strings.Contains(stripANSI(v.View()), "No matches") { + t.Fatal("no-match filter retained an actionable collection") + } + if cmd := v.HandleContentKey(keyPress("enter")); cmd != nil || v.modal != c { + t.Fatal("Enter on no matches dispatched or dismissed") + } + v.HandleContentKey(tea.KeyPressMsg{Code: 'u', Mod: tea.ModCtrl}) + if c.filter != "" || c.selected().ID != 24 { + t.Fatal("clearing filter failed to restore choices") + } + v.HandleContentKey(keyPress("esc")) + v.postingList.postings[0].Collections = []mail.Collection{{ID: 25, Name: "Travel plans"}} + v.HandleContentKey(keyPress("n")) + v.HandleContentKey(keyPress("travel")) + collection := collectionModal(v) + if collection.selected() == nil || collection.selected().ID != 25 { + t.Fatal("filter targeted the wrong collection") + } + if !strings.Contains(stripANSI(v.View()), "[x] Travel plans") { + t.Fatal("filtered collection lost membership mark") + } + cmd = v.HandleContentKey(keyPress("enter")) + cmd() + if recorded.method != "DELETE" || recorded.path != "/topics/501/collecting" || recorded.rawQueries[len(recorded.rawQueries)-1] != "collection_id=25" { + t.Fatalf("wrong filtered collection operation: %s %s %v", recorded.method, recorded.path, recorded.rawQueries) + } +} + +func TestLabelCreationPreservesFilterOnBack(t *testing.T) { + v := modalViewWithPostings(t) + v.startFolderPicker() + v.HandleContentKey(keyPress("missing")) + p := folderModal(v) + if p.selected().kind != folderPickerCreate { + t.Fatal("create is unreachable with no matching labels") + } + v.HandleContentKey(keyPress("enter")) + if !p.creating || !strings.Contains(stripANSI(v.View()), "Create label") { + t.Fatal("create did not stay in modal") + } + p.input.SetValue(strings.Repeat("Holiday receipts ", 10)) + p.input.SetCursor(70) + for _, width := range []int{24, 40, 80} { + v.Resize(width, 24) + frame := p.view(newStyles(), width) + if lipgloss.Width(frame) > width { + t.Fatalf("create label exceeds width %d: %d", width, lipgloss.Width(frame)) + } + } + v.HandleContentKey(keyPress("esc")) + if v.modal != p || p.creating || p.filter != "missing" || p.selected().kind != folderPickerCreate { + t.Fatal("back lost filtered choices") + } + v.HandleContentKey(keyPress("esc")) + if v.modal != nil { + t.Fatal("second Escape did not dismiss") + } +} + +func TestActionPickerFilteringHandlesUnicodeAndControls(t *testing.T) { + filter := "" + editPickerFilter(&filter, keyPress("café")) + editPickerFilter(&filter, tea.KeyPressMsg{Code: tea.KeyBackspace}) + if filter != "caf" { + t.Fatalf("backspace split Unicode: %q", filter) + } + editPickerFilter(&filter, keyPress("\x1b]2;owned\a")) + if filter != "caf" { + t.Fatalf("filter retained control sequence: %q", filter) + } + editPickerFilter(&filter, keyPress(strings.Repeat("é", 200))) + if len([]rune(filter)) != 80 { + t.Fatal("filter exceeded its limit") + } + if !pickerNameMatches("Café\x1b]2;owned\a receipts", "CAFÉ") { + t.Fatal("matching differs from displayed names") + } +} + +func TestActionPickerFitsSmallScreensAndScrollsAfterResize(t *testing.T) { + sources := make([]mail.Source, 0, 40) + for i := range 40 { + sources = append(sources, mail.Source{ID: int64(i + 100), Kind: mail.KindFolder, Name: fmt.Sprintf("Label %02d", i)}) + } + p := newFolderPicker(mail.Posting{Summary: "An estimate for kitchen cabinets"}, sources) + for range 39 { + p.moveCursor(keyPress("down")) + } + for _, size := range [][2]int{{80, 24}, {24, 8}, {16, 7}, {80, 24}} { + p.resize(size[0], size[1]) + frame := p.view(newStyles(), size[0]) + if lipgloss.Width(frame) > size[0] || lipgloss.Height(frame) > size[1] { + t.Fatalf("frame exceeds %v: %dx%d", size, lipgloss.Width(frame), lipgloss.Height(frame)) + } + if size[0] >= 24 && !strings.Contains(stripANSI(frame), "Label 39") { + t.Fatal("resize hid the selected label") + } + } +} + +func TestActionPickersShowTheWrappedSubject(t *testing.T) { + const subject = "Your updated travel itinerary and hotel reservation for the long weekend in New Orleans" + posting := mail.Posting{ID: 100, Name: subject, Summary: "Plus, agent controls, single-use cards, and a clearer view of your spending"} + sources := []mail.Source{{ID: 12, Kind: mail.KindFolder, Name: "Travel plans"}, {ID: 24, Kind: mail.KindCollection, Name: "Receipts"}} + folders := newFolderPicker(posting, sources) + collections := newCollectionMembershipPicker(posting, sources) + move := newMovePicker(posting, []mail.Source{{ID: 2, Kind: mail.KindBox, Name: "The Feed"}}, mail.Source{ID: 1, Kind: mail.KindBox}) + for _, picker := range []interface { + resize(int, int) + view(styles, int) string + }{folders, collections, move} { + picker.resize(80, 24) + frame := picker.view(newStyles(), 80) + text := strings.Join(strings.Fields(stripANSI(frame)), " ") + for _, line := range wrapText(subject, modalContentWidth(64)) { + if !strings.Contains(text, line) { + t.Fatalf("subject was clipped: %q", text) + } + } + if strings.Contains(text, "agent controls") || strings.Contains(text, "...") { + t.Fatalf("picker used a clipped message excerpt: %q", text) + } + if lipgloss.Width(frame) > 64 || lipgloss.Height(frame) > 24 { + t.Fatal("wrapping overflowed the menu") + } + } + if got := pickerThreadSubject(mail.Posting{Summary: "Hotel reservation confirmed"}); got != "Hotel reservation confirmed" { + t.Fatalf("missing subject fallback: %q", got) + } +} + +func TestActionPickerLongContextLeavesChoicesUsable(t *testing.T) { + for _, height := range []int{8, 12, 24} { + frame := actionPickerFrame("Label thread", strings.Repeat("A very long subject ", 100), "travel", "Type to filter", []string{"Travel plans"}, 0, 40, height) + if lipgloss.Height(frame) > height || !strings.Contains(stripANSI(frame), "Travel plans") { + t.Fatal("long subject crowded out the selected action") + } + } +} + +func TestActionPickersPreserveScrollThroughModel(t *testing.T) { + for _, key := range []string{"v", "b"} { + t.Run(key, func(t *testing.T) { + testPickerScrollThroughModel(t, key) + }) + } +} + +func TestActionPickersPreserveListThroughModel(t *testing.T) { + for _, key := range []string{"v", "b", "n"} { + t.Run(key, func(t *testing.T) { + m := modelWithBoxes() + v := m.mailView + v.boxes = append(v.boxes, mail.Source{ID: 12, Kind: mail.KindFolder, Name: "Travel plans"}, mail.Source{ID: 24, Kind: mail.KindCollection, Name: "Hotel receipts"}) + updated, _ := m.Update(keyPress("down")) + m = updated.(model) + posting := v.postingList.selectedPosting().ID + before := m.View().Content + updated, _ = m.Update(keyPress(key)) + m = updated.(model) + if v.modal == nil { + t.Fatal("picker did not open") + } + updated, _ = m.Update(keyPress("esc")) + m = updated.(model) + if v.modal != nil || v.postingList.selectedPosting().ID != posting || m.View().Content != before { + t.Fatal("dismissal changed the list or cursor") + } + }) + } +} diff --git a/internal/tui/collections.go b/internal/tui/collections.go index bb1e66ae..1ba3f57c 100644 --- a/internal/tui/collections.go +++ b/internal/tui/collections.go @@ -1,11 +1,7 @@ package tui import ( - "fmt" - "strings" - tea "charm.land/bubbletea/v2" - "charm.land/lipgloss/v2" "github.com/basecamp/hey-cli/internal/mail" "github.com/basecamp/hey-cli/internal/terminal" @@ -79,7 +75,7 @@ type collectionMembershipPicker struct { posting mail.Posting collections []mail.Collection cursor int - offset int + filter string height int } @@ -94,10 +90,11 @@ func newCollectionMembershipPicker(posting mail.Posting, sources []mail.Source) } func (p *collectionMembershipPicker) selected() *mail.Collection { - if p.cursor < 0 || p.cursor >= len(p.collections) { + choices := p.choices() + if p.cursor < 0 || p.cursor >= len(choices) { return nil } - return &p.collections[p.cursor] + return &choices[p.cursor] } func (p *collectionMembershipPicker) postingHasCollection(collectionID int64) bool { @@ -133,73 +130,42 @@ func (p *collectionMembershipPicker) handleKey(view *mailView, msg tea.KeyPressM } func (p *collectionMembershipPicker) draw(view *mailView) string { - return p.view(view.vc.styles, view.vc.width) + return overlayModal(view.contentView(), p.view(view.vc.styles, view.vc.width), view.vc.width, view.vc.height) } -func (p *collectionMembershipPicker) update(msg tea.KeyPressMsg) { - switch msg.Key().Code { - case tea.KeyUp: - if p.cursor > 0 { - p.cursor-- - } - case tea.KeyDown: - if p.cursor < len(p.collections)-1 { - p.cursor++ +func (p *collectionMembershipPicker) choices() []mail.Collection { + var choices []mail.Collection + for _, collection := range p.collections { + if pickerNameMatches(collection.Name, p.filter) { + choices = append(choices, collection) } } - p.ensureVisible() -} - -// resize takes the height alone: the rows are laid out against the width it is drawn -// with rather than a width it has to keep. -func (p *collectionMembershipPicker) resize(_, height int) { - p.height = height - p.ensureVisible() -} - -func (p *collectionMembershipPicker) visibleRows() int { - return max(p.height-5, 1) + return choices } -func (p *collectionMembershipPicker) ensureVisible() { - if p.cursor < p.offset { - p.offset = p.cursor - } - rows := p.visibleRows() - if p.cursor >= p.offset+rows { - p.offset = p.cursor - rows + 1 +func (p *collectionMembershipPicker) update(msg tea.KeyPressMsg) { + if editPickerFilter(&p.filter, msg) { + p.cursor = 0 + return } + p.cursor = stepListCursor(p.cursor, len(p.choices()), msg) } -func (p *collectionMembershipPicker) view(styles styles, width int) string { - contentWidth := max(width-4, 1) - var body strings.Builder - body.WriteString(styles.title.Render("Thread collections")) - if p.posting.Summary != "" { - fmt.Fprintf(&body, "\n%s", truncateStr(terminal.SanitizeLine(p.posting.Summary), contentWidth)) - } - body.WriteString("\n\n") - end := min(p.offset+p.visibleRows(), len(p.collections)) - for i := p.offset; i < end; i++ { - collection := p.collections[i] - prefix := " " - if i == p.cursor { - prefix = "› " - } - mark := "[ ]" +func (p *collectionMembershipPicker) resize(_, height int) { p.height = height } + +func (p *collectionMembershipPicker) view(_ styles, width int) string { + choices := p.choices() + names := make([]string, len(choices)) + for i, collection := range choices { + mark := "[ ] " if p.postingHasCollection(collection.ID) { - mark = "[x]" - } - label := mark + " " + terminal.SanitizeLine(collection.Name) - label = truncateStr(label, max(contentWidth-lipgloss.Width(prefix), 1)) - if i == p.cursor { - label = styles.title.Render(label) + mark = "[x] " } - fmt.Fprintf(&body, "%s%s\n", prefix, label) + names[i] = mark + terminal.SanitizeLine(collection.Name) } - return body.String() + return actionPickerFrame("Thread collections", pickerThreadSubject(p.posting), p.filter, "Type to filter · Backspace to edit · Ctrl+U to clear", names, p.cursor, width, p.height) } func (p *collectionMembershipPicker) helpBindings() []helpBinding { - return []helpBinding{{"↑↓", "select"}, {"enter", "toggle"}, {"esc", "cancel"}} + return []helpBinding{{"type", "filter"}, {"↑↓", "select"}, {"enter", "toggle"}, {"esc", "cancel"}} } diff --git a/internal/tui/collections_test.go b/internal/tui/collections_test.go index 418c079e..25485cc1 100644 --- a/internal/tui/collections_test.go +++ b/internal/tui/collections_test.go @@ -603,7 +603,7 @@ func TestMailViewCollectionNavigationHelp(t *testing.T) { func TestMailViewCollectionMembershipHelp(t *testing.T) { picker := newCollectionMembershipPicker(mail.Posting{}, nil) bindings := picker.helpBindings() - if len(bindings) != 3 || bindings[1].desc != "toggle" { + if len(bindings) != 4 || bindings[0].desc != "filter" || bindings[2].desc != "toggle" { t.Errorf("bindings = %+v", bindings) } } diff --git a/internal/tui/folders.go b/internal/tui/folders.go index 8ea9d4c3..a57baf92 100644 --- a/internal/tui/folders.go +++ b/internal/tui/folders.go @@ -1,7 +1,6 @@ package tui import ( - "fmt" "strings" "charm.land/bubbles/v2/textinput" @@ -38,7 +37,7 @@ type folderPicker struct { posting mail.Posting folders []mail.Source cursor int - offset int + filter string height int creating bool input textinput.Model @@ -61,7 +60,9 @@ func newFolderPicker(posting mail.Posting, sources []mail.Source) *folderPicker func (p *folderPicker) choices() []folderPickerSelection { choices := make([]folderPickerSelection, 0, len(p.folders)+2) for _, folder := range p.folders { - choices = append(choices, folderPickerSelection{kind: folderPickerExisting, folder: folder}) + if pickerNameMatches(folder.Name, p.filter) { + choices = append(choices, folderPickerSelection{kind: folderPickerExisting, folder: folder}) + } } choices = append(choices, folderPickerSelection{kind: folderPickerCreate}) if len(p.posting.Folders) > 0 { @@ -159,7 +160,7 @@ func (p *folderPicker) handleMsg(msg tea.Msg) (tea.Cmd, bool) { } func (p *folderPicker) draw(view *mailView) string { - return p.view(view.vc.styles, view.vc.width) + return overlayModal(view.contentView(), p.view(view.vc.styles, view.vc.width), view.vc.width, view.vc.height) } func (p *folderPicker) update(msg tea.Msg) tea.Cmd { @@ -172,92 +173,53 @@ func (p *folderPicker) update(msg tea.Msg) tea.Cmd { } func (p *folderPicker) moveCursor(msg tea.KeyPressMsg) { - switch msg.Key().Code { - case tea.KeyUp: - if p.cursor > 0 { - p.cursor-- - } - case tea.KeyDown: - if p.cursor < len(p.choices())-1 { - p.cursor++ - } + if editPickerFilter(&p.filter, msg) { + p.cursor = 0 + return } - p.ensureVisible() + p.cursor = stepListCursor(p.cursor, len(p.choices()), msg) } func (p *folderPicker) resize(width, height int) { p.height = height - p.input.SetWidth(max(width-16, 10)) - p.ensureVisible() + p.input.SetWidth(max(modalContentWidth(min(width, 64))-7, 1)) + // SetWidth does not recompute the text input's horizontal window. Walk to the + // end and back so resizing also works with the cursor inside a long name. + position := p.input.Position() + p.input.CursorEnd() + p.input.SetCursor(position) } -func (p *folderPicker) visibleRows() int { - return max(p.height-5, 1) -} - -func (p *folderPicker) ensureVisible() { - if p.cursor < p.offset { - p.offset = p.cursor - } - rows := p.visibleRows() - if p.cursor >= p.offset+rows { - p.offset = p.cursor - rows + 1 - } -} - -func (p *folderPicker) view(styles styles, width int) string { - contentWidth := max(width-4, 1) - var b strings.Builder +func (p *folderPicker) view(_ styles, width int) string { if p.creating { - b.WriteString(styles.title.Render("Create label")) - b.WriteString("\n\n") - b.WriteString(styleMuted.Render("Name: ")) - b.WriteString(p.input.View()) + body := "Name: " + p.input.View() if p.status != "" { - b.WriteString("\n\n") - b.WriteString(lipgloss.NewStyle().Foreground(colorError).Render(p.status)) + body += "\n" + lipgloss.NewStyle().Foreground(colorError).Render(truncateToWidth(p.status, modalContentWidth(min(width, 64)))) } - return b.String() - } - - b.WriteString(styles.title.Render("Label thread")) - if p.posting.Summary != "" { - fmt.Fprintf(&b, "\n%s", truncateStr(terminal.SanitizeLine(p.posting.Summary), contentWidth)) + return modalFrame("Create label", body, min(width, 64)) } - b.WriteString("\n\n") choices := p.choices() - end := min(p.offset+p.visibleRows(), len(choices)) - for i := p.offset; i < end; i++ { - choice := choices[i] - prefix := " " - if i == p.cursor { - prefix = "› " - } - label := "" + names := make([]string, len(choices)) + for i, choice := range choices { switch choice.kind { case folderPickerExisting: - mark := "[ ]" + mark := "[ ] " if p.postingHasFolder(choice.folder.ID) { - mark = "[x]" + mark = "[x] " } - label = mark + " " + terminal.SanitizeLine(choice.folder.Name) + names[i] = mark + terminal.SanitizeLine(choice.folder.Name) case folderPickerCreate: - label = "+ Create a new label…" + names[i] = "Create a new label…" case folderPickerRemoveAll: - label = "− Remove all labels" - } - label = truncateStr(label, max(contentWidth-lipgloss.Width(prefix), 1)) - if i == p.cursor { - label = styles.title.Render(label) + names[i] = "Remove all labels" } - fmt.Fprintf(&b, "%s%s\n", prefix, label) } - return b.String() + return actionPickerFrame("Label thread", pickerThreadSubject(p.posting), p.filter, "Type to filter · Backspace to edit · Ctrl+U to clear", names, p.cursor, width, p.height) } func (p *folderPicker) helpBindings() []helpBinding { if p.creating { return []helpBinding{{"enter", "create"}, {"esc", "back"}} } - return []helpBinding{{"↑↓", "select"}, {"enter", "toggle"}, {"esc", "cancel"}} + return []helpBinding{{"type", "filter"}, {"↑↓", "select"}, {"enter", "toggle"}, {"esc", "cancel"}} } diff --git a/internal/tui/mail.go b/internal/tui/mail.go index 701aa49c..f0b50e68 100644 --- a/internal/tui/mail.go +++ b/internal/tui/mail.go @@ -944,6 +944,11 @@ func (v *mailView) View() string { if v.modal != nil { return v.modal.draw(v) } + return v.contentView() +} + +// contentView draws the current mail screen without its temporary picker. +func (v *mailView) contentView() string { if v.inThread { v.fitThreadViewport() var lines []string diff --git a/internal/tui/mail_test.go b/internal/tui/mail_test.go index 5fec82c9..bfbc5e72 100644 --- a/internal/tui/mail_test.go +++ b/internal/tui/mail_test.go @@ -1882,12 +1882,12 @@ func TestMailViewFolderPickerTruncatesLongNamesToOneRow(t *testing.T) { picker.resize(24, 8) view := picker.view(testVC().styles, 24) - if !strings.Contains(view, "…") || strings.Contains(view, "much wider than the picker") { + if !strings.Contains(view, "...") || strings.Contains(view, "much wider than the picker") { t.Errorf("long label was not truncated: %q", view) } for _, line := range strings.Split(view, "\n") { - if width := lipgloss.Width(line); width > 20 { - t.Errorf("picker line width = %d, want at most 20: %q", width, line) + if width := lipgloss.Width(line); width > 24 { + t.Errorf("picker line width = %d, want at most 24: %q", width, line) } } } @@ -3722,7 +3722,7 @@ func TestMailViewHelpBindingsInFolderPicker(t *testing.T) { v.HandleContentKey(keyPress("b")) bindings := v.HelpBindings() - if len(bindings) != 3 || bindings[0].key != "↑↓" || bindings[1].key != "enter" || bindings[2].key != "esc" { + if len(bindings) != 4 || bindings[0].desc != "filter" || bindings[1].key != "↑↓" || bindings[2].key != "enter" || bindings[3].key != "esc" { t.Errorf("folder picker help = %v", bindings) } } diff --git a/internal/tui/move.go b/internal/tui/move.go index 0244e66d..0002d92b 100644 --- a/internal/tui/move.go +++ b/internal/tui/move.go @@ -1,9 +1,6 @@ package tui import ( - "fmt" - "strings" - tea "charm.land/bubbletea/v2" hey "github.com/basecamp/hey-sdk/go/pkg/hey" @@ -16,9 +13,10 @@ type movePicker struct { plainModal postingID int64 - summary string + subject string destinations []mail.Source cursor int + height int } // newMovePicker offers the boxes a thread can be moved to: not where it already is, not @@ -35,7 +33,7 @@ func newMovePicker(posting mail.Posting, boxes []mail.Source, currentSource mail } return &movePicker{ postingID: posting.ID, - summary: posting.Summary, + subject: pickerThreadSubject(posting), destinations: destinations, } } @@ -62,7 +60,7 @@ func (p *movePicker) handleKey(view *mailView, msg tea.KeyPressMsg) (tea.Cmd, bo } func (p *movePicker) draw(view *mailView) string { - return p.view(view.vc.styles, view.vc.width) + return overlayModal(view.contentView(), p.view(view.vc.styles, view.vc.width), view.vc.width, view.vc.height) } func (p *movePicker) update(msg tea.KeyPressMsg) { @@ -78,26 +76,14 @@ func (p *movePicker) update(msg tea.KeyPressMsg) { } } -func (p *movePicker) view(styles styles, width int) string { - contentWidth := max(width-4, 1) - var b strings.Builder - b.WriteString(styles.title.Render("Move thread")) - if p.summary != "" { - fmt.Fprintf(&b, "\n%s", truncateStr(p.summary, contentWidth)) - } - b.WriteString("\n\n") +func (p *movePicker) resize(_, height int) { p.height = height } + +func (p *movePicker) view(_ styles, width int) string { + names := make([]string, len(p.destinations)) for i, box := range p.destinations { - prefix := " " - name := terminal.SanitizeLine(box.Name) - if i == p.cursor { - prefix = "› " - name = styles.title.Render(name) - } - fmt.Fprintf(&b, "%s%s\n", prefix, name) + names[i] = terminal.SanitizeLine(box.Name) } - b.WriteString("\n") - b.WriteString(strings.Join(wrapText("Moving to a box other than Imbox marks the thread as seen.", contentWidth), "\n")) - return b.String() + return actionPickerFrame("Move thread", p.subject, "", "Outside Imbox, moving marks the thread as seen.", names, p.cursor, width, p.height) } func (p *movePicker) helpBindings() []helpBinding { diff --git a/internal/tui/picker_scroll_test.go b/internal/tui/picker_scroll_test.go new file mode 100644 index 00000000..63e55651 --- /dev/null +++ b/internal/tui/picker_scroll_test.go @@ -0,0 +1,80 @@ +package tui + +import ( + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/basecamp/hey-cli/internal/htmlutil" +) + +func testPickerScrollThroughModel(t *testing.T, key string) { + t.Helper() + for _, position := range []string{"middle", "bottom"} { + for _, selected := range []bool{false, true} { + name := position + if selected { + name += "/selected-link" + } + t.Run(name, func(t *testing.T) { + m := openLinkThreadThroughModel(t) + v := m.mailView + v.pendingMutations = 0 + v.entries[0].Body = htmlutil.ToMarkdown(`

Read the newsletter

` + strings.Repeat("

Travel plans and hotel reservations.

", 100)) + v.rebuildTopicContent() + updated, _ := m.Update(tea.WindowSizeMsg{Width: 60, Height: 30}) + m = updated.(model) + if selected { + updated, _ = m.Update(keyPress("tab")) + m = updated.(model) + footer, visible := m.linkFooter() + if !visible || !strings.Contains(footer, "\n") { + t.Fatal("expected a wrapping link footer") + } + } + if position == "bottom" { + for range 30 { + updated, _ = m.Update(keyPress("pgdown")) + m = updated.(model) + } + } else { + for range 35 { + updated, _ = m.Update(keyPress("down")) + m = updated.(model) + } + } + offset := v.topicViewport.YOffset() + if offset == 0 { + t.Fatal("thread did not scroll") + } + link, linkKey := v.selectedLink, v.selectedLinkKey + before := m.View().Content + updated, _ = m.Update(keyPress(key)) + m = updated.(model) + if v.modal == nil { + t.Fatal("picker did not open") + } + // A taller background may clamp at the bottom while the picker is open. + want := min(offset, max(v.topicViewport.TotalLineCount()-v.topicViewport.Height(), 0)) + if got := v.topicViewport.YOffset(); got != want { + t.Fatalf("opening picker offset = %d, want %d", got, want) + } + updated, _ = m.Update(keyPress("esc")) + m = updated.(model) + if v.modal != nil { + t.Fatal("picker did not close") + } + if got := v.topicViewport.YOffset(); got != offset { + t.Errorf("dismissal offset = %d, want %d", got, offset) + } + if v.selectedLink != link || v.selectedLinkKey != linkKey { + t.Error("picker changed link selection") + } + if got := m.View().Content; got != before { + t.Error("dismissal changed the rendered screen") + } + }) + } + } +} diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 38618ddd..8e98b1b1 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -72,6 +72,9 @@ type model struct { calendarView *calendarView journalView *journalView + // Keep the reading position while modal help changes the thread viewport. + mailModalScroll *int + // The Screener, opened over the mail section with ctrl+s screenerView *screenerView @@ -311,6 +314,8 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return opened, tea.Batch(initCmd, openCmd) case tea.WindowSizeMsg: + // A terminal resize lays out the selected link at its new dimensions. + m.mailModalScroll = nil m.width = msg.Width m.height = msg.Height m.vc.width = msg.Width @@ -802,12 +807,26 @@ func (m *model) updateHelpBindings() { bindings = append(bindings, helpBinding{"ctrl+a", description}) } } + // Opening a modal removes the link footer and changes the help height. + // Save the offset before that resize can reveal an old link or clamp the + // viewport near the bottom; restore it again when the modal closes. + mailThread := m.activeView == m.mailView && m.mailView.inThread + if mailThread && m.mailView.modal != nil && m.mailModalScroll == nil { + offset := m.mailView.topicViewport.YOffset() + m.mailModalScroll = &offset + } m.help.setBindings(bindings) contentHeight := m.contentHeight() if contentHeight != m.vc.height { m.vc.height = contentHeight m.activeView.Resize(m.vc.width, contentHeight) } + if mailThread && m.mailModalScroll != nil { + m.mailView.topicViewport.SetYOffset(*m.mailModalScroll) + } + if !mailThread || m.mailView.modal == nil { + m.mailModalScroll = nil + } } // linkFooter is the link status as it goes on screen. A destination that wraps onto