diff --git a/README.md b/README.md index 4492ed7..36d9252 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,9 @@ Composer keys are fixed, not part of `[keys]`: | `junk` | `!` | Move to the junk mailbox. | | `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. | +| `new_folder` | `N` | In the folder pane, create a folder under the one selected; type a nested name to add levels. | +| `move_folder` | `M` | In the folder pane, move the selected folder under another one, after a confirmation naming the destination. Subfolders move with it. | +| `delete_folder` | `D` | In the folder pane, delete the selected folder after a confirmation. Refused while it holds mail or has subfolders. | | `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. | diff --git a/config/keys.go b/config/keys.go index b081076..87459c4 100644 --- a/config/keys.go +++ b/config/keys.go @@ -46,6 +46,9 @@ const ( KeyJunk = "junk" KeyMove = "move" KeyEmptyTrash = "empty_trash" + KeyNewFolder = "new_folder" + KeyMoveFolder = "move_folder" + KeyDeleteFolder = "delete_folder" KeyCollapse = "collapse" KeyExpandFolder = "expand_folder" KeyCollapseFolder = "collapse_folder" @@ -88,6 +91,9 @@ var keyDefaults = map[string][]string{ KeyJunk: {"!"}, KeyMove: {"m"}, KeyEmptyTrash: {"X"}, + KeyNewFolder: {"N"}, + KeyMoveFolder: {"M"}, + KeyDeleteFolder: {"D"}, KeyCollapse: {"z"}, KeyExpandFolder: {"right"}, KeyCollapseFolder: {"left"}, diff --git a/mail/client.go b/mail/client.go index baea168..06586c8 100644 --- a/mail/client.go +++ b/mail/client.go @@ -129,6 +129,50 @@ func (c *Client) Folders() ([]Folder, error) { return foldersFromList(data), nil } +// CreateMailbox creates one mailbox. Any missing parent is the caller's job, because +// servers differ on whether CREATE invents them. +func (c *Client) CreateMailbox(name string) error { + if err := c.conn.Create(name, nil).Wait(); err != nil { + return fmt.Errorf("mail: account %q: creating %q: %w", c.account, name, err) + } + + return nil +} + +// RenameMailbox renames one mailbox and leaves its inferior names alone. Servers +// differ on whether a rename cascades, so the caller repairs what is left behind. +func (c *Client) RenameMailbox(name, newName string) error { + if err := c.conn.Rename(name, newName, nil).Wait(); err != nil { + return fmt.Errorf("mail: account %q: renaming %q to %q: %w", c.account, name, newName, err) + } + + return nil +} + +// DeleteMailbox deletes one mailbox. The server refuses a mailbox that still holds +// mail only sometimes, so the caller checks first. +func (c *Client) DeleteMailbox(name string) error { + if err := c.conn.Delete(name).Wait(); err != nil { + return fmt.Errorf("mail: account %q: deleting %q: %w", c.account, name, err) + } + + return nil +} + +// MailboxMessages counts the messages in a mailbox with one STATUS command. It does not +// SELECT, so it leaves the open mailbox and its selection alone. +func (c *Client) MailboxMessages(name string) (uint32, error) { + data, err := c.conn.Status(name, &imap.StatusOptions{NumMessages: true}).Wait() + if err != nil { + return 0, fmt.Errorf("mail: account %q: counting messages in %q: %w", c.account, name, err) + } + if data.NumMessages == nil { + return 0, nil + } + + return *data.NumMessages, nil +} + // FetchEnvelopes opens a folder and returns every message's envelope, flags and // size. No message body is fetched. func (c *Client) FetchEnvelopes(folder string) ([]Message, error) { diff --git a/mail/errors.go b/mail/errors.go index b848acb..afff881 100644 --- a/mail/errors.go +++ b/mail/errors.go @@ -1,6 +1,9 @@ package mail -import "errors" +import ( + "errors" + "fmt" +) // Sentinel errors the interface maps onto user-facing phrases. The wrapped text keeps // the account, host, stage and original cause for logs; the TUI decides the wording. @@ -34,4 +37,69 @@ var ( // permanent delete of a selection would need a folder-wide EXPUNGE. Refused rather // than destroying mail the user did not select. ErrNoSafePurge = errors.New("mail: server cannot delete permanently") + + // ErrFolderExists reports that a new or moved folder would collide with one the + // listing already has. Matched case-insensitively, like every other name here. + ErrFolderExists = errors.New("mail: folder already exists") + + // ErrFolderNotEmpty reports a delete of a mailbox that still holds mail. The + // refusal carries the count, so the interface can say how much is in the way. + ErrFolderNotEmpty = errors.New("mail: folder is not empty") + + // ErrFolderHasChildren reports a delete of a mailbox that has folders below it. + // Removing it would either orphan them or destroy them, depending on the server. + ErrFolderHasChildren = errors.New("mail: folder has subfolders") + + // ErrFolderProtected reports a mailbox a rename or delete must not touch: INBOX, + // or a folder an [accounts.imap] override names. + ErrFolderProtected = errors.New("mail: folder cannot be changed") + + // ErrFolderCycle reports a move whose destination is the folder itself or one of + // its own descendants, which would make the tree a loop. + ErrFolderCycle = errors.New("mail: cannot move a folder into itself") + + // ErrFolderNoOp reports a move the folder is already in. + ErrFolderNoOp = errors.New("mail: folder is already there") ) + +// FolderNotEmptyError says how many messages block a delete. It matches +// ErrFolderNotEmpty, so a caller that only needs the reason can ignore the count. +type FolderNotEmptyError struct { + Folder string + Count uint32 +} + +func (e *FolderNotEmptyError) Error() string { + return fmt.Sprintf("%s: %q holds %s", ErrFolderNotEmpty, e.Folder, countNoun(int(e.Count), "message")) +} + +// Is reports the sentinel this refusal belongs to. +func (e *FolderNotEmptyError) Is(target error) bool { + return target == ErrFolderNotEmpty +} + +// FolderHasChildrenError says how many folders sit below the one a delete named. The +// count includes deeper descendants, not just immediate children. +type FolderHasChildrenError struct { + Folder string + Count int +} + +func (e *FolderHasChildrenError) Error() string { + return fmt.Sprintf("%s: %q has %s below it", ErrFolderHasChildren, e.Folder, countNoun(e.Count, "folder")) +} + +// Is reports the sentinel this refusal belongs to. +func (e *FolderHasChildrenError) Is(target error) bool { + return target == ErrFolderHasChildren +} + +// countNoun renders "1 message" or "12 messages". It is the mail package's own copy +// because the interface's countLabel is not reachable from here. +func countNoun(n int, noun string) string { + if n == 1 { + return "1 " + noun + } + + return fmt.Sprintf("%d %ss", n, noun) +} diff --git a/mail/folderops.go b/mail/folderops.go new file mode 100644 index 0000000..71bc959 --- /dev/null +++ b/mail/folderops.go @@ -0,0 +1,440 @@ +package mail + +import ( + "fmt" + "strings" + + "github.com/renderorange/chute/config" +) + +// Folder management: create, move and delete a mailbox. +// +// Servers disagree about how much of the work a single command does. RFC 3501 tells a +// server to create missing parents for CREATE and to rename inferior names for RENAME, +// but the in-process server this package tests against does neither, and neither do +// some real ones. So this file does that work itself: it creates every missing +// ancestor, and after a rename it repairs any descendant the server left behind. +// +// Every operation ends by listing the mailboxes again and returning what the server +// reported. The interface draws that listing rather than a locally edited tree, so a +// server that normalises a name shows its version. + +// roleConfigKeys names the [accounts.imap] settings that pin a role to a mailbox, in +// the order a refusal lists them. The values are the config keys, not the roles, so the +// message can tell the user which line to change. +var roleConfigKeys = []struct { + role Role + key string +}{ + {RoleSent, "sent"}, + {RoleDrafts, "drafts"}, + {RoleTrash, "trash"}, + {RoleArchive, "archive"}, + {RoleJunk, "junk"}, +} + +// NewFolder creates the mailbox named name, making any missing ancestors on the way. +// name is a full path whose levels are separated by the account's delimiter. +func (s *Session) NewFolder(name string) ([]Folder, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if err := s.ensureListingLocked(); err != nil { + return nil, err + } + + segments, err := FolderPath(name, s.delimiterLocked()) + if err != nil { + return nil, fmt.Errorf("mail: account %q: %w", s.acct.Name, err) + } + + full := strings.Join(segments, string(s.delimiterLocked())) + if _, exists := s.folderNamedLocked(full); exists { + return nil, fmt.Errorf("%w: account %q: %q", ErrFolderExists, s.acct.Name, full) + } + + client, err := s.acquireLocked() + if err != nil { + return nil, err + } + + // One CREATE per level, shallowest first. A level the listing already has is + // skipped: creating it again is what the server would refuse. + for i := range segments { + path := strings.Join(segments[:i+1], string(s.delimiterLocked())) + if _, exists := s.folderNamedLocked(path); exists { + continue + } + if err := client.CreateMailbox(path); err != nil { + s.resetLocked() + return nil, err + } + } + + return s.refreshFoldersLocked(client) +} + +// MoveFolder renames name so that it sits under parent, keeping its leaf. An empty +// parent moves it to the top level. It returns the folder's new full name and the +// listing the server confirmed. +func (s *Session) MoveFolder(name, parent string) (string, []Folder, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if err := s.ensureListingLocked(); err != nil { + return "", nil, err + } + + folder, ok := s.folderNamedLocked(name) + if !ok { + return "", nil, fmt.Errorf("mail: account %q: no mailbox named %q", s.acct.Name, name) + } + if err := s.refuseProtectedLocked(folder); err != nil { + return "", nil, err + } + + delimiter := s.delimiterLocked() + parent = strings.TrimSpace(parent) + dest := folder.Leaf() + if parent != "" { + if _, ok := s.folderNamedLocked(parent); !ok { + return "", nil, fmt.Errorf("mail: account %q: no mailbox named %q", s.acct.Name, parent) + } + dest = parent + string(delimiter) + folder.Leaf() + } + + switch { + case strings.EqualFold(dest, folder.Name): + return dest, nil, fmt.Errorf("%w: account %q: %q", ErrFolderNoOp, s.acct.Name, folder.Name) + + case insideFolder(parent, folder.Name, delimiter): + return dest, nil, fmt.Errorf("%w: account %q: %q is inside %q", ErrFolderCycle, s.acct.Name, parent, folder.Name) + } + + if _, exists := s.folderNamedLocked(dest); exists { + return dest, nil, fmt.Errorf("%w: account %q: %q", ErrFolderExists, s.acct.Name, dest) + } + + client, err := s.acquireLocked() + if err != nil { + return dest, nil, err + } + + if err := client.RenameMailbox(folder.Name, dest); err != nil { + s.resetLocked() + return dest, nil, err + } + + folders, repaired, err := s.moveDescendantsLocked(client, folder.Name, dest, delimiter) + if err != nil { + s.resetLocked() + return dest, nil, err + } + if repaired { + if folders, err = s.listLocked(client); err != nil { + s.resetLocked() + return dest, nil, err + } + } + + s.folders = folders + + return dest, FilterFolders(folders, s.acct.IMAP.HideFolders), nil +} + +// DeleteFolder deletes an empty mailbox. It refuses a folder that still holds mail or +// has folders below it, because neither outcome is what the user asked for: the first +// loses mail, the second orphans or destroys a subtree depending on the server. +func (s *Session) DeleteFolder(name string) ([]Folder, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if err := s.ensureListingLocked(); err != nil { + return nil, err + } + + folder, ok := s.folderNamedLocked(name) + if !ok { + return nil, fmt.Errorf("mail: account %q: no mailbox named %q", s.acct.Name, name) + } + if err := s.refuseProtectedLocked(folder); err != nil { + return nil, err + } + if below := s.descendantCountLocked(folder.Name); below > 0 { + return nil, &FolderHasChildrenError{Folder: folder.Name, Count: below} + } + + client, err := s.acquireLocked() + if err != nil { + return nil, err + } + + // The count comes from the server, not from the cached listing: the listing holds + // folder names, not folder contents, and another client can deliver mail between + // the interface's check and this one. A container marked \Noselect holds no mail by + // definition, and some servers refuse STATUS on one. + var count uint32 + if folder.Selectable() { + count, err = client.MailboxMessages(folder.Name) + if err != nil { + s.resetLocked() + return nil, err + } + } + if count > 0 { + return nil, &FolderNotEmptyError{Folder: folder.Name, Count: count} + } + + if err := client.DeleteMailbox(folder.Name); err != nil { + s.resetLocked() + return nil, err + } + + return s.refreshFoldersLocked(client) +} + +// FolderConflict reports the sentence explaining why a rename or delete of folder is +// refused, or "" when it is allowed. The interface asks before it offers the action and +// the session asks again before it runs it, so both renderings come from this one rule. +// +// INBOX is the protocol's special case: renaming it moves its messages out and leaves an +// empty INBOX behind, and deleting it is not allowed at all. A folder a config override +// names is blocked because a literal name does not travel through a rename; a folder the +// server marks with an attribute does, so those stay editable. +func FolderConflict(acct config.Account, folder Folder) string { + if folder.Role() == RoleInbox { + return "INBOX cannot be moved or deleted" + } + + for _, setting := range roleConfigKeys { + override := strings.TrimSpace(roleOverride(acct, setting.role)) + if override != "" && strings.EqualFold(override, folder.Name) { + return fmt.Sprintf("%q is set as %s in [accounts.imap]; change that setting first", folder.Name, setting.key) + } + } + + return "" +} + +// refuseProtectedLocked types the conflict for the session's callers. +func (s *Session) refuseProtectedLocked(folder Folder) error { + reason := FolderConflict(s.acct, folder) + if reason == "" { + return nil + } + + return fmt.Errorf("%w: account %q: %s", ErrFolderProtected, s.acct.Name, reason) +} + +// moveDescendantsLocked renames every folder the server left behind under the old name. +// A server that cascades the rename itself leaves nothing to find, which makes this a +// LIST and no writes. The repairs run shallowest first, so each new parent exists +// before its children are renamed into it. +func (s *Session) moveDescendantsLocked(client sessionClient, oldName, newName string, delimiter rune) ([]Folder, bool, error) { + if delimiter == 0 { + return nil, false, nil + } + + folders, err := s.listLocked(client) + if err != nil { + return nil, false, err + } + + var left []Folder + for _, folder := range folders { + if IsBelow(folder.Name, oldName, delimiter) { + left = append(left, folder) + } + } + + // Deepest last: the parent must exist at its new path before a child is moved + // under it. + for i := 1; i < len(left); i++ { + for j := i; j > 0 && left[j].Depth() < left[j-1].Depth(); j-- { + left[j], left[j-1] = left[j-1], left[j] + } + } + + for _, folder := range left { + // Drop the ancestor's own levels from the child's path and graft the new ones + // on, rather than slicing bytes: a server that returned the name in a different + // case still yields the right suffix. + levels := strings.Split(folder.Name, string(delimiter)) + drop := strings.Count(oldName, string(delimiter)) + 1 + if len(levels) <= drop { + continue + } + + dest := newName + string(delimiter) + strings.Join(levels[drop:], string(delimiter)) + if err := client.RenameMailbox(folder.Name, dest); err != nil { + return nil, true, err + } + } + + return folders, len(left) > 0, nil +} + +// ensureListingLocked loads the mailbox list when there is none. Every refusal in this +// file reads that list, and the interface has always listed before it offers an action, +// so this only covers a programmatic first call. +func (s *Session) ensureListingLocked() error { + if len(s.folders) > 0 { + return nil + } + + client, err := s.acquireLocked() + if err != nil { + return err + } + if _, err := s.listLocked(client); err != nil { + s.resetLocked() + return err + } + + return nil +} + +// listLocked lists every mailbox and caches the unfiltered result, which is what role +// resolution reads even when hide_folders keeps a mailbox off screen. +func (s *Session) listLocked(client sessionClient) ([]Folder, error) { + folders, err := client.Folders() + if err != nil { + return nil, err + } + + s.folders = folders + + return folders, nil +} + +// FolderMessages counts the messages in a mailbox with one STATUS, without selecting +// it. The interface asks before it offers to delete a folder, so the confirmation it +// shows is never about an action the server would refuse. +func (s *Session) FolderMessages(name string) (uint32, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if err := s.ensureListingLocked(); err != nil { + return 0, err + } + + folder, ok := s.folderNamedLocked(name) + if !ok { + return 0, fmt.Errorf("mail: account %q: no mailbox named %q", s.acct.Name, name) + } + if !folder.Selectable() { + // A \Noselect container holds no mail by definition, and some servers refuse + // STATUS on one. + return 0, nil + } + + client, err := s.acquireLocked() + if err != nil { + return 0, err + } + + count, err := client.MailboxMessages(folder.Name) + if err != nil { + s.resetLocked() + return 0, err + } + + return count, nil +} + +// refreshFoldersLocked lists the mailboxes after a change and returns the view the +// interface draws. +func (s *Session) refreshFoldersLocked(client sessionClient) ([]Folder, error) { + folders, err := s.listLocked(client) + if err != nil { + s.resetLocked() + return nil, err + } + + return FilterFolders(folders, s.acct.IMAP.HideFolders), nil +} + +// delimiterLocked is the hierarchy separator the server advertises. Zero means the +// server named none, which makes every mailbox a top-level name. +func (s *Session) delimiterLocked() rune { + for _, folder := range s.folders { + if folder.Delimiter != 0 { + return folder.Delimiter + } + } + + return 0 +} + +// descendantCountLocked counts the folders below name, at any depth. +func (s *Session) descendantCountLocked(name string) int { + delimiter := s.delimiterLocked() + + count := 0 + for _, folder := range s.folders { + if IsBelow(folder.Name, name, delimiter) { + count++ + } + } + + return count +} + +// FolderPath splits a typed path into levels and rejects the shapes that cannot +// name a mailbox. A server with no delimiter gets one level, which is what its names +// are. +// +// The messages are user-facing: the create prompt shows them as the user types, so the +// refusal it previews is the one the session would return. +func FolderPath(name string, delimiter rune) ([]string, error) { + name = strings.TrimSpace(name) + if name == "" { + return nil, fmt.Errorf("a folder needs a name") + } + + for _, r := range name { + if r < 0x20 || r == 0x7f { + return nil, fmt.Errorf("%q holds a control character", name) + } + } + + if delimiter == 0 { + return []string{name}, nil + } + + sep := string(delimiter) + if strings.HasPrefix(name, sep) || strings.HasSuffix(name, sep) { + return nil, fmt.Errorf("%q cannot start or end with %q", name, delimiter) + } + + segments := strings.Split(name, sep) + for _, segment := range segments { + if strings.TrimSpace(segment) == "" { + return nil, fmt.Errorf("%q has an empty level", name) + } + } + + return segments, nil +} + +// IsBelow reports whether name sits under ancestor in the hierarchy. The comparison is +// case-insensitive because mailbox names are matched that way everywhere else. +func IsBelow(name, ancestor string, delimiter rune) bool { + if delimiter == 0 || len(name) <= len(ancestor)+1 { + return false + } + if !strings.EqualFold(name[:len(ancestor)], ancestor) { + return false + } + + return rune(name[len(ancestor)]) == delimiter +} + +// insideFolder reports whether name is candidate itself or one of its descendants. +func insideFolder(name, candidate string, delimiter rune) bool { + if name == "" { + return false + } + + return strings.EqualFold(name, candidate) || IsBelow(name, candidate, delimiter) +} diff --git a/mail/folderops_test.go b/mail/folderops_test.go new file mode 100644 index 0000000..75a67cd --- /dev/null +++ b/mail/folderops_test.go @@ -0,0 +1,530 @@ +package mail + +import ( + "errors" + "strings" + "testing" + + "github.com/emersion/go-imap/v2" + "github.com/renderorange/chute/config" +) + +// session connects a real client to the in-process server and wraps it in the +// persistent session the interface uses. Folder management goes through the session, +// not the client, because the refusals depend on the cached listing. +func (s *testServer) session(t *testing.T, acct config.Account) *Session { + t.Helper() + + if acct.Name == "" { + acct = s.account() + } + acct.IMAP.Host = s.account().IMAP.Host + acct.IMAP.Port = s.account().IMAP.Port + acct.IMAP.Username = s.account().IMAP.Username + + session := newSession(acct, func(acct config.Account) (sessionClient, error) { + return connectWith(dialInsecure, acct, "secret") + }) + t.Cleanup(func() { + session.Close() + }) + + return session +} + +// folderNames lists the mailboxes in a listing, for a readable failure message. +func folderNames(folders []Folder) []string { + names := make([]string, 0, len(folders)) + for _, folder := range folders { + names = append(names, folder.Name) + } + + return names +} + +// hasFolder reports whether a listing contains a mailbox by name. +func hasFolder(folders []Folder, name string) bool { + for _, folder := range folders { + if folder.Name == name { + return true + } + } + + return false +} + +// TestNewFolderCreatesNestedParents is the issue's "support nested" gate. Some servers +// create the parents themselves and some do not (the in-process server does not), so +// chute creates every missing ancestor before the leaf. +func TestNewFolderCreatesNestedParents(t *testing.T) { + server := newTestServer(t, testCaps()) + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + folders, err := session.NewFolder("Work/2026/Q1") + if err != nil { + t.Fatalf("NewFolder: %v", err) + } + + for _, want := range []string{"Work", "Work/2026", "Work/2026/Q1"} { + if !hasFolder(folders, want) { + t.Errorf("listing %v is missing %q", folderNames(folders), want) + } + } +} + +// TestNewFolderSkipsExistingParents proves an ancestor that already exists is not +// created twice: the second CREATE would be refused by the server. +func TestNewFolderSkipsExistingParents(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + folders, err := session.NewFolder("Work/2026") + if err != nil { + t.Fatalf("NewFolder: %v", err) + } + if !hasFolder(folders, "Work/2026") { + t.Errorf("listing %v is missing Work/2026", folderNames(folders)) + } +} + +// TestNewFolderAtTopLevel creates a plain mailbox with no parents to invent. +func TestNewFolderAtTopLevel(t *testing.T) { + server := newTestServer(t, testCaps()) + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + folders, err := session.NewFolder("Receipts") + if err != nil { + t.Fatalf("NewFolder: %v", err) + } + if !hasFolder(folders, "Receipts") { + t.Errorf("listing %v is missing Receipts", folderNames(folders)) + } +} + +// TestNewFolderRefusesExistingName keeps a case-insensitive duplicate out of the +// listing: IMAP mailbox names are matched case-insensitively by this interface +// everywhere else, so creating both "Work" and "work" would be two rows for one +// mailbox. +func TestNewFolderRefusesExistingName(t *testing.T) { + server := newTestServer(t, testCaps()) + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + _, err := session.NewFolder("inbox") + if !errors.Is(err, ErrFolderExists) { + t.Fatalf("NewFolder(inbox) = %v, want ErrFolderExists", err) + } +} + +// TestNewFolderRejectsMalformedNames covers the shapes a prompt can produce. None of +// them may reach CREATE. +func TestNewFolderRejectsMalformedNames(t *testing.T) { + server := newTestServer(t, testCaps()) + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + for _, name := range []string{"", " ", "Work/", "/Work", "Work//2026", "Work/ /2026", "Work\x00"} { + t.Run(name, func(t *testing.T) { + if _, err := session.NewFolder(name); err == nil { + t.Errorf("NewFolder(%q) succeeded, want a refusal", name) + } + }) + } +} + +// TestMoveFolderCarriesSubfolders is the nesting gate for a move. The in-process server +// renames only the named mailbox, exactly like a server that ignores the RFC's inferior +// names rule, so the session has to repair the descendants itself. +func TestMoveFolderCarriesSubfolders(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + server.createMailbox(t, "Work/2026") + server.createMailbox(t, "Work/2026/Q1") + server.createMailbox(t, "Archive") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + dest, folders, err := session.MoveFolder("Work", "Archive") + if err != nil { + t.Fatalf("MoveFolder: %v", err) + } + if dest != "Archive/Work" { + t.Errorf("destination = %q, want Archive/Work", dest) + } + + for _, want := range []string{"Archive/Work", "Archive/Work/2026", "Archive/Work/2026/Q1"} { + if !hasFolder(folders, want) { + t.Errorf("listing %v is missing %q", folderNames(folders), want) + } + } + for _, gone := range []string{"Work", "Work/2026", "Work/2026/Q1"} { + if hasFolder(folders, gone) { + t.Errorf("listing %v still holds %q", folderNames(folders), gone) + } + } +} + +// TestMoveFolderToTopLevel drops a nested folder back to the root. +func TestMoveFolderToTopLevel(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Archive") + server.createMailbox(t, "Archive/2026") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + dest, folders, err := session.MoveFolder("Archive/2026", "") + if err != nil { + t.Fatalf("MoveFolder: %v", err) + } + if dest != "2026" { + t.Errorf("destination = %q, want 2026", dest) + } + if !hasFolder(folders, "2026") || hasFolder(folders, "Archive/2026") { + t.Errorf("listing %v is wrong after the move", folderNames(folders)) + } +} + +// TestMoveFolderRefusesOwnSubtree stops the cycle a move into a descendant would make. +func TestMoveFolderRefusesOwnSubtree(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + server.createMailbox(t, "Work/2026") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + if _, _, err := session.MoveFolder("Work", "Work/2026"); !errors.Is(err, ErrFolderCycle) { + t.Fatalf("MoveFolder into own subtree = %v, want ErrFolderCycle", err) + } +} + +// TestMoveFolderRefusesExistingName reports the collision before the server does, so +// the message can name the folder that is in the way. +func TestMoveFolderRefusesExistingName(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + server.createMailbox(t, "Archive") + server.createMailbox(t, "Archive/Work") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + if _, _, err := session.MoveFolder("Work", "Archive"); !errors.Is(err, ErrFolderExists) { + t.Fatalf("MoveFolder onto an existing name = %v, want ErrFolderExists", err) + } +} + +// TestMoveFolderRefusesSameParent refuses a move that would not change the name. +func TestMoveFolderRefusesSameParent(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + server.createMailbox(t, "Work/2026") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + if _, _, err := session.MoveFolder("Work/2026", "Work"); !errors.Is(err, ErrFolderNoOp) { + t.Fatalf("MoveFolder within its own parent = %v, want ErrFolderNoOp", err) + } +} + +// TestMoveFolderRefusesInbox refuses the one mailbox the protocol cannot rename +// cleanly: renaming INBOX moves its messages out and leaves an empty INBOX behind. +func TestMoveFolderRefusesInbox(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Archive") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + if _, _, err := session.MoveFolder("INBOX", "Archive"); !errors.Is(err, ErrFolderProtected) { + t.Fatalf("MoveFolder(INBOX) = %v, want ErrFolderProtected", err) + } +} + +// TestMoveFolderRefusesOverrideNamedFolder protects the mapping that resolves a role. +// A folder the server marks with an attribute travels with the attribute through a +// rename; a name typed into the config does not, so that one is refused and the status +// names the key to remove. +func TestMoveFolderRefusesOverrideNamedFolder(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Archive") + session := server.session(t, config.Account{Name: "memory", IMAP: config.IMAP{Trash: "Trash"}}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + _, _, err := session.MoveFolder("Trash", "Archive") + if !errors.Is(err, ErrFolderProtected) { + t.Fatalf("MoveFolder(override-named Trash) = %v, want ErrFolderProtected", err) + } + if !strings.Contains(err.Error(), "trash") { + t.Errorf("error %q does not name the config key to change", err) + } +} + +// TestDeleteFolderRefusesNotEmpty is the issue's central refusal, and it carries the +// count so the status can say how much mail is in the way. +func TestDeleteFolderRefusesNotEmpty(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + server.appendMessage(t, "Work", "keep me") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + _, err := session.DeleteFolder("Work") + if !errors.Is(err, ErrFolderNotEmpty) { + t.Fatalf("DeleteFolder(non-empty) = %v, want ErrFolderNotEmpty", err) + } + + var notEmpty *FolderNotEmptyError + if !errors.As(err, ¬Empty) { + t.Fatalf("error %v does not carry the message count", err) + } + if notEmpty.Count != 1 { + t.Errorf("count = %d, want 1", notEmpty.Count) + } +} + +// TestDeleteFolderRefusesChildren stops a delete that would orphan or destroy a +// subtree, depending on how the server implements it. +func TestDeleteFolderRefusesChildren(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + server.createMailbox(t, "Work/2026") + server.createMailbox(t, "Work/2026/Q1") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + _, err := session.DeleteFolder("Work") + if !errors.Is(err, ErrFolderHasChildren) { + t.Fatalf("DeleteFolder(with children) = %v, want ErrFolderHasChildren", err) + } + + var hasChildren *FolderHasChildrenError + if !errors.As(err, &hasChildren) { + t.Fatalf("error %v does not carry the subfolder count", err) + } + if hasChildren.Count != 2 { + t.Errorf("count = %d, want 2", hasChildren.Count) + } +} + +// TestDeleteFolderRemovesEmpty proves the happy path drops the mailbox and the listing. +func TestDeleteFolderRemovesEmpty(t *testing.T) { + server := newTestServer(t, testCaps()) + server.createMailbox(t, "Work") + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + folders, err := session.DeleteFolder("Work") + if err != nil { + t.Fatalf("DeleteFolder: %v", err) + } + if hasFolder(folders, "Work") { + t.Errorf("listing %v still holds Work", folderNames(folders)) + } +} + +// TestDeleteFolderRefusesInbox keeps the account's primary mailbox on the server. +func TestDeleteFolderRefusesInbox(t *testing.T) { + server := newTestServer(t, testCaps()) + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + if _, err := session.DeleteFolder("INBOX"); !errors.Is(err, ErrFolderProtected) { + t.Fatalf("DeleteFolder(INBOX) = %v, want ErrFolderProtected", err) + } +} + +// TestDeleteFolderRefusesOverrideNamedFolder is the delete half of the mapping rule. +func TestDeleteFolderRefusesOverrideNamedFolder(t *testing.T) { + server := newTestServer(t, testCaps()) + session := server.session(t, config.Account{Name: "memory", IMAP: config.IMAP{Trash: "Trash"}}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + if _, err := session.DeleteFolder("Trash"); !errors.Is(err, ErrFolderProtected) { + t.Fatalf("DeleteFolder(override-named Trash) = %v, want ErrFolderProtected", err) + } +} + +// TestDeleteFolderRemovesAnEmptyContainer covers the \Noselect case: a container holds no +// mail, so the count is zero without a STATUS a server may refuse. +func TestDeleteFolderRemovesAnEmptyContainer(t *testing.T) { + before := []Folder{ + {Name: "INBOX", Delimiter: '/'}, + {Name: "Work", Delimiter: '/', Attrs: []imap.MailboxAttr{imap.MailboxAttrNoSelect}}, + } + client := &fakeClient{folders: before} + session := newSession(config.Account{Name: "fake"}, func(config.Account) (sessionClient, error) { + return client, nil + }) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + if _, err := session.DeleteFolder("Work"); err != nil { + t.Fatalf("DeleteFolder(container): %v", err) + } + if client.countedMailbox != "" { + t.Errorf("STATUS was issued for %q, want none for a container", client.countedMailbox) + } + if client.deletedMailbox != "Work" { + t.Errorf("deleted %q, want Work", client.deletedMailbox) + } +} + +// TestFolderOpsRefreshCachedListing proves a folder made in this session can be +// operated on again without a reload: the session's own listing, which every refusal +// reads, was updated by the operation. +func TestFolderOpsRefreshCachedListing(t *testing.T) { + server := newTestServer(t, testCaps()) + session := server.session(t, config.Account{}) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + if _, err := session.NewFolder("Temp"); err != nil { + t.Fatalf("NewFolder: %v", err) + } + + if _, err := session.DeleteFolder("Temp"); err != nil { + t.Fatalf("DeleteFolder after NewFolder: %v", err) + } +} + +// TestMoveFolderLeavesCascadedDescendantsAlone is the other half of the nesting fix: a +// server that already renamed the subtree must not be asked to rename it a second time, +// because the old names are gone and the repair would fail after a successful move. +func TestMoveFolderLeavesCascadedDescendantsAlone(t *testing.T) { + before := []Folder{ + {Name: "INBOX", Delimiter: '/'}, + {Name: "Work", Delimiter: '/'}, + {Name: "Work/2026", Delimiter: '/'}, + {Name: "Archive", Delimiter: '/'}, + } + after := []Folder{ + {Name: "INBOX", Delimiter: '/'}, + {Name: "Archive", Delimiter: '/'}, + {Name: "Archive/Work", Delimiter: '/'}, + {Name: "Archive/Work/2026", Delimiter: '/'}, + } + + client := &fakeClient{folders: before} + session := newSession(config.Account{Name: "fake"}, func(config.Account) (sessionClient, error) { + return client, nil + }) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + // The next listing the session asks for is the one after the rename. + client.foldersQueue = [][]Folder{after} + + if _, _, err := session.MoveFolder("Work", "Archive"); err != nil { + t.Fatalf("MoveFolder: %v", err) + } + if len(client.renamedMailboxes) != 1 { + t.Fatalf("renames = %v, want only the named mailbox", client.renamedMailboxes) + } +} + +// TestMoveFolderRepairsShallowestFirst pins the repair order: a child renamed before +// its new parent exists is refused by a server that checks the parent path. +func TestMoveFolderRepairsShallowestFirst(t *testing.T) { + before := []Folder{ + {Name: "INBOX", Delimiter: '/'}, + {Name: "Work", Delimiter: '/'}, + {Name: "Work/2026", Delimiter: '/'}, + {Name: "Work/2026/Q1", Delimiter: '/'}, + {Name: "Archive", Delimiter: '/'}, + } + + // The server moved only the named mailbox, so both descendants are still under + // the old name when the session lists again. + client := &fakeClient{folders: before} + session := newSession(config.Account{Name: "fake"}, func(config.Account) (sessionClient, error) { + return client, nil + }) + + if _, err := session.Folders(); err != nil { + t.Fatalf("Folders: %v", err) + } + + client.foldersQueue = [][]Folder{{ + {Name: "INBOX", Delimiter: '/'}, + {Name: "Archive", Delimiter: '/'}, + {Name: "Archive/Work", Delimiter: '/'}, + {Name: "Work/2026", Delimiter: '/'}, + {Name: "Work/2026/Q1", Delimiter: '/'}, + }} + + if _, _, err := session.MoveFolder("Work", "Archive"); err != nil { + t.Fatalf("MoveFolder: %v", err) + } + + want := []renameCall{ + {from: "Work", to: "Archive/Work"}, + {from: "Work/2026", to: "Archive/Work/2026"}, + {from: "Work/2026/Q1", to: "Archive/Work/2026/Q1"}, + } + if len(client.renamedMailboxes) != len(want) { + t.Fatalf("renames = %v, want %v", client.renamedMailboxes, want) + } + for i := range want { + if client.renamedMailboxes[i] != want[i] { + t.Errorf("rename %d = %v, want %v", i, client.renamedMailboxes[i], want[i]) + } + } +} diff --git a/mail/session.go b/mail/session.go index ddefa15..10262c1 100644 --- a/mail/session.go +++ b/mail/session.go @@ -26,6 +26,10 @@ type sessionClient interface { MoveToFolder(folder, dest string, uids []imap.UID) error PurgeMessages(folder string, uids []imap.UID) error EmptyFolder(folder string) error + CreateMailbox(name string) error + RenameMailbox(name, newName string) error + DeleteMailbox(name string) error + MailboxMessages(name string) (uint32, error) Unseen(folder string) (uint32, error) Poll(folder string, since imap.UID) (PollResult, error) Search(folder string, criteria imap.SearchCriteria) ([]Message, error) diff --git a/mail/session_test.go b/mail/session_test.go index ed4801c..10b679c 100644 --- a/mail/session_test.go +++ b/mail/session_test.go @@ -44,6 +44,19 @@ type fakeClient struct { emptyFolder string emptyErr error + // Folder management: what the session asked the server to do, and the canned + // answers the refusals read. + createdMailboxes []string + renamedMailboxes []renameCall + deletedMailbox string + countedMailbox string + mailboxMessages uint32 + mailboxErr error + + // foldersQueue answers successive Folders calls, for the servers that cascade a + // rename and the ones that do not. + foldersQueue [][]Folder + compose *Compose appendCalls []appendCall appendErr error @@ -77,6 +90,16 @@ func (f *fakeClient) Folders() ([]Folder, error) { return nil, f.err } + // A queued listing lets a test show the session a different answer on a later + // call, which is how a cascading server differs from one that leaves the + // descendants behind. + if len(f.foldersQueue) > 0 { + next := f.foldersQueue[0] + f.foldersQueue = f.foldersQueue[1:] + + return next, nil + } + return f.folders, nil } @@ -243,6 +266,60 @@ func (f *fakeClient) EmptyFolder(folder string) error { return f.err } +// CreateMailbox records a mailbox the session asked the server to create. +func (f *fakeClient) CreateMailbox(name string) error { + f.requests++ + f.createdMailboxes = append(f.createdMailboxes, name) + + if f.mailboxErr != nil { + return f.mailboxErr + } + + return f.err +} + +// RenameMailbox records one rename, so a test can assert the cascade order. +func (f *fakeClient) RenameMailbox(name, newName string) error { + f.requests++ + f.renamedMailboxes = append(f.renamedMailboxes, renameCall{from: name, to: newName}) + + if f.mailboxErr != nil { + return f.mailboxErr + } + + return f.err +} + +// DeleteMailbox records the mailbox the session asked the server to remove. +func (f *fakeClient) DeleteMailbox(name string) error { + f.requests++ + f.deletedMailbox = name + + if f.mailboxErr != nil { + return f.mailboxErr + } + + return f.err +} + +// MailboxMessages returns the canned message count for a folder operation. +func (f *fakeClient) MailboxMessages(name string) (uint32, error) { + f.requests++ + f.countedMailbox = name + + if f.mailboxErr != nil { + return 0, f.mailboxErr + } + + return f.mailboxMessages, f.err +} + +// renameCall records one RENAME so a test can see the order the session used. +type renameCall struct { + from string + to string +} + // Search records the criteria a session ran and returns the canned messages. func (f *fakeClient) Search(folder string, criteria imap.SearchCriteria) ([]Message, error) { f.requests++ diff --git a/tui/client.go b/tui/client.go index e306ee0..e9e62f2 100644 --- a/tui/client.go +++ b/tui/client.go @@ -38,6 +38,19 @@ type purgeMessagesFunc func(acct config.Account, folder string, uids []imap.UID) // emptyTrashFunc deletes every message in the account's trash mailbox. type emptyTrashFunc func(acct config.Account) error +// newFolderFunc creates a mailbox, returning the listing the server confirmed. +type newFolderFunc func(acct config.Account, name string) ([]mail.Folder, error) + +// moveFolderFunc renames a mailbox under a new parent, returning its new full name and +// the listing the server confirmed. An empty parent is the top level. +type moveFolderFunc func(acct config.Account, name, parent string) (string, []mail.Folder, error) + +// deleteFolderFunc removes an empty mailbox, returning the listing the server confirmed. +type deleteFolderFunc func(acct config.Account, name string) ([]mail.Folder, error) + +// folderMessagesFunc counts the messages in one mailbox, for the delete check. +type folderMessagesFunc func(acct config.Account, name string) (uint32, error) + // fetchComposeFunc reads one message as an editable draft. type fetchComposeFunc func(acct config.Account, folder string, uid imap.UID) (*mail.Compose, error) @@ -78,6 +91,10 @@ type loaders struct { moveToFolder moveToFolderFunc purgeMessages purgeMessagesFunc emptyTrash emptyTrashFunc + newFolder newFolderFunc + moveFolder moveFolderFunc + deleteFolder deleteFolderFunc + folderMessages folderMessagesFunc fetchCompose fetchComposeFunc saveDraft saveDraftFunc @@ -121,6 +138,18 @@ func sessionLoaders(manager *mail.Manager) loaders { emptyTrash: func(acct config.Account) error { return manager.For(acct).EmptyTrash() }, + newFolder: func(acct config.Account, name string) ([]mail.Folder, error) { + return manager.For(acct).NewFolder(name) + }, + moveFolder: func(acct config.Account, name, parent string) (string, []mail.Folder, error) { + return manager.For(acct).MoveFolder(name, parent) + }, + deleteFolder: func(acct config.Account, name string) ([]mail.Folder, error) { + return manager.For(acct).DeleteFolder(name) + }, + folderMessages: func(acct config.Account, name string) (uint32, error) { + return manager.For(acct).FolderMessages(name) + }, fetchCompose: func(acct config.Account, folder string, uid imap.UID) (*mail.Compose, error) { return manager.For(acct).FetchCompose(folder, uid) }, @@ -251,3 +280,39 @@ type uidsMsg struct { uids []imap.UID err error } + +// folderCreatedMsg carries the listing a successful create returned, and the name to +// put the cursor on. +type folderCreatedMsg struct { + account string + name string + folders []mail.Folder + err error +} + +// folderMovedMsg carries the listing a successful move returned. oldName and newName are +// full paths, so the open folder and the remembered selection can follow the move. +type folderMovedMsg struct { + account string + oldName string + newName string + folders []mail.Folder + err error +} + +// folderDeletedMsg carries the listing a successful delete returned. +type folderDeletedMsg struct { + account string + name string + folders []mail.Folder + err error +} + +// folderCheckedMsg carries the message count that decides whether a delete may be +// confirmed. The count comes from the server, not the listing. +type folderCheckedMsg struct { + account string + name string + count uint32 + err error +} diff --git a/tui/confirm.go b/tui/confirm.go index 8c37531..34f2d15 100644 --- a/tui/confirm.go +++ b/tui/confirm.go @@ -7,6 +7,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/emersion/go-imap/v2" + "github.com/renderorange/chute/mail" ) // confirmKind says what a confirmation is asking about. The modal text and the action @@ -18,6 +19,8 @@ const ( confirmDiscardDraft confirmPurge confirmEmptyTrash + confirmDeleteFolder + confirmMoveFolder ) // triageReady reports whether a message panel owns the selection. Without this @@ -68,12 +71,19 @@ func (m Model) handleConfirmKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { m.confirmOpen = false m.pendingDelete = nil m.pendingEmpty = 0 + m.pendingFolder = "" + m.pendingFolderParent = "" + m.pendingFolderBelow = 0 switch m.confirmKind { case confirmDiscardDraft: m.status = "kept editing" case confirmPurge, confirmEmptyTrash: m.status = "kept in Trash" + case confirmDeleteFolder: + m.status = "kept folder" + case confirmMoveFolder: + m.status = "move cancelled" default: m.status = "delete cancelled" } @@ -89,9 +99,14 @@ func (m Model) handleConfirmKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { uids := m.pendingDelete kind := m.confirmKind + folder := m.pendingFolder + folderAt := m.pendingFolderParent m.confirmOpen = false m.pendingDelete = nil m.pendingEmpty = 0 + m.pendingFolder = "" + m.pendingFolderParent = "" + m.pendingFolderBelow = 0 switch kind { case confirmPurge: @@ -103,6 +118,12 @@ func (m Model) handleConfirmKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case confirmEmptyTrash: return m, m.emptyTrashCmd() + + case confirmDeleteFolder: + return m, m.deleteFolderCmd(folder) + + case confirmMoveFolder: + return m, m.moveFolderCmd(folder, folderAt) } if len(uids) == 0 { @@ -231,6 +252,27 @@ func (m Model) renderConfirmModal(width, height int) string { "", MutedStyle.Render("enter:empty esc:cancel"), } + case confirmDeleteFolder: + lines = []string{ + ErrorStyle.Render("delete folder"), + "", + TruncateDisplay(fmt.Sprintf("delete %s? cannot be undone", m.pendingFolder), width-6), + } + if role := m.pendingFolderRole(); role != mail.RoleNone { + lines = append(lines, MutedStyle.Render(TruncateDisplay(fmt.Sprintf("it serves the %s role", role), width-6))) + } + lines = append(lines, "", MutedStyle.Render("enter:delete esc:cancel")) + case confirmMoveFolder: + lines = []string{ + TitleStyle.Render("move folder"), + "", + TruncateDisplay(fmt.Sprintf("move %s to %s?", m.pendingFolder, m.pendingFolderDestination()), width-6), + } + if m.pendingFolderBelow > 0 { + lines = append(lines, MutedStyle.Render( + fmt.Sprintf("%s move with it", countLabel(m.pendingFolderBelow, "folder")))) + } + lines = append(lines, "", MutedStyle.Render("enter:move esc:cancel")) } modal := ModalStyle.Render(strings.Join(lines, "\n")) diff --git a/tui/folderdelete.go b/tui/folderdelete.go new file mode 100644 index 0000000..1e82748 --- /dev/null +++ b/tui/folderdelete.go @@ -0,0 +1,55 @@ +package tui + +import ( + "fmt" + + tea "github.com/charmbracelet/bubbletea" + "github.com/renderorange/chute/mail" +) + +// beginDeleteFolder asks the server how much mail is in the folder before it asks the +// user to confirm. The refusal and the confirmation are separate on purpose: confirming +// an action that is certain to fail is a keystroke spent for nothing, and the count is +// what tells the user what to do about it. +func (m Model) beginDeleteFolder() (tea.Model, tea.Cmd) { + if !m.folderActionsReady() { + return m, nil + } + if len(m.cfg.Accounts) == 0 { + return m, nil + } + + folder, ok := m.folderActionTarget() + if !ok { + m.status = "no folder selected" + + return m, nil + } + if reason := mail.FolderConflict(m.cfg.Accounts[m.account], folder); reason != "" { + m.status = reason + + return m, nil + } + + // The subfolder count is in the listing, so it needs no round trip: refusing here + // keeps the confirmation for deletes that can actually run. + if below := m.folderDescendants(folder.Name); below > 0 { + m.status = fmt.Sprintf("%s has %s below it; delete those first", folder.Name, countLabel(below, "folder")) + + return m, nil + } + if m.folderMessages == nil { + return m, nil + } + + acct := m.cfg.Accounts[m.account] + name := folder.Name + count := m.folderMessages + m.status = "checking " + name + "..." + + return m, func() tea.Msg { + messages, err := count(acct, name) + + return folderCheckedMsg{account: acct.Name, name: name, count: messages, err: err} + } +} diff --git a/tui/foldermove.go b/tui/foldermove.go new file mode 100644 index 0000000..2e58e55 --- /dev/null +++ b/tui/foldermove.go @@ -0,0 +1,186 @@ +package tui + +import ( + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/renderorange/chute/mail" +) + +// beginMoveFolder opens the destination picker for the folder under the cursor. The +// picker lists parents, not full names, because a move keeps the folder's own name: the +// confirmation shows the full path that results. +func (m Model) beginMoveFolder() (tea.Model, tea.Cmd) { + if !m.folderActionsReady() { + return m, nil + } + if len(m.cfg.Accounts) == 0 { + return m, nil + } + + folder, ok := m.folderActionTarget() + if !ok { + m.status = "no folder selected" + + return m, nil + } + if reason := mail.FolderConflict(m.cfg.Accounts[m.account], folder); reason != "" { + m.status = reason + + return m, nil + } + + rows := m.folderParentRows(folder) + if len(rows) == 0 { + m.status = "no folder can hold it" + + return m, nil + } + + m.folderMoveOpen = true + m.folderMoveName = folder.Name + m.folderMoveRows = rows + m.folderMoveMatches = rows + m.folderMoveCursor = 0 + m.folderMoveFilter = "" + m.status = "" + + return m, nil +} + +// handleFolderMoveKey applies a keypress while the destination picker is open, with the +// same shape as the message-move picker: an action this picker honours still runs, and +// every other printable key belongs to the query. +func (m Model) handleFolderMoveKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch m.keys.resolve(msg.String()) { + case actionForceQuit: + return m, tea.Quit + + case actionQuit, actionBack, actionMoveFolder: + m.closeFolderMove() + + return m, nil + + case actionOpen: + return m.chooseFolderParent() + + case actionUp: + m.folderMoveCursor = max(0, m.folderMoveCursor-1) + + case actionDown: + m.folderMoveCursor = max(0, min(m.folderMoveCursor+1, len(m.folderMoveMatches)-1)) + } + + switch msg.Type { + case tea.KeyBackspace: + if runes := []rune(m.folderMoveFilter); len(runes) > 0 { + m.folderMoveFilter = string(runes[:len(runes)-1]) + m.applyFolderMoveFilter() + } + + case tea.KeySpace: + m.folderMoveFilter += " " + m.applyFolderMoveFilter() + + case tea.KeyRunes: + m.folderMoveFilter += string(msg.Runes) + m.applyFolderMoveFilter() + } + + return m, nil +} + +// applyFolderMoveFilter re-derives the visible destinations and puts the cursor back at +// the top, because the row it pointed at may be gone. +func (m *Model) applyFolderMoveFilter() { + m.folderMoveMatches = matchFolderParents(m.folderMoveRows, m.folderMoveFilter) + m.folderMoveCursor = 0 + m.status = "" +} + +// closeFolderMove dismisses the picker and forgets the query, so reopening it starts from +// the whole list. +func (m *Model) closeFolderMove() { + m.folderMoveOpen = false + m.folderMoveFilter = "" + m.folderMoveMatches = nil + m.folderMoveRows = nil +} + +// chooseFolderParent turns the chosen parent into a move confirmation. The destination +// path is what the question is about, so it is shown before anything reaches the server. +func (m Model) chooseFolderParent() (tea.Model, tea.Cmd) { + if len(m.folderMoveMatches) == 0 { + m.status = "no folders match" + + return m, nil + } + if m.folderMoveCursor < 0 || m.folderMoveCursor >= len(m.folderMoveMatches) { + m.closeFolderMove() + + return m, nil + } + + target := m.folderMoveMatches[m.folderMoveCursor] + folder, ok := m.folderByName(m.folderMoveName) + + m.closeFolderMove() + if !ok { + m.status = "no folder selected" + + return m, nil + } + + m.confirmOpen = true + m.confirmKind = confirmMoveFolder + m.pendingFolder = folder.Name + m.pendingFolderParent = target.name + m.pendingFolderBelow = m.folderDescendants(folder.Name) + m.status = "" + + return m, nil +} + +// renderFolderMoveModal centres the destination picker. The query line appears only once +// something is typed, so the default dialog keeps its rows. +func (m Model) renderFolderMoveModal(width, height int) string { + inner := max(10, width-14) + + chrome := 6 + lines := []string{TitleStyle.Render(TruncateDisplay("move "+m.folderMoveName+" under", max(1, width-6)))} + if m.folderMoveFilter != "" { + chrome++ + lines = append(lines, NormalStyle.Render(TruncateDisplay(m.folderMoveFilter+"_", inner))) + } + + if len(m.folderMoveMatches) == 0 { + lines = append(lines, MutedStyle.Render("no folders match")) + } else { + rows := max(1, min(len(m.folderMoveMatches), height-chrome)) + start := clamp(m.folderMoveCursor-rows/2, 0, max(0, len(m.folderMoveMatches)-rows)) + end := min(start+rows, len(m.folderMoveMatches)) + + for i := start; i < end; i++ { + lines = append(lines, folderParentRow(m.folderMoveMatches[i], i == m.folderMoveCursor, inner)) + } + } + + lines = append(lines, "", MutedStyle.Render("enter:choose esc:close")) + + modal := ModalStyle.Render(strings.Join(lines, "\n")) + + return lipgloss.Place(width, height, lipgloss.Center, lipgloss.Center, modal) +} + +// folderParentRow renders one destination: a highlighted row with the full mailbox path, +// so two folders with the same leaf are told apart. +func folderParentRow(parent folderParent, selected bool, width int) string { + label := TruncateDisplay(parent.label, max(1, width-2)) + + if selected { + return SelectedStyle.Render("> " + label) + } + + return NormalStyle.Render(" " + label) +} diff --git a/tui/foldernew.go b/tui/foldernew.go new file mode 100644 index 0000000..7fa14b9 --- /dev/null +++ b/tui/foldernew.go @@ -0,0 +1,129 @@ +package tui + +import ( + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// beginNewFolder opens the create prompt for the folder under the cursor. The new folder +// is created under that folder, which is why the prompt shows the resolved path: the +// base is a fact about where the cursor was, and the user should see it before +// committing. +func (m Model) beginNewFolder() (tea.Model, tea.Cmd) { + if !m.folderActionsReady() { + return m, nil + } + + folder, ok := m.folderActionTarget() + if !ok { + m.status = "no folder selected" + + return m, nil + } + + m.newFolderOpen = true + m.folderBase = folder + m.folderName = "" + m.status = "" + + return m, nil +} + +// handleNewFolderKey edits the name. Every printable key belongs to it, which is why this +// prompt reads the key type rather than the binding table: a folder may be called +// "Quick notes", and a keymap lookup would treat the q as quit. The filter prompt makes +// the same choice for the same reason. +func (m Model) handleNewFolderKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.Type { + case tea.KeyCtrlC: + return m, tea.Quit + + case tea.KeyEsc: + m.newFolderOpen = false + m.folderName = "" + m.status = "new folder cancelled" + + return m, nil + + case tea.KeyEnter: + return m.createFolder() + + case tea.KeyBackspace: + if runes := []rune(m.folderName); len(runes) > 0 { + m.folderName = string(runes[:len(runes)-1]) + } + + case tea.KeySpace: + m.folderName += " " + + case tea.KeyRunes: + m.folderName += string(msg.Runes) + } + + return m, nil +} + +// createFolder starts the create in the background. Nothing reaches the server while the +// name is still illegal or already taken, so the status explains the problem instead. +func (m Model) createFolder() (tea.Model, tea.Cmd) { + if problem := m.folderNewProblem(); problem != "" { + m.status = problem + + return m, nil + } + + name := m.folderNewTarget() + if name == "" { + m.status = "a folder needs a name" + + return m, nil + } + if m.newFolder == nil || len(m.cfg.Accounts) == 0 { + return m, nil + } + + acct := m.cfg.Accounts[m.account] + create := m.newFolder + + m.newFolderOpen = false + m.folderName = "" + m.status = "" + + return m, func() tea.Msg { + folders, err := create(acct, name) + + return folderCreatedMsg{account: acct.Name, name: name, folders: folders, err: err} + } +} + +// renderNewFolderModal centres the create prompt. The second line is the full name the +// server will be asked for, or the reason the typed name cannot be used, which makes the +// base folder and the nesting visible while there is still time to change them. +func (m Model) renderNewFolderModal(width, height int) string { + inner := max(1, width-6) + + target := m.folderNewTarget() + problem := m.folderNewProblem() + + preview := MutedStyle.Render(TruncateDisplay("in "+m.folderBase.Name, inner)) + if problem != "" { + preview = ErrorStyle.Render(TruncateDisplay(problem, inner)) + } else if target != "" { + preview = NormalStyle.Render(TruncateDisplay("will create: "+target, inner)) + } + + lines := []string{ + TitleStyle.Render("new folder"), + "", + NormalStyle.Render(TruncateDisplay(m.folderName+"_", inner)), + preview, + "", + MutedStyle.Render("enter:create esc:cancel"), + } + + modal := ModalStyle.Render(strings.Join(lines, "\n")) + + return lipgloss.Place(width, height, lipgloss.Center, lipgloss.Center, modal) +} diff --git a/tui/folderops.go b/tui/folderops.go new file mode 100644 index 0000000..4a98252 --- /dev/null +++ b/tui/folderops.go @@ -0,0 +1,549 @@ +package tui + +import ( + "errors" + "fmt" + "sort" + "strings" + + tea "github.com/charmbracelet/bubbletea" + "github.com/emersion/go-imap/v2" + "github.com/renderorange/chute/mail" + "github.com/sahilm/fuzzy" +) + +// Folder management: the pieces the create prompt, the move picker and the delete check +// share. The rules about which names are legal and which folders may be touched live in +// the mail package, so the sentence the interface shows before an action is the one the +// session would return after it. + +// folderParent is one destination in the move picker: a mailbox that can hold the moved +// folder, or the top level when name is empty. +type folderParent struct { + name string + label string +} + +// folderActionsReady reports whether a folder-management key should act. The folder pane +// owns these keys; the overlay is the same list in the two-column layout, which has no +// folder pane, so it owns them there too. +func (m Model) folderActionsReady() bool { + return m.focus == focusFolders || m.foldersOpen +} + +// folderActionTarget is the folder a management action applies to: the row under the +// tree cursor, or the row under the overlay cursor while the overlay is open. +func (m Model) folderActionTarget() (mail.Folder, bool) { + if m.foldersOpen { + if m.folderOverlayCursor < 0 || m.folderOverlayCursor >= len(m.folders) { + return mail.Folder{}, false + } + + return m.folders[m.folderOverlayCursor], true + } + + return m.selectedFolder() +} + +// folderDelimiter is the hierarchy separator the server advertised. Zero means the +// server named none, which makes every mailbox a top-level name. +func (m Model) folderDelimiter() rune { + for _, folder := range m.folders { + if folder.Delimiter != 0 { + return folder.Delimiter + } + } + + return 0 +} + +// folderDescendants counts the folders below name, at any depth. Delete refuses while +// this is non-zero, so a mistaken press cannot orphan or destroy a subtree. +func (m Model) folderDescendants(name string) int { + delimiter := m.folderDelimiter() + + count := 0 + for _, folder := range m.folders { + if mail.IsBelow(folder.Name, name, delimiter) { + count++ + } + } + + return count +} + +// folderPath joins a parent and a leaf with the server's delimiter. An empty parent +// means the top level. +func (m Model) folderPath(parent, leaf string) string { + delimiter := m.folderDelimiter() + if parent == "" || delimiter == 0 { + return leaf + } + + return parent + string(delimiter) + leaf +} + +// folderNewTarget is the full name the create prompt would send, or "" while the field +// is empty. +func (m Model) folderNewTarget() string { + typed := strings.TrimSpace(m.folderName) + if typed == "" { + return "" + } + + return m.folderPath(m.folderBase.Name, typed) +} + +// folderNewProblem explains why the typed name cannot be created, or returns "". The +// check is the session's own, so the prompt refuses exactly what the server would. +func (m Model) folderNewProblem() string { + typed := strings.TrimSpace(m.folderName) + if typed == "" { + return "" + } + + if _, err := mail.FolderPath(typed, m.folderDelimiter()); err != nil { + return err.Error() + } + + if _, exists := m.folderByName(m.folderNewTarget()); exists { + return "a folder named " + m.folderNewTarget() + " already exists" + } + + return "" +} + +// folderParentRows lists the destinations a move can use: the top level and every +// mailbox that is not the folder itself, not one of its descendants, not its current +// parent, and not a name the move would collide with. A destination that cannot work is +// noise in a list the user is choosing from, the same rule the message-move picker uses. +func (m Model) folderParentRows(folder mail.Folder) []folderParent { + delimiter := m.folderDelimiter() + + rows := make([]folderParent, 0, len(m.folders)) + if _, exists := m.folderByName(folder.Leaf()); !exists { + rows = append(rows, folderParent{name: "", label: "(top level)"}) + } + + for _, candidate := range m.folders { + if sameFolder(candidate.Name, folder.Name) { + continue + } + if mail.IsBelow(candidate.Name, folder.Name, delimiter) { + continue + } + if sameFolder(candidate.Name, folder.Parent()) { + continue + } + if _, exists := m.folderByName(m.folderPath(candidate.Name, folder.Leaf())); exists { + continue + } + + rows = append(rows, folderParent{name: candidate.Name, label: candidate.Name}) + } + + return rows +} + +// matchFolderParents narrows the destination list, using the same fuzzy, case-insensitive +// rules as the message-move picker and the list filter. +func matchFolderParents(rows []folderParent, query string) []folderParent { + query = strings.TrimSpace(query) + if query == "" { + return rows + } + + labels := make([]string, len(rows)) + for i, row := range rows { + labels[i] = row.label + } + + matched := make([]folderParent, 0, len(rows)) + for _, hit := range fuzzy.FindNoSort(query, labels) { + matched = append(matched, rows[hit.Index]) + } + + return matched +} + +// applyFolderList installs the listing a folder operation produced and reveals the +// folder it names. The listing is the server's answer, never a locally edited tree, so a +// server that normalises a name shows its version. +func (m *Model) applyFolderList(folders []mail.Folder, selectName string) { + m.folders = folders + m.state = stateConnected + + if selectName != "" { + m.expandTo(selectName) + + if index := m.treeRowIndex(selectName); index >= 0 { + m.folderCursor = index + } + if index := m.folderIndexByName(selectName); index >= 0 { + m.folderOverlayCursor = index + } + } + + // A delete names no folder to select, and the row the overlay cursor pointed at may + // have been the one removed. + m.folderOverlayCursor = clamp(m.folderOverlayCursor, 0, max(0, len(folders)-1)) + m.clampFolderScroll() +} + +// folderIndexByName is the position of a mailbox in the flat listing, which is what the +// overlay cursor indexes. It is -1 when the listing does not have the name. +func (m Model) folderIndexByName(name string) int { + for i, folder := range m.folders { + if folder.Name == name { + return i + } + } + + return -1 +} + +// renameFolderState follows a move through everything that names a mailbox: the open +// folder, the tree's expansion set, the cached bodies and the selection the state file +// remembers. Without it the next load would select a name the server no longer has. +func (m *Model) renameFolderState(oldName, newName string) { + delimiter := m.folderDelimiter() + + if moved := renamedPath(m.openFolder, oldName, newName, delimiter); moved != m.openFolder { + m.forgetFolderSubtree(m.openFolder) + m.openFolder = moved + } + + if len(m.folderExpanded) > 0 { + expanded := make(map[string]bool, len(m.folderExpanded)) + for name, open := range m.folderExpanded { + expanded[renamedPath(name, oldName, newName, delimiter)] = open + } + + m.folderExpanded = expanded + m.rememberExpanded() + } + + if name, ok := m.selection.Folders[m.accountName()]; ok { + m.selection.Folders[m.accountName()] = renamedPath(name, oldName, newName, delimiter) + } + if names, ok := m.selection.Expanded[m.accountName()]; ok { + rewritten := make([]string, 0, len(names)) + for _, name := range names { + rewritten = append(rewritten, renamedPath(name, oldName, newName, delimiter)) + } + sort.Strings(rewritten) + + m.selection.Expanded[m.accountName()] = rewritten + } + + m.rememberSelection() +} + +// forgetFolderSubtree drops the cached state of messages in a mailbox that moved or +// disappeared. The bodies are keyed by the old path, and a stale key would either miss +// the renamed folder or answer for a mailbox that is gone. +func (m *Model) forgetFolderSubtree(name string) { + if name == "" { + return + } + + in := func(folder string) bool { + return sameFolder(folder, name) || mail.IsBelow(folder, name, m.folderDelimiter()) + } + + for key := range m.bodies { + if in(key.folder) { + delete(m.bodies, key) + } + } + for key := range m.markSeenOnLoad { + if in(key.folder) { + delete(m.markSeenOnLoad, key) + } + } + for key := range m.lastSeen { + if in(key.folder) { + delete(m.lastSeen, key) + } + } + + if in(m.loadingBody.folder) { + m.loadingBody = bodyKey{} + } +} + +// folderAfterDelete is where the reader lands when name is deleted: the next selectable +// mailbox after it in the listing, else the previous one, else none. +func (m Model) folderAfterDelete(name string) (string, bool) { + index := -1 + for i, folder := range m.folders { + if sameFolder(folder.Name, name) { + index = i + + break + } + } + if index < 0 { + return "", false + } + + for i := index + 1; i < len(m.folders); i++ { + if m.folders[i].Selectable() { + return m.folders[i].Name, true + } + } + for i := index - 1; i >= 0; i-- { + if m.folders[i].Selectable() { + return m.folders[i].Name, true + } + } + + return "", false +} + +// clearFolderFromState forgets a deleted mailbox in the tree's expansion set and in the +// selection the state file remembers, so neither names a folder the server has dropped. +func (m *Model) clearFolderFromState(name string) { + delimiter := m.folderDelimiter() + + for key := range m.folderExpanded { + if sameFolder(key, name) || mail.IsBelow(key, name, delimiter) { + delete(m.folderExpanded, key) + } + } + + if sameFolder(m.selection.Folders[m.accountName()], name) { + delete(m.selection.Folders, m.accountName()) + } + if names, ok := m.selection.Expanded[m.accountName()]; ok { + kept := make([]string, 0, len(names)) + for _, expanded := range names { + if sameFolder(expanded, name) || mail.IsBelow(expanded, name, delimiter) { + continue + } + + kept = append(kept, expanded) + } + + if len(kept) == 0 { + delete(m.selection.Expanded, m.accountName()) + } else { + m.selection.Expanded[m.accountName()] = kept + } + } + + m.rememberExpanded() +} + +// pendingFolderDestination is the full name the folder a confirmation is about will have +// after the move. +func (m Model) pendingFolderDestination() string { + folder := mail.Folder{Name: m.pendingFolder, Delimiter: m.folderDelimiter()} + + return m.folderPath(m.pendingFolderParent, folder.Leaf()) +} + +// pendingFolderRole is the role the folder a confirmation is about serves, or RoleNone. +// A delete confirmation says so, because losing the sent or drafts mailbox is not +// obvious from the folder's name. +func (m Model) pendingFolderRole() mail.Role { + folder, ok := m.folderByName(m.pendingFolder) + if !ok { + return mail.RoleNone + } + + return folder.Role() +} + +// applyFolderCreated installs the listing after a create and names it in the status bar. +func (m *Model) applyFolderCreated(msg folderCreatedMsg) { + if msg.err != nil { + m.status = folderOpStatus(msg.err) + + return + } + + m.applyFolderList(msg.folders, msg.name) + m.status = "created " + msg.name +} + +// applyFolderMoved installs the listing after a move and follows the folder through the +// state that names it. +func (m *Model) applyFolderMoved(msg folderMovedMsg) { + if msg.err != nil { + m.status = folderOpStatus(msg.err) + + return + } + + m.renameFolderState(msg.oldName, msg.newName) + m.applyFolderList(msg.folders, msg.newName) + m.status = "moved " + msg.oldName + " to " + msg.newName +} + +// applyFolderDeleted installs the listing after a delete, and moves the reader on when +// the folder it was reading is the one that went. +func (m Model) applyFolderDeleted(msg folderDeletedMsg) (tea.Model, tea.Cmd) { + if msg.err != nil { + m.status = folderOpStatus(msg.err) + + return m, nil + } + + // Where to land is a fact about the old listing, so it is read before it changes. + following, hasFollowing := m.folderAfterDelete(msg.name) + wasOpen := sameFolder(m.openFolder, msg.name) + + m.forgetFolderSubtree(msg.name) + m.clearFolderFromState(msg.name) + m.applyFolderList(msg.folders, "") + + if !wasOpen { + m.status = "deleted " + msg.name + + return m, nil + } + + m.openFolder = "" + m.messages = nil + m.rows = nil + m.filter = "" + m.messageCursor = 0 + m.messageScroll = 0 + m.readerScroll = 0 + m.visualAnchor = noVisualAnchor + m.collapsed = make(map[imap.UID]bool) + m.loadingBody = bodyKey{} + m.openUnseen = 0 + m.clearSearch() + + if !hasFollowing { + m.focus = focusFolders + m.status = "deleted " + msg.name + + return m, nil + } + + next, cmd := m.openFolderByName(following, true) + // openFolderByName clears the status, so the confirmation has to follow it. + nextTyped := next.(Model) + nextTyped.status = "deleted " + msg.name + "; opened " + following + + return nextTyped, cmd +} + +// applyFolderChecked opens the delete confirmation when the server says the folder is +// empty, and explains what is in the way when it does not. +func (m Model) applyFolderChecked(msg folderCheckedMsg) (tea.Model, tea.Cmd) { + if msg.err != nil { + m.status = folderOpStatus(msg.err) + + return m, nil + } + + if msg.count > 0 { + m.status = fmt.Sprintf("%s has %s; empty it first", msg.name, countLabel(int(msg.count), "message")) + + return m, nil + } + + folder, ok := m.folderByName(msg.name) + if !ok { + m.status = "no folder selected" + + return m, nil + } + + m.confirmOpen = true + m.confirmKind = confirmDeleteFolder + m.pendingFolder = folder.Name + m.pendingFolderParent = "" + m.pendingFolderBelow = 0 + m.status = "" + + return m, nil +} + +// deleteFolderCmd removes the confirmed folder in the background. +func (m Model) deleteFolderCmd(name string) tea.Cmd { + if m.deleteFolder == nil || len(m.cfg.Accounts) == 0 { + return nil + } + + acct := m.cfg.Accounts[m.account] + remove := m.deleteFolder + + return func() tea.Msg { + folders, err := remove(acct, name) + + return folderDeletedMsg{account: acct.Name, name: name, folders: folders, err: err} + } +} + +// moveFolderCmd renames the confirmed folder in the background. +func (m Model) moveFolderCmd(name, parent string) tea.Cmd { + if m.moveFolder == nil || len(m.cfg.Accounts) == 0 { + return nil + } + + acct := m.cfg.Accounts[m.account] + move := m.moveFolder + + return func() tea.Msg { + newName, folders, err := move(acct, name, parent) + + return folderMovedMsg{account: acct.Name, oldName: name, newName: newName, folders: folders, err: err} + } +} + +// folderOpStatus renders a folder-operation failure. The counted refusals name the +// number that blocks the action: "not empty" without a count does not tell the user what +// to do next. +func folderOpStatus(err error) string { + var notEmpty *mail.FolderNotEmptyError + if errors.As(err, ¬Empty) { + return fmt.Sprintf("%s has %s; empty it first", notEmpty.Folder, countLabel(int(notEmpty.Count), "message")) + } + + var children *mail.FolderHasChildrenError + if errors.As(err, &children) { + return fmt.Sprintf("%s has %s below it; delete those first", children.Folder, countLabel(children.Count, "folder")) + } + + switch { + case errors.Is(err, mail.ErrFolderExists): + return "that folder already exists" + + case errors.Is(err, mail.ErrFolderProtected): + return "that folder cannot be changed" + + case errors.Is(err, mail.ErrFolderCycle): + return "a folder cannot move inside itself" + + case errors.Is(err, mail.ErrFolderNoOp): + return "already there" + } + + return statusText(err) +} + +// sameFolder compares mailbox names the way the server does. +func sameFolder(a, b string) bool { + return strings.EqualFold(a, b) +} + +// renamedPath rewrites name when oldName becomes newName: the folder itself, or anything +// below it. A name outside the subtree is returned unchanged. +func renamedPath(name, oldName, newName string, delimiter rune) string { + if name == "" { + return "" + } + if sameFolder(name, oldName) { + return newName + } + if !mail.IsBelow(name, oldName, delimiter) { + return name + } + + return newName + string(delimiter) + name[len(oldName)+len(string(delimiter)):] +} diff --git a/tui/folderops_test.go b/tui/folderops_test.go new file mode 100644 index 0000000..f7c0b9e --- /dev/null +++ b/tui/folderops_test.go @@ -0,0 +1,510 @@ +package tui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/renderorange/chute/config" + "github.com/renderorange/chute/mail" +) + +// folderPane loads a listing and puts focus on the folder pane, which is where the +// management keys live. +func folderPane(t *testing.T, folders []mail.Folder) Model { + t.Helper() + + m := loaded(t, 140, 40, folders, nil) + m.focus = focusFolders + + return m +} + +// folderTree is the listing most tests share: a top-level folder, a nested one, and a +// destination. +func folderTree() []mail.Folder { + return []mail.Folder{ + {Name: "Archive", Delimiter: '/'}, + {Name: "INBOX", Delimiter: '/'}, + {Name: "Work", Delimiter: '/'}, + {Name: "Work/2026", Delimiter: '/'}, + } +} + +// cursorOn puts the tree cursor on a folder, revealing its path. +func cursorOn(t *testing.T, m Model, name string) Model { + t.Helper() + + folder, ok := m.folderByName(name) + if !ok { + t.Fatalf("the listing has no folder %q", name) + } + + m.moveFolderCursorTo(folder) + + return m +} + +// typeName sends every rune of name to the open prompt. +func typeName(t *testing.T, m Model, name string) Model { + t.Helper() + + for _, r := range name { + m = press(t, m, keyMsg(string(r))) + } + + return m +} + +// pickDestination puts the picker cursor on a destination and accepts it. +func pickDestination(t *testing.T, m Model, label string) Model { + t.Helper() + + for i, row := range m.folderMoveMatches { + if row.label == label { + m.folderMoveCursor = i + + return press(t, m, tea.KeyMsg{Type: tea.KeyEnter}) + } + } + + t.Fatalf("the picker has no destination %q, only %v", label, m.folderMoveMatches) + + return m +} + +// TestFolderManagementKeysNeedTheFolderPane is the guard that keeps the three new keys +// from firing in the panes that already own a letter: d deletes messages, so D must not +// delete a folder from the message list. +func TestFolderManagementKeysNeedTheFolderPane(t *testing.T) { + for _, key := range []string{"N", "M", "D"} { + t.Run(key, func(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + m.focus = focusMessages + + next := press(t, m, keyMsg(key)) + + if next.newFolderOpen || next.folderMoveOpen || next.confirmOpen { + t.Errorf("%s opened a folder dialog from the message list", key) + } + if next.status != "" { + t.Errorf("%s set status %q outside the folder pane", key, next.status) + } + }) + } +} + +// TestNewFolderPromptShowsThePathItWillCreate proves the cursor's folder is visible +// before the name is sent, which is what makes "create under the cursor" safe. +func TestNewFolderPromptShowsThePathItWillCreate(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + m = press(t, m, keyMsg("N")) + + if !m.newFolderOpen { + t.Fatal("N did not open the create prompt") + } + + m = typeName(t, m, "2026/Q1") + + if got, want := m.folderNewTarget(), "Work/2026/Q1"; got != want { + t.Errorf("target = %q, want %q", got, want) + } + if view := m.View(); !strings.Contains(view, "will create: Work/2026/Q1") { + t.Errorf("the prompt does not name the path it will create:\n%s", view) + } +} + +// TestNewFolderCreatesUnderTheCursorFolder covers the whole create flow: the name the +// server is asked for, the listing it returns, and the cursor landing on the new row +// with its parent revealed. +func TestNewFolderCreatesUnderTheCursorFolder(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + + var asked []string + m.newFolder = func(acct config.Account, name string) ([]mail.Folder, error) { + asked = append(asked, name) + + folders := folderTree() + + return append(folders, mail.Folder{Name: name, Delimiter: '/'}), nil + } + + m = press(t, m, keyMsg("N")) + m = typeName(t, m, "2027") + m = press(t, m, tea.KeyMsg{Type: tea.KeyEnter}) + + if len(asked) != 1 || asked[0] != "Work/2027" { + t.Fatalf("the server was asked to create %v, want [Work/2027]", asked) + } + if !strings.Contains(m.status, "created Work/2027") { + t.Errorf("status = %q, want the creation named", m.status) + } + if _, ok := m.folderByName("Work/2027"); !ok { + t.Errorf("the listing the server returned was not installed") + } + if folder, ok := m.selectedFolder(); !ok || folder.Name != "Work/2027" { + t.Errorf("the cursor is on %q, want the new folder", folder.Name) + } + if !m.folderExpanded["Work"] { + t.Error("the parent was not revealed, so the new folder would still be hidden") + } + if m.newFolderOpen { + t.Error("the prompt stayed open after the create") + } +} + +// TestNewFolderPromptTakesEveryLetter is the trap the keymap creates: q is quit, and a +// prompt that resolves bindings would make "q" uncancellable to type. +func TestNewFolderPromptTakesEveryLetter(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + m = press(t, m, keyMsg("N")) + m = press(t, m, keyMsg("q")) + + if !m.newFolderOpen { + t.Fatal("q closed the prompt instead of typing into it") + } + if got, want := m.folderName, "q"; got != want { + t.Errorf("name = %q, want %q", got, want) + } +} + +// TestNewFolderRefusesATakenName keeps a duplicate off the server, and says which name is +// in the way. +func TestNewFolderRefusesATakenName(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + m = press(t, m, keyMsg("N")) + m = typeName(t, m, "2026") + + next, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m = next.(Model) + + if cmd != nil { + t.Error("a taken name still asked the server to create it") + } + if !strings.Contains(m.status, "already exists") { + t.Errorf("status = %q, want it to say the name is taken", m.status) + } +} + +// TestFolderMovePickerOffersOnlyWorkableDestinations covers the three exclusions: the +// folder itself, its descendants, its current parent, and a destination whose resulting +// name is taken. +func TestFolderMovePickerOffersOnlyWorkableDestinations(t *testing.T) { + folders := append(folderTree(), mail.Folder{Name: "Archive/Work", Delimiter: '/'}) + m := cursorOn(t, folderPane(t, folders), "Work") + + m = press(t, m, keyMsg("M")) + + if !m.folderMoveOpen { + t.Fatalf("M did not open the move picker: %q", m.status) + } + + got := make([]string, 0, len(m.folderMoveMatches)) + for _, row := range m.folderMoveMatches { + got = append(got, row.label) + } + + // INBOX is a workable destination, and so is Archive/Work: a mailbox can always hold a + // child of the same name. Archive is not offered, because the move would produce + // Archive/Work, which already exists. A top-level row is absent while the folder is + // already at the top level, and Work/2026 is absent because it is inside the folder being + // moved. + want := []string{"INBOX", "Archive/Work"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("destinations = %v, want %v", got, want) + } +} + +// TestFolderMoveConfirmationNamesTheDestination is the issue's "show the destination +// location on confirmation screen", including how many folders travel with it. +func TestFolderMoveConfirmationNamesTheDestination(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + m = press(t, m, keyMsg("M")) + m = pickDestination(t, m, "Archive") + + if !m.confirmOpen || m.confirmKind != confirmMoveFolder { + t.Fatal("choosing a destination did not open the move confirmation") + } + if got, want := m.pendingFolderDestination(), "Archive/Work"; got != want { + t.Errorf("destination = %q, want %q", got, want) + } + + view := m.View() + if !strings.Contains(view, "move Work to Archive/Work?") { + t.Errorf("the confirmation does not name the destination:\n%s", view) + } + if !strings.Contains(view, "1 folder move with it") { + t.Errorf("the confirmation does not say the subtree travels:\n%s", view) + } +} + +// TestFolderMoveRewritesTheOpenFolderAndTheSelection is the bookkeeping a rename needs: +// the reader's folder, the tree's expansion set and the remembered selection all name +// the mailbox, and all three would otherwise point at a name the server no longer has. +func TestFolderMoveRewritesTheOpenFolderAndTheSelection(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + m.openFolder = "Work/2026" + m.folderExpanded["Work"] = true + m.selection.Folders = map[string]string{m.accountName(): "Work/2026"} + m.selection.Expanded = map[string][]string{m.accountName(): {"Work"}} + + m.moveFolder = func(acct config.Account, name, parent string) (string, []mail.Folder, error) { + return "Archive/Work", []mail.Folder{ + {Name: "Archive", Delimiter: '/'}, + {Name: "Archive/Work", Delimiter: '/'}, + {Name: "Archive/Work/2026", Delimiter: '/'}, + {Name: "INBOX", Delimiter: '/'}, + }, nil + } + + m = press(t, m, keyMsg("M")) + m = pickDestination(t, m, "Archive") + m = press(t, m, tea.KeyMsg{Type: tea.KeyEnter}) + + if got, want := m.openFolder, "Archive/Work/2026"; got != want { + t.Errorf("openFolder = %q, want %q", got, want) + } + if !m.folderExpanded["Archive/Work"] { + t.Errorf("expansion set = %v, want the renamed ancestor expanded", m.folderExpanded) + } + if m.folderExpanded["Work"] { + t.Error("the expansion set still names the old ancestor") + } + if got, want := m.selection.Folders[m.accountName()], "Archive/Work/2026"; got != want { + t.Errorf("remembered folder = %q, want %q", got, want) + } + if got, want := strings.Join(m.selection.Expanded[m.accountName()], ","), "Archive/Work"; got != want { + t.Errorf("remembered expansion = %q, want %q", got, want) + } + if folder, ok := m.selectedFolder(); !ok || folder.Name != "Archive/Work" { + t.Errorf("the cursor is on %q, want the moved folder", folder.Name) + } +} + +// TestFolderMoveRefusesAMappedFolder protects the setting that resolves a role: a literal +// name does not survive a rename, so the user has to change the config first. +func TestFolderMoveRefusesAMappedFolder(t *testing.T) { + cfg := testConfig() + cfg.Accounts[0].IMAP.Trash = "Trash" + + m := loadedWith(t, cfg, []mail.Folder{ + {Name: "INBOX", Delimiter: '/'}, + {Name: "Trash", Delimiter: '/'}, + {Name: "Archive", Delimiter: '/'}, + }) + m.focus = focusFolders + m = cursorOn(t, m, "Trash") + + m = press(t, m, keyMsg("M")) + + if m.folderMoveOpen { + t.Fatal("the picker opened for a folder the config names") + } + for _, want := range []string{"Trash", "[accounts.imap]", "trash"} { + if !strings.Contains(m.status, want) { + t.Errorf("status = %q, want it to name %q", m.status, want) + } + } +} + +// TestFolderDeleteChecksEmptinessFirst proves the confirmation is only reached for a +// delete that can run, and that the refusal says how much mail is in the way. +func TestFolderDeleteChecksEmptinessFirst(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work/2026") + + var asked []string + m.folderMessages = func(acct config.Account, name string) (uint32, error) { + asked = append(asked, name) + + return 3, nil + } + + m = press(t, m, keyMsg("D")) + + if len(asked) != 1 || asked[0] != "Work/2026" { + t.Fatalf("the server was asked about %v, want [Work/2026]", asked) + } + if m.confirmOpen { + t.Error("the confirmation opened for a folder that still holds mail") + } + for _, want := range []string{"3 messages", "empty it first"} { + if !strings.Contains(m.status, want) { + t.Errorf("status = %q, want it to say %q", m.status, want) + } + } +} + +// TestFolderDeleteRefusesAFolderWithSubfolders refuses before any round trip: the count +// is in the listing. +func TestFolderDeleteRefusesAFolderWithSubfolders(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + + m.folderMessages = func(config.Account, string) (uint32, error) { + t.Error("the server was asked about a folder that has subfolders") + + return 0, nil + } + + m = press(t, m, keyMsg("D")) + + if m.confirmOpen { + t.Error("the confirmation opened for a folder with subfolders") + } + for _, want := range []string{"1 folder", "delete those first"} { + if !strings.Contains(m.status, want) { + t.Errorf("status = %q, want it to say %q", m.status, want) + } + } +} + +// TestFolderDeleteConfirmsAnEmptyFolder covers the confirmation and the call that removes +// the mailbox. +func TestFolderDeleteConfirmsAnEmptyFolder(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work/2026") + m.folderMessages = func(config.Account, string) (uint32, error) { return 0, nil } + + var removed []string + m.deleteFolder = func(acct config.Account, name string) ([]mail.Folder, error) { + removed = append(removed, name) + + return []mail.Folder{ + {Name: "Archive", Delimiter: '/'}, + {Name: "INBOX", Delimiter: '/'}, + {Name: "Work", Delimiter: '/'}, + }, nil + } + + m = press(t, m, keyMsg("D")) + + if !m.confirmOpen || m.confirmKind != confirmDeleteFolder { + t.Fatal("an empty folder did not reach the delete confirmation") + } + if view := m.View(); !strings.Contains(view, "delete Work/2026?") { + t.Errorf("the confirmation does not name the folder:\n%s", view) + } + + m = press(t, m, tea.KeyMsg{Type: tea.KeyEnter}) + + if len(removed) != 1 || removed[0] != "Work/2026" { + t.Fatalf("the server was asked to delete %v, want [Work/2026]", removed) + } + if _, ok := m.folderByName("Work/2026"); ok { + t.Error("the deleted folder is still in the listing") + } + if !strings.Contains(m.status, "deleted Work/2026") { + t.Errorf("status = %q, want the delete named", m.status) + } +} + +// TestDeletingTheOpenFolderMovesTheReaderOn keeps the reader off a mailbox that no longer +// exists: the folder that followed it in the listing opens instead. +func TestDeletingTheOpenFolderMovesTheReaderOn(t *testing.T) { + folders := []mail.Folder{ + {Name: "Archive", Delimiter: '/'}, + {Name: "INBOX", Delimiter: '/'}, + {Name: "Work", Delimiter: '/'}, + } + + m := cursorOn(t, folderPane(t, folders), "Work") + m.openFolder = "Work" + m.messages = sampleMessages(2) + m.loadMessages = fakeMessages(nil, nil) + m.folderMessages = func(config.Account, string) (uint32, error) { return 0, nil } + m.deleteFolder = func(config.Account, string) ([]mail.Folder, error) { + return []mail.Folder{ + {Name: "Archive", Delimiter: '/'}, + {Name: "INBOX", Delimiter: '/'}, + }, nil + } + + m = press(t, m, keyMsg("D")) + m = press(t, m, tea.KeyMsg{Type: tea.KeyEnter}) + + if got, want := m.openFolder, "INBOX"; got != want { + t.Errorf("openFolder = %q, want the folder that followed %q", got, want) + } + for _, want := range []string{"deleted Work", "opened INBOX"} { + if !strings.Contains(m.status, want) { + t.Errorf("status = %q, want it to say %q", m.status, want) + } + } +} + +// TestFolderOverlayRunsTheFolderKeys keeps folder management reachable in the two-column +// layout, which draws no folder pane. +func TestFolderOverlayRunsTheFolderKeys(t *testing.T) { + m := folderPane(t, folderTree()) + m.foldersOpen = true + for i, folder := range m.folders { + if folder.Name == "Work" { + m.folderOverlayCursor = i + } + } + + m = press(t, m, keyMsg("M")) + + if !m.folderMoveOpen { + t.Fatalf("the overlay did not open the move picker: %q", m.status) + } + if got, want := m.folderMoveName, "Work"; got != want { + t.Errorf("moving %q, want %q", got, want) + } +} + +// TestFolderDialogsFitTheMinimumFrame covers the 60x20 floor the layout is tested at: +// a folder name long enough to fill the frame must not widen a dialog. +func TestFolderDialogsFitTheMinimumFrame(t *testing.T) { + long := "A very long folder name that runs past the frame at sixty columns wide" + folders := []mail.Folder{ + {Name: "Archive", Delimiter: '/'}, + {Name: "INBOX", Delimiter: '/'}, + {Name: long, Delimiter: '/'}, + } + + base := loaded(t, 60, 20, folders, nil) + base.focus = focusFolders + base.moveFolderCursorTo(folders[2]) + + create := press(t, base, keyMsg("N")) + create = typeName(t, create, long) + assertExactFrame(t, create, "create prompt at 60x20") + + mover := press(t, base, keyMsg("M")) + if !mover.folderMoveOpen { + t.Fatalf("the picker did not open: %q", mover.status) + } + assertExactFrame(t, mover, "move picker at 60x20") + + confirm := pickDestination(t, mover, "Archive") + if !confirm.confirmOpen { + t.Fatal("choosing a destination did not open the confirmation") + } + assertExactFrame(t, confirm, "move confirmation at 60x20") + + remove := cursorOn(t, base, "Archive") + remove.folderMessages = func(config.Account, string) (uint32, error) { return 0, nil } + remove = press(t, remove, keyMsg("D")) + assertExactFrame(t, remove, "delete confirmation at 60x20") +} + +// TestFolderOpFailureKeepsTheListing proves a refused operation leaves the tree as it was +// and reports the reason, rather than half-applying a listing the server never sent. +func TestFolderOpFailureKeepsTheListing(t *testing.T) { + m := cursorOn(t, folderPane(t, folderTree()), "Work") + m.newFolder = func(config.Account, string) ([]mail.Folder, error) { + return nil, &mail.FolderNotEmptyError{Folder: "Work", Count: 4} + } + + m = press(t, m, keyMsg("N")) + m = typeName(t, m, "2027") + m = press(t, m, tea.KeyMsg{Type: tea.KeyEnter}) + + if len(m.folders) != len(folderTree()) { + t.Errorf("folders = %d, want the listing left alone", len(m.folders)) + } + for _, want := range []string{"4 messages", "empty it first"} { + if !strings.Contains(m.status, want) { + t.Errorf("status = %q, want it to say %q", m.status, want) + } + } +} diff --git a/tui/folders_overlay.go b/tui/folders_overlay.go index f60cb08..e8c7455 100644 --- a/tui/folders_overlay.go +++ b/tui/folders_overlay.go @@ -43,6 +43,15 @@ func (m Model) handleFoldersKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case actionDown: m.folderOverlayCursor = min(m.folderOverlayCursor+1, len(m.folders)-1) + case actionNewFolder: + return m.beginNewFolder() + + case actionMoveFolder: + return m.beginMoveFolder() + + case actionDeleteFolder: + return m.beginDeleteFolder() + case actionOpen: if m.folderOverlayCursor < 0 || m.folderOverlayCursor >= len(m.folders) { return m, nil diff --git a/tui/footer.go b/tui/footer.go index d35f708..b81fd5a 100644 --- a/tui/footer.go +++ b/tui/footer.go @@ -137,8 +137,19 @@ func (m Model) footerHints() []footerHint { return []footerHint{hint(actionOpen, "search"), hint(actionBack, "cancel")} case m.filterOpen: return []footerHint{hint(actionOpen, "keep"), hint(actionBack, "clear")} + case m.newFolderOpen: + return []footerHint{hint(actionOpen, "create"), hint(actionBack, "cancel")} + case m.folderMoveOpen: + return []footerHint{ + literalHint("type", "filter"), + hintPair(actionUp, actionDown, "choose"), + hint(actionOpen, "choose"), + hint(actionBack, "close"), + } case m.confirmOpen && m.confirmKind == confirmDiscardDraft: return []footerHint{hint(actionOpen, "discard"), hint(actionBack, "keep editing")} + case m.confirmOpen && m.confirmKind == confirmMoveFolder: + return []footerHint{hint(actionOpen, "move"), hint(actionBack, "cancel")} case m.confirmOpen: return []footerHint{hint(actionOpen, "delete"), hint(actionBack, "cancel")} case m.compose != nil: @@ -185,6 +196,17 @@ func (m Model) footerHints() []footerHint { hintPair(actionUp, actionDown, "extend"), hint(actionQuit, "quit"), } + // The folder pane's keys are its own: d, m and f act on messages, which that pane does + // not show, so advertising them there points at keys that do nothing. Folder management + // leads instead, because it is the only thing those keys do in this pane. + case m.focus == focusFolders: + return []footerHint{ + hint(actionDeleteFolder, "delete"), + hint(actionMoveFolder, "move"), + hint(actionNewFolder, "new"), + hint(actionOpen, "open"), + hint(actionQuit, "quit"), + } case m.focus == focusReader: hints := []footerHint{ hint(actionDelete, "delete"), diff --git a/tui/footer_test.go b/tui/footer_test.go index af589d2..ea17fb2 100644 --- a/tui/footer_test.go +++ b/tui/footer_test.go @@ -17,18 +17,40 @@ type footerCase struct { // hint. It is asserted whole rather than by substring so a hint that grows past // 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. +// reminder, not the keymap, and the rest waits for the help screen. This is the message +// list's set; the folders pane has its own, pinned in folderFooterHints. const footerDefaultHints = "d:delete f:flag m:move enter:open q:quit" +// folderFooterHints is the folders pane: its keys act on the tree, not on messages, so +// advertising d, m and f there would point at keys that do nothing in that pane (#105). +const folderFooterHints = "D:delete M:move N:new enter:open q:quit" + +// listModel is sized with the message list focused, which is the context the default +// footer set describes. +func listFooterModel(width, height int) Model { + m := sized(width, height) + m.focus = focusMessages + + return m +} + // footerCases builds one model per footer context. Every model is 105 columns // unless the case is about the composer, whose hints are wider. func footerCases(t *testing.T) []footerCase { t.Helper() + // The list is the default context: a model that has not navigated yet sits on the + // folders pane, whose footer names its own keys. base := func(width int) Model { - return sized(width, 40) + m := sized(width, 40) + m.focus = focusMessages + + return m } + folderPane := sized(105, 40) + folderPane.focus = focusFolders + reader := base(105) reader.focus = focusReader @@ -61,6 +83,7 @@ func footerCases(t *testing.T) []footerCase { return []footerCase{ {"default", base(105)}, {"default narrow", base(60)}, + {"folders", folderPane}, {"reader", reader}, {"reader narrow", readerNarrow}, {"visual range", visual}, @@ -110,7 +133,7 @@ func TestFooterKeysResolveToTheirActions(t *testing.T) { // TestFooterFollowsARebind proves the hints come from the binding table rather // than from a second copy of the keymap: rebinding delete moves the hint with it. func TestFooterFollowsARebind(t *testing.T) { - m := sized(105, 40) + m := listFooterModel(105, 40) m.keys[actionDelete] = []string{"x"} footer := m.renderFooter() @@ -126,7 +149,7 @@ func TestFooterFollowsARebind(t *testing.T) { // TestFooterRemovedBindingIsDropped proves a hint disappears when its action has // no keys, instead of rendering a bare ":label". func TestFooterRemovedBindingIsDropped(t *testing.T) { - m := sized(105, 40) + m := listFooterModel(105, 40) m.keys[actionToggleFlag] = nil footer := m.renderFooter() @@ -136,11 +159,31 @@ func TestFooterRemovedBindingIsDropped(t *testing.T) { } } +// TestFooterFolderPaneIsItsOwnSet pins the pane's set exactly, the way the list's is +// pinned. #105 gave the folder pane keys of its own, and a footer that still advertised +// d:delete there would name a key that does nothing in that pane. +func TestFooterFolderPaneIsItsOwnSet(t *testing.T) { + for _, width := range []int{60, 105} { + m := sized(width, 40) + if m.focus != focusFolders { + t.Fatalf("%d columns: focus = %v, want folders", width, m.focus) + } + + footer := m.renderFooter() + if footer != folderFooterHints { + t.Errorf("folder footer at %d = %q, want %q", width, footer, folderFooterHints) + } + if got, limit := lipgloss.Width(footer), ContentWidth(width); got > limit { + t.Errorf("folder footer at %d is %d cells, want at most %d", width, got, limit) + } + } +} + // TestFooterAt105IsTheFullSet pins the tablet footer exactly: the priority keys, // nothing else. #26 cut this from ten hints to five on the owner's report that // the footer was overwhelming. func TestFooterAt105IsTheFullSet(t *testing.T) { - m := sized(105, 40) + m := listFooterModel(105, 40) if got := m.renderFooter(); got != footerDefaultHints { t.Errorf("footer at 105 =\n %q\nwant\n %q", got, footerDefaultHints) @@ -150,7 +193,7 @@ func TestFooterAt105IsTheFullSet(t *testing.T) { // TestFooterAt105FillsTheBudget proves the exact-fit string is legal: within the // content width and never cut. func TestFooterAt105FillsTheBudget(t *testing.T) { - m := sized(105, 40) + m := listFooterModel(105, 40) footer := m.renderFooter() if got, limit := lipgloss.Width(footer), ContentWidth(105); got > limit { @@ -164,7 +207,7 @@ func TestFooterAt105FillsTheBudget(t *testing.T) { // TestFooterAt60KeepsWholeHints proves the narrow footer drops nothing at the // supported floor: the five hints fit in 54 cells. func TestFooterAt60KeepsWholeHints(t *testing.T) { - m := sized(60, 40) + m := listFooterModel(60, 40) footer := m.renderFooter() if footer != footerDefaultHints { @@ -179,7 +222,7 @@ func TestFooterAt60KeepsWholeHints(t *testing.T) { // 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(44, 20) + m := listFooterModel(44, 20) footer := m.renderFooter() const want = "d:delete f:flag m:move enter:open" @@ -201,7 +244,7 @@ func TestFooterDropsWholeHintsWhenItMust(t *testing.T) { // invite more hints back in. The set is fixed; the width is only a safety net. func TestFooterWideStaysCalm(t *testing.T) { for _, width := range []int{120, 130, 140, 200} { - if got := sized(width, 40).renderFooter(); got != footerDefaultHints { + if got := listFooterModel(width, 40).renderFooter(); got != footerDefaultHints { t.Errorf("footer at %d = %q, want the five-hint set", width, got) } } @@ -211,7 +254,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(), hintSeparator) { + for _, hint := range strings.Split(listFooterModel(width, 40).renderFooter(), hintSeparator) { if hint == "r:reload" { t.Errorf("width %d: the footer claims r:reload", width) } @@ -223,6 +266,7 @@ func TestFooterNeverSaysRReload(t *testing.T) { // that none of them is truncated at the tablet width. func TestFooterModalContexts(t *testing.T) { want := map[string][]string{ + "folders": {"D:delete", "M:move", "N:new", "enter:open", "q:quit"}, "reader": {"n:next", "p:prev", "q:quit"}, "reader narrow": {"n:next", "p:prev"}, "visual range": {"up/down:extend", "esc:cancel", "d:delete"}, @@ -289,7 +333,7 @@ func TestFooterComposerKeepsItsLiteralKeys(t *testing.T) { // stays in the footer. At 105 the panel is reachable, so the key is optional and // does not spend the budget. func TestFooterReachesHiddenFolders(t *testing.T) { - two := sized(110, 40) + two := listFooterModel(110, 40) if mode := two.layout().Mode; mode != ModeTwo { t.Fatalf("110 columns is mode %d, want ModeTwo", mode) } @@ -297,7 +341,7 @@ func TestFooterReachesHiddenFolders(t *testing.T) { t.Errorf("two-column footer does not reach the hidden folders panel: %q", footer) } - single := sized(105, 40) + single := listFooterModel(105, 40) if mode := single.layout().Mode; mode != ModeSingle { t.Fatalf("105 columns is mode %d, want ModeSingle", mode) } diff --git a/tui/help.go b/tui/help.go index 276509c..5438429 100644 --- a/tui/help.go +++ b/tui/help.go @@ -85,6 +85,18 @@ func helpGroups() []helpGroup { helpAction(actionAttachments, "attachments"), }, }, + // The folders group is deliberately three rows: the help body has one screen of + // budget, and the pane's navigation keys (open, expand, fold, overlay) are already + // documented under global and list. What is new is that this pane now owns keys of its + // own, and those are what it has to name. + { + title: "folders", + rows: []helpRow{ + helpAction(actionNewFolder, "new folder"), + helpAction(actionMoveFolder, "move folder"), + helpAction(actionDeleteFolder, "delete folder"), + }, + }, { title: "selection", rows: []helpRow{ diff --git a/tui/keys.go b/tui/keys.go index a3faf2f..edd58fa 100644 --- a/tui/keys.go +++ b/tui/keys.go @@ -40,6 +40,9 @@ const ( actionJunk actionMove actionEmptyTrash + actionNewFolder + actionMoveFolder + actionDeleteFolder actionCollapse actionExpandFolder actionCollapseFolder @@ -82,6 +85,9 @@ var actionNames = map[action]string{ actionJunk: config.KeyJunk, actionMove: config.KeyMove, actionEmptyTrash: config.KeyEmptyTrash, + actionNewFolder: config.KeyNewFolder, + actionMoveFolder: config.KeyMoveFolder, + actionDeleteFolder: config.KeyDeleteFolder, actionCollapse: config.KeyCollapse, actionExpandFolder: config.KeyExpandFolder, actionCollapseFolder: config.KeyCollapseFolder, diff --git a/tui/keys_test.go b/tui/keys_test.go index f06b49d..e432f1e 100644 --- a/tui/keys_test.go +++ b/tui/keys_test.go @@ -58,16 +58,17 @@ func TestNavigationKeysAreArrowsOnly(t *testing.T) { } } -// TestMoveAndReadBindingsMatchTheIssue records #88's rebind: m moves a message, u -// toggles read/unread, and the old uppercase M is gone rather than left behind as a -// silent alias. +// TestMoveAndReadBindingsMatchTheIssue records #88's rebind: m moves a message and u +// toggles read/unread. #88 removed uppercase M as a second name for the message move; +// #105 gives M to the folder pane's move, which is a different intent, so the key is +// bound again without reviving the alias. func TestMoveAndReadBindingsMatchTheIssue(t *testing.T) { b := defaultBindings() for key, want := range map[string]action{ "m": actionMove, "u": actionToggleRead, - "M": actionNone, + "M": actionMoveFolder, } { if got := b.resolve(key); got != want { t.Errorf("%q resolves to action %d, want %d", key, got, want) diff --git a/tui/model.go b/tui/model.go index de7a93c..2e239bc 100644 --- a/tui/model.go +++ b/tui/model.go @@ -112,6 +112,22 @@ type Model struct { pendingDelete []imap.UID pendingEmpty int + // Folder management. The create prompt holds the typed name and the folder it will + // be created under; the move picker holds its own filtered destination list; the + // confirmation holds the folder it is about and the parent it moves to. + newFolderOpen bool + folderName string + folderBase mail.Folder + folderMoveOpen bool + folderMoveName string + folderMoveCursor int + folderMoveFilter string + folderMoveRows []folderParent + folderMoveMatches []folderParent + pendingFolder string + pendingFolderParent string + pendingFolderBelow int + // filter narrows the loaded list; filterOpen is the prompt that edits it. filter string filterOpen bool @@ -149,6 +165,10 @@ type Model struct { moveToFolder moveToFolderFunc purgeMessages purgeMessagesFunc emptyTrash emptyTrashFunc + newFolder newFolderFunc + moveFolder moveFolderFunc + deleteFolder deleteFolderFunc + folderMessages folderMessagesFunc fetchCompose fetchComposeFunc saveDraft saveDraftFunc appendSent appendSentFunc @@ -183,6 +203,10 @@ func New(cfg *config.Config, version string, mailOptions ...mail.Option) Model { moveToFolder: load.moveToFolder, purgeMessages: load.purgeMessages, emptyTrash: load.emptyTrash, + newFolder: load.newFolder, + moveFolder: load.moveFolder, + deleteFolder: load.deleteFolder, + folderMessages: load.folderMessages, fetchCompose: load.fetchCompose, saveDraft: load.saveDraft, appendSent: load.appendSent, @@ -535,6 +559,38 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m.afterRemoval(msg.uids, fmt.Sprintf("emptied Trash (%s)", countLabel(len(msg.uids), "message"))) + case folderCreatedMsg: + if msg.account != m.accountName() { + return m, nil + } + + m.applyFolderCreated(msg) + + return m, nil + + case folderMovedMsg: + if msg.account != m.accountName() { + return m, nil + } + + m.applyFolderMoved(msg) + + return m, nil + + case folderDeletedMsg: + if msg.account != m.accountName() { + return m, nil + } + + return m.applyFolderDeleted(msg) + + case folderCheckedMsg: + if msg.account != m.accountName() { + return m, nil + } + + return m.applyFolderChecked(msg) + case searchMsg: m.applySearch(msg) @@ -577,6 +633,12 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { if m.moveOpen { return m.handleMoveKey(msg) } + if m.newFolderOpen { + return m.handleNewFolderKey(msg) + } + if m.folderMoveOpen { + return m.handleFolderMoveKey(msg) + } if m.foldersOpen { return m.handleFoldersKey(msg) } @@ -637,6 +699,15 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case actionEmptyTrash: return m.beginEmptyTrash() + case actionNewFolder: + return m.beginNewFolder() + + case actionMoveFolder: + return m.beginMoveFolder() + + case actionDeleteFolder: + return m.beginDeleteFolder() + case actionCollapse: return m.toggleCollapse() @@ -1053,6 +1124,14 @@ func (m Model) View() string { if modal := m.renderConfirmModal(ContentWidth(m.width), ContentHeight(m.height)); modal != "" { panels = modal } + case m.newFolderOpen: + if modal := m.renderNewFolderModal(ContentWidth(m.width), ContentHeight(m.height)); modal != "" { + panels = modal + } + case m.folderMoveOpen: + if modal := m.renderFolderMoveModal(ContentWidth(m.width), ContentHeight(m.height)); modal != "" { + panels = modal + } case m.attachOpen: if modal := m.renderAttachmentModal(ContentWidth(m.width), ContentHeight(m.height)); modal != "" { panels = modal