diff --git a/README.md b/README.md index 4ec32e1..84f4b5d 100644 --- a/README.md +++ b/README.md @@ -129,11 +129,13 @@ only one action, an action needs at least one key, and an unknown name is a load ## State -chute remembers the last account and the folder each account had open, in +chute remembers the last account, the folder each account had open, and which folders +each account had expanded in the folder tree, in `$XDG_STATE_HOME/chute/state.toml` or `~/.local/state/chute/state.toml` when `XDG_STATE_HOME` is unset. It holds names only — no credentials, no addresses, no message data — is written `0600`, and deleting it is safe: the config remains the authority and a -name that no longer exists is ignored. +name that no longer exists is ignored. A folder absent from the expanded set is folded, +so a new state file opens the tree showing only its top level. ## Flags @@ -179,7 +181,7 @@ Composer keys are fixed, not part of `[keys]`: | `down` | `down` | Move down one message. | | `top` | `home`, `g` | First message. | | `bottom` | `end`, `G` | Last message. | -| `open` | `enter` | Open the message, or load the folder under the cursor. | +| `open` | `enter` | Open the message, or load the folder under the cursor. In the folder pane, a collapsed folder expands first (`right` expands without opening); the next `enter` loads it. | | `filter` | `/` | Fuzzy, case-insensitive filter over the loaded list's sender, subject and recipients. | | `search` | `S` | Server-side search of the open folder; free text plus `from:`, `subject:`, `text:`, `body:` and `since:YYYY-MM-DD`. `esc` returns to the folder. | | `visual_range` | `v` | Anchor a selection range for the actions below. | @@ -189,6 +191,8 @@ Composer keys are fixed, not part of `[keys]`: | `move` | `m` | Move to a mailbox chosen from a picker; type to filter the folder list. | | `empty_trash` | `X` | Delete everything in Trash, after a confirmation. Only works inside Trash. | | `collapse` | `z` | Fold or unfold the conversation under the cursor. | +| `expand_folder` | `right` | In the folder pane, expand the folder under the cursor. | +| `collapse_folder` | `left` | In the folder pane, fold the folder under the cursor. | | `toggle_flag` | `f` | Flag or unflag. | | `toggle_read` | `u` | Mark read or unread. | | `attachments` | `s` | List attachments and save them to `download_dir`. | diff --git a/config/keys.go b/config/keys.go index c99cf81..b081076 100644 --- a/config/keys.go +++ b/config/keys.go @@ -47,6 +47,8 @@ const ( KeyMove = "move" KeyEmptyTrash = "empty_trash" KeyCollapse = "collapse" + KeyExpandFolder = "expand_folder" + KeyCollapseFolder = "collapse_folder" KeySearch = "search" KeySettings = "settings" KeyHelp = "help" @@ -87,6 +89,8 @@ var keyDefaults = map[string][]string{ KeyMove: {"m"}, KeyEmptyTrash: {"X"}, KeyCollapse: {"z"}, + KeyExpandFolder: {"right"}, + KeyCollapseFolder: {"left"}, KeySearch: {"S"}, KeySettings: {","}, KeyHelp: {"?"}, diff --git a/config/state.go b/config/state.go index bc1a718..ceb02bd 100644 --- a/config/state.go +++ b/config/state.go @@ -14,9 +14,10 @@ const stateFilename = "state.toml" // State is the last selection, remembered so a restart lands where the user left. // -// It holds names only: which account was active, and which folder each account had -// open. No credentials, no addresses, no message data. The config remains the -// authority — a name that no longer exists there is simply ignored. +// It holds names only: which account was active, which folder each account had +// open, and which folders each account had expanded in the folder tree. No +// credentials, no addresses, no message data. The config remains the authority — a +// name that no longer exists there is simply ignored. type State struct { // Account is the account that was active, by name. Empty means none was recorded. Account string `toml:"account"` @@ -24,6 +25,11 @@ type State struct { // Folders maps an account name to the folder it had open. A missing entry means // the account has no recorded folder. Folders map[string]string `toml:"folders"` + + // Expanded maps an account name to the folders whose subfolders were shown. A + // folder absent from the list is collapsed, which is also the default for a new + // state file: the tree opens showing only its top level. + Expanded map[string][]string `toml:"expanded"` } // StatePath is the last-selection file: $XDG_STATE_HOME/chute/state.toml, or diff --git a/config/state_test.go b/config/state_test.go index 43ec5a9..ba6e14e 100644 --- a/config/state_test.go +++ b/config/state_test.go @@ -70,8 +70,9 @@ func TestSaveStateRoundTrips(t *testing.T) { dir := withStateDir(t) want := State{ - Account: "work", - Folders: map[string]string{"work": "Archive", "fastmail": "INBOX"}, + Account: "work", + Folders: map[string]string{"work": "Archive", "fastmail": "INBOX"}, + Expanded: map[string][]string{"work": {"Work", "Work/2024"}}, } if err := SaveState(want); err != nil { t.Fatalf("SaveState: %v", err) @@ -92,7 +93,11 @@ func TestSaveStateRoundTrips(t *testing.T) { } // A second write replaces the file without changing its mode. - next := State{Account: "fastmail", Folders: map[string]string{"fastmail": "Sent"}} + next := State{ + Account: "fastmail", + Folders: map[string]string{"fastmail": "Sent"}, + Expanded: map[string][]string{"fastmail": {"Archive"}}, + } if err := SaveState(next); err != nil { t.Fatalf("second SaveState: %v", err) } @@ -108,11 +113,17 @@ func TestSaveStateRoundTrips(t *testing.T) { } // TestStateFileHoldsOnlyNames is the issue's privacy criterion: account and folder -// names, and nothing that could carry a credential or message content. +// names, and nothing that could carry a credential or message content. The expanded +// set is folder names too, so it belongs on the same side of that line. func TestStateFileHoldsOnlyNames(t *testing.T) { dir := withStateDir(t) - if err := SaveState(State{Account: "work", Folders: map[string]string{"work": "Archive"}}); err != nil { + state := State{ + Account: "work", + Folders: map[string]string{"work": "Archive"}, + Expanded: map[string][]string{"work": {"Work", "Work/2024"}}, + } + if err := SaveState(state); err != nil { t.Fatalf("SaveState: %v", err) } @@ -126,8 +137,8 @@ func TestStateFileHoldsOnlyNames(t *testing.T) { t.Fatalf("decoding state: %v", err) } - if len(raw) != 2 { - t.Fatalf("top-level keys = %v, want exactly account and folders", raw) + if len(raw) != 3 { + t.Fatalf("top-level keys = %v, want exactly account, folders and expanded", raw) } if raw["account"] != "work" { t.Errorf("account = %v, want work", raw["account"]) @@ -141,6 +152,14 @@ func TestStateFileHoldsOnlyNames(t *testing.T) { t.Errorf("folders = %v, want work = Archive", folders) } + expanded, ok := raw["expanded"].(map[string]any) + if !ok { + t.Fatalf("expanded = %T, want a table", raw["expanded"]) + } + if got, want := expanded["work"], []any{"Work", "Work/2024"}; !reflect.DeepEqual(got, want) { + t.Errorf("expanded[work] = %v, want %v", got, want) + } + for _, forbidden := range []string{"password", "username", "imap", "smtp"} { if strings.Contains(strings.ToLower(string(data)), forbidden) { t.Errorf("state file mentions %q:\n%s", forbidden, data) diff --git a/tui/accounts.go b/tui/accounts.go index cfcdc85..d0fff27 100644 --- a/tui/accounts.go +++ b/tui/accounts.go @@ -103,6 +103,7 @@ func (m Model) selectAccount(index int) (tea.Model, tea.Cmd) { m.folders = nil m.folderCursor = 0 m.folderScroll = 0 + m.folderExpanded = nil m.openFolder = "" m.messages = nil diff --git a/tui/collapse_test.go b/tui/collapse_test.go index 7627edd..2baed46 100644 --- a/tui/collapse_test.go +++ b/tui/collapse_test.go @@ -136,7 +136,9 @@ func TestCollapseFitsTheFrame(t *testing.T) { assertExactFrame(t, m, "collapsed thread") } -// TestCollapseKeyOutsideTheListIsInert proves the triage guard applies. +// TestCollapseKeyOutsideTheListIsInert proves the triage guard applies: z collapses +// threads, so in the folder pane it does nothing. Folding a folder is left's job +// (TestArrowKeysExpandAndFoldTheFolder), not the thread gesture's. func TestCollapseKeyOutsideTheListIsInert(t *testing.T) { m := loaded(t, 140, 40, []mail.Folder{{Name: "INBOX", Delimiter: '/'}}, nil) m.focus = focusFolders diff --git a/tui/folders.go b/tui/folders.go index df95bdd..e3742c6 100644 --- a/tui/folders.go +++ b/tui/folders.go @@ -25,40 +25,45 @@ func (m Model) folderRows() int { return rows } -// moveFolderCursor moves the selection and keeps it inside the scroll window. +// moveFolderCursor moves the selection and keeps it inside the scroll window. The +// cursor indexes the visible tree, not the listing: a hidden subfolder cannot be +// selected, and a collapsed parent keeps the cursor where the user left it. func (m *Model) moveFolderCursor(delta int) { - if len(m.folders) == 0 { + rows := m.folderTree() + if len(rows) == 0 { return } - m.folderCursor = clamp(m.folderCursor+delta, 0, len(m.folders)-1) + m.folderCursor = clamp(m.folderCursor+delta, 0, len(rows)-1) - rows := m.folderRows() + visible := m.folderRows() if m.folderCursor < m.folderScroll { m.folderScroll = m.folderCursor } - if m.folderCursor >= m.folderScroll+rows { - m.folderScroll = m.folderCursor - rows + 1 + if m.folderCursor >= m.folderScroll+visible { + m.folderScroll = m.folderCursor - visible + 1 } } -// clampFolderScroll keeps the stored scroll offset valid after a reload or resize. +// clampFolderScroll keeps the stored scroll offset valid after a reload, a resize or a +// fold that changed how many rows are drawn. func (m *Model) clampFolderScroll() { - rows := m.folderRows() - maxScroll := max(0, len(m.folders)-rows) + rows := len(m.folderTree()) + visible := m.folderRows() + maxScroll := max(0, rows-visible) m.folderScroll = clamp(m.folderScroll, 0, maxScroll) - m.folderCursor = clamp(m.folderCursor, 0, max(0, len(m.folders)-1)) + m.folderCursor = clamp(m.folderCursor, 0, max(0, rows-1)) if m.folderCursor < m.folderScroll { m.folderScroll = m.folderCursor } - if m.folderCursor >= m.folderScroll+rows { - m.folderScroll = m.folderCursor - rows + 1 + if m.folderCursor >= m.folderScroll+visible { + m.folderScroll = m.folderCursor - visible + 1 } } -// folderLines renders the visible slice of the folder list. +// folderLines renders the visible slice of the folder tree. func (m Model) folderLines(rows, width int) []string { if rows < 1 { return nil @@ -77,24 +82,50 @@ func (m Model) folderLines(rows, width int) []string { return []string{MutedStyle.Render("no folders")} } - start := clamp(m.folderScroll, 0, max(0, len(m.folders)-rows)) - end := min(start+rows, len(m.folders)) + tree := m.folderTree() + start := clamp(m.folderScroll, 0, max(0, len(tree)-rows)) + end := min(start+rows, len(tree)) lines := make([]string, 0, end-start) for i := start; i < end; i++ { - lines = append(lines, m.folderLine(i, width)) + lines = append(lines, m.folderTreeLine(tree[i], i == m.folderCursor, width)) } return lines } -// folderLine renders one folder, indented by depth and marked when selected. -func (m Model) folderLine(index, width int) string { - return folderRow(m.folders[index], index == m.folderCursor, width) +// folderTreeLine renders one row of the folder tree in the shape imap-notes uses: the +// +/- marker leads the row and the cursor is the bold row, with no separate glyph, so +// the marker is never displaced by the selection. A folder with no subfolders shows a +// blank marker rather than a sign that promises nothing. +func (m Model) folderTreeLine(row folderTreeRow, selected bool, width int) string { + folder := m.folders[row.index] + + marker := " " + if row.hasChildren { + if row.expanded { + marker = "- " + } else { + marker = "+ " + } + } + + label := strings.Repeat(" ", row.depth) + folder.Leaf() + label = Truncate(label, max(1, width-2)) + line := marker + label + + switch { + case selected: + return SelectedStyle.Render(line) + case !folder.Selectable(): + return MutedStyle.Render(line) + } + + return NormalStyle.Render(line) } -// folderRow renders one folder row: indent, leaf, marker and styling. The label -// is truncated so a long name never wraps onto a second line. +// folderRow renders one folder row for a flat list: the folders overlay and the move +// picker show every mailbox, including the ones the tree currently hides. func folderRow(folder mail.Folder, selected bool, width int) string { label := strings.Repeat(" ", folder.Depth()) + folder.Leaf() label = Truncate(label, max(1, width-2)) @@ -111,21 +142,22 @@ func folderRow(folder mail.Folder, selected bool, width int) string { // selectedFolder is the folder under the cursor, if there is one. func (m Model) selectedFolder() (mail.Folder, bool) { - if m.folderCursor < 0 || m.folderCursor >= len(m.folders) { + row, ok := m.selectedTreeRow() + if !ok { return mail.Folder{}, false } - return m.folders[m.folderCursor], true + return m.folders[row.index], true } -// moveFolderCursorTo puts the folder cursor on folder, if the listing still has it. +// moveFolderCursorTo puts the folder cursor on folder and reveals its path, if the +// listing still has it. func (m *Model) moveFolderCursorTo(folder mail.Folder) { - for i := range m.folders { - if m.folders[i].Name == folder.Name { - m.folderCursor = i + m.expandTo(folder.Name) - return - } + if index := m.treeRowIndex(folder.Name); index >= 0 { + m.folderCursor = index + m.clampFolderScroll() } } diff --git a/tui/folders_overlay.go b/tui/folders_overlay.go index c6334ee..f60cb08 100644 --- a/tui/folders_overlay.go +++ b/tui/folders_overlay.go @@ -22,7 +22,7 @@ func (m Model) openFolders() (tea.Model, tea.Cmd) { } m.foldersOpen = true - m.folderOverlayCursor = m.folderCursor + m.folderOverlayCursor = m.folderIndex() m.status = "" return m, nil @@ -44,8 +44,14 @@ func (m Model) handleFoldersKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.folderOverlayCursor = min(m.folderOverlayCursor+1, len(m.folders)-1) case actionOpen: - m.folderCursor = m.folderOverlayCursor + if m.folderOverlayCursor < 0 || m.folderOverlayCursor >= len(m.folders) { + return m, nil + } + // The overlay is a flat picker: it opens a mailbox, it does not fold the tree. + // Reveal the chosen folder's path first so the tree cursor can land on it. + m.moveFolderCursorTo(m.folders[m.folderOverlayCursor]) m.foldersOpen = false + return m.openSelectedFolder() } diff --git a/tui/folders_test.go b/tui/folders_test.go index 954d5a7..0abacfb 100644 --- a/tui/folders_test.go +++ b/tui/folders_test.go @@ -179,18 +179,22 @@ func TestResizeClampsFolderScroll(t *testing.T) { } } -func TestFolderLineIndentation(t *testing.T) { +func TestFolderTreeIndentation(t *testing.T) { m := loaded(t, 140, 40, []mail.Folder{ {Name: "Work", Delimiter: '/'}, {Name: "Work/Projects", Delimiter: '/'}, }, nil) + m.setFolderExpanded("Work", true) - nested := m.folderLine(1, 40) - if !strings.Contains(nested, " Projects") { - t.Errorf("nested line = %q, want two spaces before the leaf", nested) + lines := m.folderLines(10, 40) + if len(lines) < 2 { + t.Fatalf("folder lines = %v, want Work and its child", lines) } - if strings.Contains(nested, "Work/") { - t.Errorf("nested line = %q, want the leaf only", nested) + if !strings.Contains(lines[1], " Projects") { + t.Errorf("nested line = %q, want two spaces before the leaf", lines[1]) + } + if strings.Contains(lines[1], "Work/") { + t.Errorf("nested line = %q, want the leaf only", lines[1]) } } @@ -199,7 +203,7 @@ func TestFolderLineTruncates(t *testing.T) { {Name: "a folder name long enough to need truncation", Delimiter: '/'}, }, nil) - line := m.folderLine(0, 20) + line := m.folderLines(1, 20)[0] if !strings.Contains(line, "...") { t.Errorf("folder line %q has no ellipsis", line) } diff --git a/tui/foldertree.go b/tui/foldertree.go new file mode 100644 index 0000000..ce332e9 --- /dev/null +++ b/tui/foldertree.go @@ -0,0 +1,222 @@ +package tui + +import ( + "strings" + + "github.com/renderorange/chute/mail" +) + +// folderTreeRow is one visible row of the folder pane: which folder it is, how deep +// the tree draws it, and whether it hides subfolders. The expansion set lives on the +// model, keyed by mailbox name; a name that is not in it is collapsed, which is also +// what an absent state file means. +type folderTreeRow struct { + index int // into Model.folders + depth int + hasChildren bool + expanded bool +} + +// folderTree is the visible rows of the listing: every root, and the descendants of +// each expanded folder. It is derived on demand from the listing and the expansion +// set, so no second copy of the tree can go stale. +// +// A parent is the nearest ancestor the listing actually contains. Servers may omit an +// intermediate container, and some omit the parent entirely; those folders become roots +// rather than getting an invented parent row. The depth drawn is the tree depth, not +// the delimiter count, so an orphan still lines up with what is on screen. +func (m Model) folderTree() []folderTreeRow { + if len(m.folders) == 0 { + return nil + } + + byName := make(map[string]int, len(m.folders)) + for i, folder := range m.folders { + byName[folder.Name] = i + } + + children := make(map[string][]int, len(m.folders)) + roots := make([]int, 0, 4) + + for i, folder := range m.folders { + if parent := listedParent(folder, byName); parent != "" { + children[parent] = append(children[parent], i) + } else { + roots = append(roots, i) + } + } + + rows := make([]folderTreeRow, 0, len(m.folders)) + + var walk func(index, depth int) + walk = func(index, depth int) { + kids := children[m.folders[index].Name] + expanded := m.folderExpanded[m.folders[index].Name] + + rows = append(rows, folderTreeRow{ + index: index, + depth: depth, + hasChildren: len(kids) > 0, + expanded: expanded, + }) + + if !expanded { + return + } + for _, kid := range kids { + walk(kid, depth+1) + } + } + + for _, root := range roots { + walk(root, 0) + } + + return rows +} + +// listedParent is the nearest ancestor of folder that the listing contains, or "" for +// a root. Walking the whole path is what keeps a folder under a listed grandparent when +// the server skipped the parent in between. +func listedParent(folder mail.Folder, byName map[string]int) string { + for _, name := range ancestorNames(folder) { + if _, ok := byName[name]; ok { + return name + } + } + + return "" +} + +// ancestorNames lists a folder's ancestors nearest first: Work/Projects/2025 becomes +// ["Work/Projects", "Work"]. A folder with no delimiter has none. +func ancestorNames(folder mail.Folder) []string { + if folder.Delimiter == 0 { + return nil + } + + var names []string + + name := folder.Name + for { + idx := strings.LastIndex(name, string(folder.Delimiter)) + if idx < 0 { + return names + } + name = name[:idx] + names = append(names, name) + } +} + +// selectedTreeRow is the visible row under the cursor. +func (m Model) selectedTreeRow() (folderTreeRow, bool) { + rows := m.folderTree() + if m.folderCursor < 0 || m.folderCursor >= len(rows) { + return folderTreeRow{}, false + } + + return rows[m.folderCursor], true +} + +// treeRowIndex is the visible index of the folder with this name, or -1 when the +// expansion set hides it. +func (m Model) treeRowIndex(name string) int { + for i, row := range m.folderTree() { + if m.folders[row.index].Name == name { + return i + } + } + + return -1 +} + +// folderIndex is the position of the selected folder in the flat listing, which is what +// the folders overlay and the move picker index. It is 0 when nothing is selected. +func (m Model) folderIndex() int { + row, ok := m.selectedTreeRow() + if !ok { + return 0 + } + + return row.index +} + +// setFolderExpanded records one folder's state and re-clamps the scroll, because the +// number of visible rows just changed. It does not write the state file: the caller +// decides whether the change was the user's. +func (m *Model) setFolderExpanded(name string, expanded bool) { + if m.folderExpanded == nil { + m.folderExpanded = make(map[string]bool) + } + + if expanded { + m.folderExpanded[name] = true + } else { + delete(m.folderExpanded, name) + } + + m.clampFolderScroll() +} + +// expandTo reveals a folder by expanding its ancestors, for display only. It is what +// makes a remembered or opened nested folder visible without the user expanding its +// path by hand, and it deliberately does not persist: nothing the user chose changed. +func (m *Model) expandTo(name string) { + if m.folderExpanded == nil { + m.folderExpanded = make(map[string]bool) + } + + for _, folder := range m.folders { + if folder.Name != name { + continue + } + for _, ancestor := range ancestorNames(folder) { + if _, ok := m.folderByName(ancestor); ok { + m.folderExpanded[ancestor] = true + } + } + + return + } +} + +// folderByName finds a folder in the flat listing. +func (m Model) folderByName(name string) (mail.Folder, bool) { + for _, folder := range m.folders { + if folder.Name == name { + return folder, true + } + } + + return mail.Folder{}, false +} + +// expandFolderAtCursor reveals the subfolders of the folder under the cursor. It +// reports false when there is nothing to reveal, so the caller can fall through to +// opening the folder: enter expands first, then opens. +func (m *Model) expandFolderAtCursor() bool { + row, ok := m.selectedTreeRow() + if !ok || !row.hasChildren || row.expanded { + return false + } + + m.setFolderExpanded(m.folders[row.index].Name, true) + m.status = "" + m.rememberExpanded() + + return true +} + +// collapseFolderAtCursor folds the folder under the cursor. It is the left-arrow half +// of the tree gesture: folding something already folded, or a folder with nothing under +// it, is a no-op rather than a message, because the key is pressed casually. +func (m *Model) collapseFolderAtCursor() { + row, ok := m.selectedTreeRow() + if !ok || !row.hasChildren || !row.expanded { + return + } + + m.setFolderExpanded(m.folders[row.index].Name, false) + m.status = "" + m.rememberExpanded() +} diff --git a/tui/foldertree_test.go b/tui/foldertree_test.go new file mode 100644 index 0000000..af09290 --- /dev/null +++ b/tui/foldertree_test.go @@ -0,0 +1,312 @@ +package tui + +import ( + "strings" + "testing" + + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" + "github.com/renderorange/chute/config" + "github.com/renderorange/chute/mail" +) + +// treeFolders is a listing two levels deep: Work, a year under it, and a quarter under +// the year. INBOX is a leaf, so it must never grow a marker. +func treeFolders() []mail.Folder { + return []mail.Folder{ + {Name: "INBOX", Delimiter: '/'}, + {Name: "Work", Delimiter: '/'}, + {Name: "Work/2024", Delimiter: '/'}, + {Name: "Work/2024/Q1", Delimiter: '/'}, + {Name: "Work/2025", Delimiter: '/'}, + } +} + +// folderPaneText renders more rows than any fixture has, so a hidden row cannot pass by +// being scrolled off instead of folded. +func folderPaneText(m Model) string { + return strings.Join(m.folderLines(20, 24), "\n") +} + +// updateNamed presses a named key (enter, esc, left, right) and returns the model. +func updateNamed(t *testing.T, m Model, key string) Model { + t.Helper() + + next, _ := m.Update(namedKey(key)) + + return next.(Model) +} + +// TestFolderTreeCollapsesByDefault is the issue's default: a new install shows the top +// level, and a folder with subfolders advertises them with a "+". +func TestFolderTreeCollapsesByDefault(t *testing.T) { + m := loaded(t, 140, 40, treeFolders(), nil) + + text := folderPaneText(m) + for _, hidden := range []string{"2024", "Q1", "2025"} { + if strings.Contains(text, hidden) { + t.Errorf("pane shows %q while the tree is collapsed:\n%s", hidden, text) + } + } + if !strings.Contains(text, "+ Work") { + t.Errorf("Work has no + marker:\n%s", text) + } + if strings.Contains(text, "+ INBOX") { + t.Errorf("INBOX has subfolders it does not have:\n%s", text) + } + if got, want := len(m.folderTree()), 2; got != want { + t.Errorf("visible rows = %d, want %d", got, want) + } +} + +// TestEnterExpandsThenOpens pins the owner's ruling: enter reveals a collapsed folder +// first, and the next enter behaves exactly as it always has and loads the folder. +func TestEnterExpandsThenOpens(t *testing.T) { + m := loaded(t, 140, 40, treeFolders(), nil) + m.folderCursor = 1 // Work + + m = updateNamed(t, m, "enter") + + if m.openFolder != "" { + t.Errorf("enter opened %q, want the first press to expand only", m.openFolder) + } + if !m.folderExpanded["Work"] { + t.Error("Work is not expanded after enter") + } + if text := folderPaneText(m); !strings.Contains(text, "- Work") || !strings.Contains(text, "2024") { + t.Errorf("pane does not show the markers and children of an expanded folder:\n%s", text) + } + + m = updateNamed(t, m, "enter") + + if got, want := m.openFolder, "Work"; got != want { + t.Errorf("openFolder = %q, want %q on the second enter", got, want) + } +} + +// TestEnterOpensALeaf proves the two-step does not delay a folder that has nothing to +// reveal: the first press still opens it. +func TestEnterOpensALeaf(t *testing.T) { + m := loaded(t, 140, 40, treeFolders(), nil) + m.folderCursor = 0 // INBOX + + m = updateNamed(t, m, "enter") + + if got, want := m.openFolder, "INBOX"; got != want { + t.Errorf("openFolder = %q, want %q", got, want) + } +} + +// TestArrowKeysExpandAndFoldTheFolder is the tree gesture: right reveals the subfolders, +// left folds them, and neither enters the folder. Enter keeps its own meaning. +func TestArrowKeysExpandAndFoldTheFolder(t *testing.T) { + m := loaded(t, 140, 40, treeFolders(), nil) + m.folderCursor = 1 // Work + + m = updateNamed(t, m, "right") + + if m.openFolder != "" { + t.Errorf("right opened %q, want the tree to expand only", m.openFolder) + } + if !m.folderExpanded["Work"] { + t.Error("right did not expand Work") + } + if text := folderPaneText(m); !strings.Contains(text, "- Work") || !strings.Contains(text, "2024") { + t.Errorf("pane does not show the markers and children of an expanded folder:\n%s", text) + } + + m = updateNamed(t, m, "left") + + if m.folderExpanded["Work"] { + t.Error("left left Work expanded") + } + if strings.Contains(folderPaneText(m), "2024") { + t.Errorf("left did not fold Work:\n%s", folderPaneText(m)) + } + + m = updateNamed(t, m, "right") + + if !strings.Contains(folderPaneText(m), "2024") { + t.Errorf("right did not expand Work again:\n%s", folderPaneText(m)) + } +} + +// TestArrowKeysOnALeafDoNothing is the no-signal case: a folder with nothing under it +// neither expands nor reports anything, because left and right are casual keys. +func TestArrowKeysOnALeafDoNothing(t *testing.T) { + m := loaded(t, 140, 40, treeFolders(), nil) + m.folderCursor = 0 // INBOX + before := folderPaneText(m) + + m = updateNamed(t, m, "left") + m = updateNamed(t, m, "right") + + if m.status != "" { + t.Errorf("status = %q, want nothing for a leaf", m.status) + } + if m.openFolder != "" { + t.Errorf("openFolder = %q, want nothing", m.openFolder) + } + if got := folderPaneText(m); got != before { + t.Errorf("pane changed on a leaf:\n%s", got) + } +} + +// TestFolderArrowsAreInertOutsideTheFolderPane proves the guard: left and right do not +// fold the tree while the message list or the reader has focus. +func TestFolderArrowsAreInertOutsideTheFolderPane(t *testing.T) { + m := loaded(t, 140, 40, treeFolders(), nil) + m.focus = focusMessages + + m = updateNamed(t, m, "right") + m = updateNamed(t, m, "left") + + if len(m.folderExpanded) != 0 { + t.Errorf("expanded = %v, want none while the list has focus", m.folderExpanded) + } +} + +// TestMissingParentIsNotInvented covers the server that lists Work/Projects/2025 but not +// Work/Projects: the folder nests under its nearest listed ancestor and no row is +// conjured for the missing one. A folder with no listed ancestor is a root. +func TestMissingParentIsNotInvented(t *testing.T) { + m := loaded(t, 140, 40, []mail.Folder{ + {Name: "Work", Delimiter: '/'}, + {Name: "Work/Projects/2025", Delimiter: '/'}, + }, nil) + m.folderCursor = 0 // Work is the only visible root + m = updateNamed(t, m, "enter") + + rows := m.folderTree() + if len(rows) != 2 { + t.Fatalf("visible rows = %d, want Work and its grandchild", len(rows)) + } + if got, want := rows[1].depth, 1; got != want { + t.Errorf("grandchild depth = %d, want %d under the listed grandparent", got, want) + } + + text := folderPaneText(m) + if strings.Contains(text, "Projects") { + t.Errorf("pane invents a Projects row:\n%s", text) + } + if !strings.Contains(text, "2025") { + t.Errorf("pane lost the grandchild:\n%s", text) + } + + orphan := loaded(t, 140, 40, []mail.Folder{{Name: "A/B/C", Delimiter: '/'}}, nil) + rows = orphan.folderTree() + if len(rows) != 1 || rows[0].depth != 0 { + t.Fatalf("orphan rows = %+v, want one root at depth 0", rows) + } + if text := folderPaneText(orphan); !strings.Contains(text, "C") || strings.Contains(text, "B") { + t.Errorf("orphan pane = %q, want the leaf C at the root", text) + } +} + +// TestFolderToggleIsPersisted proves an explicit fold is written for the active account, +// sorted, and that folding everything removes the account's entry rather than storing an +// empty list. +func TestFolderToggleIsPersisted(t *testing.T) { + m, rec := stateModel(t, config.State{}, treeFolders()) + m = startModel(t, m) + m.folderCursor = 1 // Work + + m = updateNamed(t, m, "right") + + if rec.calls != 1 { + t.Fatalf("state writes = %d, want 1 for the expand", rec.calls) + } + if got, want := rec.saved.Expanded["fastmail"], []string{"Work"}; len(got) != 1 || got[0] != want[0] { + t.Errorf("expanded = %v, want %v", got, want) + } + + m = updateNamed(t, m, "left") + + if _, ok := rec.saved.Expanded["fastmail"]; ok { + t.Errorf("expanded still records fastmail after folding everything: %v", rec.saved.Expanded) + } +} + +// TestRememberedExpansionIsApplied proves the state file opens the tree where it was +// left, and that restoring it is not itself a change: no write happens at startup. +func TestRememberedExpansionIsApplied(t *testing.T) { + sel := config.State{Expanded: map[string][]string{"fastmail": {"Work"}}} + m, rec := stateModel(t, sel, treeFolders()) + + m = startModel(t, m) + + if text := folderPaneText(m); !strings.Contains(text, "2024") { + t.Errorf("remembered expansion was not applied:\n%s", text) + } + if rec.calls != 0 { + t.Errorf("state writes = %d at startup, want none", rec.calls) + } +} + +// TestRememberedNestedFolderRevealsItsPath proves a remembered folder deep in the tree +// is still visible when the tree defaults to collapsed: its ancestors are opened for +// display, without being recorded as the user's choice. +func TestRememberedNestedFolderRevealsItsPath(t *testing.T) { + sel := config.State{Folders: map[string]string{"fastmail": "Work/2024/Q1"}} + m, rec := stateModel(t, sel, treeFolders()) + m.cfg.Accounts[m.account].StartFolder = nil + + m = startModel(t, m) + + if got, want := m.openFolder, "Work/2024/Q1"; got != want { + t.Errorf("openFolder = %q, want %q", got, want) + } + if text := folderPaneText(m); !strings.Contains(text, "Q1") { + t.Errorf("the open folder's path is hidden:\n%s", text) + } + if rec.calls != 0 { + t.Errorf("state writes = %d, want none: revealing a path is not a user change", rec.calls) + } +} + +// TestFolderCursorIgnoresHiddenRows proves the cursor moves over what is drawn: moving +// down from the last visible row does not land on a folded child. +func TestFolderCursorIgnoresHiddenRows(t *testing.T) { + m := loaded(t, 140, 40, treeFolders(), nil) + m.folderCursor = 1 // Work, the last visible row + + m.moveFolderCursor(1) + + if got, want := m.folderCursor, 1; got != want { + t.Errorf("cursor = %d, want %d: a folded child is not selectable", got, want) + } +} + +// TestFolderTreeSelectionIsBoldNotAGlyph follows the imap-notes shape the owner chose: +// the cursor is the bold row, so it never displaces the +/- marker. +func TestFolderTreeSelectionIsBoldNotAGlyph(t *testing.T) { + profile := lipgloss.ColorProfile() + lipgloss.SetColorProfile(termenv.TrueColor) + t.Cleanup(func() { lipgloss.SetColorProfile(profile) }) + + m := loaded(t, 140, 40, treeFolders(), nil) + m.folderCursor = 1 // Work + + rows := m.folderLines(20, 24) + if strings.Contains(rows[1], "> ") { + t.Errorf("selected row carries a cursor glyph: %q", rows[1]) + } + if !boldSGR.MatchString(rows[1]) { + t.Errorf("selected row is not bold: %q", rows[1]) + } + if boldSGR.MatchString(rows[0]) { + t.Errorf("unselected row is bold: %q", rows[0]) + } +} + +// TestFolderTreeFrameStaysExact keeps the gap and the tree inside the terminal at the +// supported floor and at the tablet width. +func TestFolderTreeFrameStaysExact(t *testing.T) { + for _, size := range [][2]int{{60, 20}, {105, 59}, {140, 40}} { + m := loaded(t, size[0], size[1], treeFolders(), nil) + m.folderExpanded["Work"] = true + m.clampFolderScroll() + + assertExactFrame(t, m, "folder tree") + } +} diff --git a/tui/footer.go b/tui/footer.go index 0998286..d35f708 100644 --- a/tui/footer.go +++ b/tui/footer.go @@ -6,11 +6,12 @@ import ( "github.com/charmbracelet/lipgloss" ) -// hintSeparator sits between two hints. It is one cell, not two: at 105 columns -// the content width is 99, and the priority set plus back plus the compose keys -// costs 99 with single spaces and 109 with double ones. A second space would -// push a hint off the footer, which is the defect this file exists to fix. -const hintSeparator = " " +// hintSeparator sits between two hints. Two cells matches imap-notes, whose footer +// joins its command keys with two spaces (`tui/view.go:135`). The earlier one-cell +// separator was a width compromise from when the footer carried ten hints; the set +// has since shrunk to the five mistake-preventing keys (#26), which cost 44 cells +// with this separator and fit the 54-cell floor at 60 columns. +const hintSeparator = " " // footerHint is one "key:label" reminder. A hint is either derived from the // binding table (actions) or literal, for the composer, whose keys are read diff --git a/tui/footer_test.go b/tui/footer_test.go index 1bccb9e..af589d2 100644 --- a/tui/footer_test.go +++ b/tui/footer_test.go @@ -18,7 +18,7 @@ type footerCase struct { // the budget fails here instead of being silently dropped. The owner asked for // this set to shrink to the mistake-preventing keys (#26): the footer is a // reminder, not the keymap, and the rest waits for the help screen. -const footerDefaultHints = "d:delete f:flag m:move enter:open q:quit" +const footerDefaultHints = "d:delete f:flag m:move enter:open q:quit" // footerCases builds one model per footer context. Every model is 105 columns // unless the case is about the composer, whose hints are wider. @@ -176,15 +176,15 @@ func TestFooterAt60KeepsWholeHints(t *testing.T) { } // TestFooterDropsWholeHintsWhenItMust keeps the packing rule covered. The default -// set fits from 60 columns up, so the drop path is exercised just below it: at 40 -// columns the quit hint no longer fits and is dropped whole, never cut. +// set fits from 60 columns up (44 cells in 54), so the drop path is exercised just +// below it: at 44 columns the quit hint no longer fits and is dropped whole, never cut. func TestFooterDropsWholeHintsWhenItMust(t *testing.T) { - m := sized(40, 20) + m := sized(44, 20) footer := m.renderFooter() - const want = "d:delete f:flag m:move enter:open" + const want = "d:delete f:flag m:move enter:open" if footer != want { - t.Errorf("footer at 40 = %q, want %q", footer, want) + t.Errorf("footer at 44 = %q, want %q", footer, want) } if !strings.HasPrefix(footerDefaultHints, footer) { t.Errorf("footer at 40 is not a whole-hint prefix of the full set: %q", footer) @@ -211,7 +211,7 @@ func TestFooterWideStaysCalm(t *testing.T) { // whole hints, not substrings, because "ctrl+r:reload" contains "r:reload". func TestFooterNeverSaysRReload(t *testing.T) { for _, width := range []int{60, 80, 95, 105, 115, 130, 140, 200} { - for _, hint := range strings.Split(sized(width, 40).renderFooter(), " ") { + for _, hint := range strings.Split(sized(width, 40).renderFooter(), hintSeparator) { if hint == "r:reload" { t.Errorf("width %d: the footer claims r:reload", width) } diff --git a/tui/help.go b/tui/help.go index b7f78ee..276509c 100644 --- a/tui/help.go +++ b/tui/help.go @@ -71,7 +71,7 @@ func helpGroups() []helpGroup { rows: []helpRow{ helpPair(actionUp, actionDown, "move"), helpPair(actionTop, actionBottom, "first/last"), - helpAction(actionOpen, "open"), + helpPair(actionOpen, actionExpandFolder, "open / expand"), helpPair(actionFilter, actionSearch, "filter / search"), helpAction(actionVisualRange, "select range"), helpAction(actionDelete, "delete"), @@ -79,7 +79,7 @@ func helpGroups() []helpGroup { helpAction(actionJunk, "junk"), helpAction(actionMove, "move to folder"), helpAction(actionEmptyTrash, "empty Trash"), - helpAction(actionCollapse, "collapse thread"), + helpPair(actionCollapse, actionCollapseFolder, "collapse thread / folder"), helpAction(actionToggleFlag, "flag"), helpAction(actionToggleRead, "read/unread"), helpAction(actionAttachments, "attachments"), diff --git a/tui/keys.go b/tui/keys.go index 1b668cb..a3faf2f 100644 --- a/tui/keys.go +++ b/tui/keys.go @@ -41,6 +41,8 @@ const ( actionMove actionEmptyTrash actionCollapse + actionExpandFolder + actionCollapseFolder actionSearch actionSettings actionHelp @@ -81,6 +83,8 @@ var actionNames = map[action]string{ actionMove: config.KeyMove, actionEmptyTrash: config.KeyEmptyTrash, actionCollapse: config.KeyCollapse, + actionExpandFolder: config.KeyExpandFolder, + actionCollapseFolder: config.KeyCollapseFolder, actionSearch: config.KeySearch, actionSettings: config.KeySettings, actionHelp: config.KeyHelp, diff --git a/tui/layout.go b/tui/layout.go index b97b090..0b542c1 100644 --- a/tui/layout.go +++ b/tui/layout.go @@ -87,10 +87,11 @@ func ComputeLayout(width, height int) Layout { // ComputeLayoutWith sizes the panels for a terminal of the given dimensions and a // configured sizing. // -// Widths always sum to ContentWidth: the reader absorbs whatever the other panels do not -// take, and it keeps MinReaderWidth by shrinking the message list first and the folder pane -// second. A configured width that cannot fit is trimmed to those floors rather than -// rejected, because the same config is used at every terminal size. +// The pane widths plus the PanelGap columns between them always sum to ContentWidth: +// the reader absorbs whatever the other panels do not take, and it keeps +// MinReaderWidth by shrinking the message list first and the folder pane second. A +// configured width that cannot fit is trimmed to those floors rather than rejected, +// because the same config is used at every terminal size. func ComputeLayoutWith(width, height int, widths Widths) Layout { w := ContentWidth(width) h := ContentHeight(height) @@ -100,8 +101,10 @@ func ComputeLayoutWith(width, height int, widths Widths) Layout { folders := folderColumns(w, widths) messages := messageColumns(w, widths, autoMessagesPercentT) + gaps := 2 * PanelGap + // Give the reader its minimum back, from the list first and the folders last. - if short := MinReaderWidth - (w - folders - messages); short > 0 { + if short := MinReaderWidth - (w - folders - messages - gaps); short > 0 { cut := min(short, messages-MinMessagesWidth) messages -= cut short -= cut @@ -110,30 +113,35 @@ func ComputeLayoutWith(width, height int, widths Widths) Layout { folders -= min(short, folders-MinFoldersWidth) } } - if rest := w - folders - messages; rest < 1 { - messages = max(0, w-folders-1) + if rest := w - folders - messages - gaps; rest < 1 { + messages = max(0, w-folders-1-gaps) } return Layout{ Mode: ModeThree, Folders: Box{X: 0, Y: 0, Width: folders, Height: h}, - Messages: Box{X: folders, Y: 0, Width: messages, Height: h}, - Reader: Box{X: folders + messages, Y: 0, Width: w - folders - messages, Height: h}, + Messages: Box{X: folders + PanelGap, Y: 0, Width: messages, Height: h}, + Reader: Box{ + X: folders + PanelGap + messages + PanelGap, + Y: 0, + Width: w - folders - messages - gaps, + Height: h, + }, } case width >= NarrowBreakpoint: messages := messageColumns(w, widths, autoMessagesPercentTwo) - if w-messages < MinReaderWidth { - messages = max(0, w-MinReaderWidth) + if w-messages-PanelGap < MinReaderWidth { + messages = max(0, w-MinReaderWidth-PanelGap) } - if messages > w-1 { - messages = max(0, w-1) + if messages > w-PanelGap-1 { + messages = max(0, w-PanelGap-1) } return Layout{ Mode: ModeTwo, Messages: Box{X: 0, Y: 0, Width: messages, Height: h}, - Reader: Box{X: messages, Y: 0, Width: w - messages, Height: h}, + Reader: Box{X: messages + PanelGap, Y: 0, Width: w - messages - PanelGap, Height: h}, } } diff --git a/tui/layout_test.go b/tui/layout_test.go index 7b69c53..ff91559 100644 --- a/tui/layout_test.go +++ b/tui/layout_test.go @@ -10,8 +10,8 @@ func TestComputeLayoutThreeColumns(t *testing.T) { } available := ContentWidth(140) - if got := layout.Folders.Width + layout.Messages.Width + layout.Reader.Width; got != available { - t.Errorf("column widths sum to %d, want %d", got, available) + if got := layout.Folders.Width + layout.Messages.Width + layout.Reader.Width + 2*PanelGap; got != available { + t.Errorf("column widths plus gaps sum to %d, want %d", got, available) } if layout.Folders.Width < MinFoldersWidth || layout.Folders.Width > MaxFoldersWidth { t.Errorf("folders width = %d, want %d..%d", layout.Folders.Width, MinFoldersWidth, MaxFoldersWidth) @@ -22,10 +22,11 @@ func TestComputeLayoutThreeColumns(t *testing.T) { if layout.Reader.Width < MinReaderWidth { t.Errorf("reader width = %d, want at least %d", layout.Reader.Width, MinReaderWidth) } - if layout.Folders.X != 0 || layout.Messages.X != layout.Folders.Width { - t.Errorf("x offsets = %d, %d; want 0, %d", layout.Folders.X, layout.Messages.X, layout.Folders.Width) + if layout.Folders.X != 0 || layout.Messages.X != layout.Folders.Width+PanelGap { + t.Errorf("x offsets = %d, %d; want 0, %d", + layout.Folders.X, layout.Messages.X, layout.Folders.Width+PanelGap) } - if got, want := layout.Reader.X, layout.Messages.X+layout.Messages.Width; got != want { + if got, want := layout.Reader.X, layout.Messages.X+layout.Messages.Width+PanelGap; got != want { t.Errorf("reader x = %d, want %d", got, want) } } @@ -39,8 +40,8 @@ func TestComputeLayoutThreeColumnsAtBreakpoint(t *testing.T) { if layout.Reader.Width < MinReaderWidth { t.Errorf("reader width = %d at the breakpoint, want at least %d", layout.Reader.Width, MinReaderWidth) } - if got, want := layout.Folders.Width+layout.Messages.Width+layout.Reader.Width, ContentWidth(ThreeColumnBreakpoint); got != want { - t.Errorf("column widths sum to %d, want %d", got, want) + if got, want := layout.Folders.Width+layout.Messages.Width+layout.Reader.Width+2*PanelGap, ContentWidth(ThreeColumnBreakpoint); got != want { + t.Errorf("column widths plus gaps sum to %d, want %d", got, want) } } @@ -63,8 +64,8 @@ func TestComputeLayoutTwoColumns(t *testing.T) { if !layout.Folders.Empty() { t.Errorf("width %d: folders box should be empty, got %+v", width, layout.Folders) } - if got, want := layout.Messages.Width+layout.Reader.Width, ContentWidth(width); got != want { - t.Errorf("width %d: columns sum to %d, want %d", width, got, want) + if got, want := layout.Messages.Width+layout.Reader.Width+PanelGap, ContentWidth(width); got != want { + t.Errorf("width %d: columns plus gap sum to %d, want %d", width, got, want) } if layout.Messages.Width < MinMessagesWidth { t.Errorf("width %d: messages width = %d, want at least %d", width, layout.Messages.Width, MinMessagesWidth) @@ -136,18 +137,19 @@ func TestComputeLayoutHeightsMatch(t *testing.T) { } } -// assertColumnsSum checks the invariant every layout must hold: the visible columns add up -// to the content width, so no pane can overlap another or leave a gap. +// assertColumnsSum checks the invariant every layout must hold: the visible columns and +// the PanelGap columns between them add up to the content width, so no pane can overlap +// another or leave the frame short. func assertColumnsSum(t *testing.T, layout Layout, width int) { t.Helper() - sum := layout.Folders.Width + layout.Messages.Width + layout.Reader.Width + sum := layout.Folders.Width + layout.Messages.Width + layout.Reader.Width + 2*PanelGap if layout.Mode == ModeTwo { - sum = layout.Messages.Width + layout.Reader.Width + sum = layout.Messages.Width + layout.Reader.Width + PanelGap } if want := ContentWidth(width); sum != want { - t.Errorf("width %d: columns sum to %d, want %d (%+v)", width, sum, want, layout) + t.Errorf("width %d: columns and gaps sum to %d, want %d (%+v)", width, sum, want, layout) } } @@ -165,7 +167,7 @@ func TestComputeLayoutWithColumnWidths(t *testing.T) { if got := layout.Messages.Width; got != 70 { t.Errorf("messages width = %d, want 70", got) } - if got, want := layout.Reader.Width, ContentWidth(200)-100; got != want { + if got, want := layout.Reader.Width, ContentWidth(200)-100-2*PanelGap; got != want { t.Errorf("reader width = %d, want %d", got, want) } assertColumnsSum(t, layout, 200) @@ -210,7 +212,7 @@ func TestColumnWidthBeatsPercent(t *testing.T) { func TestReaderMinimumTrimsTheList(t *testing.T) { layout := ComputeLayoutWith(120, 40, Widths{MessagesWidth: 150}) - want := ContentWidth(120) - layout.Folders.Width - MinReaderWidth + want := ContentWidth(120) - layout.Folders.Width - 2*PanelGap - MinReaderWidth if got := layout.Messages.Width; got != want { t.Errorf("messages width = %d, want %d to leave the reader its minimum", got, want) } @@ -229,7 +231,7 @@ func TestReaderMinimumTrimsTheFoldersLast(t *testing.T) { t.Errorf("messages width = %d, want the floor %d", got, MinMessagesWidth) } - want := ContentWidth(120) - MinMessagesWidth - MinReaderWidth + want := ContentWidth(120) - MinMessagesWidth - 2*PanelGap - MinReaderWidth if got := layout.Folders.Width; got != want { t.Errorf("folders width = %d, want %d, the remainder once the reader has its minimum", got, want) } @@ -271,8 +273,8 @@ func TestAutomaticMessagesWidthGrowsWithTheTerminal(t *testing.T) { if got := atBreakpoint.Folders.Width; got != 28 { t.Errorf("folders width at %d columns = %d, want the automatic 28", ThreeColumnBreakpoint, got) } - if got := atBreakpoint.Reader.Width; got != 46 { - t.Errorf("reader width at %d columns = %d, want 46", ThreeColumnBreakpoint, got) + if got := atBreakpoint.Reader.Width; got != 46-2*PanelGap { + t.Errorf("reader width at %d columns = %d, want %d", ThreeColumnBreakpoint, got, 46-2*PanelGap) } } @@ -287,7 +289,7 @@ func TestTwoPaneHonoursMessagesWidth(t *testing.T) { if got := layout.Messages.Width; got != 50 { t.Errorf("messages width = %d, want 50", got) } - if got, want := layout.Reader.Width, ContentWidth(115)-50; got != want { + if got, want := layout.Reader.Width, ContentWidth(115)-50-PanelGap; got != want { t.Errorf("reader width = %d, want %d", got, want) } assertColumnsSum(t, layout, 115) diff --git a/tui/model.go b/tui/model.go index 2892430..de7a93c 100644 --- a/tui/model.go +++ b/tui/model.go @@ -53,6 +53,11 @@ type Model struct { folderCursor int folderScroll int + // folderExpanded is the folder tree's open set, keyed by mailbox name. A name that + // is absent is collapsed; the set is seeded from the state file and written back on + // every explicit expand or collapse. + folderExpanded map[string]bool + openFolder string messages []mail.Message rows []Row @@ -191,6 +196,7 @@ func New(cfg *config.Config, version string, mailOptions ...mail.Option) Model { bodies: make(map[bodyKey]*mail.Body), markSeenOnLoad: make(map[bodyKey]bool), collapsed: make(map[imap.UID]bool), + folderExpanded: make(map[string]bool), lastSeen: make(map[folderKey]imap.UID), visualAnchor: noVisualAnchor, keys: bindingsFromConfig(cfg.KeyBindings()), @@ -326,10 +332,17 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.state = stateConnected m.status = "" m.folders = msg.folders + m.folderExpanded = expandedFolders(m.selection, msg.account) m.folderCursor = 0 m.folderScroll = 0 m.foldersOpen = false m.folderOverlayCursor = 0 + + // The folder being read keeps its path open after a reload; a listing that no + // longer has it simply expands nothing. + if m.openFolder != "" { + m.expandTo(m.openFolder) + } m.clampFolderScroll() if !m.started { @@ -627,6 +640,20 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case actionCollapse: return m.toggleCollapse() + case actionExpandFolder: + if m.focus == focusFolders { + m.expandFolderAtCursor() + } + + return m, nil + + case actionCollapseFolder: + if m.focus == focusFolders { + m.collapseFolderAtCursor() + } + + return m, nil + case actionSearch: return m.beginSearch() @@ -683,6 +710,12 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case actionOpen: if m.focus == focusFolders { + // Enter reveals a collapsed folder before it opens anything: the first press + // expands, the next behaves as it always has and loads the folder. + if m.expandFolderAtCursor() { + return m, nil + } + return m.openSelectedFolder() } if m.focus == focusMessages { @@ -770,9 +803,11 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { // jumpToEnd moves the active panel's cursor to its last row. func (m *Model) jumpToEnd() { - if m.focus == focusFolders && len(m.folders) > 0 { - m.folderCursor = len(m.folders) - 1 - m.clampFolderScroll() + if m.focus == focusFolders { + if rows := m.folderTree(); len(rows) > 0 { + m.folderCursor = len(rows) - 1 + m.clampFolderScroll() + } } if m.focus == focusMessages && len(m.rows) > 0 { m.messageCursor = len(m.rows) - 1 @@ -803,6 +838,7 @@ func (m Model) openSelectedFolder() (tea.Model, tea.Cmd) { // user made, and must not create a state file for someone who switches nothing. func (m Model) openFolderByName(name string, remember bool) (tea.Model, tea.Cmd) { m.openFolder = name + m.expandTo(name) m.filter = "" m.messages = nil m.rows = nil @@ -1065,15 +1101,22 @@ func (m Model) renderPanels(layout Layout) string { switch layout.Mode { case ModeThree: + gap := blankBlock(PanelGap, layout.Folders.Height) + return JoinHorizontal( m.renderPanel("folders", layout.Folders, folderBody, m.focus == focusFolders), + gap, m.renderPanel("messages", layout.Messages, messageBody, m.focus == focusMessages), + gap, m.renderPanel("reader", layout.Reader, readerBody, m.focus == focusReader), ) case ModeTwo: + gap := blankBlock(PanelGap, layout.Messages.Height) + return JoinHorizontal( m.renderPanel("messages", layout.Messages, messageBody, m.focus == focusMessages), + gap, m.renderPanel("reader", layout.Reader, readerBody, m.focus == focusReader), ) } diff --git a/tui/palette.go b/tui/palette.go index cc7ce0c..e339ae5 100644 --- a/tui/palette.go +++ b/tui/palette.go @@ -37,6 +37,13 @@ const ( PanelPaddingHorizontal = 1 ) +// PanelGap is the blank column between two panels, added to the padding each panel +// already carries. Without it the two panes' one-cell paddings meet and the message +// list, whose date column runs to the edge, reads as if it touches the reader. It is +// a layout quantity, not padding: ComputeLayout subtracts it from the pane widths, so +// the visible columns still add up to the content width and the frame stays exact. +const PanelGap = 2 + // Breakpoints, measured in terminal columns. const ( // NarrowBreakpoint is the width below which only one panel fits. diff --git a/tui/render.go b/tui/render.go index c7bedde..39b655b 100644 --- a/tui/render.go +++ b/tui/render.go @@ -59,6 +59,23 @@ func JoinHorizontal(parts ...string) string { return lipgloss.JoinHorizontal(lipgloss.Top, parts...) } +// blankBlock returns width blank cells over height lines, for the gap between panels. +// JoinHorizontal pads a short part with empty lines, and an empty line is zero cells +// wide, so the gap has to be a real block or every row after the first loses its width. +func blankBlock(width, height int) string { + if width < 1 || height < 1 { + return "" + } + + line := strings.Repeat(" ", width) + lines := make([]string, height) + for i := range lines { + lines[i] = line + } + + return strings.Join(lines, "\n") +} + // JoinVertical stacks blocks, left aligned. func JoinVertical(parts ...string) string { return lipgloss.JoinVertical(lipgloss.Left, parts...) diff --git a/tui/render_test.go b/tui/render_test.go index 208ad16..09eac2b 100644 --- a/tui/render_test.go +++ b/tui/render_test.go @@ -419,7 +419,7 @@ func TestConfiguredWidthsReachTheFrame(t *testing.T) { if got := layout.Messages.Width; got != 70 { t.Errorf("messages width = %d, want the configured 70", got) } - if got, want := layout.Reader.Width, ContentWidth(200)-100; got != want { + if got, want := layout.Reader.Width, ContentWidth(200)-100-2*PanelGap; got != want { t.Errorf("reader width = %d, want %d", got, want) } @@ -497,3 +497,49 @@ func TestViewAtEachBreakpointHasNoEmptyPanel(t *testing.T) { } } } + +// TestPanelGapIsRealColumns proves the inter-panel gap is drawn, not just reserved in +// the arithmetic: every line of the gap block is blank and exactly PanelGap cells, so +// JoinHorizontal cannot pad the lower rows with zero-width empty lines. +func TestPanelGapIsRealColumns(t *testing.T) { + lines := strings.Split(blankBlock(PanelGap, 5), "\n") + if len(lines) != 5 { + t.Fatalf("gap block has %d lines, want 5", len(lines)) + } + for i, line := range lines { + if strings.TrimSpace(line) != "" { + t.Errorf("gap line %d is not blank: %q", i, line) + } + if got := lipgloss.Width(line); got != PanelGap { + t.Errorf("gap line %d is %d cells, want %d", i, got, PanelGap) + } + } +} + +// titleStart is the column a panel title begins at, ignoring the focus marker. +func titleStart(line, name string) int { + index := strings.Index(line, name) + if index >= 2 && line[index-2:index] == "> " { + return index - 2 + } + + return index +} + +// TestPanelGapMovesTheTitlesApart ties the gap to the rendered frame: the second and +// third panel titles sit exactly where the layout puts them, so the join inserts the +// gap rather than the panes merely happening to be narrow. +func TestPanelGapMovesTheTitlesApart(t *testing.T) { + m := loaded(t, 140, 40, sampleFolders(3), nil) // folders keeps the focus marker + layout := m.layout() + line := titleLine(m.View()) + + if got, want := titleStart(line, "messages")-titleStart(line, "folders"), + layout.Messages.X-layout.Folders.X; got != want { + t.Errorf("folders to messages = %d columns, want %d", got, want) + } + if got, want := titleStart(line, "reader")-titleStart(line, "messages"), + layout.Reader.X-layout.Messages.X; got != want { + t.Errorf("messages to reader = %d columns, want %d", got, want) + } +} diff --git a/tui/state.go b/tui/state.go index 51df5bd..bd8de0d 100644 --- a/tui/state.go +++ b/tui/state.go @@ -1,6 +1,7 @@ package tui import ( + "sort" "strings" "github.com/renderorange/chute/config" @@ -87,3 +88,45 @@ func (m *Model) rememberSelection() { _ = m.saveState(m.selection) } } + +// expandedFolders is the set of open folders recorded for one account. A missing +// account, or a state file written before the tree existed, means every folder is +// collapsed, which is what a fresh install shows. +func expandedFolders(state config.State, account string) map[string]bool { + names := state.Expanded[account] + set := make(map[string]bool, len(names)) + + for _, name := range names { + set[name] = true + } + + return set +} + +// rememberExpanded writes the tree's open folders for the active account and saves the +// state. Only an explicit expand or collapse calls this: revealing a path at startup or +// on open is not a change the user made. Sorted, because a map has no order and the +// file is compared in tests. +func (m *Model) rememberExpanded() { + if m.selection.Expanded == nil { + m.selection.Expanded = make(map[string][]string) + } + + names := make([]string, 0, len(m.folderExpanded)) + for name, expanded := range m.folderExpanded { + if expanded { + names = append(names, name) + } + } + sort.Strings(names) + + if len(names) == 0 { + delete(m.selection.Expanded, m.accountName()) + } else { + m.selection.Expanded[m.accountName()] = names + } + + if m.saveState != nil { + _ = m.saveState(m.selection) + } +}