diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d2cc9b..afeef67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ ### Changed +- Load chat names directly in the backup chat selector, with streamed results, + account-scoped caching, stop/reload controls, and manual chat entry. +- Show Since and Until date/time filters in the main backup forms. +- Label TUI export formats as JSON, HTML, and Both to match the CLI options. +- Simplify TUI forms with task-specific settings, wide text editors, direct + typing and paste, Tab navigation, visible choice controls and inline errors. +- Place editable values and compact, scrollable selectors beside their argument + labels, with independent wheel scrolling and preserved multi-selections. +- Keep selected multi-select names visible, distinguish checkboxes from single + choices, and provide a selected-only view and Add-item editor for custom lists. +- Support the full multi-select flow with mouse clicks, keep scrolled checkboxes + in place, avoid skipping options in small lists, and add a clickable Add action. +- Use Enter to toggle highlighted multi-select items and Left Arrow to accept + the choices and close the list, including chat category selection. +- Render backup measurements with animated Bubbles progress bars and skip + reprocessing unchanged task output while waiting for worker updates. - Require Go 1.26 or newer for the Bubble Tea v2 terminal interface. - Open the interactive workspace when `ta` runs without arguments in a terminal; piped invocations and `ta --help` continue to display command help. @@ -13,6 +29,15 @@ ### Added +- Calendar pickers for Since and Until, with mouse selection, month navigation, + Today and Clear controls, and manual timestamp entry. +- File and folder choosers for TUI path fields, with native macOS Open/Save + dialogs, multiple-file selection, and a terminal browser for remote sessions + and systems without a graphical chooser. Manual path entry stays available. +- Searchable TUI dropdowns and inline multi-select lists for saved accounts, media, chat + categories and account sections. Check multiple chats or accounts in browser + results. Multi-account backups run as a queue with isolated output folders, + per-account progress and retained results, including failures and cancellation. - `ta tui`: a responsive Bubble Tea workspace covering public commands and their options, including installed extensions. Includes quick-start presets, command and option search, common/advanced forms, inline validation, command diff --git a/cmd/progress.go b/cmd/progress.go index d7622b8..271372b 100644 --- a/cmd/progress.go +++ b/cmd/progress.go @@ -70,9 +70,9 @@ func newBackupProgress(output io.Writer) *backupProgress { width = columns } } - lines := p.lines(time.Now(), width) + lines, status := p.frame(time.Now(), width) if terminal && os.Getenv("TA_TUI_CHILD") == "1" { - taskui.WriteProgress(output, lines) + taskui.WriteStatus(output, status) return } if terminal { @@ -175,6 +175,11 @@ func (p *backupProgress) finish(err error) { } func (p *backupProgress) lines(now time.Time, width int) []string { + lines, _ := p.frame(now, width) + return lines +} + +func (p *backupProgress) frame(now time.Time, width int) ([]string, taskui.Progress) { p.mu.Lock() defer p.mu.Unlock() paint := func(color text.Color, value string) string { @@ -275,7 +280,9 @@ func (p *backupProgress) lines(now time.Time, width int) []string { paint(labelColor, runewidth.Truncate(label, limit, "…")), text.Snip(bar, limit, "…"), text.Snip(metrics, limit, "…"), - } + }, taskui.Progress{Label: label, Detail: size, Summary: metrics, + Percent: percent / 100, Determinate: p.plan.Ready || p.finished, + CompletedFiles: p.completeFiles, TotalFiles: p.plan.Files} } func formatProgressBytes(bytes int64) string { diff --git a/cmd/root.go b/cmd/root.go index d4d77ea..4768229 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -31,6 +31,7 @@ func New() *cobra.Command { } root.PersistentFlags().Lookup("ns").Usage = "saved Telegram login; concurrent terminals need separate namespaces (the same account is supported); list with ta accounts" root.AddCommand(NewArchive(), NewStats(), NewRender(), NewSchedule(), NewAccount(), NewSync(), NewCron(), NewAccounts(), NewVersion(), newSessionRecover(), NewTUI()) + annotateTUIChoices(root) viper.SetEnvPrefix("TA") bindProductEnvironment(root) brandCommands(root) diff --git a/cmd/tui.go b/cmd/tui.go index 49860e4..1d55b8d 100644 --- a/cmd/tui.go +++ b/cmd/tui.go @@ -2,10 +2,14 @@ package cmd import ( "context" + "encoding/csv" "fmt" + "maps" "os" + "strings" tea "charm.land/bubbletea/v2" + "github.com/mo1ein/TelegramArchive/consts" "github.com/mo1ein/TelegramArchive/internal/tui" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -33,7 +37,31 @@ func runTUI(cmd *cobra.Command, _ []string) error { root.InitDefaultCompletionCmd() taskCtx, cancel := context.WithCancel(cmd.Context()) defer cancel() - model := tui.New(tui.Catalog(root), inheritedArguments(cmd), viper.GetString("ns"), taskCtx) + storage := maps.Clone(viper.GetStringMapString("storage")) + if _, configured := productSetting("STORAGE"); !configured && !cmd.Flags().Changed("storage") { + storage = defaultProductStorage(consts.HomeDir) + } + model := tui.New(tui.Catalog(root), inheritedArguments(cmd), viper.GetString("ns"), taskCtx, + tui.WithAccountLoader(func(ctx context.Context, override string) ([]string, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + options := maps.Clone(storage) + if override != "" { + values, err := csv.NewReader(strings.NewReader(override)).Read() + if err != nil { + return nil, err + } + for _, value := range values { + key, setting, ok := strings.Cut(value, "=") + if !ok { + return nil, fmt.Errorf("storage settings need key=value pairs") + } + options[key] = setting + } + } + return tuiSavedAccounts(options) + })) _, err := tea.NewProgram(model, tea.WithContext(cmd.Context()), tea.WithInput(cmd.InOrStdin()), tea.WithOutput(cmd.OutOrStdout())).Run() return err } diff --git a/cmd/tui_options.go b/cmd/tui_options.go new file mode 100644 index 0000000..82468ee --- /dev/null +++ b/cmd/tui_options.go @@ -0,0 +1,97 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "io" + "os" + "slices" + "strings" + "time" + + "github.com/mo1ein/TelegramArchive/internal/archive" + transport "github.com/mo1ein/TelegramArchive/internal/telegram" + "github.com/spf13/cobra" + "go.etcd.io/bbolt" +) + +func annotateTUIChoices(root *cobra.Command) { + options := map[string][]string{ + "media": append([]string{"all", "none"}, archive.MediaKinds...), + "types": transport.ChatTypes, + "include": append([]string{"all"}, transport.AccountKinds...), + "account-include": append([]string{"all"}, transport.AccountKinds...), + } + for _, path := range []string{"archive", "account", "sync", "cron add"} { + command, _, err := root.Find(strings.Fields(path)) + if err != nil { + continue + } + for name, values := range options { + if flag := command.Flags().Lookup(name); flag != nil { + if flag.Annotations == nil { + flag.Annotations = map[string][]string{} + } + flag.Annotations["ta:choices"] = slices.Clone(values) + } + } + } +} + +// Discover names locally without authorizing a Telegram connection or opening +// any per-account session. Legacy databases are opened read-only and briefly. +func tuiSavedAccounts(options map[string]string) ([]string, error) { + path := options["path"] + if path == "" { + return nil, fmt.Errorf("session storage has no path") + } + if _, err := os.Stat(path); os.IsNotExist(err) { + return nil, nil + } else if err != nil { + return nil, err + } + var names []string + switch options["type"] { + case "bolt": + entries, err := os.ReadDir(path) + if err != nil { + return nil, err + } + for _, entry := range entries { + if entry.Type().IsRegular() && !strings.HasPrefix(entry.Name(), ".") { + names = append(names, entry.Name()) + } + } + case "file": + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + var values map[string]json.RawMessage + if err := json.NewDecoder(io.LimitReader(file, 32<<20)).Decode(&values); err != nil { + return nil, fmt.Errorf("read saved account names: %w", err) + } + for name := range values { + names = append(names, name) + } + case "legacy": + db, err := bbolt.Open(path, 0600, &bbolt.Options{ReadOnly: true, Timeout: 150 * time.Millisecond}) + if err != nil { + return nil, fmt.Errorf("read saved account names: %w", err) + } + defer db.Close() + if err := db.View(func(tx *bbolt.Tx) error { + return tx.ForEach(func(name []byte, _ *bbolt.Bucket) error { + names = append(names, string(name)) + return nil + }) + }); err != nil { + return nil, err + } + default: + return nil, fmt.Errorf("unsupported session storage %q", options["type"]) + } + slices.Sort(names) + return slices.Compact(names), nil +} diff --git a/cmd/tui_options_test.go b/cmd/tui_options_test.go new file mode 100644 index 0000000..ae652d3 --- /dev/null +++ b/cmd/tui_options_test.go @@ -0,0 +1,371 @@ +package cmd + +import ( + "context" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/mo1ein/TelegramArchive/internal/tui" + "github.com/spf13/viper" + "go.etcd.io/bbolt" +) + +func TestBackupTimeFiltersAreEssentialFields(t *testing.T) { + viper.Reset() + defer viper.Reset() + for _, action := range tui.Catalog(New()) { + if action.Group == "Quick start" || !slices.Contains([]string{"archive", "account", "sync", "cron add"}, strings.Join(action.Path, " ")) { + continue + } + found := map[string]bool{} + for _, field := range tui.NewForm(action, nil).Fields { + if field.Name == "since" || field.Name == "until" { + found[field.Name] = true + if field.Advanced { + t.Errorf("%s / %s is hidden under More options", action.Title, field.Name) + } + } + } + if len(found) != 2 { + t.Errorf("%s is missing a since or until field", action.Title) + } + } +} + +func TestChatCategoriesEnterTogglesAndLeftAccepts(t *testing.T) { + viper.Reset() + defer viper.Reset() + var action tui.Action + for _, candidate := range tui.Catalog(New()) { + if strings.Join(candidate.Path, " ") == "archive" && candidate.Group != "Quick start" { + action = candidate + break + } + } + action.Group = "Quick start" + m := tui.New([]tui.Action{action}, nil, "personal", context.Background(), tui.WithSavedAccounts([]string{"personal"})) + update := func(msg tea.Msg) { next, _ := m.Update(msg); m = next.(tui.Model) } + update(tea.KeyPressMsg{Code: tea.KeyEnter}) + for range 3 { + update(tea.KeyPressMsg{Code: tea.KeyTab}) + } + update(tea.KeyPressMsg{Code: tea.KeyEnter}) // Open Chat categories. + update(tea.KeyPressMsg{Code: tea.KeyDown}) + update(tea.KeyPressMsg{Code: tea.KeyEnter}) // Uncheck Bots; keep choosing. + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, "[ ] Bots") || !strings.Contains(view, "[Done]") { + t.Fatalf("Enter should toggle the category and keep the list open:\n%s", view) + } + update(tea.KeyPressMsg{Code: tea.KeyDown}) + update(tea.KeyPressMsg{Code: tea.KeyEnter}) // Uncheck Groups. + update(tea.KeyPressMsg{Code: tea.KeyEnter}) // Check Groups again. + if view := ansi.Strip(m.View().Content); !strings.Contains(view, "[✓] Groups") || !strings.Contains(view, "[ ] Bots") { + t.Fatalf("repeated Enter presses should toggle only the highlighted item:\n%s", view) + } + update(tea.KeyPressMsg{Code: tea.KeyLeft}) + view = ansi.Strip(m.View().Content) + if strings.Contains(view, "[Done]") || !strings.Contains(view, "Essentials") || !strings.Contains(view, "Personal, Groups, Channels") { + t.Fatalf("Left should close the list and accept its choices in the form:\n%s", view) + } + update(tea.KeyPressMsg{Code: tea.KeyLeft}) + if strings.Contains(ansi.Strip(m.View().Content), "[Done]") { + t.Fatal("repeating Left after accepting must not reopen the selector") + } + update(tea.KeyPressMsg{Code: 'r', Mod: tea.ModCtrl}) + update(tea.KeyPressMsg{Code: 'c', Text: "c"}) + if view := ansi.Strip(m.View().Content); !strings.Contains(view, "--types=personal,groups,channels") { + t.Fatalf("the accepted categories did not reach the actual archive command:\n%s", view) + } +} + +func TestArchiveMediaCanBeSelectedWithOnlyTheMouse(t *testing.T) { + for _, size := range [][2]int{{55, 20}, {80, 24}, {110, 32}} { + t.Run(strings.Join([]string{strconv.Itoa(size[0]), strconv.Itoa(size[1])}, "x"), func(t *testing.T) { + viper.Reset() + defer viper.Reset() + var action tui.Action + for _, candidate := range tui.Catalog(New()) { + if strings.Join(candidate.Path, " ") == "archive" && candidate.Group != "Quick start" { + action = candidate + break + } + } + action.Group = "Quick start" + m := tui.New([]tui.Action{action}, nil, "personal", context.Background(), tui.WithSavedAccounts([]string{"personal"})) + update := func(msg tea.Msg) { next, _ := m.Update(msg); m = next.(tui.Model) } + update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + locate := func(text string) (int, int, bool) { + for y, line := range strings.Split(ansi.Strip(m.View().Content), "\n") { + if index := strings.Index(line, text); index >= 0 { + return ansi.StringWidth(line[:index]), y, true + } + } + return 0, 0, false + } + click := func(text string) { + t.Helper() + x, y, ok := locate(text) + if !ok { + t.Fatalf("mouse target %q is missing:\n%s", text, ansi.Strip(m.View().Content)) + } + update(tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft}) + update(tea.MouseReleaseMsg{X: x, Y: y, Button: tea.MouseLeft}) + } + click("[ Open ]") + click("Media to") + click("[Clear]") + for _, name := range []string{"Photos", "Videos", "Documents"} { + found := false + for range 12 { + if _, _, ok := locate("[ ] " + name); ok { + click("[ ] " + name) + found = true + break + } + x, y, ok := locate("⌕ ") + if !ok { + t.Fatal("the selector's scroll area is missing") + } + update(tea.MouseWheelMsg{X: x, Y: y, Button: tea.MouseWheelDown}) + } + if !found { + t.Fatalf("mouse scrolling never made %q selectable:\n%s", name, ansi.Strip(m.View().Content)) + } + } + click("[Done]") + click("[ Review ]") + view := ansi.Strip(m.View().Content) + for _, name := range []string{"Photos", "Videos", "Documents"} { + if !strings.Contains(view, name) { + t.Fatalf("the mouse-only selection lost %q in review:\n%s", name, view) + } + } + }) + } +} + +func TestArchiveMediaSelectionsRemainVisible(t *testing.T) { + viper.Reset() + defer viper.Reset() + var action tui.Action + for _, candidate := range tui.Catalog(New()) { + if strings.Join(candidate.Path, " ") == "archive" && candidate.Group != "Quick start" { + action = candidate + break + } + } + if action.Command == nil { + t.Fatal("archive action is missing") + } + // Exercise the public UI through the actual command metadata, with no + // Telegram calls or flag mutations. A one-item dashboard opens that action. + action.Group = "Quick start" + m := tui.New([]tui.Action{action}, nil, "personal", context.Background(), tui.WithSavedAccounts([]string{"personal"})) + update := func(msg tea.Msg) { next, _ := m.Update(msg); m = next.(tui.Model) } + update(tea.KeyPressMsg{Code: tea.KeyEnter}) + for y, line := range strings.Split(ansi.Strip(m.View().Content), "\n") { + if strings.Contains(line, "Media to download") { + update(tea.MouseClickMsg{X: 40, Y: y, Button: tea.MouseLeft}) + break + } + } + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, "[All]") || !strings.Contains(view, "[Clear]") { + t.Fatalf("archive media did not open a multi-select:\n%s", view) + } + update(tea.KeyPressMsg{Code: 'd', Mod: tea.ModCtrl}) + choices := action.Command.Flags().Lookup("media").Annotations["ta:choices"] + for _, value := range []string{"photos", "videos", "documents"} { + index := slices.Index(choices, value) + if index < 0 { + t.Fatalf("missing supported media category %q", value) + } + update(tea.KeyPressMsg{Code: tea.KeyHome}) + for range index { + update(tea.KeyPressMsg{Code: tea.KeyDown}) + } + update(tea.KeyPressMsg{Code: ' ', Text: " "}) + } + update(tea.KeyPressMsg{Code: tea.KeyLeft}) + view = ansi.Strip(m.View().Content) + for _, name := range []string{"Photos", "Videos", "Documents"} { + if !strings.Contains(view, name) { + t.Fatalf("selected media category %q disappeared after applying:\n%s", name, view) + } + } + update(tea.KeyPressMsg{Code: tea.KeyEnter}) + update(tea.KeyPressMsg{Code: 's', Mod: tea.ModCtrl}) + view = ansi.Strip(m.View().Content) + for _, name := range []string{"[✓] Photos", "[✓] Videos", "[✓] Documents"} { + if !strings.Contains(view, name) { + t.Fatalf("the selected-only list lost %q:\n%s", name, view) + } + } + update(tea.KeyPressMsg{Code: 'r', Mod: tea.ModCtrl}) + update(tea.KeyPressMsg{Code: 'c', Text: "c"}) + if view := ansi.Strip(m.View().Content); !strings.Contains(view, "--media=photos,videos,documents") { + t.Fatalf("review did not preserve all selected media in the actual command:\n%s", view) + } +} + +func TestAllBackupFormsExposeEveryKnownMultiSelect(t *testing.T) { + viper.Reset() + defer viper.Reset() + counts := map[string]int{} + for _, action := range tui.Catalog(New()) { + path := strings.Join(action.Path, " ") + for _, field := range tui.NewForm(action, nil).Fields { + if field.Name != "media" && field.Name != "types" && field.Name != "include" && field.Name != "account-include" { + continue + } + if !slices.Contains([]string{"archive", "account", "sync", "cron add"}, path) { + continue + } + if !field.Multi || len(field.Choices) == 0 { + t.Fatalf("%s (%s) / %s is missing its multi-select options", path, action.Title, field.Name) + } + counts[path]++ + } + } + for _, path := range []string{"archive", "account", "sync", "cron add"} { + if counts[path] == 0 { + t.Fatalf("the multi-select audit did not reach %s", path) + } + } +} + +func TestTUIBackupListFieldsExposeCheckboxChoices(t *testing.T) { + viper.Reset() + defer viper.Reset() + for _, action := range tui.Catalog(New()) { + if len(action.Path) != 1 || action.Path[0] != "archive" { + continue + } + for _, field := range tui.NewForm(action, nil).Fields { + if field.Name == "media" && (!field.Multi || !slices.Contains(field.Choices, "photos") || !slices.Contains(field.Choices, "videos")) { + t.Fatal("media choices remain a free-text list") + } + if field.Name == "types" && (!field.Multi || !slices.Contains(field.Choices, "private_channels")) { + t.Fatal("chat categories do not expose every supported choice") + } + } + } +} + +func TestTUIPathFieldsUseTheRightDialogWithoutTreatingPeersAsPaths(t *testing.T) { + viper.Reset() + defer viper.Reset() + want := map[string]string{ + "archive/output": "directory", "account/output": "directory", "sync/output": "directory", "cron add/output": "directory", + "login/desktop": "directory", "render/arguments": "directory", "stats/arguments": "open", + "chat export/output": "save", "chat users/output": "save", "backup/dst": "save", "recover/file": "open", + "download/dir": "directory", "download/file": "open", "upload/path": "any", + "download/url": "", "upload/to": "", "migrate/to": "", + } + for _, action := range tui.Catalog(New()) { + if action.Group == "Quick start" { + continue + } + for _, field := range tui.NewForm(action, nil).Fields { + key := strings.Join(action.Path, " ") + "/" + field.Name + if kind, ok := want[key]; ok { + if field.PathKind != kind { + t.Errorf("%s: expected %q dialog, got %q", key, kind, field.PathKind) + } + if (key == "stats/arguments" || key == "download/file" || key == "upload/path") && !field.PathMultiple { + t.Errorf("%s must accept several paths", key) + } + delete(want, key) + } + } + } + if len(want) != 0 { + t.Fatalf("missing expected path fields: %v", want) + } +} + +func TestTUIAccountDiscoveryReadsMetadataWithoutCreatingOrOpeningSessions(t *testing.T) { + dir := t.TempDir() + for _, name := range []string{"work", "personal", ".ignored"} { + if err := os.WriteFile(filepath.Join(dir, name), []byte("synthetic session placeholder"), 0600); err != nil { + t.Fatal(err) + } + } + names, err := tuiSavedAccounts(map[string]string{"type": "bolt", "path": dir}) + if err != nil || !slices.Equal(names, []string{"personal", "work"}) { + t.Fatalf("account names require valid session databases: %v %v", names, err) + } + missing := filepath.Join(dir, "missing") + if _, err := tuiSavedAccounts(map[string]string{"type": "bolt", "path": missing}); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(missing); !os.IsNotExist(err) { + t.Fatal("opening the picker created a new session directory") + } + file := filepath.Join(dir, "sessions.json") + if err := os.WriteFile(file, []byte(`{"work":{},"personal":{}}`), 0600); err != nil { + t.Fatal(err) + } + names, err = tuiSavedAccounts(map[string]string{"type": "file", "path": file}) + if err != nil || !slices.Equal(names, []string{"personal", "work"}) { + t.Fatalf("file storage discovery: %v %v", names, err) + } + legacy := filepath.Join(dir, "legacy.db") + db, err := bbolt.Open(legacy, 0600, nil) + if err != nil { + t.Fatal(err) + } + err = db.Update(func(tx *bbolt.Tx) error { _, err := tx.CreateBucket([]byte("work")); return err }) + db.Close() + if err != nil { + t.Fatal(err) + } + names, err = tuiSavedAccounts(map[string]string{"type": "legacy", "path": legacy}) + if err != nil || !slices.Equal(names, []string{"work"}) { + t.Fatalf("legacy account discovery: %v %v", names, err) + } +} + +func TestMultiAccountPlansParseThroughTheRealBackupCommands(t *testing.T) { + viper.Reset() + defer viper.Reset() + for _, action := range tui.Catalog(New()) { + path := strings.Join(action.Path, " ") + if action.Group == "Quick start" || !slices.Contains([]string{"archive", "account", "sync"}, path) { + continue + } + form := tui.NewForm(action, nil) + for i := range form.Fields { + field := &form.Fields[i] + if field.Name == "ns" { + field.Type, field.Multi, field.Dirty, field.Value = "accounts", true, true, "personal,work" + field.Choices = []string{"personal", "work"} + } + } + plan, err := form.Plan(nil) + if err != nil || len(plan.Tasks) != 2 { + t.Fatalf("%s could not plan both accounts: %v", path, err) + } + for _, task := range plan.Tasks { + root := New() + leaf, args, err := root.Find(task.Args) + if err != nil { + t.Fatal(err) + } + if err := leaf.ParseFlags(args); err != nil { + t.Fatalf("%s: %v", path, err) + } + namespace, _ := leaf.Flags().GetString("ns") + output, _ := leaf.Flags().GetString("output") + if namespace != task.Account || output != task.Directory { + t.Fatalf("%s runs with the wrong account or folder: %v", path, task.Args) + } + } + } +} diff --git a/docs/tui.md b/docs/tui.md index b8da0e3..9264fbb 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -13,11 +13,14 @@ ta --ns work tui # start with a saved account namespace ta --proxy socks5://localhost:1080 tui ``` -From a local checkout, build with `make build` and run `./bin/ta`. Opening the -workspace does not connect to Telegram or lock a saved session. Selecting an -account or chat browser starts its read operation; backups and other changes go -through configuration and review. Ordinary CLI commands remain available, and -`ta` displays help when its input or output is redirected. +From a local checkout, build with `make build` and run `./bin/ta`. Use +`make install` to update the `ta` executable on your PATH as well; building +`bin/ta` alone leaves an older installed copy in place. Reopen the workspace +after updating. Opening the workspace does not connect to Telegram or lock a +saved session. Opening a browser or the **Chats to back up** selector starts +its read operation; backups and other changes go through configuration and +review. Ordinary CLI commands remain available, and `ta` displays help when its +input or output is redirected. ## Browse and act @@ -32,10 +35,11 @@ Start with the dashboard's buttons or the first three Quick start workflows: The chat browser shows each page as it arrives, including archived chats. It reports connection and loading stages instead of waiting for every chat and forum topic. Connection setup is limited to 30 seconds, page requests to 20 -seconds, and a browse to 90 seconds. If loading is slow, **Stop loading** keeps -received chats and enables their action buttons. Errors with no results open -Activity so the reason is visible. The browser uses the same proxy settings and -fallback environment variables as archive operations. +seconds, and a browse to 90 seconds. You can select a received chat and choose +**Archive** or **Export** immediately; the browser stops its lookup before +opening that chat's settings. **Stop loading** also keeps received chats. +Errors with no results open Activity so the reason is visible. The browser uses +the same proxy settings and fallback environment variables as archive operations. Lists support ↑/↓, mouse selection, wheel scrolling and `/` search. Enter or the Details button opens the selected item's details. The **Results**, **Activity** @@ -68,27 +72,104 @@ catalogue. Tab or ←/→ changes dashboard sections; `/` searches every section Installed extensions appear when the workspace starts; reopen it after changing the installed extensions. -Quick start also includes QR login, a single-chat archive, all joined channels, +Quick start also includes QR login, Saved Messages, all joined channels, a complete incremental backup, account data and recurring backups. Presets fill in options for you to review and change. ## Configure and review -In a form, select a field and press Enter to edit it. Boolean switches toggle -immediately. Space or ←/→ cycles fixed choices, such as an output format or -login method. A dot marks explicitly set options; an asterisk marks required -fields. Ctrl+D restores the default. - -Common options appear first. Ctrl+A shows every public option, including proxy, -storage, concurrency, filters and connection settings. `/` searches all options, -including advanced ones. Descriptions appear below the selected field. - -List options use commas, for example `photos,videos` or `pdf,zip`. Quote a list -item containing a comma: `"Friends, family",telegram`. For positional arguments, +Choice fields use compact dropdowns attached to their argument's value column. +Click a field to open its list, click each checkbox to select several items, +then click **Done** or **Review** to save. This entire flow works with the mouse. +For the keyboard, Enter opens the list, ↑/↓ moves through items, each Enter +checks or unchecks the highlighted item, and ← saves and closes the list. +The list shows up to four options +with a scrollbar and position indicator; use ↑/↓, PageUp/PageDown, Home/End or +the mouse wheel over the list to scroll. Other arguments stay in the form. +Multi-select items use **[✓]** checkboxes and a distinct color; clicking the +label or checkbox toggles a choice, as do Enter and Space. Clicked items stay in place +under the pointer. Selected names stay visible in the field and in its **Selected:** line. +Ctrl+S shows only your checked items; press it again to show every option. +Tab saves and moves to the next setting; Shift+Tab moves back. ← or **Done** +saves without moving; Esc undoes the current selection. Ctrl+R saves and opens +Review. The other settings and page actions stay visible while choosing. + +Type or paste to filter the list; ↓ returns from the search box to the choices. +Filtering and scrolling keep items checked outside the current view. **All**, +**Clear** and **Done** sit beside the field; Ctrl+A and Ctrl+D select all or clear +while choosing. Scrolling outside the list saves it and moves through arguments. +Small terminals reduce the dropdown height to keep page actions visible. +Media offers **All media**, **No media**, or individual categories. +Single-choice fields use a dropdown and apply the highlighted option with Enter. +Export format offers **JSON**, **HTML**, and **Both**; Both exports JSON and HTML. + +**Chats to back up** loads the selected account's chat names directly when you +open the field. You can search and check chats as pages arrive, including +archived chats and Saved Messages. Choices save chat IDs while showing names. +**Stop loading** keeps received chats available; **Reload chats** or Ctrl+L +retries the lookup. Completed lists are reused for the same account and +connection settings. Changing accounts clears account-specific chat choices. +Choose one account to browse its chats; for several accounts, use all chats or +add chat names manually. + +**Since (date/time)** and **Until (date/time)** appear in the main backup forms. +Leave them empty for no limit. Since is inclusive and Until is exclusive. +Enter or **Calendar** opens a calendar beside the field; shorter terminals show +a compact calendar view. Click a day to select it, or use the arrow keys and +Enter. PageUp/PageDown, the month arrows, or the wheel over the calendar change +months. **Today** highlights today; **Clear** removes the date limit. Esc cancels +without changing the saved value. Tab saves the highlighted day and moves on. +**Type date/time** keeps manual entry available: use `2026-11-01` for a date, +`2026-11-01T18:30:00+03:30` for a time with a time zone, or Unix seconds. +Calendar dates use midnight UTC, matching the CLI's date format. + +Lists with custom values, including extensions, MIME filters, chat names and +source links, use an Add-item multi-select. Type or paste one item and click +**Add** to add and check it, then repeat for more items. Enter also adds items. +Use **Done**, Tab or +Ctrl+R to save; pending text is included. Commas inside an added item remain +part of that item. **Clear** removes an optional list's values. Sensitive lists +keep a masked text editor. + +Path fields have **Browse…** and **Type path** controls. Press Enter or click +**Browse…** to choose a file or folder. On macOS this opens the system dialog; +backup destinations use a folder chooser, input files use an Open dialog, and +output files use a Save dialog. Fields that accept several files allow multiple +selections. The chooser starts near the current path, including unfinished +text edits. Cancel keeps the existing value and any text you were editing. +Alt+O also opens Browse while typing. + +Remote sessions and systems without a graphical chooser use a terminal browser. +Enter or click opens a folder; Space selects an item. Use **Use this folder** +for the current folder or **Use selected** for checked files. Type to filter, +use ← to go up, and Ctrl+H to show hidden items. The Save browser offers F2 to +edit the filename, then **Save here** to select its destination. Choosing a +save path prepares the command for Review; it does not write the output file. + +Each workflow starts with its essential settings. Labels and editable values +share a compact argument table, with the selected field's description below it. +Start typing or paste to edit a text field directly in its value column. +Tab saves and moves to the next setting; Shift+Tab moves back. Invalid values +keep the editor open with an explanation. Enter saves; Esc undoes the current +edit. Ctrl+R also saves an active edit before opening the review. + +Boolean switches and fixed choices use visible selectors. Space, Enter or ←/→ +changes them. Choosing all chats clears an earlier specific-chat selection, +and choosing a specific chat switches back to that scope. An asterisk marks +required settings. Ctrl+D restores a setting's default. + +Ctrl+A or **More options** shows every public option, including account, +proxy, storage, concurrency, filters and connection settings. Ctrl+F searches +all options, including advanced ones. Connection details that do not apply to +the selected login method stay out of the essential form. + +On the command line, list options use commas, for example `photos,videos` or +`pdf,zip`. Quote a list item containing a comma: `"Friends, family",telegram`. +For positional arguments, separate values with spaces and quote paths containing spaces: `"exports/Book Club/result.json" "exports/Work/result.json"`. -While editing a path, Tab completes a unique matching file or directory name. +While editing a path, Alt+/ completes a unique matching file or directory name. `~/` can be expanded this way. Paths are passed as typed; shell variables, wildcards, command substitution and pipes are not evaluated. @@ -104,8 +185,32 @@ saved as a new configuration file. ## Tasks, prompts and cancellation -Tasks run inside the workspace. Archive progress shows the current file or -history scan, completion, speed and ETA when available. Activity output updates +### Back up several accounts or chats + +Choose **Back up multiple accounts**, then open **Accounts to back up** and +check the saved accounts you want. Account names are discovered locally without +connecting to Telegram. Ctrl+L while choosing accounts refreshes the saved list. +You can also check rows with Space in **Your Telegram accounts** and choose +**Back up selected**. Busy accounts cannot be checked in the account browser. + +Review shows each account and its destination. Multi-account backups run once, +one account at a time, with the same backup settings. Each gets a separate +folder under `/accounts/`, so archives from different accounts do not +mix. A single-account backup keeps its usual output folder. The running screen +identifies the current account, and results retain a completed, failed, cancelled +or not-run status for every selected account. One failure does not prevent the +remaining accounts from running. Cancelling stops the active backup and the +remaining queue. Use separate scheduled backups for recurring account backups. + +In **Browse your chats**, check several rows with Space and choose **Archive +selected**. The resulting form also offers the loaded chat names as a checkbox +list. These chats stay tied to the account used to browse them. Returning to the +browser restores its checks, search and selection. + +Tasks run inside the workspace. Backups use an animated Bubbles progress bar +with the actual percentage, completed file count, transferred size, speed and +ETA when available. History scans show a spinner and discovered work until a +total is known. They do not show a guessed percentage. Activity output updates without taking over the terminal. When a task finishes, its result stays visible; there is no extra Enter-to-return prompt. @@ -158,14 +263,36 @@ edit the proxy for the current workspace session. | Buttons | Tab/Shift+Tab, ←/→ | Select an action | | Buttons | Enter | Activate | | Options | ↑/↓, Tab/Shift+Tab | Select a field | -| Options | Enter | Edit text or toggle a switch | +| Options | Type, paste, or Enter | Edit text or change a selection | | Options | Space or ←/→ | Toggle or cycle choices | | Options | Ctrl+A / Ctrl+D | All options / reset field | | Options | Ctrl+R | Validate and review | +| Choice dropdown | ↑/↓ or mouse wheel over list | Scroll options within the field | +| Multi-select dropdown | Enter / Space | Toggle the highlighted item; keep choosing | +| Choice dropdown | Tab / Shift+Tab | Save and move to the next / previous setting | +| Multi-select dropdown | ← | Save choices and return to the form | +| Single-choice dropdown | Enter | Apply the highlighted option | +| Choice dropdown | Esc | Undo the current selection | +| Choice dropdown | Ctrl+A / Ctrl+D | Select all / clear multi-selections | +| Choice dropdown | Ctrl+S | Show selected items / all options | +| Custom list | Type or paste, then Enter | Add and check one literal item | +| Account dropdown | Ctrl+L | Refresh saved accounts | +| Chat dropdown | Ctrl+L / Reload chats | Reload the selected account's chats | +| Dates | Enter / Calendar | Open the date picker | +| Calendar | Arrow keys / Enter | Move between days / choose a day | +| Calendar | PageUp / PageDown | Previous / next month | +| Calendar | Ctrl+PageUp / Ctrl+PageDown | Previous / next year | +| Calendar | T / Delete / I | Highlight today / clear the limit / type a timestamp | +| Calendar | Esc | Cancel without changing the date | +| Paths | Enter / Alt+O / Browse… | Open the file or folder chooser | +| Path browser | Enter / Space | Open a folder / select an item | +| Path browser | Ctrl+Enter / Esc | Confirm / cancel the selection | +| Path browser | Ctrl+H / F2 | Show hidden items / edit a save filename | | Editing | Enter / Esc | Save / cancel an edit | | Editing | Ctrl+U / Ctrl+K / Ctrl+W | Clear / delete to end / delete a word | | Editing | Home/End, ←/→ | Move cursor | -| Editing | Tab | Complete a unique path | +| Editing | Tab / Shift+Tab | Save and move to the next / previous setting | +| Editing | Alt+/ | Complete a unique path | | Search | Enter / Esc | Finish / clear search | | Review | Enter / Esc / c | Run / edit / toggle command preview | | Results | ↑/↓, PageUp/PageDown | Select a row or scroll | diff --git a/go.mod b/go.mod index 72b4f69..9bd7156 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/mo1ein/TelegramArchive go 1.26.0 require ( + charm.land/bubbles/v2 v2.2.1 charm.land/bubbletea/v2 v2.0.10 charm.land/lipgloss/v2 v2.0.6 github.com/AlecAivazis/survey/v2 v2.3.7 @@ -30,10 +31,12 @@ require ( ) require ( + github.com/atotto/clipboard v0.1.4 // indirect github.com/bcicen/jstream v1.0.1 // indirect github.com/beevik/ntp v1.5.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/charmbracelet/colorprofile v0.4.3 // indirect + github.com/charmbracelet/harmonica v0.2.0 // indirect github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect diff --git a/go.sum b/go.sum index db3b6d0..b637a0a 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU= +charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc= charm.land/bubbletea/v2 v2.0.10 h1:oolvo20VBpI0PfqE7iFjkZ1bx0WpmXGfnKz5Yldjq5o= charm.land/bubbletea/v2 v2.0.10/go.mod h1:QOatcnhOjYIfxzUSTz6raF7Ex4R/rIuHa3SnBdCCpMc= charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ= @@ -6,6 +8,8 @@ github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkk github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo= github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 h1:+vx7roKuyA63nhn5WAunQHLTznkw5W8b1Xc0dNjp83s= github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDeC1lPdgDeDbhX8XFpy1jqjK0IBG8W5K+xYqA0w= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/bcicen/jstream v1.0.1 h1:BXY7Cu4rdmc0rhyTVyT3UkxAiX3bnLpKLas9btbH5ck= github.com/bcicen/jstream v1.0.1/go.mod h1:9ielPxqFry7Y4Tg3j4BfjPocfJ3TbsRtXOAYXYmRuAQ= github.com/beevik/ntp v1.5.0 h1:y+uj/JjNwlY2JahivxYvtmv4ehfi3h74fAuABB9ZSM4= @@ -16,6 +20,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ= +github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA= github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro= github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ= diff --git a/internal/taskui/progress.go b/internal/taskui/progress.go index 629a46b..d4e7784 100644 --- a/internal/taskui/progress.go +++ b/internal/taskui/progress.go @@ -9,8 +9,28 @@ import ( const ProgressPrefix = "ta-progress;" +// Progress carries measurements separately from the terminal's presentation. +// Percent is a fraction in [0, 1]; scans have no reliable total yet. +type Progress struct { + Label string `json:"label"` + Detail string `json:"detail"` + Summary string `json:"summary"` + Percent float64 `json:"percent"` + Determinate bool `json:"determinate"` + CompletedFiles int64 `json:"completed_files"` + TotalFiles int64 `json:"total_files"` +} + +func WriteStatus(out io.Writer, status Progress) { + writeFrame(out, status) +} + func WriteProgress(out io.Writer, lines []string) { - data, err := json.Marshal(lines) + writeFrame(out, lines) +} + +func writeFrame(out io.Writer, value any) { + data, err := json.Marshal(value) if err != nil || len(data) > 4096 { return } diff --git a/internal/taskui/progress_test.go b/internal/taskui/progress_test.go new file mode 100644 index 0000000..39eb360 --- /dev/null +++ b/internal/taskui/progress_test.go @@ -0,0 +1,30 @@ +package taskui + +import ( + "bytes" + "encoding/json" + "strings" + "testing" +) + +func TestProgressFrameCarriesMeasurementsWithoutEmbeddingTerminalLayout(t *testing.T) { + status := Progress{Label: "synthetic.mp4", Detail: "30 MiB / 100 MiB", Summary: "ETA 10s", Percent: .3, Determinate: true, CompletedFiles: 2, TotalFiles: 8} + var out bytes.Buffer + WriteStatus(&out, status) + prefix := "\x1b]777;" + ProgressPrefix + if !strings.HasPrefix(out.String(), prefix) || !strings.HasSuffix(out.String(), "\a") { + t.Fatal("missing framed worker progress") + } + var decoded Progress + if err := json.Unmarshal([]byte(strings.TrimSuffix(strings.TrimPrefix(out.String(), prefix), "\a")), &decoded); err != nil { + t.Fatal(err) + } + if decoded != status { + t.Fatalf("lost a transfer measurement: %#v", decoded) + } + out.Reset() + WriteStatus(&out, Progress{Label: strings.Repeat("x", 8192)}) + if out.Len() != 0 { + t.Fatal("an oversized frame should not enter the child terminal stream") + } +} diff --git a/internal/tui/accounts.go b/internal/tui/accounts.go new file mode 100644 index 0000000..16274b6 --- /dev/null +++ b/internal/tui/accounts.go @@ -0,0 +1,106 @@ +package tui + +import ( + "context" + "slices" + "strings" + + tea "charm.land/bubbletea/v2" +) + +type Option func(*Model) +type AccountLoader func(context.Context, string) ([]string, error) + +func WithAccountLoader(loader AccountLoader) Option { + return func(m *Model) { m.accountLoader = loader } +} + +func WithSavedAccounts(names []string) Option { + return func(m *Model) { + m.accounts = slices.Clone(names) + m.accountsLoaded = true + } +} + +type accountsLoadedMsg struct { + names []string + err error +} + +func (m Model) loadAccounts() tea.Cmd { + if m.accountLoader == nil { + return nil + } + loader, ctx, storage := m.accountLoader, m.ctx, m.globals["storage"] + if field := m.form.field("storage"); field != nil && field.Dirty { + storage = field.Value + } + return func() tea.Msg { + names, err := loader(ctx, storage) + return accountsLoadedMsg{names, err} + } +} + +func backupAction(path []string) bool { + return slices.Contains([]string{"archive", "account", "sync"}, strings.Join(path, " ")) +} + +func (m *Model) configureAccountField() { + field := m.form.field("ns") + if field == nil || strings.Join(m.form.Action.Path, " ") == "login" { + return + } + field.Choices = slices.Clone(m.accounts) + if !backupAction(m.form.Action.Path) { + if field.Value != "" && !slices.Contains(field.Choices, field.Value) { + field.Choices = append(field.Choices, field.Value) + } + return + } + if field.Type != "accounts" { + selected := slices.Clone(m.accountSelection) + if len(selected) == 0 { + selected = []string{field.Value} + } + field.Value = csvString(selected) + } + field.Type, field.Label, field.Multi, field.Advanced, field.Dirty = "accounts", "Accounts to back up", true, false, true + field.Help = "Choose one or more saved accounts. Each account in a multi-account backup gets its own folder." + if m.accountsLoaded && m.accountError == "" { + selected, _ := readCSV(field.Value) + selected = slices.DeleteFunc(selected, func(name string) bool { return !slices.Contains(m.accounts, name) }) + if len(selected) == 0 && len(m.accounts) > 0 { + selected = []string{m.accounts[0]} + } + field.Value = csvString(selected) + } +} + +func (m *Model) configureChatField() { + field := m.form.field("chat") + if field == nil || !chatChoiceAction(m.form.Action.Path) { + return + } + field.AllowCustom = true + field.Choices = []string{"me"} + field.ChoiceLabels = map[string]string{"me": "Saved Messages"} + selected, _ := readCSV(field.Value) + for _, value := range selected { + if !slices.Contains(field.Choices, value) { + field.Choices = append(field.Choices, value) + } + } + if m.source == nil || m.source.data.Kind != "chat ls" { + return + } + account, err := m.chatChoiceAccount() + if err != nil || planAccount(m.source.plan, m.globals["ns"]) != account || !m.sourceChatConnectionMatches() { + return + } + for _, row := range m.source.data.Items { + if !slices.Contains(field.Choices, row.ID) { + field.Choices = append(field.Choices, row.ID) + } + field.ChoiceLabels[row.ID] = row.Title + } +} diff --git a/internal/tui/batch.go b/internal/tui/batch.go new file mode 100644 index 0000000..92dd6a8 --- /dev/null +++ b/internal/tui/batch.go @@ -0,0 +1,100 @@ +package tui + +import ( + "crypto/sha256" + "fmt" + "path/filepath" + "slices" + "strings" + "time" + "unicode" +) + +type AccountTask struct { + Account, Directory string + Args []string +} + +func (f Form) withAccounts(plan Plan) (Plan, error) { + field := f.field("ns") + if field == nil || field.Type != "accounts" { + return plan, nil + } + if err := validate(*field); err != nil { + return plan, field.Error(err) + } + names, err := readCSV(field.Value) + if err != nil || len(names) == 0 { + return plan, fmt.Errorf("choose at least one saved account") + } + seen := map[string]bool{} + accounts := make([]string, 0, len(names)) + for _, name := range names { + if strings.TrimSpace(name) == "" { + return plan, fmt.Errorf("choose a saved account") + } + if !seen[name] { + accounts = append(accounts, name) + seen[name] = true + } + } + plan.Args = replaceArgument(plan.Args, "ns", accounts[0]) + if len(accounts) == 1 { + return plan, nil + } + if every := f.field("every"); every != nil { + interval, _ := time.ParseDuration(every.Value) + if interval > 0 { + return plan, fmt.Errorf("multi-account backups run once; set the repeat interval to 0 and use scheduled backups for recurring runs") + } + } + output := f.field("output") + if output == nil { + return plan, fmt.Errorf("this workflow does not support multiple backup accounts") + } + root := output.Value + if root == "" { + root = "data" + } + for _, account := range accounts { + directory := filepath.Join(root, "accounts", accountFolder(account)) + args := replaceArgument(plan.Args, "ns", account) + args = replaceArgument(args, "output", directory) + plan.Tasks = append(plan.Tasks, AccountTask{Account: account, Directory: directory, Args: args}) + } + return plan, nil +} + +func accountFolder(name string) string { + label := strings.Map(func(r rune) rune { + if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' || r == '_' { + return r + } + return '-' + }, name) + label = strings.Trim(label, "-") + if label == "" { + label = "account" + } + if runes := []rune(label); len(runes) > 36 { + label = string(runes[:36]) + } + digest := sha256.Sum256([]byte(name)) + return fmt.Sprintf("%s-%x", label, digest[:6]) +} + +func replaceArgument(args []string, name, value string) []string { + result := make([]string, 0, len(args)+1) + flag := "--" + name + for i := 0; i < len(args); i++ { + if strings.HasPrefix(args[i], flag+"=") { + continue + } + if args[i] == flag && i+1 < len(args) { + i++ + continue + } + result = append(result, args[i]) + } + return append(slices.Clip(result), flag+"="+value) +} diff --git a/internal/tui/batch_run.go b/internal/tui/batch_run.go new file mode 100644 index 0000000..ab8216e --- /dev/null +++ b/internal/tui/batch_run.go @@ -0,0 +1,77 @@ +package tui + +import ( + "errors" + "fmt" + "strings" + "time" + + tea "charm.land/bubbletea/v2" +) + +type accountOutcome struct { + task AccountTask + status string + err error + output string +} + +func (m Model) taskPlan() Plan { + plan := m.plan + if len(plan.Tasks) > 0 && m.batchIndex < len(plan.Tasks) { + plan.Args = plan.Tasks[m.batchIndex].Args + plan.Tasks = nil + } + return plan +} + +func (m *Model) finishAccount(msg finishedMsg) (tea.Cmd, bool) { + if len(m.plan.Tasks) == 0 { + return nil, false + } + task := m.plan.Tasks[m.batchIndex] + status := "completed" + if msg.err != nil { + status = "failed" + } + if m.cancelling { + status = "cancelled" + } + lines := strings.Split(m.output, "\n") + if len(lines) > 100 { + lines = lines[len(lines)-100:] + } + output := strings.Join(lines, "\n") + if len(output) > 32<<10 { + output = strings.ToValidUTF8(output[len(output)-(32<<10):], "") + } + m.batchResults = append(m.batchResults, accountOutcome{task, status, msg.err, output}) + if !m.cancelling && m.ctx.Err() == nil && m.batchIndex+1 < len(m.plan.Tasks) { + m.batchIndex++ + return m.startTask(), true + } + for _, remaining := range m.plan.Tasks[m.batchIndex+1:] { + m.batchResults = append(m.batchResults, accountOutcome{task: remaining, status: "not run"}) + } + m.data = resultData{Kind: "account backups"} + var failures []error + var activity []string + for _, outcome := range m.batchResults { + detail := "Account: " + safeText(outcome.task.Account) + "\nFolder: " + safeText(outcome.task.Directory) + "\nStatus: " + outcome.status + if outcome.err != nil { + detail += "\n" + outcome.err.Error() + failures = append(failures, fmt.Errorf("%s: %w", safeText(outcome.task.Account), outcome.err)) + } + if outcome.output != "" { + detail += "\n\n" + outcome.output + } + m.data.Items = append(m.data.Items, item{ID: outcome.task.Account, Title: safeText(outcome.task.Account), Subtitle: outcome.status + " · " + safeText(outcome.task.Directory), Detail: detail, Status: outcome.status}) + activity = append(activity, detail) + } + m.output = strings.Join(activity, "\n\n────────────────\n\n") + m.last = finishedMsg{err: errors.Join(failures...), elapsed: time.Since(m.batchStarted)} + m.screen, m.resultTab, m.resultSelected, m.scroll = result, 0, 0, 0 + m.responding, m.loading, m.buttonsFocused = false, false, false + m.status, m.progress = nil, nil + return nil, true +} diff --git a/internal/tui/batch_test.go b/internal/tui/batch_test.go new file mode 100644 index 0000000..809b9f5 --- /dev/null +++ b/internal/tui/batch_test.go @@ -0,0 +1,130 @@ +package tui + +import ( + "context" + "errors" + "path/filepath" + "slices" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" +) + +func batchModel(t *testing.T) Model { + t.Helper() + root, action := fixture() + m := New(Catalog(root), nil, "personal", context.Background(), WithSavedAccounts([]string{"personal", "work", "other"})) + m.open(action) + set(&m.form, "ns", "personal,work,other") + set(&m.form, "output", "exports") + m.prepareReview() + if m.screen != review || len(m.plan.Tasks) != 3 { + t.Fatalf("batch plan failed: %s", m.err) + } + return m +} + +func TestBatchPlansSeparateAccountsAndFoldersWithoutChangingCLIFlags(t *testing.T) { + m := batchModel(t) + for i, task := range m.plan.Tasks { + root, _ := fixture() + leaf, args, err := root.Find(task.Args) + if err != nil { + t.Fatal(err) + } + if err := leaf.ParseFlags(args); err != nil { + t.Fatal(err) + } + namespace, _ := leaf.Flags().GetString("ns") + output, _ := leaf.Flags().GetString("output") + if namespace != task.Account || output != task.Directory || !strings.HasPrefix(output, filepath.Join("exports", "accounts")+string(filepath.Separator)) { + t.Fatalf("incorrect child arguments: %v", task.Args) + } + for _, other := range m.plan.Tasks[i+1:] { + if strings.EqualFold(task.Directory, other.Directory) { + t.Fatal("different accounts share an output folder") + } + } + } + if m.form.Action.Command.Root().PersistentFlags().Lookup("ns").Changed { + t.Fatal("building a queue mutated CLI flags") + } + if !strings.Contains(m.plan.Preview(), "--ns=work") || !strings.Contains(m.plan.Preview(), "--ns=personal") { + t.Fatal("command preview omitted a queued account") + } + for _, name := range []string{"../escape", "Work", "work", "a/b", "a_b", "..."} { + folder := accountFolder(name) + if filepath.Base(folder) != folder || strings.Contains(folder, "..") || folder == "" { + t.Fatalf("unsafe account folder for %q: %q", name, folder) + } + } +} + +func TestBatchContinuesAfterAnAccountFailsAndRetainsEveryResult(t *testing.T) { + m := batchModel(t) + failure := errors.New("synthetic account unavailable") + var ran []string + m.run = func(ctx context.Context, plan Plan) tea.Cmd { + return func() tea.Msg { + for _, arg := range plan.Args { + if strings.HasPrefix(arg, "--ns=") { + name := strings.TrimPrefix(arg, "--ns=") + ran = append(ran, name) + if name == "work" { + return finishedMsg{err: failure} + } + } + } + return finishedMsg{} + } + } + command := m.begin() + for range 4 { + if command == nil { + break + } + next, follow := m.Update(command()) + m, command = next.(Model), follow + } + if !slices.Equal(ran, []string{"personal", "work", "other"}) { + t.Fatalf("queue stopped early or reordered accounts: %v", ran) + } + if m.screen != result || m.data.Kind != "account backups" || len(m.data.Items) != 3 || m.data.Items[0].Status != "completed" || m.data.Items[1].Status != "failed" || m.data.Items[2].Status != "completed" { + t.Fatal("the final result lost an account's outcome") + } + if !errors.Is(m.last.err, failure) { + t.Fatal("the failed account's error was discarded") + } +} + +func TestCancellingBatchStopsRemainingAccounts(t *testing.T) { + m := batchModel(t) + ran := 0 + m.run = func(ctx context.Context, plan Plan) tea.Cmd { + return func() tea.Msg { ran++; return finishedMsg{err: ctx.Err()} } + } + command := m.begin() + next, command := m.Update(command()) + m = next.(Model) + m.cancelJob() + next, command = m.Update(command()) + m = next.(Model) + if command != nil || ran != 2 || len(m.data.Items) != 3 || m.data.Items[2].Status != "not run" { + t.Fatal("cancelled queue launched another account or hid skipped work") + } +} + +func TestSingleAccountKeepsItsFolderAndRecurringMultiAccountIsRejected(t *testing.T) { + m := batchModel(t) + set(&m.form, "ns", "work") + plan, err := m.form.Plan(nil) + if err != nil || len(plan.Tasks) != 0 || !slices.Contains(plan.Args, "--ns=work") || !slices.Contains(plan.Args, "--output=exports") { + t.Fatalf("single-account backup changed its destination: %v %v", plan.Args, err) + } + set(&m.form, "ns", "personal,work") + set(&m.form, "every", "1h") + if _, err := m.form.Plan(nil); err == nil || !strings.Contains(err.Error(), "run once") { + t.Fatal("a recurring first account would prevent the remaining accounts from running") + } +} diff --git a/internal/tui/catalog.go b/internal/tui/catalog.go index 196b059..a483ce8 100644 --- a/internal/tui/catalog.go +++ b/internal/tui/catalog.go @@ -47,9 +47,10 @@ func Catalog(root *cobra.Command) []Action { {"accounts", "Your Telegram accounts", "Select a saved account for your next backup.", nil}, {"cron list", "Scheduled backups", "Review schedules, run a backup, or inspect its logs.", nil}, {"login", "Connect a Telegram account", "Sign in with a QR code to get started.", map[string]string{"type": "qr"}}, - {"archive", "Archive a chat", "Save a chat with media, JSON and an offline HTML reader.", map[string]string{"chat": "me", "media": "all", "format": "both"}}, + {"archive", "Back up Saved Messages", "Save your personal notes, files and media as JSON and HTML.", map[string]string{"chat": "me", "media": "all", "format": "both"}}, {"archive", "Back up all channels", "Archive your joined channels, including private channels.", map[string]string{"all": "true", "types": "channels", "media": "all", "format": "both"}}, - {"sync", "Back up everything", "Incrementally sync chats, account data and Saved Messages.", map[string]string{"everything": "true", "format": "both"}}, + {"sync", "Back up everything", "Incrementally sync chats, account data and Saved Messages.", map[string]string{"everything": "true", "media": "all", "format": "both"}}, + {"sync", "Back up multiple accounts", "Choose saved accounts and create a separate backup for each.", map[string]string{"everything": "true", "media": "all", "format": "both"}}, {"account", "Save account data", "Choose account sections and back up Saved Messages.", map[string]string{"format": "both"}}, {"cron add", "Schedule a backup", "Install a recurring backup every six hours.", map[string]string{"everything": "true", "every": "6h", "format": "both"}}, } { @@ -86,6 +87,11 @@ type Field struct { Choices []string Required, Advanced, Global, Dirty bool Secret bool + Multi bool + ChoiceLabels map[string]string + PathKind string + PathMultiple bool + AllowCustom bool } type Form struct { @@ -118,21 +124,27 @@ func NewForm(action Action, globals map[string]string) Form { } _, required := flag.Annotations[cobra.BashCompOneRequiredFlag] global := cmd.Root().PersistentFlags().Lookup(flag.Name) == flag - field := Field{Name: flag.Name, Label: strings.ReplaceAll(flag.Name, "-", " "), Help: flag.Usage, Type: flag.Value.Type(), Value: value, Default: value, Required: required, Global: global, Advanced: !slices.Contains(common, flag.Name), Secret: flag.Name == "proxy" || strings.Contains(flag.Name, "password") || strings.Contains(flag.Name, "passcode") || strings.Contains(flag.Name, "token")} + field := Field{Name: flag.Name, Label: fieldLabel(flag.Name), Help: flag.Usage, Type: flag.Value.Type(), Value: value, Default: value, Required: required, Global: global, Advanced: !essential(action.Path, flag.Name), Secret: flag.Name == "proxy" || strings.Contains(flag.Name, "password") || strings.Contains(flag.Name, "passcode") || strings.Contains(flag.Name, "token")} if flag.Name == "ns" { - field.Label = "account namespace" + field.Label = "Saved account" } if flag.Name == "type" && strings.Join(action.Path, " ") == "login" { - field.Label = "login method" + field.Label = "Sign-in method" } field.Choices = choices(action.Path, flag.Name, flag.Usage) + if values := flag.Annotations["ta:choices"]; len(values) > 0 { + field.Choices = slices.Clone(values) + } + field.Multi = flag.Value.Type() == "stringSlice" || flag.Value.Type() == "stringArray" + field.PathKind = flagPathKind(action.Path, flag) + field.PathMultiple = field.Multi && field.PathKind != "" if value, ok := globals[flag.Name]; ok && global { field.Value, field.Dirty = value, true } if value, ok := action.Preset[flag.Name]; ok { field.Value, field.Dirty = value, true } - field.Advanced = field.Advanced && !required && !field.Dirty + field.Advanced = field.Advanced && !required && (!field.Dirty || field.Global) form.Fields = append(form.Fields, field) }) // Some inherited commands accept arguments without declaring them in Use. @@ -159,6 +171,13 @@ func NewForm(action Action, globals map[string]string) Form { required := cmd.ValidateArgs(nil) != nil noArgs := !required && cmd.ValidateArgs([]string{"example"}) != nil form.Fields = append(form.Fields, Field{Name: "arguments", Label: argumentLabel, Help: argumentHelp, Type: "arguments", Required: required, Advanced: noArgs}) + argument := &form.Fields[len(form.Fields)-1] + switch strings.Join(action.Path, " ") { + case "render": + argument.PathKind = "directory" + case "stats": + argument.PathKind, argument.PathMultiple = "open", true + } slices.SortStableFunc(form.Fields, func(a, b Field) int { rank := func(f Field) int { if f.Required { @@ -226,9 +245,31 @@ func (f Field) Display() string { } return "○ off" } + if choiceField(f) { + if !f.Multi { + return f.optionLabel(f.Value) + } + values, err := readCSV(f.Value) + if err == nil { + for i := range values { + values[i] = f.optionLabel(values[i]) + } + return strings.Join(values, ", ") + } + } return f.Value } +func (f Field) optionLabel(value string) string { + if label, ok := f.ChoiceLabels[value]; ok { + return safeText(label) + } + if customChoices(f) { + return safeText(value) + } + return choiceLabel(f.Name, value) +} + func (f Form) field(name string) *Field { for i := range f.Fields { if f.Fields[i].Name == name { @@ -238,4 +279,6 @@ func (f Form) field(name string) *Field { return nil } -func (f Field) Error(err error) error { return fmt.Errorf("%s: %w", f.Label, err) } +func (f Field) Error(err error) error { + return fmt.Errorf("%s: %w", strings.ToLower(f.Label), err) +} diff --git a/internal/tui/chat_choices.go b/internal/tui/chat_choices.go new file mode 100644 index 0000000..e54c060 --- /dev/null +++ b/internal/tui/chat_choices.go @@ -0,0 +1,299 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "maps" + "slices" + "strings" + "time" + + tea "charm.land/bubbletea/v2" +) + +type chatLookup struct { + picker *choicePicker + plan Plan + ctx context.Context + cancel context.CancelFunc + job *job + count int +} + +type chatLookupStartedMsg struct { + lookup *chatLookup + job *job + err error +} + +type chatLookupPollMsg struct{ lookup *chatLookup } + +func chatChoiceAction(path []string) bool { + return slices.Contains([]string{"archive", "sync", "cron add"}, strings.Join(path, " ")) +} + +func planAccount(plan Plan, fallback string) string { + return planSetting(plan, "ns", fallback) +} + +func planSetting(plan Plan, name, fallback string) string { + for _, arg := range plan.Args { + if value, ok := strings.CutPrefix(arg, "--"+name+"="); ok { + return value + } + } + return fallback +} + +func (m Model) sourceChatConnectionMatches() bool { + if m.source == nil { + return false + } + for _, name := range []string{"storage", "proxy"} { + initial := planSetting(Plan{Args: m.base}, name, "") + current := initial + if field := m.form.field(name); field != nil && field.Dirty { + current = field.Value + } + if planSetting(m.source.plan, name, initial) != current { + return false + } + } + return true +} + +func (m Model) chatChoiceAccount() (string, error) { + field := m.form.field("ns") + if field == nil { + return m.globals["ns"], nil + } + if !field.Multi { + return field.Value, nil + } + names, err := readCSV(field.Value) + if err != nil || len(names) == 0 { + return "", fmt.Errorf("choose a saved account to load its chats") + } + if len(names) != 1 { + return "", fmt.Errorf("select one account to browse its chats; for several accounts, use all chats or add chat names manually") + } + return names[0], nil +} + +// Listing chats only needs the current account and connection settings. An +// unfinished local backup setting must not prevent browsing available chats. +func (m Model) chatChoicePlan() (Plan, error) { + account, err := m.chatChoiceAccount() + if err != nil { + return Plan{}, err + } + for _, action := range m.actions { + if strings.Join(action.Path, " ") != "chat ls" { + continue + } + form := NewForm(action, m.globals) + for _, source := range m.form.Fields { + if !source.Global { + continue + } + if target := form.field(source.Name); target != nil { + target.Value, target.Dirty = source.Value, source.Dirty + } + } + if namespace := form.field("ns"); namespace != nil { + namespace.Value, namespace.Dirty = account, true + } + plan, err := form.Plan(m.base) + plan.width, plan.height = max(20, m.width-6), max(5, m.height-17) + return plan, err + } + return Plan{}, errNoChatBrowser +} + +var errNoChatBrowser = errors.New("chat browser is unavailable in this build") + +func (m *Model) stopChatLookup() { + if lookup := m.chatLookup; lookup != nil { + lookup.cancel() + if lookup.job != nil && lookup.job.cancel != nil { + lookup.job.cancel() + } + lookup.picker.loading = false + m.chatLookup = nil + } +} + +func (m *Model) closePicker() { + m.stopChatLookup() + m.picker = nil +} + +func (m *Model) resetChatSelection() { + m.stopChatLookup() + m.chatChoiceKey = [32]byte{} + if field := m.form.field("chat"); field != nil && chatChoiceAction(m.form.Action.Path) { + selected, _ := readCSV(field.Value) + selected = slices.DeleteFunc(selected, func(value string) bool { return value != "me" }) + field.Value, field.Dirty = csvString(selected), true + m.configureChatField() + } + if m.picker != nil && m.picker.field == "chat" { + m.closePicker() + } +} + +func (m *Model) loadChatChoices(refresh bool) tea.Cmd { + p := m.picker + if p == nil || p.field != "chat" || !chatChoiceAction(m.form.Action.Path) { + return nil + } + m.stopChatLookup() + p.loadErr = "" + plan, err := m.chatChoicePlan() + if err != nil { + if !errors.Is(err, errNoChatBrowser) { + p.loadErr = safeText(err.Error()) + } + return nil + } + key := chatCacheKey(plan) + if key != m.chatChoiceKey { + m.chatChoiceKey = key + m.configureChatField() + field := m.form.field("chat") + p.choices, p.labels = slices.Clone(field.Choices), maps.Clone(field.ChoiceLabels) + p.cursor, p.offset = 0, 0 + } + if cached, ok := m.chatCache[key]; ok && !refresh { + m.mergeChatChoices(cached.data.Items) + return nil + } + ctx, cancel := context.WithTimeout(m.ctx, 95*time.Second) + lookup := &chatLookup{picker: p, plan: plan, ctx: ctx, cancel: cancel} + m.chatLookup = lookup + p.loading, p.loadStage = true, "Loading chats for "+safeText(planAccount(plan, "the selected account"))+"…" + command := m.run(ctx, plan) + if command == nil { + m.stopChatLookup() + p.loadErr = "Chat loading is unavailable. You can add names or IDs manually." + return nil + } + return func() tea.Msg { + switch msg := command().(type) { + case startedMsg: + return chatLookupStartedMsg{lookup: lookup, job: msg.job} + case finishedMsg: + return chatLookupStartedMsg{lookup: lookup, err: msg.err} + default: + return chatLookupStartedMsg{lookup: lookup, err: fmt.Errorf("could not start chat loading")} + } + } +} + +func chatLookupPoll(lookup *chatLookup) tea.Cmd { + return tea.Tick(100*time.Millisecond, func(time.Time) tea.Msg { return chatLookupPollMsg{lookup} }) +} + +func (m *Model) chatLookupStarted(msg chatLookupStartedMsg) tea.Cmd { + if m.chatLookup != msg.lookup || m.picker != msg.lookup.picker { + if msg.job != nil && msg.job.cancel != nil { + msg.job.cancel() + } + msg.lookup.cancel() + return nil + } + if msg.err != nil || msg.job == nil { + msg.lookup.picker.loadErr = "Could not load chats." + if msg.err != nil { + msg.lookup.picker.loadErr = safeText(msg.err.Error()) + } + m.stopChatLookup() + return nil + } + msg.lookup.job = msg.job + return chatLookupPoll(msg.lookup) +} + +func (m *Model) pollChatChoices(lookup *chatLookup) tea.Cmd { + if m.chatLookup != lookup || m.picker != lookup.picker || lookup.job == nil { + return nil + } + j := lookup.job + j.mu.Lock() + count := len(j.items) + var rows []item + if count != lookup.count || j.done { + rows = slices.Clone(j.items) + } + stage, done, err, overflow := j.stage, j.done, j.err, j.overflow + output := "" + if done && err != nil { + output = redactOutput(j.terminal.text()) + } + j.mu.Unlock() + if count != lookup.count { + m.mergeChatChoices(rows) + lookup.count = count + } + if stage != "" { + lookup.picker.loadStage = stage + } + if !done { + return chatLookupPoll(lookup) + } + if err != nil || overflow { + message := "Chat loading failed." + if err != nil { + message = err.Error() + } + if output != "" { + lines := strings.Split(strings.TrimSpace(output), "\n") + message = lines[len(lines)-1] + } + if overflow { + message = "Only part of the chat list could be loaded. Reload or add a chat manually." + } else if errors.Is(lookup.ctx.Err(), context.DeadlineExceeded) { + message = "Chat loading timed out. Check your connection or proxy and reload." + } + lookup.picker.loadErr = safeText(message) + } else { + m.cacheChats(lookup.plan, resultData{Kind: "chat ls", Items: rows}) + } + m.stopChatLookup() + return nil +} + +func (m *Model) mergeChatChoices(rows []item) { + field := m.form.field("chat") + if field == nil { + return + } + known := map[string]bool{} + for _, id := range field.Choices { + known[id] = true + } + if field.ChoiceLabels == nil { + field.ChoiceLabels = map[string]string{} + } + for _, row := range rows { + if !known[row.ID] { + field.Choices = append(field.Choices, row.ID) + known[row.ID] = true + } + field.ChoiceLabels[row.ID] = safeText(row.Title) + } + if p := m.picker; p != nil && p.field == "chat" { + listed := make(map[string]bool, len(p.choices)) + for _, id := range p.choices { + listed[id] = true + } + for _, id := range field.Choices { + if !listed[id] { + p.choices = append(p.choices, id) + listed[id] = true + } + } + p.labels = maps.Clone(field.ChoiceLabels) + } +} diff --git a/internal/tui/chat_choices_test.go b/internal/tui/chat_choices_test.go new file mode 100644 index 0000000..05a2a9a --- /dev/null +++ b/internal/tui/chat_choices_test.go @@ -0,0 +1,226 @@ +package tui + +import ( + "context" + "errors" + "slices" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" +) + +func chatChoiceModel(t *testing.T) Model { + t.Helper() + root, action := fixture() + chat := &cobra.Command{Use: "chat"} + list := &cobra.Command{Use: "ls", Args: cobra.NoArgs, RunE: func(*cobra.Command, []string) error { panic("must not execute Telegram calls in tests") }} + list.Flags().String("filter", "true", "chat filter") + list.Flags().String("output", "table", "output") + chat.AddCommand(list) + root.AddCommand(chat) + m := New(Catalog(root), nil, "personal", t.Context(), WithSavedAccounts([]string{"personal", "work"})) + m.open(action) + return m +} + +func startChatChoiceTest(t *testing.T, m Model) Model { + t.Helper() + focusField(&m, "chat") + next, command := m.Update(key(tea.KeyEnter, "")) + if command == nil { + t.Fatal("a fresh chat selector did not start its lookup") + } + next, poll := next.(Model).Update(command()) + if poll == nil { + t.Fatal("chat lookup did not begin polling") + } + return update(next.(Model), poll()) +} + +func TestChatChoicesCacheIsScopedToTheSelectedAccount(t *testing.T) { + m := chatChoiceModel(t) + calls := 0 + var latest Plan + m.run = func(_ context.Context, plan Plan) tea.Cmd { + calls++ + latest = plan + j := &job{terminal: newTranscript(80, 24), done: true, streamSeen: true, items: []item{{ID: "42", Title: "Personal chat"}}, cancel: func() {}} + return func() tea.Msg { return startedMsg{j} } + } + m = startChatChoiceTest(t, m) + m = update(m, key(tea.KeyLeft, "")) + next, command := m.Update(key(tea.KeyEnter, "")) + m = next.(Model) + if command != nil || calls != 1 || m.picker.label("42") != "Personal chat" { + t.Fatal("reopening the same account's chats should reuse the completed list") + } + m = update(m, key(tea.KeyEscape, "")) + focusField(&m, "ns") + m.openPicker(*m.form.field("ns")) + m.picker.selected = map[string]bool{"work": true} + m.applyPicker() + focusField(&m, "chat") + next, command = m.Update(key(tea.KeyEnter, "")) + m = next.(Model) + if command == nil || calls != 2 || !slices.Contains(latest.Args, "--ns=work") || slices.Contains(m.picker.choices, "42") { + t.Fatal("switching accounts reused the previous account's chat names") + } + m.closePicker() +} + +func TestClosingChatChoicesCancelsAndIgnoresLateWorkers(t *testing.T) { + m := chatChoiceModel(t) + stopped := false + var ctx context.Context + j := &job{terminal: newTranscript(80, 24), cancel: func() { stopped = true }} + m.run = func(child context.Context, _ Plan) tea.Cmd { + ctx = child + return func() tea.Msg { return startedMsg{j} } + } + focusField(&m, "chat") + next, command := m.Update(key(tea.KeyEnter, "")) + m = update(next.(Model), key(tea.KeyEscape, "")) + m = update(m, command()) + if m.picker != nil || m.chatLookup != nil || !stopped || ctx.Err() == nil || m.screen != configure { + t.Fatal("a dismissed chat lookup changed the form or left a late worker running") + } +} + +func TestChatLookupFailureKeepsPartialChoicesAndCanBeReloaded(t *testing.T) { + m := chatChoiceModel(t) + j := &job{terminal: newTranscript(80, 24), done: true, streamSeen: true, err: errors.New("failed"), items: []item{{ID: "42", Title: "Received chat"}}, cancel: func() {}} + j.terminal.write([]byte("connection refused\n")) + m.run = func(context.Context, Plan) tea.Cmd { return func() tea.Msg { return startedMsg{j} } } + m = startChatChoiceTest(t, m) + if m.chatLookup != nil || m.picker.loading || m.picker.label("42") != "Received chat" || !strings.Contains(ansi.Strip(m.View().Content), "connection refused") { + t.Fatal("a failed lookup should retain received chats and show its error") + } + next, command := m.Update(key('l', "", tea.ModCtrl)) + m = next.(Model) + if command == nil || !m.picker.loading || m.picker.loadErr != "" { + t.Fatal("Reload did not start a fresh lookup and clear the previous error") + } + m.closePicker() +} + +func TestChatChoicesAllowManualUsernamesAndClearIDsOnAccountChange(t *testing.T) { + m := chatChoiceModel(t) + set(&m.form, "chat", "me,42") + m.form.field("chat").ChoiceLabels["42"] = "Old account chat" + focusField(&m, "ns") + m.openPicker(*m.form.field("ns")) + m.picker.selected = map[string]bool{"work": true} + m.applyPicker() + if m.form.field("chat").Value != "me" || slices.Contains(m.form.field("chat").Choices, "42") { + t.Fatal("changing accounts must clear account-specific chat IDs") + } + m.run = func(context.Context, Plan) tea.Cmd { return nil } + focusField(&m, "chat") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "@manual_chat"}) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyLeft, "")) + if m.picker != nil || m.form.field("chat").Value != "me,@manual_chat" { + t.Fatal("chat names should remain addable when a lookup is unavailable") + } +} + +func TestSinceUntilAreVisibleAndAcceptDateTimes(t *testing.T) { + root, action := fixture() + action.Command.Flags().String("until", "", "exclusive date/time") + m := New(Catalog(root), nil, "personal", t.Context()) + m.open(action) + for _, name := range []string{"since", "until"} { + focusField(&m, name) + if m.focus < 0 { + t.Fatalf("%s must be visible without More options", name) + } + } + focusField(&m, "since") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "2026-11-01T18:30:00+03:30"}) + m = update(m, key(tea.KeyTab, "")) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "2026-11-14T00:00:00Z"}) + m = update(m, key('r', "", tea.ModCtrl)) + if m.screen != review || !slices.Contains(m.plan.Args, "--since=2026-11-01T18:30:00+03:30") || !slices.Contains(m.plan.Args, "--until=2026-11-14T00:00:00Z") { + t.Fatal("Since and Until date/time inputs were not saved into the backup plan") + } +} + +func TestOldBrowserChatNamesAreNotReusedForDifferentStorage(t *testing.T) { + m := chatChoiceModel(t) + m.source = &resultSnapshot{plan: Plan{Args: []string{"--ns=personal", "--storage=type=bolt,path=old"}}, data: resultData{Kind: "chat ls", Items: []item{{ID: "42", Title: "Old session chat"}}}} + set(&m.form, "storage", "type=bolt,path=new") + m.configureChatField() + if slices.Contains(m.form.field("chat").Choices, "42") { + t.Fatal("a browser snapshot from different session storage leaked into the chat field") + } +} + +func TestStopLoadingButtonKeepsTheChatSelectorUsable(t *testing.T) { + m := chatChoiceModel(t) + stopped := false + j := &job{terminal: newTranscript(80, 24), streamSeen: true, items: []item{{ID: "42", Title: "Received chat"}}, cancel: func() { stopped = true }} + m.run = func(context.Context, Plan) tea.Cmd { return func() tea.Msg { return startedMsg{j} } } + m = startChatChoiceTest(t, m) + m = clickChoiceText(t, m, "[Stop loading]") + if !stopped || m.chatLookup != nil || m.picker == nil || m.picker.loading || m.picker.label("42") != "Received chat" { + t.Fatal("Stop loading must retain received chats without leaving the form") + } + m = clickChoiceText(t, m, "[ ] Received chat") + m = clickChoiceText(t, m, "[Done]") + if m.form.field("chat").Value != "42" || m.picker != nil { + t.Fatal("a received chat could not be selected after stopping the lookup") + } +} + +func TestChatFieldLoadsNamesWithoutOpeningTheChatBrowserFirst(t *testing.T) { + m := chatChoiceModel(t) + set(&m.form, "proxy", "socks5://example.invalid:1080") + set(&m.form, "since", "unfinished-date") + j := &job{terminal: newTranscript(80, 24), structured: true, streamSeen: true, started: time.Now()} + stopped := false + j.cancel = func() { stopped = true } + var lookupPlan Plan + var lookupContext context.Context + m.run = func(ctx context.Context, plan Plan) tea.Cmd { + lookupPlan, lookupContext = plan, ctx + return func() tea.Msg { return startedMsg{j} } + } + focusField(&m, "chat") + next, command := m.Update(key(tea.KeyEnter, "")) + if command == nil { + t.Fatal("opening Chats to back up directly must start loading chats") + } + next, poll := next.(Model).Update(command()) + m = next.(Model) + if poll == nil || !slices.Equal(lookupPlan.Path, []string{"chat", "ls"}) || !slices.Contains(lookupPlan.Args, "--ns=personal") || !slices.Contains(lookupPlan.Args, "--proxy=socks5://example.invalid:1080") { + t.Fatal("the chat selector did not look up chats for the form's account and connection") + } + j.mu.Lock() + j.items = []item{{ID: "42", Title: "Friends"}, {ID: "84", Title: "Work"}} + j.stage = "2 chats received" + j.mu.Unlock() + m = update(m, poll()) + if m.screen != configure || m.picker == nil || m.picker.label("42") != "Friends" || m.picker.label("84") != "Work" { + t.Fatal("streamed chat names were not shown in the original form") + } + m = update(m, key(tea.KeyEnd, "")) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyUp, "")) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyLeft, "")) + if m.picker != nil || m.form.field("chat").Value != "42,84" || !stopped || lookupContext.Err() == nil { + t.Fatal("accepting chat choices must save IDs and stop the unfinished lookup") + } + set(&m.form, "since", "") + plan, err := m.form.Plan(nil) + if err != nil || !slices.Contains(plan.Args, "--chat=42,84") { + t.Fatalf("selected chat IDs did not reach the backup plan: %v", err) + } +} diff --git a/internal/tui/date_picker.go b/internal/tui/date_picker.go new file mode 100644 index 0000000..3e4e0ef --- /dev/null +++ b/internal/tui/date_picker.go @@ -0,0 +1,303 @@ +package tui + +import ( + "fmt" + "strconv" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +const calendarWidth, calendarHeight = 30, 9 + +type datePicker struct { + field string + day time.Time +} + +func dateField(field Field) bool { return field.Name == "since" || field.Name == "until" } + +func calendarDay(value time.Time) time.Time { + return time.Date(value.Year(), value.Month(), value.Day(), 0, 0, 0, 0, time.UTC) +} + +func (m *Model) openDatePicker(field Field) { + day := calendarDay(time.Now()) + value := field.Value + if m.editing { + value = m.editor.Value() + } + for _, layout := range []string{time.RFC3339, "2006-01-02"} { + if parsed, err := time.Parse(layout, value); err == nil { + day = calendarDay(parsed) + break + } + } + if seconds, err := strconv.ParseInt(value, 10, 64); err == nil { + day = calendarDay(time.Unix(seconds, 0).UTC()) + } + m.calendar = &datePicker{field: field.Name, day: day} + m.editing, m.buttonsFocused, m.err = false, false, "" + m.buttonFocus = 0 + m.editor.Blur() +} + +func (m *Model) closeDatePicker() { + m.calendar, m.buttonsFocused, m.buttonFocus = nil, false, 0 +} + +func (m *Model) applyDatePicker(value string) { + if m.calendar == nil { + return + } + if field := m.form.field(m.calendar.field); field != nil { + field.Value, field.Dirty = value, true + } + m.closeDatePicker() + m.err = "" +} + +func (m *Model) typeDate() { + m.closeDatePicker() + m.editField() +} + +func (p *datePicker) moveMonth(delta int) { + first := time.Date(p.day.Year(), p.day.Month()+time.Month(delta), 1, 0, 0, 0, 0, time.UTC) + last := first.AddDate(0, 1, -1).Day() + p.day = first.AddDate(0, 0, min(p.day.Day(), last)-1) +} + +// Every month uses six rows, so controls stay under the pointer when paging. +func (p datePicker) firstCell() time.Time { + first := time.Date(p.day.Year(), p.day.Month(), 1, 0, 0, 0, 0, time.UTC) + return first.AddDate(0, 0, -(int(first.Weekday())+6)%7) +} + +func (m Model) inlineCalendar() bool { + return m.screen == configure && m.calendar != nil && m.height >= 25 +} + +func (m Model) calendarBounds() choiceBounds { + if m.inlineCalendar() { + g := m.formLayout(m.width-4, m.height-9) + return choiceBounds{2 + g.controlX, 3 + g.top + g.fieldRow(m.focus) + 1, calendarWidth, calendarHeight} + } + return choiceBounds{2, 5, calendarWidth, calendarHeight} +} + +func (m Model) calendarView() string { + p := m.calendar + frame := lipgloss.NewStyle().Foreground(violet) + heading := p.day.Format("January 2006") + inner := calendarWidth - 2 + space := calendarWidth - len(heading) - 6 + lines := []string{ + frame.Render("╭ ") + selectedStyle.Render("‹") + strings.Repeat(" ", space/2) + titleStyle.Render(heading) + strings.Repeat(" ", space-space/2) + selectedStyle.Render("›") + frame.Render(" ╮"), + frame.Render("│") + dim.Render(" Mo Tu We Th Fr Sa Su ") + frame.Render("│"), + } + today := calendarDay(time.Now()) + first := p.firstCell() + for week := range 6 { + var row strings.Builder + row.WriteString(frame.Render("│")) + for column := range 7 { + day := first.AddDate(0, 0, week*7+column) + style := textStyle + if day.Month() != p.day.Month() { + style = dim + } + if day.Equal(today) { + style = accent.Underline(true) + } + if day.Equal(p.day) { + style = lipgloss.NewStyle().Background(mint).Foreground(lipgloss.Color("#102C2C")).Bold(true) + } + row.WriteString(style.Render(fmt.Sprintf(" %2d ", day.Day()))) + } + row.WriteString(frame.Render("│")) + lines = append(lines, row.String()) + } + lines = append(lines, frame.Render("╰"+strings.Repeat("─", inner)+"╯")) + return strings.Join(lines, "\n") +} + +func (m Model) datePickerView() string { + label := m.calendar.field + if field := m.form.field(label); field != nil { + label = field.Label + } + return titleStyle.Render(label+" · "+m.calendar.day.Format("2006-01-02")) + "\n\n" + m.calendarView() +} + +func (m *Model) calendarAction(id string) bool { + if m.calendar == nil { + return false + } + switch id { + case "date-choose": + m.applyDatePicker(m.calendar.day.Format("2006-01-02")) + case "date-today": + m.calendar.day = calendarDay(time.Now()) + case "date-clear": + m.applyDatePicker("") + case "date-type": + m.typeDate() + case "date-cancel": + m.closeDatePicker() + default: + return false + } + return true +} + +func (m Model) updateDatePicker(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { + key := msg.String() + if key == "f6" { + m.buttonsFocused, m.buttonFocus = !m.buttonsFocused, 0 + return m, nil + } + if m.buttonsFocused { + switch key { + case "tab", "shift+tab", "left", "right": + delta := 1 + if key == "shift+tab" || key == "left" { + delta = -1 + } + m.buttonFocus = (m.buttonFocus + len(m.buttons()) + delta) % len(m.buttons()) + return m, nil + case "enter": + return m, m.activate(m.buttons()[m.buttonFocus].ID) + } + } + p := m.calendar + switch key { + case "esc": + m.closeDatePicker() + case "left": + p.day = p.day.AddDate(0, 0, -1) + case "right": + p.day = p.day.AddDate(0, 0, 1) + case "up": + p.day = p.day.AddDate(0, 0, -7) + case "down": + p.day = p.day.AddDate(0, 0, 7) + case "pgup": + p.moveMonth(-1) + case "pgdown": + p.moveMonth(1) + case "ctrl+pgup": + p.moveMonth(-12) + case "ctrl+pgdown": + p.moveMonth(12) + case "home": + p.day = p.day.AddDate(0, 0, 1-p.day.Day()) + case "end": + p.day = time.Date(p.day.Year(), p.day.Month()+1, 0, 0, 0, 0, 0, time.UTC) + case "t": + m.calendarAction("date-today") + case "delete", "backspace", "ctrl+d": + m.calendarAction("date-clear") + case "i": + m.typeDate() + case "enter", "tab", "shift+tab", "ctrl+r", "ctrl+enter": + m.applyDatePicker(p.day.Format("2006-01-02")) + if key == "ctrl+r" || key == "ctrl+enter" { + m.prepareReview() + } else if key == "tab" || key == "shift+tab" { + delta := 1 + if key == "shift+tab" { + delta = -1 + } + if m.focus+delta >= len(m.visibleFields()) { + m.buttonsFocused, m.buttonFocus = true, 1 + } else { + m.focus = max(0, m.focus+delta) + } + } + default: + if msg.Text != "" { + m.typeDate() + return m, m.updateEditor(msg) + } + } + return m, nil +} + +func (m Model) datePickerClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { + if msg.Button != tea.MouseLeft { + return m, nil + } + b := m.calendarBounds() + x, y := msg.X-b.x, msg.Y-b.y + if b.contains(msg.X, msg.Y) { + switch { + case y == 0 && x >= 1 && x <= 3: + m.calendar.moveMonth(-1) + case y == 0 && x >= b.width-4 && x <= b.width-2: + m.calendar.moveMonth(1) + case y >= 2 && y < 8 && x >= 1 && x < b.width-1: + day := m.calendar.firstCell().AddDate(0, 0, (y-2)*7+(x-1)/4) + m.applyDatePicker(day.Format("2006-01-02")) + } + return m, nil + } + if m.inlineCalendar() && msg.Y == b.y-1 { + start := b.x + for _, action := range calendarActions { + size := lipgloss.Width(action.label) + 2 + if msg.X >= start && msg.X < start+size { + m.calendarAction(action.id) + return m, nil + } + start += size + 1 + } + } + if msg.Y == m.height-5 { + return m.mouseClick(msg) + } + if m.inlineCalendar() { + g := m.formLayout(m.width-4, m.height-9) + index, hit := g.fieldAtRow(msg.Y - 3 - g.top) + m.closeDatePicker() + if hit && index < len(m.visibleFields()) { + m.focus = index + return m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + } + } + return m, nil +} + +var calendarActions = []choiceAction{{"date-today", "Today"}, {"date-clear", "Clear"}, {"date-type", "Type date/time"}} + +func calendarToolbar() string { + var parts []string + for _, action := range calendarActions { + parts = append(parts, selectedStyle.Render("["+action.label+"]")) + } + return strings.Join(parts, " ") +} + +func (m *Model) dateControlClick(msg tea.MouseClickMsg) bool { + fields := m.visibleFields() + if m.calendar != nil || len(fields) == 0 || m.focus >= len(fields) { + return false + } + field := m.form.Fields[fields[m.focus]] + if !dateField(field) { + return false + } + g := m.formLayout(m.width-4, m.height-9) + x, y := msg.X-2-g.controlX, msg.Y-3-g.top-g.fieldRow(m.focus) + if y != 1 || x < 0 || x >= 31 { + return false + } + if x < 12 { + m.openDatePicker(field) + } else if !m.editing { + m.editField() + } + return true +} diff --git a/internal/tui/date_picker_test.go b/internal/tui/date_picker_test.go new file mode 100644 index 0000000..0be528d --- /dev/null +++ b/internal/tui/date_picker_test.go @@ -0,0 +1,195 @@ +package tui + +import ( + "slices" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +func datePickerModel(t *testing.T, name, value string) Model { + t.Helper() + root, action := fixture() + action.Command.Flags().String("until", "", "exclusive date/time") + m := New(Catalog(root), nil, "personal", t.Context()) + m.open(action) + set(&m.form, name, value) + focusField(&m, name) + return m +} + +func TestCalendarSelectsBothBackupDateFilters(t *testing.T) { + for _, name := range []string{"since", "until"} { + t.Run(name, func(t *testing.T) { + m := datePickerModel(t, name, "2026-11-14") + m = update(m, key(tea.KeyEnter, "")) + if m.calendar == nil || m.editing || !m.inlineCalendar() { + t.Fatal("Enter should open an inline calendar") + } + m = update(m, key(tea.KeyRight, "")) + m = update(m, key(tea.KeyDown, "")) + if m.form.field(name).Value != "2026-11-14" { + t.Fatal("moving in the calendar changed the saved date") + } + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key('r', "", tea.ModCtrl)) + if m.calendar != nil || m.screen != review || !slices.Contains(m.plan.Args, "--"+name+"=2026-11-22") { + t.Fatal("choosing a day did not reach the backup plan") + } + }) + } +} + +func TestCalendarPagesMonthsWithoutSkippingShortMonths(t *testing.T) { + for _, example := range []struct{ from, to string }{ + {"2028-01-31", "2028-02-29"}, + {"2026-01-31", "2026-02-28"}, + {"2026-12-31", "2027-01-31"}, + } { + m := datePickerModel(t, "since", example.from) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyPgDown, "")) + m = update(m, key(tea.KeyEnter, "")) + if got := m.form.field("since").Value; got != example.to { + t.Fatalf("paging from %s: got %s, want %s", example.from, got, example.to) + } + } + m := datePickerModel(t, "since", "2026-01-01") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyLeft, "")) + m = update(m, key(tea.KeyEscape, "")) + if m.calendar != nil || m.form.field("since").Value != "2026-01-01" { + t.Fatal("Esc should discard calendar navigation across a year") + } +} + +func TestCalendarMouseSelectsDaysAndControlsAtEverySupportedSize(t *testing.T) { + for _, size := range [][2]int{{55, 20}, {80, 24}, {55, 25}, {110, 32}} { + m := datePickerModel(t, "since", "2026-11-14") + m.width, m.height = size[0], size[1] + m = clickChoiceText(t, m, "[ Calendar ]") + if m.calendar == nil { + t.Fatalf("calendar control did not open at %v", size) + } + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, "Mo Tu We Th Fr Sa Su") || !strings.Contains(view, "November 2026") { + t.Fatalf("calendar grid is missing at %v: %s", size, view) + } + for _, row := range strings.Split(view, "\n") { + if ansi.StringWidth(row) > m.width { + t.Fatalf("calendar overflow at %v: %q", size, row) + } + } + if len(strings.Split(view, "\n")) > m.height { + t.Fatalf("calendar exceeds terminal height at %v", size) + } + m = clickChoiceText(t, m, "›") + if m.calendar.day.Format("2006-01-02") != "2026-12-14" { + t.Fatal("mouse next-month control did not page the month") + } + b := m.calendarBounds() + // December 2026 starts on Tuesday: the first Thursday is December 3. + m = update(m, tea.MouseClickMsg{X: b.x + 1 + 3*4, Y: b.y + 2, Button: tea.MouseLeft}) + if m.calendar != nil || m.form.field("since").Value != "2026-12-03" { + t.Fatalf("mouse day selection disagrees with the grid at %v", size) + } + m = update(m, key(tea.KeyEnter, "")) + m = clickChoiceText(t, m, "Clear") + if m.calendar != nil || m.form.field("since").Value != "" { + t.Fatalf("Clear did not remove the date limit at %v", size) + } + } +} + +func TestCalendarKeepsManualTimestampsAndSupportsToday(t *testing.T) { + for _, value := range []string{"2026-11-14T18:30:00+03:30", "1794672000"} { + m := datePickerModel(t, "since", value) + m = update(m, key(tea.KeyEnter, "")) + if m.calendar == nil || m.calendar.day.Format("2006-01-02") != "2026-11-14" { + t.Fatalf("calendar did not start at the existing timestamp %s", value) + } + m = clickChoiceText(t, m, "Type date/time") + if m.calendar != nil || !m.editing || m.editor.Value() != value { + t.Fatal("switching to manual entry lost the timestamp") + } + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: "2026-11-01T12:45:00Z"}) + m = update(m, key('r', "", tea.ModCtrl)) + if m.screen != review || !slices.Contains(m.plan.Args, "--since=2026-11-01T12:45:00Z") { + t.Fatal("manual timestamp did not reach the backup plan") + } + } + m := datePickerModel(t, "until", "2020-01-01") + m = update(m, key(tea.KeyEnter, "")) + m = clickChoiceText(t, m, "Today") + m = update(m, key(tea.KeyEnter, "")) + if m.form.field("until").Value != time.Now().Format("2006-01-02") { + t.Fatal("Today did not select today's local date") + } +} + +func TestCalendarTabAndReviewSaveTheHighlightedDay(t *testing.T) { + for _, reviewWithMouse := range []bool{false, true} { + m := datePickerModel(t, "since", "2026-11-14") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyLeft, "")) + if reviewWithMouse { + m = clickChoiceText(t, m, "[ Review ]") + } else { + m = update(m, key(tea.KeyTab, "")) + if m.form.Fields[m.visibleFields()[m.focus]].Name != "until" { + t.Fatal("Tab did not move to Until") + } + m = update(m, key('r', "", tea.ModCtrl)) + } + if m.screen != review || m.calendar != nil || !slices.Contains(m.plan.Args, "--since=2026-11-13") { + t.Fatal("leaving the calendar lost the highlighted day") + } + } +} + +func TestCalendarKeepsMouseTargetsWhenAnotherFieldIsClicked(t *testing.T) { + for _, height := range []int{25, 40} { + m := datePickerModel(t, "since", "2026-11-14") + m.height = height + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyRight, "")) + if height == 25 { + m = clickChoiceText(t, m, "▸ Since") + if m.calendar == nil || m.calendar.field != "since" { + t.Fatal("clicking the active field opened a different field after the form scrolled") + } + } else { + m = clickChoiceText(t, m, "Until (date/time)") + if m.calendar == nil || m.calendar.field != "until" { + t.Fatal("clicking Until below an expanded calendar opened a different field") + } + } + if m.form.field("since").Value != "2026-11-14" { + t.Fatal("clicking outside the calendar should discard unchosen navigation") + } + } +} + +func TestSmallCalendarButtonsReturnSafelyToTheForm(t *testing.T) { + for _, label := range []string{"Type date/time", "Cancel"} { + m := datePickerModel(t, "since", "2026-11-14") + m.width, m.height = 55, 20 + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyF6, "")) + for m.buttons()[m.buttonFocus].Label != label { + m = update(m, key(tea.KeyTab, "")) + } + // Check the scrolled button bar and activate its last actions by keyboard. + if !strings.Contains(ansi.Strip(m.View().Content), label) { + t.Fatal("the focused calendar action scrolled out of view") + } + m = update(m, key(tea.KeyEnter, "")) + if m.calendar != nil || !strings.Contains(ansi.Strip(m.View().Content), "[ Review ]") { + t.Fatal("calendar action did not safely restore the form") + } + } +} diff --git a/internal/tui/fields.go b/internal/tui/fields.go new file mode 100644 index 0000000..efc8dad --- /dev/null +++ b/internal/tui/fields.go @@ -0,0 +1,109 @@ +package tui + +import ( + "slices" + "strings" +) + +func specialChoice(field, value string) bool { + return (value == "all" && slices.Contains([]string{"media", "include", "account-include"}, field)) || (value == "none" && field == "media") +} + +// The full CLI remains available under More options. Everyday forms expose +// only the decisions relevant to the selected task. +func essential(path []string, name string) bool { + var names []string + switch strings.Join(path, " ") { + case "archive": + names = []string{"chat", "all", "types", "media", "format", "output", "since", "until"} + case "sync": + names = []string{"everything", "chat", "all", "media", "format", "output", "since", "until"} + case "account": + names = []string{"include", "media", "format", "output", "since", "until"} + case "login": + names = []string{"type", "desktop", "passcode", "ns"} + case "cron add": + names = []string{"everything", "chat", "every", "at-startup", "format", "output", "since", "until"} + default: + return slices.Contains(common, name) + } + return slices.Contains(names, name) +} + +func fieldLabel(name string) string { + if label, ok := map[string]string{ + "chat": "Chats to back up", "all": "All joined chats", "everything": "Entire account", + "media": "Media to download", "format": "Export format", "output": "Save to folder", + "every": "Repeat backup every", "at-startup": "Catch up at startup", "ns": "Saved account", + "desktop": "Telegram data folder", "passcode": "Local app passcode", "since": "Since (date/time)", + "until": "Until (date/time)", "resume": "Resume interrupted backup", "types": "Chat categories", + "include": "Account sections", "proxy": "Connection proxy", + }[name]; ok { + return label + } + return strings.ReplaceAll(name, "-", " ") +} + +func choiceLabel(name, value string) string { + if name == "ns" { + return safeText(value) + } + if name == "media" && value == "all" { + return "All media" + } + if name == "media" && value == "none" { + return "No media" + } + if name == "type" { + switch value { + case "desktop": + return "Installed app" + case "qr": + return "QR code" + case "code": + return "Phone code" + } + } + if name == "format" { + switch value { + case "json": + return "JSON" + case "html": + return "HTML" + case "both": + return "Both" + } + } + label := strings.ReplaceAll(value, "_", " ") + if label != "" { + runes := []rune(label) + label = strings.ToUpper(string(runes[0])) + string(runes[1:]) + } + return label +} + +func (f *Form) reconcileSelection(changed string) { + clear := func(name, value string) { + if field := f.field(name); field != nil && field.Value != value { + field.Value, field.Dirty = value, true + } + } + field := f.field(changed) + if field == nil { + return + } + switch { + case changed == "all" && field.Value == "true": + clear("chat", "") + clear("everything", "false") + case changed == "everything" && field.Value == "true": + clear("chat", "") + clear("all", "false") + if media := f.field("media"); media != nil && !media.Dirty { + media.Value, media.Dirty = "all", true + } + case changed == "chat" && field.Value != "": + clear("all", "false") + clear("everything", "false") + } +} diff --git a/internal/tui/form_view.go b/internal/tui/form_view.go new file mode 100644 index 0000000..22a7655 --- /dev/null +++ b/internal/tui/form_view.go @@ -0,0 +1,230 @@ +package tui + +import ( + "fmt" + "strings" + + "charm.land/lipgloss/v2" +) + +type formGeometry struct { + top, rows, start, focus, extra int + labelWidth, controlX, controlWidth int +} + +func (m Model) formLayout(width, height int) formGeometry { + g := formGeometry{top: 3, rows: max(1, height-6), focus: m.focus, labelWidth: min(27, width/3)} + g.controlX = g.labelWidth + 2 + g.controlWidth = width - g.controlX + fields := m.visibleFields() + if m.inlinePicker() { + g.extra = min(7, max(1, g.rows-1)) + } else if m.inlineCalendar() { + g.extra = calendarHeight + } else if len(fields) > 0 && m.focus < len(fields) && (m.form.Fields[fields[m.focus]].PathKind != "" || dateField(m.form.Fields[fields[m.focus]])) { + g.extra = 1 + } + g.start = max(0, m.focus-max(1, g.rows-g.extra)+1) + return g +} + +func (g formGeometry) fieldRow(index int) int { + row := index - g.start + if index > g.focus { + row += g.extra + } + return row +} + +func (g formGeometry) fieldAtRow(row int) (int, bool) { + if row < 0 || row >= g.rows { + return 0, false + } + focusRow := g.focus - g.start + if row > focusRow && row <= focusRow+g.extra { + return 0, false + } + if row > focusRow { + row -= g.extra + } + return g.start + row, true +} + +func (m Model) formView(width, height int) string { + fields := m.visibleFields() + g := m.formLayout(width, height) + mode := "Essentials" + if m.advanced { + mode = "All settings" + } + status := fmt.Sprintf("%s · %d settings", mode, len(fields)) + if m.searching { + status = m.inputView(width, false) + } else if m.fieldSearch != "" { + status = fmt.Sprintf("Options matching %q · %d found", m.fieldSearch, len(fields)) + } + lines := []string{titleStyle.Render(clip(m.form.Action.Title, width)), dim.Render(clip(status+" · Ctrl+F to find any option", width)), ""} + if len(fields) == 0 { + return strings.Join(append(lines, "No matching settings. Esc clears the search."), "\n") + } + var rows []string + for n := g.start; n < len(fields) && g.fieldRow(n) < g.rows; n++ { + field := m.form.Fields[fields[n]] + marker, style := " ", dim + if n == m.focus { + marker, style = "▸ ", accent + } + label := field.Label + if field.Required { + label += " *" + } + name := style.Width(g.labelWidth).Render(clip(marker+label, g.labelWidth)) + value := dim.Render(clip(field.Display(), g.controlWidth-2)) + if n == m.focus { + value = m.fieldControl(field, g.controlWidth) + if m.inlinePicker() { + value = m.choiceToolbar(field, min(60, g.controlWidth)) + } else if m.inlineCalendar() { + value = calendarToolbar() + } + } + rows = append(rows, name+" "+value) + if n == m.focus && g.extra > 0 { + control := "" + if m.inlinePicker() { + control = m.inlineChoicesView(field, min(60, g.controlWidth), g.extra) + } else if m.inlineCalendar() { + control = m.calendarView() + } else if dateField(field) { + control = selectedStyle.Render("[ Calendar ]") + " " + dim.Render("[ Type date/time ]") + } else if field.PathKind != "" { + control = selectedStyle.Render("[ Browse… ]") + " " + dim.Render("[ Type path ]") + } + for _, row := range strings.Split(control, "\n") { + rows = append(rows, strings.Repeat(" ", g.controlX)+row) + } + } + } + lines = append(lines, fit(strings.Join(rows, "\n"), width, g.rows)) + field := m.form.Fields[fields[m.focus]] + lines = append(lines, dim.Render(clip(m.fieldHelp(field), width)), dim.Render(clip(m.fieldHint(field), width))) + err := m.err + if m.inlinePicker() { + if m.picker.err != "" { + err = m.picker.err + } else if m.picker.loadErr != "" { + err = m.picker.loadErr + } else if m.picker.field == "ns" && m.accountError != "" { + err = "Could not refresh saved accounts: " + m.accountError + } + } + if err != "" { + lines = append(lines, warning.Render(clip(err, width))) + } else { + lines = append(lines, dim.Render(fmt.Sprintf("Setting %d of %d", m.focus+1, len(fields)))+" "+accent.Render("Ctrl+R Review")) + } + return strings.Join(lines, "\n") +} + +func (m Model) fieldControl(field Field, width int) string { + if choiceField(field) { + width = min(60, width) + } + value := field.Display() + switch { + case field.Type == "bool": + value = accent.Render("● Off") + dim.Render(" ○ On") + if field.Value == "true" { + value = dim.Render("○ Off") + accent.Render(" ● On") + } + case choiceField(field): + value = accent.Render(field.Display()) + dim.Render(" ▾") + if field.Multi { + value = accent.Render(field.Display()) + dim.Render(" ▾ multiple") + } + case m.editing: + value = m.inputView(max(1, width-2), field.Secret) + case dateField(field): + if value == "" || value == "—" { + value = "Choose a date" + } + value = accent.Render(value) + dim.Render(" ▾") + case field.Value == "": + value = dim.Render(placeholder(field)) + } + style := lipgloss.NewStyle().Background(panel).Foreground(ink).Padding(0, 1).Width(width) + return style.Render(clip(value, width-2)) +} + +func (m Model) fieldHelp(field Field) string { + if field.Multi && choiceField(field) { + if m.inlinePicker() && m.picker.field == field.Name { + field.Value = csvString(m.picker.values()) + } + if field.Value != "" { + return "Selected: " + field.Display() + } + } + if field.Name == "format" { + return "Choose JSON, HTML, or Both. Both exports JSON and HTML." + } + if field.Name == "since" { + return "Include data from this date/time (inclusive). Use YYYY-MM-DD, RFC3339 with a time zone, or Unix seconds." + } + if field.Name == "until" { + return "Include data before this date/time (exclusive). Use YYYY-MM-DD, RFC3339 with a time zone, or Unix seconds." + } + if field.Name == "chat" { + if len(field.Choices) > 0 { + return "Choose the chats to back up from this account. Your choices stay checked while filtering." + } + return "Use me for Saved Messages, an @username or a chat ID. You can also choose a chat from Browse your chats." + } + return field.Help +} + +func (m Model) fieldHint(field Field) string { + if dateField(field) { + if m.calendar != nil { + return "Click a day or Enter to select · PgUp/PgDn changes month · Esc cancels" + } + if m.editing { + return "Type a date/time · Calendar opens the picker · Tab saves · Esc undoes" + } + return "Enter or Calendar opens the picker · Type date/time for an exact timestamp" + } + if m.inlinePicker() && field.Name == "chat" && chatChoiceAction(m.form.Action.Path) { + if m.picker.loading { + return selectedStyle.Render("[Stop loading]") + " " + m.picker.loadStage + } + return selectedStyle.Render("[Reload chats]") + " Enter toggles · ← saves · Ctrl+L reloads" + } + if field.PathKind != "" { + if m.editing { + return "Alt+O browses · Tab saves · Esc undoes this edit" + } + return "Enter or Browse opens the chooser · Type a path for a new destination" + } + if customChoices(field) { + return "Enter adds a typed item or toggles a choice · ← saves and closes · Add/Done work with the mouse" + } + if field.Multi && choiceField(field) { + if m.inlinePicker() { + return "Enter or Space toggles an item · ← saves and closes · Done also saves · Ctrl+S shows chosen items" + } + return "Enter or click opens choices · Type to filter · Tab next" + } + if len(field.Choices) > 0 { + if m.inlinePicker() { + return "↑ / ↓ or wheel scrolls · Enter selects · Tab next" + } + return "Enter opens the dropdown · ← / → changes the selection" + } + if field.Type == "bool" { + return "← / → or Space changes the selection · Tab next" + } + if m.editing { + return "Tab saves and moves on · Esc undoes this edit · Ctrl+U clears" + } + return "Start typing, paste, or press Enter to edit · Tab next" +} diff --git a/internal/tui/inline_choices.go b/internal/tui/inline_choices.go new file mode 100644 index 0000000..ae752b4 --- /dev/null +++ b/internal/tui/inline_choices.go @@ -0,0 +1,211 @@ +package tui + +import ( + "fmt" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +func multiChoices(field Field) bool { return field.Multi && choiceField(field) } +func customChoices(field Field) bool { + return field.Multi && (field.AllowCustom || len(field.Choices) == 0) && field.PathKind == "" && field.Type != "accounts" && !field.Secret +} +func choiceField(field Field) bool { + return len(field.Choices) > 0 || field.Type == "accounts" || customChoices(field) +} +func (m Model) inlinePicker() bool { return m.screen == configure && m.picker != nil } + +type choiceBounds struct{ x, y, width, height int } + +func (b choiceBounds) contains(x, y int) bool { + return x >= b.x && x < b.x+b.width && y >= b.y && y < b.y+b.height +} + +// The dropdown is attached to the argument's value column and has its own +// bounded viewport. Rendering, mouse hit testing and wheel routing share it. +func (m Model) inlineChoiceBounds() choiceBounds { + g := m.formLayout(m.width-4, m.height-9) + return choiceBounds{2 + g.controlX, 3 + g.top + g.fieldRow(m.focus) + 1, min(60, g.controlWidth), g.extra} +} + +type choiceWindow struct{ start, end, rows, thumbStart, thumbSize int } + +func choiceListWindow(height, count, cursor, offset int) choiceWindow { + w := choiceWindow{rows: max(1, height-3)} + cursor = max(0, min(max(0, count-1), cursor)) + w.start = max(0, min(max(0, count-w.rows), offset)) + if cursor < w.start { + w.start = cursor + } else if cursor >= w.start+w.rows { + w.start = cursor - w.rows + 1 + } + w.end = min(count, w.start+w.rows) + w.thumbSize = max(1, w.rows*w.rows/max(1, count)) + w.thumbStart = w.start * (w.rows - w.thumbSize) / max(1, count-w.rows) + return w +} + +type choiceAction struct{ id, label string } + +func inlineChoiceActions(p *choicePicker) []choiceAction { + if len(p.choices) == 0 && p.field == "ns" { + return []choiceAction{{"picker-connect", "Connect account"}, {"picker-refresh", "Refresh"}} + } + if !p.multi { + return []choiceAction{{"picker-apply", "Done"}} + } + if p.custom { + return []choiceAction{{"picker-add", "Add"}, {"picker-all", "All"}, {"picker-clear", "Clear"}, {"picker-apply", "Done"}} + } + return []choiceAction{{"picker-all", "All"}, {"picker-clear", "Clear"}, {"picker-apply", "Done"}} +} + +func (m Model) choiceToolbar(field Field, width int) string { + p := m.picker + var actions []string + for _, action := range inlineChoiceActions(p) { + actions = append(actions, selectedStyle.Render("["+action.label+"]")) + } + toolbar := strings.Join(actions, " ") + values := p.values() + if p.multi { + field.Value = csvString(values) + } + selection := field.Display() + if p.multi && len(values) > 1 { + selection = fmt.Sprintf("%d · %s", len(values), selection) + } + if lipgloss.Width(toolbar)+lipgloss.Width(selection)+2 > width && p.multi { + selection = fmt.Sprintf("%d ✓", len(p.values())) + } + selection = clip(selection, max(1, width-lipgloss.Width(toolbar)-1)) + space := max(1, width-lipgloss.Width(toolbar)-lipgloss.Width(selection)) + return clip(accent.Render(selection)+strings.Repeat(" ", space)+toolbar, width) +} + +func (m Model) inlineChoicesView(_ Field, width, height int) string { + p := m.picker + rows := p.filtered() + w := choiceListWindow(height, len(rows), p.cursor, p.offset) + inner := max(1, width-2) + border := line + if !p.searching { + border = violet + } + frame := lipgloss.NewStyle().Foreground(border) + query := p.query + query.SetWidth(max(1, inner-3)) + lines := []string{frame.Render("╭" + strings.Repeat("─", inner) + "╮"), frame.Render("│") + fit(dim.Render("⌕ ")+query.View(), inner, 1) + frame.Render("│")} + for row := range w.rows { + index := w.start + row + value := "" + style := textStyle + if index < len(rows) { + mark, pointer := "○", " " + if p.multi { + mark = "[ ]" + } + if p.checked(rows[index]) { + mark, style = "●", accent + if p.multi { + mark = "[✓]" + } + } + if index == p.cursor && !p.searching { + pointer, style = "▸", selectedStyle.Bold(true) + } + value = pointer + " " + mark + " " + p.label(rows[index]) + } else if row == 0 && len(rows) == 0 { + value, style = "No matching options", dim + if p.custom { + value = "Type an item; Enter adds it" + if p.query.Value() != "" { + value = "+ Add " + safeText(p.query.Value()) + " ↵" + } + } else if p.selectedOnly { + value = "No selected items" + } + if len(p.choices) == 0 && p.field == "ns" { + value = "No saved accounts" + } + } + track := " " + if len(rows) > w.rows { + track = dim.Render("│") + if row >= w.thumbStart && row < w.thumbStart+w.thumbSize { + track = accent.Render("┃") + } + } + lines = append(lines, frame.Render("│")+style.Width(inner-1).Render(clip(value, inner-1))+track+frame.Render("│")) + } + page := "" + if len(rows) > 0 { + page = fmt.Sprintf(" %d–%d / %d ", w.start+1, w.end, len(rows)) + } + page = clip(page, inner) + lines = append(lines, frame.Render("╰"+page+strings.Repeat("─", max(0, inner-lipgloss.Width(page)))+"╯")) + return fit(strings.Join(lines, "\n"), width, height) +} + +func (m *Model) inlineChoiceClick(msg tea.MouseClickMsg) (bool, tea.Cmd) { + if !m.inlinePicker() { + return false, nil + } + if m.picker.field == "chat" && chatChoiceAction(m.form.Action.Path) && msg.Y == m.height-8 && msg.X >= 2 && msg.X < 16 { + if m.picker.loading { + m.stopChatLookup() + return true, nil + } + return true, m.loadChatChoices(true) + } + b := m.inlineChoiceBounds() + x, y := msg.X-b.x, msg.Y-b.y + if msg.Y == b.y-1 && x >= 0 && x < b.width { + start := b.width + actions := inlineChoiceActions(m.picker) + for index := len(actions) - 1; index >= 0; index-- { + action := actions[index] + size := lipgloss.Width(action.label) + 2 + start -= size + if x >= start && x < start+size { + if action.id == "picker-refresh" { + return true, m.loadAccounts() + } + return true, m.activate(action.id) + } + start-- + } + return true, nil + } + if !b.contains(msg.X, msg.Y) { + return false, nil + } + p := m.picker + if y == 1 { + p.searching = true + p.query.Focus() + return true, nil + } + rows := p.filtered() + if p.custom && len(rows) == 0 && y == 2 && p.query.Value() != "" { + p.addCustom() + return true, nil + } + w := choiceListWindow(b.height, len(rows), p.cursor, p.offset) + index := w.start + y - 2 + if y >= 2 && y < b.height-1 && index < len(rows) { + if x == b.width-2 && len(rows) > w.rows { + p.cursor = (y - 2) * (len(rows) - 1) / max(1, w.rows-1) + return true, nil + } + p.cursor, p.searching = index, false + p.query.Blur() + p.toggle(rows[index]) + if !p.multi { + m.applyPicker() + } + } + return true, nil +} diff --git a/internal/tui/inline_choices_test.go b/internal/tui/inline_choices_test.go new file mode 100644 index 0000000..3e71321 --- /dev/null +++ b/internal/tui/inline_choices_test.go @@ -0,0 +1,274 @@ +package tui + +import ( + "context" + "fmt" + "slices" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +func inlineModel(t *testing.T, accounts ...string) Model { + t.Helper() + root, action := fixture() + m := New(Catalog(root), nil, accounts[0], context.Background(), WithSavedAccounts(accounts)) + m.open(action) + focusField(&m, "ns") + return m +} + +func TestMultiChoicesAreVisibleWithinTheFormAndTabSaves(t *testing.T) { + m := inlineModel(t, "personal", "work", "family") + assertForm := func() { + t.Helper() + view := ansi.Strip(m.View().Content) + for _, want := range []string{m.form.Action.Title, "Essentials", "Accounts to back up", "personal", "work", "family", "[ Review ]"} { + if !strings.Contains(view, want) { + t.Fatalf("the inline choices hid %q:\n%s", want, view) + } + } + } + if strings.Contains(ansi.Strip(m.View().Content), "[ ] family") { + t.Fatal("a closed selector should stay compact") + } + m = update(m, key(tea.KeyEnter, "")) + assertForm() + m = update(m, key(tea.KeyRight, "")) + m = update(m, key(' ', " ")) + before := m.focus + m = update(m, key(tea.KeyTab, "")) + if m.picker != nil || m.focus != before+1 || m.form.field("ns").Value != "personal,work" { + t.Fatal("Tab must save the checked cards and advance to the next setting") + } +} + +func TestInlineReviewSavesSelectionAndEscapeUndoesIt(t *testing.T) { + m := inlineModel(t, "personal", "work") + set(&m.form, "chat", "me") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyRight, "")) + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyEscape, "")) + if m.form.field("ns").Value != "personal" || m.screen != configure { + t.Fatal("Esc should undo the selection without leaving the form") + } + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyRight, "")) + m = update(m, key(' ', " ")) + m = update(m, key('r', "", tea.ModCtrl)) + if m.screen != review || m.picker != nil || len(m.plan.Tasks) != 2 { + t.Fatal("review did not save the currently checked accounts") + } +} + +func TestInlineEmptySelectionBlocksLeavingTheControl(t *testing.T) { + for _, leave := range []tea.KeyPressMsg{key(tea.KeyTab, ""), key('r', "", tea.ModCtrl)} { + m := inlineModel(t, "personal", "work") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key('d', "", tea.ModCtrl)) + focus := m.focus + m = update(m, leave) + if m.screen != configure || m.focus != focus || m.picker == nil || m.picker.err == "" { + t.Fatal("an empty selection must retain focus and explain the problem") + } + } +} + +func clickChoiceText(t *testing.T, m Model, text string) Model { + t.Helper() + for y, line := range strings.Split(ansi.Strip(m.View().Content), "\n") { + if index := strings.Index(line, text); index >= 0 { + return update(m, tea.MouseClickMsg{X: ansi.StringWidth(line[:index]), Y: y, Button: tea.MouseLeft}) + } + } + t.Fatalf("could not find clickable %q in:\n%s", text, ansi.Strip(m.View().Content)) + return m +} + +func TestInlineChoicesCanBeClickedAndKeepChecksWhileFiltering(t *testing.T) { + for _, size := range [][2]int{{55, 20}, {80, 24}, {110, 32}, {120, 20}} { + m := inlineModel(t, "personal", "work") + m.width, m.height = size[0], size[1] + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyDown, "")) + m = clickChoiceText(t, m, "[ ] work") + if m.picker == nil || !m.picker.checked("work") { + t.Fatalf("clicking an inline item did not check it at %v", size) + } + m = update(m, tea.PasteMsg{Content: "personal"}) + if !m.picker.checked("work") || !slices.Equal(m.picker.filtered(), []string{"personal"}) { + t.Fatal("filtering discarded a checked item outside the search") + } + m = clickChoiceText(t, m, "[Done]") + if m.picker != nil || m.form.field("ns").Value != "personal,work" { + t.Fatal("Done did not save the selection") + } + } +} + +func TestInlineDropdownFitsAndScrollsAfterResizing(t *testing.T) { + accounts := []string{"personal", "名字", "آرشیو"} + for n := range 24 { + accounts = append(accounts, fmt.Sprintf("account-%02d", n)) + } + for _, size := range [][2]int{{55, 20}, {80, 24}, {110, 32}, {120, 20}, {120, 36}} { + m := inlineModel(t, accounts...) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyEnd, "")) + m = update(m, tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, "account-23") || !strings.Contains(view, "[ Review ]") || len(strings.Split(view, "\n")) > size[1] { + t.Fatalf("the final item or page actions were hidden at %v:\n%s", size, view) + } + for _, line := range strings.Split(view, "\n") { + if ansi.StringWidth(line) > size[0] { + t.Fatalf("choice grid overflow at %v: %q", size, line) + } + } + m = clickChoiceText(t, m, "[ ] account-23") + if !m.picker.checked("account-23") { + t.Fatal("mouse selection disagreed with the scrolled grid") + } + } +} + +func TestInlineMouseReviewSavesAndEmptyAccountsOfferConnection(t *testing.T) { + m := inlineModel(t, "personal", "work") + set(&m.form, "chat", "me") + m = update(m, key(tea.KeyEnter, "")) + m = clickChoiceText(t, m, "[ ] work") + m = clickChoiceText(t, m, "[ Review ]") + if m.screen != review || len(m.plan.Tasks) != 2 { + t.Fatal("the form Review button did not apply the active selection") + } + m = inlineModel(t, "personal") + m = update(m, accountsLoadedMsg{}) + m = update(m, key(tea.KeyEnter, "")) + if !strings.Contains(ansi.Strip(m.View().Content), "No saved accounts") { + t.Fatal("an empty list should explain how to get started") + } +} + +func TestTypingFiltersInlineAndEscapeDiscardsUnsavedChecks(t *testing.T) { + m := inlineModel(t, "personal", "work") + m = update(m, key('w', "w")) + if m.picker == nil || !slices.Equal(m.picker.filtered(), []string{"work"}) { + t.Fatal("typing should filter the cards directly in the form") + } + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(' ', " ")) + m = update(m, tea.PasteMsg{Content: "unmatched"}) + m = update(m, key(tea.KeyEscape, "")) + if m.picker != nil || m.form.field("ns").Value != "personal" { + t.Fatal("Escape during filtering should undo the unsaved card selection") + } +} + +func TestInlineAccountRefreshHasItsOwnShortcut(t *testing.T) { + m := inlineModel(t, "personal", "work") + m.accountLoader = func(context.Context, string) ([]string, error) { + return []string{"personal", "work", "family"}, nil + } + m = update(m, key(tea.KeyEnter, "")) + next, command := m.Update(key('l', "", tea.ModCtrl)) + if command == nil { + t.Fatal("Ctrl+L should refresh saved accounts") + } + m = update(next.(Model), command()) + if !slices.Contains(m.picker.choices, "family") || m.screen != configure || !m.picker.checked("personal") { + t.Fatal("refresh should update the inline choices and preserve checks") + } +} + +func TestDropdownWheelScrollsIndependentlyAndPreservesChecks(t *testing.T) { + accounts := []string{"personal"} + for index := range 24 { + accounts = append(accounts, fmt.Sprintf("account-%02d", index)) + } + m := inlineModel(t, accounts...) + m.width, m.height = 110, 32 + m = update(m, key(tea.KeyEnter, "")) + bounds := m.inlineChoiceBounds() + if bounds.height > 7 || bounds.width >= m.width-4 { + t.Fatal("the dropdown should be bounded inside the argument's value column") + } + focus := m.focus + for range 3 { + m = update(m, tea.MouseWheelMsg{X: bounds.x + 3, Y: bounds.y + 2, Button: tea.MouseWheelDown}) + } + if m.focus != focus || m.picker == nil || m.picker.cursor != 9 || !m.picker.checked("personal") { + t.Fatal("scrolling inside the dropdown moved the form or discarded checks") + } + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, "┃") || !strings.Contains(view, "account-08") || strings.Contains(view, "▸ [✓] personal") { + t.Fatalf("the dropdown did not scroll its visible options:\n%s", view) + } + m = clickChoiceText(t, m, "[ ] account-08") + if !m.picker.checked("account-08") || !m.picker.checked("personal") { + t.Fatal("clicking after scrolling toggled the wrong item") + } + m = update(m, tea.MouseWheelMsg{X: 3, Y: bounds.y + 2, Button: tea.MouseWheelDown}) + if m.picker != nil || m.focus != focus+3 || m.form.field("ns").Value != "personal,account-08" { + t.Fatal("scrolling outside the dropdown should save it and move through the arguments") + } +} + +func TestClickingAnArgumentBelowTheDropdownTargetsItsOriginalRow(t *testing.T) { + m := inlineModel(t, "personal", "work") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(' ', " ")) + m = clickChoiceText(t, m, "Chats to back up") + fields := m.visibleFields() + if m.picker == nil || m.picker.field != "chat" || !m.picker.custom || m.editing || m.form.Fields[fields[m.focus]].Name != "chat" || m.form.field("ns").Value != "personal,work" { + t.Fatal("closing the dropdown changed the field under the mouse") + } +} + +func TestSingleChoicesUseTheSameCompactDropdown(t *testing.T) { + m := inlineModel(t, "personal") + focusField(&m, "format") + m = update(m, key(tea.KeyEnter, "")) + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, "Chats to back up") || !strings.Contains(view, "○ HTML") || !strings.Contains(view, "○ Both") { + t.Fatal("the single selector should stay anchored in the argument form") + } + m = clickChoiceText(t, m, "○ HTML") + if m.picker != nil || m.form.field("format").Value != "html" || m.screen != configure { + t.Fatal("clicking a single choice should apply it in place") + } +} + +func TestClickingAScrolledCheckboxKeepsItUnderTheMouse(t *testing.T) { + accounts := []string{"personal"} + for index := range 20 { + accounts = append(accounts, fmt.Sprintf("account-%02d", index)) + } + m := inlineModel(t, accounts...) + m = clickChoiceText(t, m, "Accounts to back up") + b := m.inlineChoiceBounds() + for range 3 { + m = update(m, tea.MouseWheelMsg{X: b.x + 3, Y: b.y + 2, Button: tea.MouseWheelDown}) + } + for y, line := range strings.Split(ansi.Strip(m.View().Content), "\n") { + if index := strings.Index(line, "[ ] account-05"); index >= 0 { + x := ansi.StringWidth(line[:index]) + click := tea.MouseClickMsg{X: x, Y: y, Button: tea.MouseLeft} + m = update(m, click) + m = update(m, tea.MouseReleaseMsg{X: x, Y: y, Button: tea.MouseLeft}) + after := strings.Split(ansi.Strip(m.View().Content), "\n") + if !strings.Contains(after[y], "[✓] account-05") { + t.Fatalf("clicking moved the item away from the mouse:\n%s", strings.Join(after, "\n")) + } + m = update(m, click) + if m.picker.checked("account-05") || !m.picker.checked("personal") { + t.Fatal("a second click should uncheck the same item and retain the other choices") + } + return + } + } + t.Fatal("the scrolled checkbox was not visible") +} diff --git a/internal/tui/input.go b/internal/tui/input.go new file mode 100644 index 0000000..ec3f127 --- /dev/null +++ b/internal/tui/input.go @@ -0,0 +1,185 @@ +package tui + +import ( + "fmt" + "strings" + + "charm.land/bubbles/v2/textinput" + tea "charm.land/bubbletea/v2" +) + +func (m *Model) startInput(value, placeholder string, secret bool) { + m.editor = textinput.New() + m.editor.Prompt = "" + m.editor.Placeholder = placeholder + m.editor.CharLimit = 4096 + m.editor.SetVirtualCursor(true) + styles := textinput.DefaultDarkStyles() + styles.Focused.Text = textStyle + styles.Focused.Placeholder = dim + styles.Cursor.Color, styles.Cursor.Blink = mint, false + m.editor.SetStyles(styles) + m.editor.SetWidth(m.editorWidth()) + if secret { + m.editor.EchoMode = textinput.EchoPassword + m.editor.EchoCharacter = '•' + } + m.editor.SetValue(value) + m.editor.CursorEnd() + m.editor.Focus() + m.input, m.cursor = []rune(value), len([]rune(value)) +} + +func (m *Model) editField() { + fields := m.visibleFields() + if len(fields) == 0 || m.focus >= len(fields) { + return + } + field := m.form.Fields[fields[m.focus]] + if choiceField(field) { + m.openPicker(field) + return + } + m.startInput(field.Value, placeholder(field), field.Secret) + m.editing, m.buttonsFocused = true, false + m.err = "" +} + +func (m *Model) saveInput() bool { + if !m.editing { + return true + } + fields := m.visibleFields() + if len(fields) == 0 || m.focus >= len(fields) { + return false + } + field := m.form.Fields[fields[m.focus]] + field.Value, field.Dirty = string(m.input), true + err := validate(field) + if field.Required && strings.TrimSpace(field.Value) == "" { + err = fmt.Errorf("enter a value") + } + if (field.Name == "since" || field.Name == "until") && field.Value != "" && !validDate(field.Value) { + err = fmt.Errorf("use YYYY-MM-DD, RFC3339 date/time, or Unix seconds") + } + if err != nil { + m.err = field.Error(err).Error() + return false + } + m.form.Fields[fields[m.focus]] = field + m.form.reconcileSelection(field.Name) + m.editing, m.err = false, "" + m.editor.Blur() + return true +} + +func (m *Model) updateEditor(msg tea.Msg) tea.Cmd { + var command tea.Cmd + m.editor.SetWidth(m.editorWidth()) + m.editor, command = m.editor.Update(msg) + m.input, m.cursor = []rune(m.editor.Value()), m.editor.Position() + m.syncSearch() + return command +} + +func (m Model) editorWidth() int { + width := m.width - 4 + switch m.screen { + case configure: + if m.searching { + return max(1, width-1) + } + layout := m.formLayout(width, m.height-9) + return max(1, layout.controlWidth-3) + case dashboard: + if width >= 86 { + width -= 23 + } + return max(1, width-8) + default: + return max(1, width-4) + } +} + +func (m Model) updateInput(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "esc": + if m.searching { + m.input = nil + m.syncSearch() + } + m.editing, m.searching = false, false + m.editor.Blur() + case "enter": + if m.saveInput() { + m.searching = false + m.editor.Blur() + } + case "tab", "shift+tab", "up", "down": + if m.searching { + m.searching = false + m.editor.Blur() + return m, nil + } + if m.saveInput() { + delta := 1 + if msg.String() == "shift+tab" || msg.String() == "up" { + delta = -1 + } + next := m.focus + delta + if msg.String() == "tab" && next >= len(m.visibleFields()) { + m.buttonsFocused, m.buttonFocus = true, 1 + } else { + m.focus = max(0, min(len(m.visibleFields())-1, next)) + } + } + case "ctrl+r", "ctrl+enter": + if !m.searching && m.saveInput() { + m.prepareReview() + } + case "ctrl+f": + if m.screen == configure && m.saveInput() { + m.searching = true + m.startInput(m.fieldSearch, "Find an option…", false) + } + case "alt+/", "ctrl+space": + if m.editing { + m.completePath() + m.editor.SetValue(string(m.input)) + m.editor.CursorEnd() + } + case "alt+o": + if !m.searching { + fields := m.visibleFields() + if len(fields) > 0 { + return m, m.openPathDialog(m.form.Fields[fields[m.focus]]) + } + } + default: + return m, m.updateEditor(msg) + } + return m, nil +} + +func placeholder(field Field) string { + switch field.Name { + case "chat": + return "@channel, chat ID, or me for Saved Messages" + case "output", "dir", "path": + return "Folder path · Alt+/ completes a path" + case "desktop": + return "Leave empty to find your installed Telegram app" + case "since", "until": + return "YYYY-MM-DD or RFC3339 · empty means no limit" + case "proxy": + return "socks5://127.0.0.1:1080 · optional" + case "arguments": + if field.Required { + return "Enter " + field.Label + } + } + if field.Secret { + return "Hidden while you type" + } + return "Optional · leave empty to use the default" +} diff --git a/internal/tui/interaction.go b/internal/tui/interaction.go index 28165fa..12049bb 100644 --- a/internal/tui/interaction.go +++ b/internal/tui/interaction.go @@ -2,6 +2,7 @@ package tui import ( "fmt" + "slices" "strings" tea "charm.land/bubbletea/v2" @@ -11,6 +12,21 @@ import ( type button struct{ ID, Label string } func (m Model) buttons() []button { + if m.calendar != nil && !m.inlineCalendar() { + return []button{{"date-choose", "Choose"}, {"date-today", "Today"}, {"date-clear", "Clear"}, {"date-type", "Type date/time"}, {"date-cancel", "Cancel"}} + } + if m.pathDialog != nil { + return m.pathButtons() + } + if m.picker != nil && !m.inlinePicker() { + if m.picker.field == "ns" && len(m.picker.choices) == 0 { + return []button{{"picker-connect", "Connect account"}, {"picker-cancel", "Cancel"}} + } + if m.picker.multi { + return []button{{"picker-apply", "Apply selection"}, {"picker-all", "Select all"}, {"picker-clear", "Clear"}, {"picker-cancel", "Cancel"}} + } + return []button{{"picker-apply", "Choose"}, {"picker-cancel", "Cancel"}} + } switch m.screen { case dashboard: return []button{{"open", "Open"}, {"accounts", "Accounts"}, {"chats", "Chats"}, {"schedules", "Schedules"}} @@ -25,6 +41,12 @@ func (m Model) buttons() []button { return []button{{"cancel", "Cancel"}, {"input", "Respond"}, {"follow", "Follow latest"}} case result: if m.loading { + if len(m.data.Items) > 0 { + if len(m.checkedResults()) > 0 { + return []button{{"archive-selected", "Archive selected"}, {"cancel", "Stop loading"}, {"details", "Details"}} + } + return []button{{"archive", "Archive"}, {"export", "Export"}, {"cancel", "Stop loading"}, {"details", "Details"}, {"activity", "Activity"}} + } return []button{{"cancel", "Stop loading"}, {"details", "Details"}, {"activity", "Activity"}} } buttons := []button{} @@ -33,10 +55,18 @@ func (m Model) buttons() []button { } switch m.data.Kind { case "accounts": + if len(m.checkedResults()) > 0 { + buttons = append(buttons, button{"backup-selected", "Back up selected"}) + } buttons = append(buttons, button{"use", "Use account"}) case "chat ls": if len(m.data.Items) > 0 { - buttons = append(buttons, button{"archive", "Archive"}, button{"export", "Export"}, button{"members", "Members"}) + if len(m.checkedResults()) > 0 { + buttons = append(buttons, button{"archive-selected", "Archive selected"}) + } else { + buttons = append(buttons, button{"archive", "Archive"}) + } + buttons = append(buttons, button{"export", "Export"}, button{"members", "Members"}) } buttons = append(buttons, button{"refresh", "Refresh"}) if m.last.err != nil { @@ -140,6 +170,7 @@ func terminalKey(msg tea.KeyPressMsg) string { } func (m *Model) browse(action Action) tea.Cmd { m.source = nil + m.selectedResults = nil m.open(action) plan, err := m.form.Plan(m.base) if err != nil { @@ -153,12 +184,85 @@ func (m *Model) browse(action Action) tea.Cmd { return m.begin() } func (m *Model) activate(id string) tea.Cmd { + if m.calendar != nil { + if m.calendarAction(id) { + return nil + } + if id == "review" { + m.applyDatePicker(m.calendar.day.Format("2006-01-02")) + } else { + m.closeDatePicker() + } + } + if m.pathDialog != nil { + return m.pathAction(id) + } + if m.picker != nil { + switch id { + case "picker-add": + if strings.TrimSpace(m.picker.query.Value()) == "" { + m.picker.searching = true + m.picker.query.Focus() + } else { + m.picker.addCustom() + } + case "picker-apply": + m.applyPicker() + case "picker-cancel": + m.closePicker() + case "picker-all": + m.selectAllChoices() + case "picker-clear": + m.picker.clear() + case "picker-connect": + m.closePicker() + m.openPath("login", map[string]string{"type": "qr"}) + default: + if m.inlinePicker() { + m.applyPicker() + if m.picker == nil { + return m.activate(id) + } + } + } + m.buttonsFocused = false + return nil + } + if m.loading && (id == "archive" || id == "archive-selected" || id == "export" || id == "members") && len(m.resultItems()) > 0 { + m.pendingAction = id + m.pendingSelection = m.resultItems()[m.resultSelected].ID + m.cancelJob() + return nil + } if m.loading && id != "cancel" && id != "details" && id != "activity" { m.err = "Stop loading before starting another task." return nil } m.buttonsFocused = false switch id { + case "backup-selected", "archive-selected": + rows := m.checkedResults() + if len(rows) == 0 { + m.err = "Use Space to check the items to back up." + return nil + } + var selected []string + for _, row := range rows { + selected = append(selected, row.ID) + } + m.saveList() + if id == "backup-selected" { + m.accountSelection = selected + for _, name := range selected { + if !slices.Contains(m.accounts, name) { + m.accounts = append(m.accounts, name) + } + } + m.openPath("sync", map[string]string{"everything": "true", "format": "both"}) + } else { + m.selectBrowserAccount() + m.openPath("archive", map[string]string{"chat": csvString(selected), "media": "all", "format": "both"}) + } case "list": m.restoreList() case "home", "back": @@ -227,10 +331,15 @@ func (m *Model) activate(id string) tea.Cmd { return nil } m.globals["ns"] = row.ID + m.accountSelection = []string{row.ID} + if !slices.Contains(m.accounts, row.ID) { + m.accounts = append(m.accounts, row.ID) + } m.screen = dashboard m.err = "" case "archive": m.saveList() + m.selectBrowserAccount() m.openPath("archive", map[string]string{"chat": row.ID, "media": "all", "format": "both"}) case "export": m.saveList() @@ -257,7 +366,18 @@ func (m *Model) activate(id string) tea.Cmd { return nil } func (m Model) mouseClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { - if msg.Button != tea.MouseLeft || m.help || m.editing || m.searching { + if msg.Button != tea.MouseLeft || m.help || m.searching { + return m, nil + } + if m.pathDialog == nil && m.screen == configure { + if m.dateControlClick(msg) { + return m, nil + } + if handled, command := m.pathControlClick(msg); handled { + return m, command + } + } + if m.pathDialog == nil && m.editing && !m.saveInput() { return m, nil } width, height := m.width-4, m.height-7 @@ -289,8 +409,20 @@ func (m Model) mouseClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { } } bodyHeight := height - 2 + if m.pathDialog != nil { + return m, nil + } switch m.screen { case dashboard: + searchTop := 5 + if width < 86 { + searchTop += 2 + } + if msg.Y >= searchTop && msg.Y < searchTop+3 && (width < 86 || msg.X >= 25) { + m.searching = true + m.startInput(m.search, "Search workflows…", false) + return m, nil + } if width >= 86 && msg.X < 22 && msg.Y >= 5 { index := (msg.Y - 5) / 2 if index < len(Groups) { @@ -300,23 +432,32 @@ func (m Model) mouseClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { } return m, nil } - rowHeight := 3 - if bodyHeight < 23 { - rowHeight = 2 + listHeight := bodyHeight + if width < 86 { + listHeight -= 2 + } + rowHeight, _, start := m.actionListGeometry(listHeight) + listTop := 9 + if width < 86 { + listTop += 2 } - page := max(1, (bodyHeight-6)/rowHeight) - start := max(0, m.selected-page+1) - index := start + (msg.Y-7)/rowHeight + index := start + (msg.Y-listTop)/rowHeight actions := m.filteredActions() - if msg.Y >= 7 && index >= 0 && index < len(actions) { + if msg.Y >= listTop && index >= 0 && index < len(actions) { m.selected = index return m, m.activate("open") } case configure: - page := max(1, bodyHeight-11) - start := max(0, m.focus-page+1) - index := start + msg.Y - 8 - if msg.Y >= 8 && index >= 0 && index < len(m.visibleFields()) { + if len(m.visibleFields()) == 0 { + return m, nil + } + if handled, command := m.inlineChoiceClick(msg); handled { + return m, command + } + layout := m.formLayout(width, bodyHeight) + row := msg.Y - 3 - layout.top + index, fieldHit := layout.fieldAtRow(row) + if fieldHit && index < len(m.visibleFields()) { m.focus = index next, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) return next, cmd @@ -346,6 +487,18 @@ func (m Model) mouseClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { } func (m *Model) prepareReview() { + if m.calendar != nil { + m.applyDatePicker(m.calendar.day.Format("2006-01-02")) + } + if m.inlinePicker() { + m.applyPicker() + if m.picker != nil { + return + } + } + if !m.saveInput() { + return + } plan, err := m.form.Plan(m.base) if err != nil { m.err = err.Error() @@ -354,6 +507,13 @@ func (m *Model) prepareReview() { m.plan = plan for _, field := range m.form.Fields { if field.Global { + if field.Name == "ns" && field.Multi { + m.accountSelection, _ = readCSV(field.Value) + if len(m.accountSelection) == 1 { + m.globals["ns"] = m.accountSelection[0] + } + continue + } if field.Dirty { m.globals[field.Name] = field.Value } else { diff --git a/internal/tui/model.go b/internal/tui/model.go index 0a8f801..c7d8fb2 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -8,7 +8,11 @@ import ( "strings" "time" + "charm.land/bubbles/v2/progress" + "charm.land/bubbles/v2/spinner" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" + "github.com/mo1ein/TelegramArchive/internal/taskui" ) type screen int @@ -34,10 +38,18 @@ type Model struct { searching, advanced, editing, help bool input []rune cursor int + editor textinput.Model + meter progress.Model + loader spinner.Model + status *taskui.Progress + outputRevision uint64 + syncedOutput bool form Form plan Plan last finishedMsg loading bool + pendingAction string + pendingSelection string stage string taskCancel context.CancelFunc source *resultSnapshot @@ -54,13 +66,36 @@ type Model struct { buttonsFocused, responding, follow, cancelling bool started time.Time err string + accounts, accountSelection []string + accountLoader AccountLoader + accountsLoaded bool + accountError string + picker *choicePicker + batchIndex int + batchResults []accountOutcome + batchStarted time.Time + selectedResults map[string]bool + pathDialog *pathDialog + choosePath func(context.Context, pathRequest) ([]string, error) + chatLookup *chatLookup + chatChoiceKey [32]byte + calendar *datePicker } -func New(actions []Action, base []string, namespace string, ctx context.Context) Model { - return Model{actions: actions, base: slices.Clone(base), globals: map[string]string{"ns": namespace}, ctx: ctx, run: RunCommand, width: 100, height: 32} +func New(actions []Action, base []string, namespace string, ctx context.Context, options ...Option) Model { + m := Model{actions: actions, base: slices.Clone(base), globals: map[string]string{"ns": namespace}, ctx: ctx, run: RunCommand, width: 100, height: 32, + editor: textinput.New(), meter: newProgress(), + loader: spinner.New(spinner.WithSpinner(spinner.MiniDot), spinner.WithStyle(accent)), choosePath: chooseNativePath} + if namespace != "" { + m.accounts, m.accountSelection = []string{namespace}, []string{namespace} + } + for _, option := range options { + option(&m) + } + return m } -func (m Model) Init() tea.Cmd { return nil } +func (m Model) Init() tea.Cmd { return m.loadAccounts() } func (m Model) filteredActions() []Action { var out []Action @@ -98,6 +133,11 @@ func (m Model) visibleFields() []int { if !m.advanced && field.Advanced && m.fieldSearch == "" { continue } + if !m.advanced && m.fieldSearch == "" && strings.Join(m.form.Action.Path, " ") == "login" && (field.Name == "desktop" || field.Name == "passcode") { + if method := m.form.field("type"); method != nil && method.Value != "desktop" { + continue + } + } if matches(field.Label+" "+field.Name+" "+field.Help, m.fieldSearch) { out = append(out, i) } @@ -106,7 +146,14 @@ func (m Model) visibleFields() []int { } func (m *Model) open(action Action) { + m.calendar = nil + m.closePathDialog() + m.closePicker() + m.chatChoiceKey = [32]byte{} m.form = NewForm(action, m.globals) + m.configureAccountField() + m.configureChatField() + m.picker = nil m.screen, m.focus, m.scroll, m.err = configure, 0, 0, "" m.advanced, m.editing, m.searching = false, false, false m.fieldSearch = "" @@ -116,9 +163,69 @@ func (m *Model) open(action Action) { } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + // Remember the viewport just displayed before moving the cursor. Clicking + // a visible checkbox must leave the list in the same place under the mouse. + if m.inlinePicker() { + p := m.picker + p.offset = choiceListWindow(m.inlineChoiceBounds().height, len(p.filtered()), p.cursor, p.offset).start + } switch msg := msg.(type) { + case chatLookupStartedMsg: + return m, m.chatLookupStarted(msg) + case chatLookupPollMsg: + return m, m.pollChatChoices(msg.lookup) + case pathSelectedMsg: + return m, m.pathDialogResult(msg) + case pathDirectoryMsg: + if m.pathDialog != msg.dialog || msg.dialog.browser == nil || msg.dialog.browser.revision != msg.revision { + return m, nil + } + b := m.pathDialog.browser + b.loading, b.entries = false, msg.entries + if msg.err != nil { + b.err = safeText(msg.err.Error()) + } + return m, nil + case accountsLoadedMsg: + previousAccount := "" + if field := m.form.field("ns"); field != nil { + previousAccount = field.Value + } + m.accountsLoaded = true + m.accountError = "" + if msg.err != nil { + m.accountError = msg.err.Error() + } else { + m.accounts = slices.Clone(msg.names) + } + if m.screen == configure { + m.configureAccountField() + if field := m.form.field("ns"); field != nil && field.Value != previousAccount { + m.resetChatSelection() + } + } + if m.picker != nil && m.picker.field == "ns" { + m.picker.choices = slices.Clone(m.accounts) + m.picker.cursor = 0 + } + return m, nil case tea.WindowSizeMsg: m.width, m.height = msg.Width, msg.Height + if m.pathDialog != nil && m.pathDialog.browser != nil { + b := m.pathDialog.browser + b.query.SetWidth(max(1, m.width-7)) + b.name.SetWidth(max(1, m.width-16)) + b.query, _ = b.query.Update(nil) + b.name, _ = b.name.Update(nil) + } + if m.picker != nil { + m.picker.query.SetWidth(max(1, min(60, m.formLayout(m.width-4, m.height-9).controlWidth)-5)) + m.picker.query, _ = m.picker.query.Update(nil) + } + if m.editing || m.searching { + m.editor.SetWidth(m.editorWidth()) + m.editor, _ = m.editor.Update(nil) + } if m.job != nil { m.job.mu.Lock() if m.job.resize != nil { @@ -129,6 +236,13 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.job.mu.Unlock() } return m, nil + case progress.FrameMsg: + if m.screen != running { + return m, nil + } + var command tea.Cmd + m.meter, command = m.meter.Update(msg) + return m, command case startedMsg: m.job = msg.job if m.cancelling { @@ -145,12 +259,22 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.job == nil { return m, nil } + m.loader, _ = m.loader.Update(m.loader.Tick()) m.job.mu.Lock() - m.output = redactOutput(m.job.terminal.text()) - m.progress = append([]string(nil), m.job.terminal.progress...) + if !m.syncedOutput || m.outputRevision != m.job.revision { + m.output = redactOutput(m.job.terminal.text()) + m.progress = append([]string(nil), m.job.terminal.progress...) + if m.job.terminal.status != nil { + status := *m.job.terminal.status + m.status = &status + } + m.outputRevision, m.syncedOutput = m.job.revision, true + } m.stage = m.job.stage if m.job.streamSeen { - m.data = resultData{Kind: "chat ls", Items: append([]item(nil), m.job.items...)} + if m.data.Kind != "chat ls" || len(m.data.Items) != len(m.job.items) { + m.data = resultData{Kind: "chat ls", Items: append([]item(nil), m.job.items...)} + } if len(m.data.Items) > 0 { m.screen = result m.loading = !m.job.done @@ -183,13 +307,33 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.taskCancel != nil { m.taskCancel() } + if command, handled := m.finishAccount(m.last); handled { + return m, command + } m.responding = false m.buttonFocus = 0 if m.data.Kind == "" || (m.last.err != nil && len(m.data.Items) == 0) { m.resultTab = 1 } + if m.pendingAction != "" { + action := m.pendingAction + rows := m.resultItems() + selected := slices.IndexFunc(rows, func(row item) bool { return row.ID == m.pendingSelection }) + if selected < 0 { + m.resultSearch = "" + selected = slices.IndexFunc(m.resultItems(), func(row item) bool { return row.ID == m.pendingSelection }) + } + m.resultSelected = max(0, selected) + m.pendingAction = "" + m.pendingSelection = "" + m.cancelling = false + return m, m.activate(action) + } return m, nil } + if m.status != nil && m.status.Determinate && m.meter.Percent() != m.status.Percent { + return m, tea.Batch(poll(), m.meter.SetPercent(m.status.Percent)) + } return m, poll() case inputErrorMsg: if msg.err != nil { @@ -197,13 +341,57 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, nil case tea.MouseClickMsg: + if m.pathDialog != nil { + return m.pathDialogClick(msg) + } + if m.picker != nil { + return m.pickerClick(msg) + } + if m.calendar != nil { + return m.datePickerClick(msg) + } return m.mouseClick(msg) case tea.MouseWheelMsg: delta := 3 if msg.Button == tea.MouseWheelUp { delta = -3 } - if m.screen == result && m.resultTab == 0 { + if m.calendar != nil { + if m.calendarBounds().contains(msg.X, msg.Y) { + m.calendar.moveMonth(delta / 3) + } + return m, nil + } + if m.pathDialog != nil { + if b := m.pathDialog.browser; b != nil { + b.cursor = max(0, min(max(0, len(b.filtered())-1), b.cursor+delta)) + } + return m, nil + } + if m.picker != nil { + if !m.inlinePicker() || m.inlineChoiceBounds().contains(msg.X, msg.Y) { + step := delta + if m.inlinePicker() { + p := m.picker + rows := choiceListWindow(m.inlineChoiceBounds().height, len(p.filtered()), p.cursor, p.offset).rows + step = min(3, rows) + if delta < 0 { + step = -step + } + } + m.picker.cursor = max(0, min(max(0, len(m.picker.filtered())-1), m.picker.cursor+step)) + return m, nil + } + m.applyPicker() + if m.picker != nil { + return m, nil + } + } + if m.screen == configure && !m.searching { + if m.saveInput() { + m.focus = max(0, min(max(0, len(m.visibleFields())-1), m.focus+delta)) + } + } else if m.screen == result && m.resultTab == 0 { m.resultSelected = max(0, min(max(0, len(m.resultItems())-1), m.resultSelected+delta)) } else if m.screen == running || m.screen == result { m.scrollActivity(delta) @@ -215,27 +403,79 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.taskCancel != nil { m.taskCancel() } + if command, handled := m.finishAccount(msg); handled { + return m, command + } m.resultTab = 1 m.last, m.screen, m.scroll = msg, result, 0 return m, nil case tea.PasteMsg: + if m.calendar != nil { + m.typeDate() + return m, m.updateEditor(msg) + } + if m.pathDialog != nil { + if b := m.pathDialog.browser; b != nil { + if b.naming { + b.name, _ = b.name.Update(msg) + } else { + b.searching = true + b.query.Focus() + b.query, _ = b.query.Update(msg) + b.cursor = 0 + } + } + return m, nil + } + if m.picker != nil { + m.picker.searching = true + m.picker.query.Focus() + m.picker.query, _ = m.picker.query.Update(msg) + m.picker.cursor = 0 + return m, nil + } if m.screen == running && m.responding && m.job != nil { return m, m.sendInput(msg.Content) } + if !m.editing && !m.searching && m.screen == configure { + fields := m.visibleFields() + if len(fields) > 0 && choiceField(m.form.Fields[fields[m.focus]]) { + command := m.openPicker(m.form.Fields[fields[m.focus]]) + m.picker.searching = true + m.picker.query.Focus() + m.picker.query, _ = m.picker.query.Update(msg) + return m, command + } + if len(fields) > 0 && m.form.Fields[fields[m.focus]].Type != "bool" && len(m.form.Fields[fields[m.focus]].Choices) == 0 { + m.editField() + } + } if m.editing || m.searching { - m.insert(strings.NewReplacer("\n", " ", "\r", " ", "\t", " ").Replace(msg.Content)) - m.syncSearch() + return m, m.updateEditor(msg) } return m, nil case tea.KeyPressMsg: key := msg.String() + if m.pathDialog != nil { + return m.updatePathDialog(msg) + } if key == "ctrl+c" { + if m.chatLookup != nil { + m.stopChatLookup() + return m, nil + } if m.screen == running || m.loading { m.cancelJob() return m, nil } return m, tea.Quit } + if m.picker != nil { + return m.updatePicker(msg) + } + if m.calendar != nil { + return m.updateDatePicker(msg) + } if m.screen == running && m.responding { if key == "esc" { m.responding = false @@ -269,6 +509,10 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.buttonFocus = 0 return m, nil } + if m.screen == configure && m.buttonsFocused && key == "shift+tab" { + m.buttonsFocused = false + return m, nil + } if m.buttonsFocused && (key == "tab" || key == "shift+tab") { delta := 1 if key == "shift+tab" { @@ -335,7 +579,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.selected, m.search = 0, "" case "/": m.searching = true - m.input, m.cursor = []rune(m.search), len([]rune(m.search)) + m.startInput(m.search, "Search workflows…", false) case "esc": m.search, m.selected = "", 0 case "enter": @@ -349,6 +593,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } case configure: fields := m.visibleFields() + m.focus = max(0, min(max(0, len(fields)-1), m.focus)) switch key { case "esc": if m.source != nil && m.fieldSearch == "" { @@ -360,10 +605,14 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } else { m.screen, m.err = dashboard, "" } - case "up", "k", "shift+tab": + case "up", "shift+tab": m.focus = max(0, m.focus-1) - case "down", "j", "tab": - m.focus = min(max(0, len(fields)-1), m.focus+1) + case "down", "tab": + if key == "tab" && m.focus == len(fields)-1 { + m.buttonsFocused, m.buttonFocus = true, 1 + } else { + m.focus = min(max(0, len(fields)-1), m.focus+1) + } case "pgdown": m.focus = min(max(0, len(fields)-1), m.focus+8) case "pgup": @@ -371,17 +620,28 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case "ctrl+a": m.advanced = !m.advanced m.focus = 0 - case "/": + case "ctrl+f": m.searching = true - m.input, m.cursor = []rune(m.fieldSearch), len([]rune(m.fieldSearch)) - case "ctrl+r": + m.startInput(m.fieldSearch, "Find an option…", false) + case "ctrl+r", "ctrl+enter": m.prepareReview() + case "alt+o": + if len(fields) > 0 { + return m, m.openPathDialog(m.form.Fields[fields[m.focus]]) + } case "enter", "space", " ", "right", "left": if len(fields) == 0 { break } field := &m.form.Fields[fields[m.focus]] + if dateField(*field) && key != "left" { + m.openDatePicker(*field) + return m, nil + } + if field.PathKind != "" && key == "enter" { + return m, m.openPathDialog(*field) + } if field.Type == "bool" { if field.Value == "true" { field.Value = "false" @@ -389,14 +649,34 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { field.Value = "true" } field.Dirty, m.err = true, "" - } else if key != "enter" && len(field.Choices) > 0 && !strings.Contains(field.Type, "Slice") { + m.form.reconcileSelection(field.Name) + } else if choiceField(*field) { + if field.Multi && key == "left" { + return m, nil + } + if field.Multi || key == "enter" || field.Type == "accounts" { + return m, m.openPicker(*field) + } next := slices.Index(field.Choices, field.Value) + 1 if key == "left" { next -= 2 } field.Value, field.Dirty = field.Choices[(next+len(field.Choices))%len(field.Choices)], true } else { - m.input, m.cursor, m.editing = []rune(field.Value), len([]rune(field.Value)), true + m.editField() + } + default: + if msg.Text != "" && len(fields) > 0 { + field := m.form.Fields[fields[m.focus]] + if choiceField(field) { + command := m.openPicker(field) + next, _ := m.updatePicker(msg) + return next, command + } + if field.Type != "bool" && len(field.Choices) == 0 { + m.editField() + return m, m.updateEditor(msg) + } } case "ctrl+d": if len(fields) > 0 { @@ -418,12 +698,28 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.scroll++ } case result: - if m.loading && (key == "esc" || key == "e" || key == "r" || key == "a" || key == "s") { + if m.loading && (key == "esc" || key == "e" || key == "r" || key == "s") { m.cancelJob() return m, nil } rows := m.resultItems() switch key { + case "space", " ": + if (m.data.Kind == "accounts" || m.data.Kind == "chat ls") && len(rows) > 0 { + row := rows[m.resultSelected] + if m.data.Kind == "accounts" && row.Status != "ready" { + m.err = "Choose an available account." + break + } + if m.selectedResults == nil { + m.selectedResults = map[string]bool{} + } + m.selectedResults[row.ID] = !m.selectedResults[row.ID] + } + case "b": + if m.data.Kind == "accounts" { + return m, m.activate("backup-selected") + } case "esc": if m.resultSearch != "" { m.resultSearch = "" @@ -462,8 +758,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.resultSelected = min(max(0, len(rows)-1), m.resultSelected+8) case "/": m.searching = true - m.input = []rune(m.resultSearch) - m.cursor = len(m.input) + m.startInput(m.resultSearch, "Search this list…", false) case "l": m.resultTab = 1 m.scroll = 0 @@ -495,74 +790,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } -func (m Model) updateInput(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { - switch msg.String() { - case "esc": - if m.searching { - m.input = nil - m.syncSearch() - } - m.editing, m.searching = false, false - case "enter": - if m.editing { - fields := m.visibleFields() - if len(fields) > 0 { - field := &m.form.Fields[fields[m.focus]] - field.Value, field.Dirty = string(m.input), true - m.err = "" - } - } - m.editing, m.searching = false, false - case "left": - m.cursor = max(0, m.cursor-1) - case "right": - m.cursor = min(len(m.input), m.cursor+1) - case "home", "ctrl+a": - m.cursor = 0 - case "end", "ctrl+e": - m.cursor = len(m.input) - case "backspace": - if m.cursor > 0 { - m.input = slices.Delete(m.input, m.cursor-1, m.cursor) - m.cursor-- - } - case "delete": - if m.cursor < len(m.input) { - m.input = slices.Delete(m.input, m.cursor, m.cursor+1) - } - case "ctrl+u": - m.input, m.cursor = nil, 0 - case "ctrl+k": - m.input = m.input[:m.cursor] - case "ctrl+w": - start := m.cursor - for start > 0 && m.input[start-1] == ' ' { - start-- - } - for start > 0 && m.input[start-1] != ' ' { - start-- - } - m.input = slices.Delete(m.input, start, m.cursor) - m.cursor = start - case "tab": - if m.editing { - m.completePath() - } - default: - if msg.Text != "" { - m.insert(msg.Text) - } - } - m.syncSearch() - return m, nil -} - -func (m *Model) insert(value string) { - runes := []rune(value) - m.input = slices.Insert(m.input, m.cursor, runes...) - m.cursor += len(runes) -} - func (m *Model) syncSearch() { if !m.searching { return diff --git a/internal/tui/path_browser.go b/internal/tui/path_browser.go new file mode 100644 index 0000000..928704b --- /dev/null +++ b/internal/tui/path_browser.go @@ -0,0 +1,414 @@ +package tui + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "strings" + + "charm.land/bubbles/v2/textinput" + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" +) + +type pathEntry struct { + name, path string + directory bool +} + +type pathBrowser struct { + directory string + entries []pathEntry + cursor int + revision uint64 + loading bool + showHidden bool + searching bool + naming bool + err string + query, name textinput.Model + selected map[string]bool +} + +type pathDirectoryMsg struct { + dialog *pathDialog + revision uint64 + directory string + entries []pathEntry + err error +} + +func (m *Model) openPathBrowser() tea.Cmd { + directory, name, err := pathLocation(m.pathDialog.request.Initial) + b := &pathBrowser{directory: directory, query: textinput.New(), name: textinput.New(), selected: map[string]bool{}} + for _, input := range []*textinput.Model{&b.query, &b.name} { + input.Prompt, input.CharLimit = "", 4096 + input.SetVirtualCursor(true) + styles := textinput.DefaultDarkStyles() + styles.Focused.Text, styles.Cursor.Blink = textStyle, false + input.SetStyles(styles) + } + b.query.Placeholder = "Type to find a file or folder…" + b.query.SetWidth(max(1, m.width-7)) + b.name.SetWidth(max(1, m.width-16)) + if m.pathDialog.request.Initial == "" { + name = "backup.ta" + } + b.name.SetValue(name) + m.pathDialog.browser = b + if err != nil { + b.err = safeText(err.Error()) + b.directory, _ = os.Getwd() + return nil + } + return m.readPathDirectory(directory) +} + +func (m *Model) readPathDirectory(directory string) tea.Cmd { + dialog, b := m.pathDialog, m.pathDialog.browser + b.revision++ + b.loading, b.err, b.directory, b.cursor, b.entries = true, "", directory, 0, nil + b.query.SetValue("") + b.searching = false + revision := b.revision + return func() tea.Msg { + msg := pathDirectoryMsg{dialog: dialog, revision: revision, directory: directory} + if msg.err = dialog.ctx.Err(); msg.err != nil { + return msg + } + entries, err := os.ReadDir(directory) + msg.err = err + for _, entry := range entries { + path, isDir := filepath.Join(directory, entry.Name()), entry.IsDir() + if entry.Type()&os.ModeSymlink != 0 { + if info, err := os.Stat(path); err == nil { + isDir = info.IsDir() + } + } + if dialog.request.Kind == "directory" && !isDir { + continue + } + msg.entries = append(msg.entries, pathEntry{entry.Name(), path, isDir}) + } + slices.SortStableFunc(msg.entries, func(a, b pathEntry) int { + if a.directory != b.directory { + if a.directory { + return -1 + } + return 1 + } + return strings.Compare(a.name, b.name) + }) + return msg + } +} + +func (b *pathBrowser) filtered() []pathEntry { + var entries []pathEntry + for _, entry := range b.entries { + if (!strings.HasPrefix(entry.name, ".") || b.showHidden) && matches(entry.name, b.query.Value()) { + entries = append(entries, entry) + } + } + return entries +} + +func (d *pathDialog) canSelect(entry pathEntry) bool { + return d.request.Kind == "any" || (d.request.Kind == "directory" && entry.directory) || (d.request.Kind != "directory" && !entry.directory) +} + +func (m Model) pathButtons() []button { + if m.pathDialog.browser == nil { + return []button{{"path-cancel", "Cancel chooser"}} + } + label := "Choose file" + switch m.pathDialog.request.Kind { + case "directory", "any": + label = "Use this folder" + case "save": + label = "Save here" + } + if m.pathDialog.request.Multiple { + label = "Use selected" + } + return []button{{"path-open", "Open"}, {"path-choose", label}, {"path-up", "Up"}, {"path-home", "Home"}, {"path-cancel", "Cancel"}} +} + +func (m *Model) pathAction(id string) tea.Cmd { + dialog := m.pathDialog + if id == "path-cancel" { + m.closePathDialog() + m.buttonsFocused = false + return nil + } + b := dialog.browser + if b == nil || b.loading { + return nil + } + rows := b.filtered() + if b.cursor >= len(rows) { + b.cursor = max(0, len(rows)-1) + } + switch id { + case "path-up": + return m.readPathDirectory(filepath.Dir(b.directory)) + case "path-home": + home, err := os.UserHomeDir() + if err != nil { + b.err = safeText(err.Error()) + return nil + } + return m.readPathDirectory(home) + case "path-open": + if len(rows) > 0 { + row := rows[b.cursor] + if row.directory { + return m.readPathDirectory(row.path) + } + if dialog.request.Kind == "save" { + b.name.SetValue(row.name) + return nil + } + if dialog.request.Multiple { + b.selected[row.path] = !b.selected[row.path] + } else { + m.acceptPaths([]string{row.path}) + } + } + case "path-choose": + var paths []string + if dialog.request.Multiple { + for path, checked := range b.selected { + if checked { + paths = append(paths, path) + } + } + slices.Sort(paths) + } else { + switch dialog.request.Kind { + case "directory", "any": + paths = []string{b.directory} + case "save": + name := b.name.Value() + if name == "" || name == "." || name == ".." || filepath.Base(name) != name { + b.err = "Enter a filename with F2. Choose the folder by browsing." + return nil + } + paths = []string{filepath.Join(b.directory, name)} + default: + if len(rows) > 0 && !rows[b.cursor].directory { + paths = []string{rows[b.cursor].path} + } + } + } + if len(paths) == 0 { + b.err = "Select at least one file or folder with Space." + return nil + } + m.acceptPaths(paths) + } + return nil +} + +func (m Model) updatePathDialog(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { + key := msg.String() + if key == "esc" || key == "ctrl+c" { + m.closePathDialog() + return m, nil + } + b := m.pathDialog.browser + if b == nil { + return m, nil + } + if b.naming { + switch key { + case "enter", "tab": + b.naming = false + b.name.Blur() + default: + b.name, _ = b.name.Update(msg) + } + return m, nil + } + if key == "tab" || key == "shift+tab" || key == "f6" { + if !m.buttonsFocused { + m.buttonsFocused, m.buttonFocus = true, 0 + } else { + delta := 1 + if key == "shift+tab" { + delta = -1 + } + m.buttonFocus = (m.buttonFocus + len(m.buttons()) + delta) % len(m.buttons()) + } + return m, nil + } + if m.buttonsFocused && key == "enter" { + return m, m.pathAction(m.buttons()[m.buttonFocus].ID) + } + m.buttonsFocused = false + rows := b.filtered() + switch key { + case "up", "down", "pgup", "pgdown", "home", "end": + if b.searching { + b.searching = false + b.query.Blur() + return m, nil + } + delta := 1 + switch key { + case "up": + delta = -1 + case "pgup": + delta = -max(1, m.height-17) + case "pgdown": + delta = max(1, m.height-17) + case "home": + b.cursor = 0 + return m, nil + case "end": + b.cursor = max(0, len(rows)-1) + return m, nil + } + b.cursor = max(0, min(max(0, len(rows)-1), b.cursor+delta)) + case "enter", "right": + b.searching = false + return m, m.pathAction("path-open") + case "left", "backspace": + if b.searching { + b.query, _ = b.query.Update(msg) + b.cursor = 0 + } else { + return m, m.pathAction("path-up") + } + case "ctrl+enter": + return m, m.pathAction("path-choose") + case "ctrl+h": + b.showHidden, b.cursor = !b.showHidden, 0 + case "f2": + if m.pathDialog.request.Kind == "save" { + b.naming = true + b.name.Focus() + } + case "space", " ": + if !b.searching && len(rows) > 0 { + row := rows[b.cursor] + if !m.pathDialog.canSelect(row) { + return m, m.pathAction("path-open") + } + if m.pathDialog.request.Multiple { + b.selected[row.path] = !b.selected[row.path] + } else if m.pathDialog.request.Kind != "save" { + m.acceptPaths([]string{row.path}) + } + return m, nil + } + fallthrough + default: + if msg.Text != "" || key == "ctrl+u" || key == "delete" { + b.searching = true + b.query.Focus() + b.query, _ = b.query.Update(msg) + b.cursor = 0 + } + } + return m, nil +} + +func (m Model) pathDialogView(width, height int) string { + d := m.pathDialog + caption := "Choose a file" + if d.request.Kind == "directory" { + caption = "Choose a folder" + } else if d.request.Kind == "save" { + caption = "Choose where to save" + } + lines := []string{titleStyle.Render(caption + " · " + d.request.Title)} + if d.browser == nil { + return strings.Join(append(lines, "", accent.Render("Opening the macOS chooser…"), "", dim.Render("Choose a location in the system dialog, or cancel to keep the current path.")), "\n") + } + b := d.browser + query, name := b.query, b.name + query.SetWidth(max(1, width-3)) + name.SetWidth(max(1, width-12)) + lines = append(lines, dim.Render("Enter opens · Space selects · Ctrl+Enter confirms · Ctrl+H hidden"), accent.Render(clip("Location "+safeText(b.directory), width)), dim.Render("⌕ ")+query.View(), "") + rows, page := b.filtered(), max(1, height-8) + start := max(0, b.cursor-page+1) + var list []string + for index := start; index < min(len(rows), start+page); index++ { + row := rows[index] + mark, style := " ", textStyle + if d.request.Multiple && d.canSelect(row) { + mark = "○ " + if b.selected[row.path] { + mark = "✓ " + } + } + label := safeText(row.name) + if row.directory { + label += "/" + style = accent + } + pointer := " " + if index == b.cursor { + pointer, style = "▸ ", selectedStyle.Bold(true).Width(width) + } + list = append(list, style.Render(clip(pointer+mark+label, width))) + } + if len(rows) == 0 { + text := "No matching files or folders. Try clearing the search or showing hidden items." + if b.loading { + text = "Loading folder…" + } + list = append(list, dim.Render(ansi.Wrap(text, width, ""))) + } + lines = append(lines, fit(strings.Join(list, "\n"), width, page)) + filename := "" + if d.request.Kind == "save" { + filename = dim.Render("Filename ") + name.View() + dim.Render(" F2 to edit") + } + lines = append(lines, clip(filename, width)) + count := fmt.Sprintf("%d items", len(rows)) + if d.request.Multiple { + selected := 0 + for _, checked := range b.selected { + if checked { + selected++ + } + } + count += fmt.Sprintf(" · %d selected", selected) + } + lines = append(lines, dim.Render(count), warning.Render(clip(b.err, width))) + return strings.Join(lines, "\n") +} + +func (m Model) pathDialogClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { + if msg.Button != tea.MouseLeft { + return m, nil + } + if msg.Y == m.height-5 { + return m.mouseClick(msg) + } + b := m.pathDialog.browser + if b == nil || b.loading { + return m, nil + } + if msg.Y == 6 { + b.searching = true + b.query.Focus() + return m, nil + } + page, row := max(1, m.height-17), msg.Y-8 + rows := b.filtered() + index := max(0, b.cursor-page+1) + row + if row >= 0 && row < page && index < len(rows) { + b.cursor, b.searching = index, false + b.query.Blur() + if m.pathDialog.request.Multiple && m.pathDialog.canSelect(rows[index]) && msg.X < 7 { + b.selected[rows[index].path] = !b.selected[rows[index].path] + return m, nil + } + return m, m.pathAction("path-open") + } + return m, nil +} diff --git a/internal/tui/path_dialog.go b/internal/tui/path_dialog.go new file mode 100644 index 0000000..5326485 --- /dev/null +++ b/internal/tui/path_dialog.go @@ -0,0 +1,257 @@ +package tui + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + tea "charm.land/bubbletea/v2" + "github.com/kballard/go-shellquote" + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +func flagPathKind(path []string, flag *pflag.Flag) string { + if kind := flag.Annotations["ta:path"]; len(kind) > 0 { + return kind[0] + } + command := strings.Join(path, " ") + if flag.Name == "output" { + switch command { + case "archive", "account", "sync", "cron add": + return "directory" + case "chat export", "chat users": + return "save" + } + } + if command == "backup" && flag.Name == "dst" { + return "save" + } + if command == "upload" && flag.Name == "path" { + return "any" + } + if command == "download" && flag.Name == "file" { + return "open" + } + if _, ok := flag.Annotations[cobra.BashCompSubdirsInDir]; ok { + return "directory" + } + if _, ok := flag.Annotations[cobra.BashCompFilenameExt]; ok { + return "open" + } + if flag.Name == "dir" || (command == "login" && flag.Name == "desktop") { + return "directory" + } + return "" +} + +type pathRequest struct { + Title, Kind, Initial string + Multiple bool +} + +type pathDialog struct { + field string + request pathRequest + ctx context.Context + cancel context.CancelFunc + browser *pathBrowser +} + +type pathSelectedMsg struct { + dialog *pathDialog + paths []string + err error +} + +var errPathDialogUnavailable = errors.New("system path dialog unavailable") + +func (m *Model) openPathDialog(field Field) tea.Cmd { + if m.pathDialog != nil || field.PathKind == "" { + return nil + } + value := field.Value + if m.editing { + value = m.editor.Value() + } + if field.Type == "arguments" { + if paths, err := shellquote.Split(value); err == nil && len(paths) > 0 { + value = paths[0] + } + } else if field.Multi { + if paths, err := readCSV(value); err == nil && len(paths) > 0 { + value = paths[0] + } + } + ctx, cancel := context.WithCancel(m.ctx) + dialog := &pathDialog{field: field.Name, request: pathRequest{Title: field.Label, Kind: field.PathKind, Initial: value, Multiple: field.PathMultiple}, ctx: ctx, cancel: cancel} + m.pathDialog, m.err, m.buttonsFocused = dialog, "", false + choose := m.choosePath + return func() tea.Msg { + paths, err := choose(ctx, dialog.request) + return pathSelectedMsg{dialog, paths, err} + } +} + +func (m *Model) closePathDialog() { + if m.pathDialog != nil { + m.pathDialog.cancel() + m.pathDialog = nil + m.buttonsFocused = false + } +} + +func (m *Model) pathDialogResult(msg pathSelectedMsg) tea.Cmd { + if msg.dialog != m.pathDialog { + return nil + } + if errors.Is(msg.err, errPathDialogUnavailable) { + return m.openPathBrowser() + } + if msg.err != nil { + m.err = safeText(msg.err.Error()) + m.closePathDialog() + return nil + } + m.acceptPaths(msg.paths) + return nil +} + +func (m *Model) pathControlClick(msg tea.MouseClickMsg) (bool, tea.Cmd) { + fields := m.visibleFields() + if len(fields) == 0 || m.focus >= len(fields) { + return false, nil + } + field := m.form.Fields[fields[m.focus]] + if field.PathKind == "" { + return false, nil + } + g := m.formLayout(m.width-4, m.height-9) + x, y, width := 2+g.controlX, 3+g.top+g.fieldRow(m.focus), g.controlWidth + if msg.X < x || msg.X >= x+width || msg.Y < y || msg.Y > y+1 { + return false, nil + } + if msg.Y == y+1 && msg.X >= x+12 && msg.X < x+25 { + if !m.editing { + m.editField() + } + return true, nil + } + if msg.Y == y+1 && msg.X >= x+11 { + return false, nil + } + if m.editing && msg.Y != y+1 { + return false, nil + } + return true, m.openPathDialog(field) +} + +func (m *Model) acceptPaths(paths []string) { + dialog := m.pathDialog + if dialog == nil { + return + } + if len(paths) == 0 { + m.closePathDialog() + return + } + field := m.form.field(dialog.field) + if field == nil || m.screen != configure { + m.closePathDialog() + return + } + err := checkPaths(dialog.request, paths) + if err == nil { + copy := *field + copy.Value, copy.Dirty = paths[0], true + if copy.Type == "arguments" { + copy.Value = shellquote.Join(paths...) + } else if copy.Multi { + copy.Value = csvString(paths) + } + err = validate(copy) + if err == nil { + *field = copy + m.editing, m.err = false, "" + m.editor.Blur() + } + } + if err != nil { + m.err = safeText(err.Error()) + if dialog.browser != nil { + dialog.browser.err = m.err + return + } + } + m.closePathDialog() +} + +func checkPaths(request pathRequest, paths []string) error { + if !request.Multiple && len(paths) != 1 { + return fmt.Errorf("choose one path") + } + for _, path := range paths { + info, err := os.Stat(path) + if request.Kind == "save" && os.IsNotExist(err) { + parent, parentErr := os.Stat(filepath.Dir(path)) + if parentErr != nil || !parent.IsDir() { + return fmt.Errorf("choose an existing destination folder") + } + continue + } + if err != nil { + return fmt.Errorf("read selected path: %w", err) + } + switch request.Kind { + case "directory": + if !info.IsDir() { + return fmt.Errorf("choose a folder") + } + case "open", "save": + if !info.Mode().IsRegular() { + return fmt.Errorf("choose a file") + } + case "any": + if !info.IsDir() && !info.Mode().IsRegular() { + return fmt.Errorf("choose a file or folder") + } + } + } + return nil +} + +// Start from the closest existing folder, including when a destination is new. +func pathLocation(initial string) (directory, name string, err error) { + if initial == "~" || strings.HasPrefix(initial, "~/") { + home, homeErr := os.UserHomeDir() + if homeErr != nil { + return "", "", homeErr + } + initial = filepath.Join(home, strings.TrimPrefix(strings.TrimPrefix(initial, "~"), "/")) + } + if initial == "" { + initial = "." + } + path, err := filepath.Abs(initial) + if err != nil { + return "", "", err + } + name = filepath.Base(path) + for { + info, statErr := os.Stat(path) + if statErr == nil && info.IsDir() { + return path, name, nil + } + if statErr != nil && !os.IsNotExist(statErr) { + return "", "", statErr + } + parent := filepath.Dir(path) + if parent == path { + return "", "", fmt.Errorf("could not find a starting folder") + } + path = parent + } +} diff --git a/internal/tui/path_dialog_native.go b/internal/tui/path_dialog_native.go new file mode 100644 index 0000000..5ca8f1e --- /dev/null +++ b/internal/tui/path_dialog_native.go @@ -0,0 +1,78 @@ +package tui + +import ( + "context" + "fmt" + "os" + "os/exec" + "runtime" + "strconv" + "strings" +) + +// Dynamic values travel as process arguments, never as script source or +// shell code. NUL delimiters preserve filenames containing commas or newlines. +const macPathDialogScript = `ObjC.import('AppKit'); +function run(argv) { + var kind = argv[0]; + var panel = kind === 'save' ? $.NSSavePanel.savePanel : $.NSOpenPanel.openPanel; + panel.title = 'Telegram Archive'; + panel.message = argv[1]; + panel.directoryURL = $.NSURL.fileURLWithPath(argv[2]); + panel.canCreateDirectories = true; + if (kind === 'save') { + panel.nameFieldStringValue = argv[3]; + } else { + panel.canChooseFiles = kind !== 'directory'; + panel.canChooseDirectories = kind === 'directory' || kind === 'any'; + panel.allowsMultipleSelection = argv[4] === 'true'; + } + var app = $.NSApplication.sharedApplication; + app.setActivationPolicy($.NSApplicationActivationPolicyAccessory); + app.activateIgnoringOtherApps(true); + if (Number(panel.runModal) !== Number($.NSModalResponseOK)) return ''; + var paths = []; + if (kind === 'save') { + paths.push(ObjC.unwrap(panel.URL.path)); + } else { + var urls = panel.URLs; + for (var index = 0; index < Number(urls.count); index++) { + paths.push(ObjC.unwrap(urls.objectAtIndex(index).path)); + } + } + return paths.join('\u0000') + '\u0000'; +}` + +func chooseNativePath(ctx context.Context, request pathRequest) ([]string, error) { + if runtime.GOOS != "darwin" || os.Getenv("SSH_CONNECTION") != "" || os.Getenv("SSH_TTY") != "" { + return nil, errPathDialogUnavailable + } + directory, name, err := pathLocation(request.Initial) + if err != nil { + return nil, err + } + if request.Kind == "save" && request.Initial == "" { + name = "backup.ta" + } + command := exec.CommandContext(ctx, "/usr/bin/osascript", "-l", "JavaScript", "-", request.Kind, "Telegram Archive · "+request.Title, directory, name, strconv.FormatBool(request.Multiple)) + command.Stdin = strings.NewReader(macPathDialogScript) + output, err := command.Output() + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + if failure, ok := err.(*exec.ExitError); ok { + return nil, fmt.Errorf("%w: %s", errPathDialogUnavailable, strings.TrimSpace(string(failure.Stderr))) + } + return nil, fmt.Errorf("%w: %v", errPathDialogUnavailable, err) + } + return decodeDialogPaths(string(output)), nil +} + +func decodeDialogPaths(output string) []string { + output = strings.TrimSuffix(output, "\n") + if output == "" { + return nil + } + return strings.Split(strings.TrimSuffix(output, "\x00"), "\x00") +} diff --git a/internal/tui/path_dialog_test.go b/internal/tui/path_dialog_test.go new file mode 100644 index 0000000..c6d3b42 --- /dev/null +++ b/internal/tui/path_dialog_test.go @@ -0,0 +1,297 @@ +package tui + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/kballard/go-shellquote" + "golang.org/x/text/unicode/norm" +) + +func pathModel(t *testing.T, kind string, multiple bool, initial string) Model { + t.Helper() + root, action := fixture() + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + field := m.form.field("output") + field.PathKind, field.PathMultiple, field.Multi, field.Value = kind, multiple, multiple, initial + if multiple { + field.Type = "stringSlice" + } + focusField(&m, "output") + return m +} + +func openFallback(t *testing.T, m Model) Model { + t.Helper() + m.choosePath = func(context.Context, pathRequest) ([]string, error) { return nil, errPathDialogUnavailable } + next, command := m.Update(key(tea.KeyEnter, "")) + if command == nil { + t.Fatal("Enter must open the path chooser") + } + next, command = next.(Model).Update(command()) + if command == nil { + t.Fatal("an unavailable system dialog should open the terminal browser") + } + return update(next.(Model), command()) +} + +func TestPathDialogAppliesTheSelectedFolderWithoutRunningACommand(t *testing.T) { + dir := filepath.Join(t.TempDir(), "آرشیو, Book Club $(literal)") + if err := os.Mkdir(dir, 0700); err != nil { + t.Fatal(err) + } + m := pathModel(t, "directory", false, "data") + m.choosePath = func(_ context.Context, request pathRequest) ([]string, error) { + if request.Kind != "directory" || request.Title != "Save to folder" || request.Initial != "data" { + t.Errorf("wrong dialog request: %+v", request) + } + return []string{dir}, nil + } + next, command := m.Update(key(tea.KeyEnter, "")) + m = update(next.(Model), command()) + set(&m.form, "chat", "me") + m.prepareReview() + if m.pathDialog != nil || m.editing || m.screen != review || !slices.Contains(m.plan.Args, "--output="+dir) { + t.Fatal("the chosen folder did not reach review as a literal argument") + } + if m.form.Action.Command.Flags().Lookup("output").Changed { + t.Fatal("choosing a path mutated the running CLI flags") + } +} + +func TestCancellingPathDialogPreservesTheActiveEditorAndIgnoresLateResults(t *testing.T) { + m := pathModel(t, "directory", false, "data") + m = clickChoiceText(t, m, "[ Type path ]") + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: "unsaved folder"}) + m = update(m, key('o', "", tea.ModAlt)) + dialog := m.pathDialog + if dialog == nil || dialog.request.Initial != "unsaved folder" { + t.Fatal("Browse should start from the path being edited") + } + m = update(m, key(tea.KeyEscape, "")) + if dialog.ctx.Err() == nil || !m.editing || m.editor.Value() != "unsaved folder" || m.form.field("output").Value != "data" { + t.Fatal("cancelling changed the path or lost the active text edit") + } + m = update(m, pathSelectedMsg{dialog: dialog, paths: []string{t.TempDir()}}) + if m.form.field("output").Value != "data" { + t.Fatal("a dismissed chooser changed a later form") + } + m = update(m, key('o', "", tea.ModAlt)) + m = update(m, pathSelectedMsg{dialog: m.pathDialog}) // Cancel in macOS. + if !m.editing || m.editor.Value() != "unsaved folder" || m.err != "" { + t.Fatal("system cancellation should preserve the unsaved text without an error") + } +} + +func TestPathDialogFailureIsVisibleAndLeavesTheOldPath(t *testing.T) { + m := pathModel(t, "directory", false, "data") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, pathSelectedMsg{dialog: m.pathDialog, err: errors.New("chooser could not open")}) + if m.pathDialog != nil || m.form.field("output").Value != "data" || !strings.Contains(ansi.Strip(m.View().Content), "chooser could not open") { + t.Fatal("dialog failures must remain visible without replacing the saved path") + } +} + +func TestMultiplePathsPreserveCommasSpacesAndShellCharacters(t *testing.T) { + dir := t.TempDir() + paths := []string{filepath.Join(dir, "a, b.json"), filepath.Join(dir, "آرشیو ' $(literal)\n.json")} + for _, path := range paths { + if err := os.WriteFile(path, []byte("{}"), 0600); err != nil { + t.Fatal(err) + } + } + if got := decodeDialogPaths(strings.Join(paths, "\x00") + "\x00\n"); !slices.Equal(got, paths) { + t.Fatalf("system dialog corrupted filenames: %q", got) + } + for _, positional := range []bool{false, true} { + m := pathModel(t, "open", true, "") + field := m.form.field("output") + if positional { + field.Type = "arguments" + } + m = update(m, key(tea.KeyEnter, "")) + m = update(m, pathSelectedMsg{dialog: m.pathDialog, paths: paths}) + var got []string + if positional { + got, _ = shellquote.Split(m.form.field("output").Value) + } else { + got, _ = readCSV(m.form.field("output").Value) + } + if !slices.Equal(got, paths) { + t.Fatalf("selected filenames changed: %q", got) + } + } +} + +func TestPathValidationAndStartingLocationDoNotCreateDestinations(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "input.json") + if err := os.WriteFile(file, []byte("{}"), 0600); err != nil { + t.Fatal(err) + } + for _, test := range []struct { + kind, path string + valid bool + }{{"directory", dir, true}, {"directory", file, false}, {"open", file, true}, {"open", dir, false}, {"save", filepath.Join(dir, "new.json"), true}, {"save", filepath.Join(dir, "missing", "new.json"), false}, {"save", dir, false}, {"any", dir, true}} { + if err := checkPaths(pathRequest{Kind: test.kind}, []string{test.path}); (err == nil) != test.valid { + t.Fatalf("%s %s: %v", test.kind, test.path, err) + } + } + location, name, err := pathLocation(filepath.Join(dir, "missing", "new.json")) + if err != nil || location != dir || name != "new.json" { + t.Fatalf("new destinations should start in the nearest existing folder: %q %q %v", location, name, err) + } + if _, err := os.Stat(filepath.Join(dir, "missing")); !os.IsNotExist(err) { + t.Fatal("browsing created the destination before review") + } +} + +func TestTerminalPathBrowserNavigatesSelectsAndKeepsChecksOutsideSearch(t *testing.T) { + dir := t.TempDir() + child := filepath.Join(dir, "folder") + if err := os.Mkdir(child, 0700); err != nil { + t.Fatal(err) + } + for _, name := range []string{"first.json", "second.json", ".hidden.json"} { + if err := os.WriteFile(filepath.Join(dir, name), []byte("{}"), 0600); err != nil { + t.Fatal(err) + } + } + m := openFallback(t, pathModel(t, "open", true, csvString([]string{dir}))) + if got := len(m.pathDialog.browser.filtered()); got != 3 { + t.Fatalf("wrong visible entries: %d", got) + } + next, command := m.Update(key(tea.KeyEnter, "")) // First row is a folder. + m = update(next.(Model), command()) + if m.pathDialog.browser.directory != child { + t.Fatal("Enter did not open the selected folder") + } + next, command = m.Update(key(tea.KeyLeft, "")) + m = update(next.(Model), command()) + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(' ', " ")) + m = update(m, tea.PasteMsg{Content: "second"}) + m = update(m, key(tea.KeyDown, "")) // Leave search. + m = update(m, key(' ', " ")) + m.pathAction("path-choose") + got, _ := readCSV(m.form.field("output").Value) + if !slices.Equal(got, []string{filepath.Join(dir, "first.json"), filepath.Join(dir, "second.json")}) || m.pathDialog != nil { + t.Fatalf("filtering lost checked files: %q", got) + } +} + +func TestPathControlsAndBrowserFitSmallTerminalsAndSupportMouse(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "chosen"), 0700); err != nil { + t.Fatal(err) + } + for _, size := range [][2]int{{55, 20}, {80, 24}, {110, 32}, {120, 20}} { + m := pathModel(t, "directory", false, dir) + m.width, m.height = size[0], size[1] + m.err = "A path validation error" + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, m.err) || !strings.Contains(view, "[ Browse… ]") { + t.Fatalf("path controls hid actions or errors at %v:\n%s", size, view) + } + m = clickChoiceText(t, m, "[ Browse… ]") + if m.pathDialog == nil { + t.Fatal("Browse did not open the chooser") + } + m = update(m, key(tea.KeyEscape, "")) + m = openFallback(t, m) + view = ansi.Strip(m.View().Content) + if len(strings.Split(view, "\n")) > size[1] { + t.Fatalf("browser height overflow at %v", size) + } + for _, line := range strings.Split(view, "\n") { + if ansi.StringWidth(line) > size[0] { + t.Fatalf("browser width overflow at %v", size) + } + } + // Open with the keyboard so the async read can be delivered explicitly. + next, command := m.Update(key(tea.KeyEnter, "")) + m = update(next.(Model), command()) + m = clickChoiceText(t, m, "[ Use this folder ]") + if m.pathDialog != nil || m.form.field("output").Value != filepath.Join(dir, "chosen") { + t.Fatal("the mouse confirmation chose the wrong folder") + } + } +} + +func TestMacPathDialogScriptCompilesWithoutOpeningAWindow(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("The system dialog script is available on macOS") + } + command := exec.Command("/usr/bin/osacompile", "-l", "JavaScript", "-o", filepath.Join(t.TempDir(), "chooser.scpt"), "-") + command.Stdin = strings.NewReader(macPathDialogScript) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("invalid system chooser script: %v\n%s", err, output) + } +} + +func TestMacDialogBridgePreservesAPathWithoutOpeningAWindow(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("The Cocoa bridge is available on macOS") + } + path := filepath.Join(t.TempDir(), "آرشیو, $(literal)\n") + script := `ObjC.import('AppKit'); +function run(argv) { + if (!$.NSOpenPanel.instancesRespondToSelector('setCanChooseDirectories:') || + !$.NSOpenPanel.instancesRespondToSelector('setAllowsMultipleSelection:') || + !$.NSSavePanel.instancesRespondToSelector('setNameFieldStringValue:')) throw Error('Missing chooser API'); + return ObjC.unwrap($.NSURL.fileURLWithPath(argv[0]).path) + '\u0000'; +}` + command := exec.Command("/usr/bin/osascript", "-l", "JavaScript", "-", path) + command.Stdin = strings.NewReader(script) + output, err := command.Output() + if err != nil { + t.Fatal(err) + } + // Cocoa returns decomposed Unicode names on macOS; compare canonical forms. + if paths := decodeDialogPaths(string(output)); len(paths) != 1 || norm.NFC.String(paths[0]) != norm.NFC.String(path) { + t.Fatalf("Cocoa bridge changed the selected path: %q", paths) + } +} + +func TestTerminalSaveBrowserChoosesANewFilenameWithoutWritingIt(t *testing.T) { + dir := t.TempDir() + m := openFallback(t, pathModel(t, "save", false, filepath.Join(dir, "original.json"))) + m = update(m, key(tea.KeyF2, "")) + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: "new, آرشیو.json"}) + m = update(m, key(tea.KeyEnter, "")) + m = clickChoiceText(t, m, "[ Save here ]") + path := filepath.Join(dir, "new, آرشیو.json") + if m.pathDialog != nil || m.form.field("output").Value != path { + t.Fatal("the Save browser did not use the entered filename") + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatal("selecting a save destination wrote the output before review") + } +} + +func TestPathBrowserDiscardsStaleDirectoryReadsAndShowsReadErrors(t *testing.T) { + m := openFallback(t, pathModel(t, "directory", false, t.TempDir())) + dialog := m.pathDialog + command := m.readPathDirectory(filepath.Join(t.TempDir(), "missing")) + current := dialog.browser.revision + m = update(m, pathDirectoryMsg{dialog: dialog, revision: current - 1, entries: []pathEntry{{name: "stale"}}}) + if !dialog.browser.loading || len(dialog.browser.entries) != 0 { + t.Fatal("a stale folder scan replaced the current browser") + } + m = update(m, command()) + if dialog.browser.loading || dialog.browser.err == "" || !strings.Contains(ansi.Strip(m.View().Content), clip(dialog.browser.err, m.width-4)) { + t.Fatal("a failed folder read must display its cause") + } +} diff --git a/internal/tui/picker.go b/internal/tui/picker.go new file mode 100644 index 0000000..556a6d9 --- /dev/null +++ b/internal/tui/picker.go @@ -0,0 +1,504 @@ +package tui + +import ( + "fmt" + "maps" + "slices" + "strings" + + "charm.land/bubbles/v2/textinput" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +type choicePicker struct { + field, title string + choices []string + selected map[string]bool + multi bool + cursor int + offset int + query textinput.Model + searching bool + err string + labels map[string]string + custom bool + selectedOnly bool + loading bool + loadStage string + loadErr string +} + +func newChoicePicker(field Field, width int) *choicePicker { + p := &choicePicker{field: field.Name, title: field.Label, choices: slices.Clone(field.Choices), labels: maps.Clone(field.ChoiceLabels), selected: map[string]bool{}, multi: field.Multi, query: textinput.New()} + p.custom = customChoices(field) + p.query.Prompt, p.query.Placeholder, p.query.CharLimit = "", "Type to filter options…", 256 + if p.custom { + p.query.Placeholder, p.query.CharLimit = "Type an item · click Add", 4096 + } + p.query.SetWidth(max(1, width-5)) + p.query.SetVirtualCursor(true) + styles := textinput.DefaultDarkStyles() + styles.Focused.Text, styles.Focused.Placeholder, styles.Cursor.Blink = textStyle, dim, false + p.query.SetStyles(styles) + values := []string{field.Value} + if field.Multi { + values, _ = readCSV(field.Value) + } + for _, value := range values { + if p.custom && !slices.Contains(p.choices, value) && value != "" { + p.choices = append(p.choices, value) + } + p.selected[value] = true + } + if !p.multi { + p.cursor = max(0, slices.Index(p.choices, field.Value)) + } + return p +} + +func (m *Model) openPicker(field Field) tea.Cmd { + p := newChoicePicker(field, m.width-4) + if choiceField(field) { + for n, index := range m.visibleFields() { + if m.form.Fields[index].Name == field.Name { + m.focus = n + break + } + } + } + m.picker, m.err, m.buttonsFocused = p, "", false + p.query.SetWidth(max(1, min(60, m.formLayout(m.width-4, m.height-9).controlWidth)-5)) + if field.Name == "ns" { + return m.loadAccounts() + } + if field.Name == "chat" { + return m.loadChatChoices(false) + } + return nil +} + +func (p *choicePicker) filtered() []string { + var values []string + for _, value := range p.choices { + if p.selectedOnly && !p.selected[value] { + continue + } + if matches(p.label(value)+" "+value, p.query.Value()) { + values = append(values, value) + } + } + return values +} + +func (p *choicePicker) label(value string) string { + if label, ok := p.labels[value]; ok { + return safeText(label) + } + if p.custom { + return safeText(value) + } + return choiceLabel(p.field, value) +} + +func (p *choicePicker) special(value string) bool { + return !p.custom && specialChoice(p.field, value) +} + +func (p *choicePicker) addCustom() { + value := p.query.Value() + if !p.custom || strings.TrimSpace(value) == "" { + return + } + if !slices.Contains(p.choices, value) { + p.choices = append(p.choices, value) + } + p.selected[value], p.err, p.searching = true, "", false + p.query.SetValue("") + p.query.Blur() + p.cursor = max(0, slices.Index(p.filtered(), value)) +} + +func (p *choicePicker) clear() { + p.selected, p.err = map[string]bool{}, "" + if p.custom { + p.query.SetValue("") + p.searching = false + p.query.Blur() + } +} + +func (p *choicePicker) checked(value string) bool { + if p.selected[value] { + return true + } + if value == "all" && p.special(value) { + found := false + for _, option := range p.choices { + if !p.special(option) { + found = true + if !p.selected[option] { + return false + } + } + } + return found + } + if value != "none" && value != "all" && p.selected["all"] && p.special("all") { + return true + } + return false +} + +func (p *choicePicker) toggle(value string) { + p.err = "" + if !p.multi { + p.selected = map[string]bool{value: true} + return + } + if p.special(value) { + checked := p.checked(value) + p.selected = map[string]bool{} + if !checked { + p.selected[value] = true + } + return + } + if p.selected["all"] && p.special("all") { + p.selected = map[string]bool{} + for _, option := range p.choices { + if option != "all" && option != "none" { + p.selected[option] = true + } + } + } + if p.special("none") { + delete(p.selected, "none") + } + p.selected[value] = !p.selected[value] +} + +func (p *choicePicker) values() []string { + var values []string + for _, value := range p.choices { + if p.selected[value] { + values = append(values, value) + } + } + return values +} + +func (m *Model) applyPicker() { + p := m.picker + if p == nil { + return + } + field := m.form.field(p.field) + if field == nil { + return + } + p.addCustom() + values := p.values() + if !p.multi { + rows := p.filtered() + if len(rows) > 0 { + values = []string{rows[p.cursor]} + } else { + values = nil + } + } + if len(values) == 0 && (!p.custom || field.Required) { + p.err = "Choose at least one option before applying." + return + } + copy := *field + copy.Value, copy.Dirty = "", true + if p.multi { + copy.Value = csvString(values) + } else { + copy.Value = values[0] + } + if err := validate(copy); err != nil { + p.err = copy.Error(err).Error() + return + } + previous := field.Value + *field = copy + m.form.reconcileSelection(field.Name) + if field.Name == "ns" && previous != copy.Value { + m.resetChatSelection() + } + m.closePicker() + m.err = "" +} + +func (m Model) updatePicker(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) { + p := m.picker + rows := p.filtered() + inline := m.inlinePicker() + if p.multi && msg.String() == "left" { + m.applyPicker() + return m, nil + } + if inline { + switch msg.String() { + case "tab", "shift+tab", "f6", "ctrl+r", "ctrl+enter": + m.applyPicker() + if m.picker != nil { + return m, nil + } + switch msg.String() { + case "ctrl+r", "ctrl+enter": + m.prepareReview() + case "f6": + m.buttonsFocused, m.buttonFocus = true, 1 + default: + delta := 1 + if msg.String() == "shift+tab" { + delta = -1 + } + next := m.focus + delta + if next >= len(m.visibleFields()) { + m.buttonsFocused, m.buttonFocus = true, 1 + } else { + m.focus = max(0, next) + } + } + return m, nil + case "ctrl+l": + if p.field == "ns" { + return m, m.loadAccounts() + } + if p.field == "chat" { + return m, m.loadChatChoices(true) + } + case "ctrl+f": + p.searching = true + p.query.Focus() + return m, nil + } + } + if m.buttonsFocused { + switch msg.String() { + case "tab", "right", "shift+tab", "left": + delta := 1 + if msg.String() == "shift+tab" || msg.String() == "left" { + delta = -1 + } + m.buttonFocus = (m.buttonFocus + len(m.buttons()) + delta) % len(m.buttons()) + return m, nil + case "enter": + return m, m.activate(m.buttons()[m.buttonFocus].ID) + case "esc", "up", "down": + m.buttonsFocused = false + return m, nil + } + } + switch msg.String() { + case "tab", "shift+tab": + m.buttonsFocused, m.buttonFocus = true, 0 + case "ctrl+d": + p.clear() + case "ctrl+s": + if p.multi { + p.addCustom() + p.selectedOnly, p.cursor = !p.selectedOnly, 0 + p.query.SetValue("") + p.searching = false + p.query.Blur() + } + case "esc": + if inline { + m.closePicker() + } else if p.searching { + p.searching = false + p.query.Blur() + } else { + m.closePicker() + } + case "up", "down", "left", "right", "pgup", "pgdown", "home", "end": + if p.searching { + if msg.String() == "left" || msg.String() == "right" || msg.String() == "home" || msg.String() == "end" { + p.query, _ = p.query.Update(msg) + return m, nil + } + p.searching = false + p.query.Blur() + return m, nil + } + delta := 1 + columns, page := 1, 5 + if inline { + bounds := m.inlineChoiceBounds() + page = choiceListWindow(bounds.height, len(rows), p.cursor, p.offset).rows + } + switch msg.String() { + case "up": + delta = -columns + case "down": + delta = columns + case "left": + delta = -1 + case "pgup": + delta = -page + case "pgdown": + delta = page + case "home": + p.cursor = 0 + return m, nil + case "end": + p.cursor = max(0, len(rows)-1) + return m, nil + } + p.cursor = max(0, min(max(0, len(rows)-1), p.cursor+delta)) + case "enter": + if p.custom && p.searching && strings.TrimSpace(p.query.Value()) != "" { + p.addCustom() + return m, nil + } + p.searching = false + p.query.Blur() + if len(rows) > 0 { + p.cursor = max(0, min(len(rows)-1, p.cursor)) + p.toggle(rows[p.cursor]) + p.cursor = max(0, min(max(0, len(p.filtered())-1), p.cursor)) + } + if !p.multi { + m.applyPicker() + } + case "space", " ": + if !p.searching && len(rows) > 0 { + p.toggle(rows[p.cursor]) + return m, nil + } + fallthrough + default: + if msg.String() == "ctrl+r" && p.field == "ns" { + return m, m.loadAccounts() + } + if msg.String() == "ctrl+a" && !p.searching { + m.selectAllChoices() + return m, nil + } + if msg.Text != "" || msg.String() == "backspace" || msg.String() == "ctrl+u" { + p.searching = true + p.query.Focus() + p.query.SetWidth(max(1, min(60, m.formLayout(m.width-4, m.height-9).controlWidth)-5)) + p.query, _ = p.query.Update(msg) + p.cursor = 0 + } + } + return m, nil +} + +func (m Model) pickerClick(msg tea.MouseClickMsg) (tea.Model, tea.Cmd) { + if msg.Button != tea.MouseLeft { + return m, nil + } + if m.inlinePicker() { + if handled, command := m.inlineChoiceClick(msg); handled { + return m, command + } + layout := m.formLayout(m.width-4, m.height-9) + index, fieldHit := layout.fieldAtRow(msg.Y - 3 - layout.top) + m.applyPicker() + if m.picker != nil { + return m, nil + } + if fieldHit && index < len(m.visibleFields()) { + m.focus = index + return m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + } + return m.mouseClick(msg) + } + if msg.Y == m.height-5 { + return m.mouseClick(msg) + } + if msg.Y >= 6 && msg.Y <= 8 { + m.picker.searching = true + m.picker.query.Focus() + return m, nil + } + page := max(1, m.height-19) + start := max(0, m.picker.cursor-page+1) + row := msg.Y - 10 + rows := m.picker.filtered() + if row >= 0 && row < page && start+row < len(rows) { + m.picker.cursor, m.picker.searching = start+row, false + m.picker.query.Blur() + m.picker.toggle(rows[start+row]) + } + return m, nil +} + +func (m *Model) selectAllChoices() { + p := m.picker + if p == nil || !p.multi { + return + } + p.selected = map[string]bool{} + if slices.Contains(p.choices, "all") && p.special("all") { + p.selected["all"] = true + return + } + for _, option := range p.choices { + if !p.special(option) { + p.selected[option] = true + } + } +} + +func (m Model) pickerView(width, height int) string { + p := m.picker + rows := p.filtered() + help := "Choose an option with ↑ / ↓, then press Enter." + if p.multi { + help = "Space checks an item · Enter applies your selection" + } + query := p.query + query.SetWidth(max(1, width-5)) + lines := []string{titleStyle.Render(p.title), dim.Render(clip(help, width)), "", lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(line).Padding(0, 1).Width(width).Render(query.View()), ""} + page := max(1, height-10) + start := max(0, p.cursor-page+1) + for i := start; i < min(len(rows), start+page); i++ { + value := rows[i] + mark, style := "[ ]", textStyle + if p.checked(value) { + mark = "[x]" + } + if !p.multi { + mark = "○" + if p.checked(value) { + mark = "●" + } + } + if i == p.cursor { + style = selectedStyle.Bold(true).Width(width) + } + lines = append(lines, style.Render(clip(" "+mark+" "+p.label(value), width))) + } + if len(rows) == 0 { + message := "No matching options. Clear the search to see everything." + if len(p.choices) == 0 && p.field == "ns" { + message = "No saved accounts. Connect a Telegram account first." + if m.accountError != "" { + message = "Could not load saved accounts: " + m.accountError + } + } + lines = append(lines, dim.Render(clip(message, width))) + } + for lipgloss.Height(strings.Join(lines, "\n")) < height-2 { + lines = append(lines, "") + } + selection := fmt.Sprintf("%d selected", len(p.values())) + if p.selected["all"] && p.special("all") { + selection = "All selected" + } + lines = append(lines, accent.Render(selection)+dim.Render(" · Type to filter · ↓ returns to the list")) + if p.err != "" { + lines = append(lines, warning.Render(clip(p.err, width))) + } else if p.field == "ns" && m.accountError != "" { + lines = append(lines, warning.Render(clip("Could not refresh saved accounts: "+m.accountError, width))) + } + return strings.Join(lines, "\n") +} diff --git a/internal/tui/picker_test.go b/internal/tui/picker_test.go new file mode 100644 index 0000000..0913801 --- /dev/null +++ b/internal/tui/picker_test.go @@ -0,0 +1,341 @@ +package tui + +import ( + "context" + "slices" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" +) + +func TestCustomListFieldsUseAnAddableMultiSelect(t *testing.T) { + root, action := fixture() + action.Command.Flags().StringSlice("extensions", nil, "extensions") + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + m.advanced = true + focusField(&m, "extensions") + m = update(m, key(tea.KeyEnter, "")) + if m.picker == nil || !m.picker.multi || m.editing { + t.Fatal("a list with custom values must open a multi-select with an Add control") + } + for _, value := range []string{"pdf", "mp4", "zip"} { + m = update(m, tea.PasteMsg{Content: value}) + m = update(m, key(tea.KeyEnter, "")) + if m.picker == nil || !m.picker.checked(value) { + t.Fatalf("Enter did not add and select %q", value) + } + } + m = clickChoiceText(t, m, "[Done]") + if m.picker != nil || m.form.field("extensions").Value != "pdf,mp4,zip" { + t.Fatal("the custom multi-select did not save every added item") + } + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key('d', "", tea.ModCtrl)) + m = clickChoiceText(t, m, "[Done]") + if m.picker != nil || m.form.field("extensions").Value != "" { + t.Fatal("an optional custom list should be clearable") + } +} + +func TestCustomListItemsCanBeAddedAndSavedByMouse(t *testing.T) { + root, action := fixture() + action.Command.Flags().StringSlice("extensions", []string{"mp4"}, "extensions") + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + m.advanced = true + focusField(&m, "extensions") + m = clickChoiceText(t, m, "extensions") + // A partial match must still be addable as a distinct literal item. + for _, item := range []string{"mp", "pdf"} { + m = update(m, tea.PasteMsg{Content: item}) + m = clickChoiceText(t, m, "[Add]") + } + m = clickChoiceText(t, m, "[Done]") + if got := m.form.field("extensions").Value; got != "mp4,mp,pdf" || m.picker != nil { + t.Fatalf("the mouse-only Add and Done actions lost items: %q", got) + } +} + +func TestEnterTogglesAFilteredItemAndLeftSavesAllSelections(t *testing.T) { + m := inlineModel(t, "personal", "work") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "work"}) + m = update(m, key(tea.KeyEnter, "")) + if m.picker == nil || !m.picker.checked("work") || !m.picker.checked("personal") { + t.Fatal("Enter should toggle the filtered item without losing other choices") + } + m = update(m, key(tea.KeyEnter, "")) + if m.picker == nil || m.picker.checked("work") { + t.Fatal("Enter should uncheck the same highlighted item and stay open") + } + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key(tea.KeyLeft, "")) + if m.picker != nil || m.form.field("ns").Value != "personal,work" || m.screen != configure { + t.Fatal("Left must save selections beyond the filter and return to the form") + } +} + +func TestCustomStringArrayKeepsLiteralItemsAndSavesPendingInput(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + m.advanced = true + focusField(&m, "from") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "Book Club, Friends"}) + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "https://t.me/example/12"}) + m = update(m, key('r', "", tea.ModCtrl)) + if m.screen != review || m.picker != nil || !slices.Contains(m.plan.Args, "--from=Book Club, Friends") || !slices.Contains(m.plan.Args, "--from=https://t.me/example/12") { + t.Fatal("the custom list split a literal comma or discarded the pending item") + } +} + +func TestRequiredCustomListCannotBeClearedAndSecretListsStayMasked(t *testing.T) { + root, action := fixture() + _ = action.Command.MarkFlagRequired("from") + action.Command.Flags().StringSlice("tokens", nil, "private values") + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + m.advanced = true + focusField(&m, "from") + m = update(m, key(tea.KeyEnter, "")) + m = clickChoiceText(t, m, "[Done]") + if m.picker == nil || m.picker.err == "" { + t.Fatal("a required custom list must explain why an empty selection cannot be applied") + } + m = update(m, key(tea.KeyEscape, "")) + focusField(&m, "tokens") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "synthetic-private-value"}) + if !m.editing || m.picker != nil || strings.Contains(m.View().Content, "synthetic-private-value") { + t.Fatal("a secret list must use a masked editor") + } +} + +func TestCustomValuesAllAndNoneRemainLiteralItems(t *testing.T) { + root, action := fixture() + action.Command.Flags().StringSlice("include", nil, "custom extensions") + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + m.advanced = true + focusField(&m, "include") + m = update(m, key(tea.KeyEnter, "")) + for _, value := range []string{"all", "none", "mp4"} { + m = update(m, tea.PasteMsg{Content: value}) + m = update(m, key(tea.KeyEnter, "")) + } + m = update(m, key(tea.KeyHome, "")) + m = update(m, key(' ', " ")) // Deselect the literal item "all". + m = clickChoiceText(t, m, "[Done]") + if got := m.form.field("include").Value; got != "none,mp4" { + t.Fatalf("custom values were mistaken for reserved selectors: %q", got) + } +} + +func TestAccountPickerKeepsSelectionsAcrossFilteringAndCancelsWithoutSaving(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "personal", context.Background(), WithSavedAccounts([]string{"personal", "work"})) + m.open(action) + field := m.form.field("ns") + if !field.Multi || field.Advanced || field.Type != "accounts" { + t.Fatal("backup accounts must be a visible multi-select") + } + m.openPicker(*field) + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(' ', " ")) + m = update(m, key('p', "p")) + if len(m.picker.filtered()) != 1 || !m.picker.selected["work"] { + t.Fatal("filtering lost a checked account") + } + m = update(m, key(tea.KeyDown, "")) // Return from search to the first result. + m = update(m, key(tea.KeyLeft, "")) + selected, _ := readCSV(m.form.field("ns").Value) + if !slices.Equal(selected, []string{"personal", "work"}) { + t.Fatalf("incorrect account selection: %v", selected) + } + m.openPicker(*m.form.field("ns")) + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyEscape, "")) + if m.picker != nil || m.form.field("ns").Value != "personal,work" { + t.Fatal("cancelling the picker changed the applied account selection") + } +} + +func TestMediaPickerExpandsAllAndKeepsNoneExclusive(t *testing.T) { + root, action := fixture() + action.Command.Flags().StringSlice("media", []string{"all"}, "media categories") + action.Command.Flags().Lookup("media").Annotations = map[string][]string{"ta:choices": {"all", "none", "photos", "videos", "documents"}} + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + m.openPicker(*m.form.field("media")) + if !m.picker.checked("photos") || !m.picker.checked("videos") { + t.Fatal("All media should show individual categories checked") + } + m.picker.cursor = 3 + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyLeft, "")) + if got := m.form.field("media").Value; got != "photos,documents" { + t.Fatalf("unchecking one category should expand All: %s", got) + } + m.openPicker(*m.form.field("media")) + m.picker.cursor = 1 + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyLeft, "")) + if m.form.field("media").Value != "none" { + t.Fatal("No media must exclude individual categories") + } + m.openPicker(*m.form.field("media")) + m.picker.cursor = 2 + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyLeft, "")) + if m.form.field("media").Value != "photos" { + t.Fatal("choosing a category must clear No media") + } +} + +func TestSingleChoiceDropdownAndEmptyMultiSelection(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + focusField(&m, "format") + m = update(m, key(tea.KeyEnter, "")) + if m.picker == nil || m.editing { + t.Fatal("a choice should open a dropdown instead of a text editor") + } + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(tea.KeyEnter, "")) + if m.form.field("format").Value != "html" { + t.Fatal("dropdown did not apply the selected value") + } + m.openPicker(*m.form.field("ns")) + m.activate("picker-clear") + m = update(m, key(tea.KeyLeft, "")) + if m.picker == nil || m.picker.err == "" { + t.Fatal("empty account selection should remain open with an explanation") + } +} + +func TestChooseButtonAppliesHighlightedDropdownOption(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "personal", context.Background()) + m.open(action) + m.openPicker(*m.form.field("format")) + m = update(m, key(tea.KeyDown, "")) + m.activate("picker-apply") + if m.form.field("format").Value != "html" { + t.Fatal("Choose applied the old value instead of the highlighted option") + } +} + +func TestAccountNamesAllAndNoneAreOrdinaryAccountChoices(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "all", context.Background(), WithSavedAccounts([]string{"all", "none", "work"})) + m.open(action) + m.openPicker(*m.form.field("ns")) + m.selectAllChoices() + m.applyPicker() + plan, err := m.form.Plan(nil) + if err != nil || len(plan.Tasks) != 3 { + t.Fatalf("account names were mistaken for special category choices: %v", err) + } +} + +func TestAccountRefreshDoesNotChangeAnAlreadyReviewedPlan(t *testing.T) { + m := batchModel(t) + before := m.form.field("ns").Value + m = update(m, accountsLoadedMsg{names: []string{"another-account"}}) + if m.form.field("ns").Value != before || len(m.plan.Tasks) != 3 { + t.Fatal("background discovery changed the targets already shown in review") + } +} + +func TestPickerFitsTerminalsAndItsVisibleRowsAreClickable(t *testing.T) { + root, action := fixture() + for _, size := range [][2]int{{55, 20}, {80, 24}, {120, 36}} { + m := New(Catalog(root), nil, "personal", context.Background(), WithSavedAccounts([]string{"personal", "work"})) + m.width, m.height = size[0], size[1] + m.open(action) + m.openPicker(*m.form.field("ns")) + m.picker.err = "Choose at least one option" + view := ansi.Strip(m.View().Content) + if len(strings.Split(view, "\n")) > size[1] || !strings.Contains(view, m.picker.err) { + t.Fatalf("picker clipped its error at %v", size) + } + for _, line := range strings.Split(view, "\n") { + if ansi.StringWidth(line) > size[0] { + t.Fatalf("picker overflow at %v", size) + } + } + } + m := New(Catalog(root), nil, "personal", context.Background(), WithSavedAccounts([]string{"personal", "work"})) + m.open(action) + m.openPicker(*m.form.field("ns")) + for y, line := range strings.Split(ansi.Strip(m.View().Content), "\n") { + if offset := strings.Index(line, "[ ] work"); offset >= 0 { + m = update(m, tea.MouseClickMsg{X: ansi.StringWidth(line[:offset]), Y: y, Button: tea.MouseLeft}) + if !m.picker.selected["work"] { + t.Fatal("clicking a visible checkbox selected the wrong row") + } + return + } + } + t.Fatal("work account was not visible") +} + +func TestCheckedChatsBecomeNamedChoicesAndKeepTheirOriginalAccount(t *testing.T) { + root, _ := fixture() + m := New(Catalog(root), nil, "personal", context.Background(), WithSavedAccounts([]string{"personal", "work"})) + m.accountSelection = []string{"personal", "work"} + m.screen = result + m.plan = Plan{Path: []string{"chat", "ls"}, Args: []string{"--ns=work", "chat", "ls"}} + m.data = resultData{Kind: "chat ls", Items: []item{{ID: "42", Title: "First chat"}, {ID: "84", Title: "Second chat"}}} + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(' ', " ")) + m = update(m, key('/', "/")) + m = update(m, tea.PasteMsg{Content: "Second"}) + m = update(m, key(tea.KeyEnter, "")) + m.activate("archive-selected") + if m.screen != configure || m.form.field("chat").Value != "42,84" || m.form.field("ns").Value != "work" { + t.Fatal("checked chats were lost or applied to another account") + } + m.openPicker(*m.form.field("chat")) + if m.picker.label("42") != "First chat" || !m.picker.checked("42") || !m.picker.checked("84") { + t.Fatal("loaded chats should be named checkbox options, not raw IDs") + } + m.picker = nil + m.restoreList() + if len(m.checkedResults()) != 2 || m.resultSearch != "Second" { + t.Fatal("returning to the list discarded checks outside the filter") + } +} + +func TestAccountsBrowserCanPrepareSeveralBackupsWithoutRunningThem(t *testing.T) { + root, _ := fixture() + sync := &cobra.Command{Use: "sync", Args: cobra.NoArgs, RunE: func(*cobra.Command, []string) error { panic("must not run") }} + sync.Flags().Bool("everything", false, "entire account") + sync.Flags().String("format", "json", "format") + sync.Flags().String("output", "data", "destination") + root.AddCommand(sync) + m := New(Catalog(root), nil, "personal", context.Background(), WithSavedAccounts([]string{"personal", "work", "busy"})) + m.screen = result + m.data = resultData{Kind: "accounts", Items: []item{{ID: "personal", Status: "ready"}, {ID: "work", Status: "ready"}, {ID: "busy", Status: "busy"}}} + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(' ', " ")) + m = update(m, key(tea.KeyDown, "")) + m = update(m, key(' ', " ")) + if m.selectedResults["busy"] { + t.Fatal("a busy account was selectable in the account browser") + } + m.activate("backup-selected") + plan, err := m.form.Plan(nil) + if err != nil || m.screen != configure || len(plan.Tasks) != 2 { + t.Fatalf("account selection did not prepare two separate backups: %v", err) + } +} diff --git a/internal/tui/plan.go b/internal/tui/plan.go index e24c86e..cf45b90 100644 --- a/internal/tui/plan.go +++ b/internal/tui/plan.go @@ -16,6 +16,7 @@ type Plan struct { Args []string Path []string width, height int + Tasks []AccountTask } func (f Form) Plan(base []string) (Plan, error) { @@ -32,6 +33,9 @@ func (f Form) Plan(base []string) (Plan, error) { } var local, positionals []string for _, field := range f.Fields { + if field.Name == "ns" && field.Type == "accounts" { + continue + } if field.Type == "arguments" { var err error positionals, err = shellquote.Split(field.Value) @@ -97,7 +101,7 @@ func (f Form) Plan(base []string) (Plan, error) { } plan.Args = append(plan.Args, positionals...) } - return plan, nil + return f.withAccounts(plan) } func validate(field Field) error { @@ -152,8 +156,26 @@ func validate(field Field) error { if err != nil { return err } - if len(field.Choices) > 0 && !strings.Contains(field.Type, "Slice") && !slices.Contains(field.Choices, field.Value) { - return fmt.Errorf("choose %s", strings.Join(field.Choices, ", ")) + if len(field.Choices) > 0 && !field.AllowCustom { + values := []string{field.Value} + if field.Multi { + values, err = readCSV(field.Value) + if err != nil { + return err + } + } + for _, value := range values { + if !slices.Contains(field.Choices, value) { + return fmt.Errorf("choose one of the listed options") + } + } + if field.Multi && len(values) > 1 { + for _, value := range values { + if specialChoice(field.Name, value) { + return fmt.Errorf("choose All, None, or individual options") + } + } + } } return nil } @@ -180,6 +202,15 @@ func validDate(value string) bool { // Preview is suitable for display and never exposes credentials in global flags. // Execution uses Args directly; no command string is evaluated by a shell. func (p Plan) Preview() string { + if len(p.Tasks) > 0 { + var lines []string + for _, task := range p.Tasks { + copy := p + copy.Args, copy.Tasks = task.Args, nil + lines = append(lines, copy.Preview()) + } + return strings.Join(lines, "\n") + } args := append([]string{"ta"}, p.Args...) secretNext := false for i, arg := range args { diff --git a/internal/tui/progress_view.go b/internal/tui/progress_view.go new file mode 100644 index 0000000..67587a8 --- /dev/null +++ b/internal/tui/progress_view.go @@ -0,0 +1,36 @@ +package tui + +import ( + "fmt" + "strings" + + "charm.land/bubbles/v2/progress" + "charm.land/lipgloss/v2" +) + +func newProgress() progress.Model { + return progress.New(progress.WithColors(mint, violet), progress.WithoutPercentage()) +} + +func (m Model) progressView(width int) string { + status := m.status + inner := max(1, width-4) + lines := []string{titleStyle.Render(clip(status.Label, inner))} + if status.Determinate { + meter := m.meter + meter.SetWidth(max(1, inner-8)) + bar := meter.View() + if meter.Percent() != status.Percent { + bar = meter.ViewAs(status.Percent) + } + lines = append(lines, bar+accent.Render(fmt.Sprintf(" %5.1f%%", status.Percent*100))) + } else { + lines = append(lines, accent.Render(m.loader.View()+" Discovering messages and media…")) + } + detail := status.Detail + if status.Determinate && status.TotalFiles > 0 { + detail = fmt.Sprintf("%d / %d files · %s", status.CompletedFiles, status.TotalFiles, detail) + } + lines = append(lines, textStyle.Render(clip(detail, inner)), dim.Render(clip(status.Summary, inner))) + return lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(line).Padding(0, 1).Width(width).Render(strings.Join(lines, "\n")) +} diff --git a/internal/tui/results.go b/internal/tui/results.go index f36fbb5..dfc4be5 100644 --- a/internal/tui/results.go +++ b/internal/tui/results.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/json" "fmt" + "maps" "slices" "strconv" "strings" @@ -144,6 +145,12 @@ func (m *Model) openPath(path string, preset map[string]string) { m.err = "This action is unavailable in this build." } func (m *Model) begin() tea.Cmd { + m.batchIndex, m.batchResults, m.batchStarted = 0, nil, time.Now() + return m.startTask() +} + +func (m *Model) startTask() tea.Cmd { + m.selectedResults = nil if len(m.plan.Path) > 0 { switch m.plan.Path[0] { case "login", "recover", "migrate": @@ -151,6 +158,9 @@ func (m *Model) begin() tea.Cmd { } } m.loading = false + m.pendingAction = "" + m.pendingSelection = "" + m.meter = newProgress() m.cachedAt = time.Time{} m.stage = "" m.started = time.Now() @@ -161,6 +171,8 @@ func (m *Model) begin() tea.Cmd { m.last = finishedMsg{} m.output = "" m.progress = nil + m.status = nil + m.syncedOutput = false m.data = resultData{} if strings.Join(m.plan.Path, " ") == "chat ls" { m.data.Kind = "chat ls" @@ -177,7 +189,7 @@ func (m *Model) begin() tea.Cmd { m.buttonFocus = 0 m.buttonsFocused = false m.err = "" - return m.run(taskCtx, m.plan) + return m.run(taskCtx, m.taskPlan()) } type resultSnapshot struct { @@ -187,10 +199,11 @@ type resultSnapshot struct { output, search string selected, tab int last finishedMsg + checked map[string]bool } func (m *Model) saveList() { - m.source = &resultSnapshot{m.plan, m.form, m.data, m.output, m.resultSearch, m.resultSelected, m.resultTab, m.last} + m.source = &resultSnapshot{plan: m.plan, form: m.form, data: m.data, output: m.output, search: m.resultSearch, selected: m.resultSelected, tab: m.resultTab, last: m.last, checked: maps.Clone(m.selectedResults)} } func (m *Model) restoreList() { if m.source == nil { @@ -204,10 +217,36 @@ func (m *Model) restoreList() { m.buttonsFocused = false m.buttonFocus = 0 m.source = nil + m.selectedResults = maps.Clone(s.checked) m.progress = nil + m.status = nil + m.syncedOutput = false m.cancelling = false m.responding = false } + +func (m Model) checkedResults() []item { + var rows []item + for _, row := range m.data.Items { + if m.selectedResults[row.ID] { + rows = append(rows, row) + } + } + return rows +} + +func (m *Model) selectBrowserAccount() { + account := m.globals["ns"] + for _, arg := range m.plan.Args { + if strings.HasPrefix(arg, "--ns=") { + account = strings.TrimPrefix(arg, "--ns=") + } + } + m.accountSelection = []string{account} + if account != "" && !slices.Contains(m.accounts, account) { + m.accounts = append(m.accounts, account) + } +} func (m Model) resultListGeometry(height int) (int, int) { start := 7 if len(m.data.Metrics) > 0 { @@ -223,12 +262,14 @@ type browseCache struct { func chatCacheKey(plan Plan) [32]byte { return sha256.Sum256([]byte(strings.Join(plan.Args, "\x00"))) } func (m *Model) saveChatCache() { + m.cacheChats(m.plan, m.data) +} +func (m *Model) cacheChats(plan Plan, data resultData) { if m.chatCache == nil { m.chatCache = map[[32]byte]browseCache{} } - data := m.data data.Items = slices.Clone(data.Items) - key := chatCacheKey(m.plan) + key := chatCacheKey(plan) if _, exists := m.chatCache[key]; !exists && len(m.chatCache) >= 8 { var oldest [32]byte var savedAt time.Time @@ -262,6 +303,8 @@ func (m *Model) showChatCache() bool { m.scroll = 0 m.stage = "" m.progress = nil + m.status = nil + m.syncedOutput = false m.err = "" m.cancelling = false m.responding = false diff --git a/internal/tui/runner.go b/internal/tui/runner.go index 34c4e76..2444694 100644 --- a/internal/tui/runner.go +++ b/internal/tui/runner.go @@ -46,6 +46,7 @@ type job struct { pending []byte items []item seen map[string]bool + revision uint64 } const captureLimit = 4 << 20 @@ -59,6 +60,7 @@ func (w jobWriter) Write(p []byte) (int, error) { j := w.job j.mu.Lock() defer j.mu.Unlock() + j.revision++ if !w.stdout || !j.structured { j.terminal.write(p) } diff --git a/internal/tui/task_view.go b/internal/tui/task_view.go index 53099dc..a6721c0 100644 --- a/internal/tui/task_view.go +++ b/internal/tui/task_view.go @@ -11,36 +11,46 @@ import ( func (m Model) taskView(width, height int) string { if m.screen == running { - spinner := []string{"◐", "◓", "◑", "◒"}[int(time.Since(m.started).Milliseconds()/150)%4] - heading := spinner + " Working" + heading := "Working" if m.stage != "" { - heading = spinner + " " + m.stage + heading = m.stage } if m.cancelling { - heading = "◐ Cancelling…" + heading = "Stopping safely…" } - lines := []string{accent.Render(heading) + dim.Render(" "+time.Since(m.started).Round(time.Second).String()), "", titleStyle.Render(m.plan.Title), dim.Render("Task stays here · Ctrl+C cancels without closing the workspace"), ""} - if m.responding { - lines = append(lines, accent.Render("INPUT ACTIVE · Type your response; Enter submits · Esc returns to controls")) - } else { - lines = append(lines, dim.Render("Choose Respond (i) if the task asks for input. Passwords stay masked by the prompt.")) + elapsed := time.Since(m.started).Round(time.Second).String() + title := m.plan.Title + if len(m.plan.Tasks) > 0 { + title = fmt.Sprintf("Account %d / %d · %s", m.batchIndex+1, len(m.plan.Tasks), m.plan.Tasks[m.batchIndex].Account) } - lines = append(lines, "") - if len(m.progress) == 3 { - lines = append(lines, selectedStyle.Width(width).Render(m.progress[0]), accent.Render(m.progress[1]), dim.Render(m.progress[2]), "") + lines := []string{accent.Render(m.loader.View()+" "+clip(heading, width-len(elapsed)-4)) + dim.Render(" "+elapsed), titleStyle.Render(clip(title, width)), ""} + if m.status != nil { + lines = append(lines, m.progressView(width), "") + } else if len(m.progress) == 3 { + lines = append(lines, clip(m.progress[0], width), accent.Render(clip(m.progress[1], width)), dim.Render(clip(m.progress[2], width)), "") + } + activity := "ACTIVITY" + if m.responding { + activity = "INPUT ACTIVE · Enter submits · Esc returns to controls" + } else if m.status == nil { + activity += " · i to respond to a prompt" } + lines = append(lines, dim.Render(clip(activity, width))) output := m.output if output == "" { - if len(m.progress) > 0 { - output = "Activity will appear here as files finish." - } else { - output = "Preparing the task…" - if len(m.plan.Path) > 0 && m.plan.Path[0] == "chat" { - output = "Connecting to Telegram · the browser will show each page as it arrives." - } + output = "Preparing your backup…" + if m.status != nil { + output = "Files and updates will appear here." + } + if len(m.plan.Path) > 0 && m.plan.Path[0] == "chat" { + output = "Connecting to Telegram. Chats appear as each page arrives." } } - available := max(1, height-len(lines)-2) + used := 0 + for _, value := range lines { + used += lipgloss.Height(value) + } + available := max(1, height-used-1) offset := m.scroll if m.follow { offset = max(0, len(strings.Split(output, "\n"))-available) @@ -56,7 +66,7 @@ func (m Model) taskView(width, height int) string { status = "✓ Chat list · saved " + m.cachedAt.Format("15:04:05") } if m.loading { - status = fmt.Sprintf("◐ Loading · %d chats available", len(m.data.Items)) + status = fmt.Sprintf("%s Loading · %d chats available", m.loader.View(), len(m.data.Items)) } style := accent if m.last.err != nil { @@ -66,6 +76,20 @@ func (m Model) taskView(width, height int) string { if m.cancelling { status = "■ Cancelled" } + if m.data.Kind == "account backups" { + completed, failed, skipped := 0, 0, 0 + for _, row := range m.data.Items { + switch row.Status { + case "completed": + completed++ + case "failed": + failed++ + default: + skipped++ + } + } + status = fmt.Sprintf("%d completed · %d failed · %d not run", completed, failed, skipped) + } elapsed := m.last.elapsed if m.loading { elapsed = time.Since(m.started) @@ -76,7 +100,7 @@ func (m Model) taskView(width, height int) string { } lines := []string{style.Render(status) + dim.Render(elapsedLabel), "", titleStyle.Render(m.plan.Title), ""} if m.loading { - lines[3] = dim.Render(clip(m.stage+" · Stop loading to use a selected chat", width)) + lines[3] = dim.Render(clip(m.stage+" · Select a chat and choose Archive when ready", width)) } tabs := []string{"Results", "Activity", "Details"} parts := []string{} @@ -119,6 +143,9 @@ func (m Model) taskView(width, height int) string { } rows := m.resultItems() search := dim.Render(fmt.Sprintf("%d items · / search · ↑↓ select · Enter details", len(rows))) + if m.data.Kind == "accounts" || m.data.Kind == "chat ls" { + search = dim.Render(fmt.Sprintf("%d items · %d checked · Space check · / search", len(rows), len(m.checkedResults()))) + } if m.searching { search = accent.Render("/ ") + m.inputView(width-3, false) } else if m.resultSearch != "" { @@ -130,12 +157,22 @@ func (m Model) taskView(width, height int) string { for i := start; i < min(len(rows), start+page); i++ { row := rows[i] marker := " " + check := "" + if m.data.Kind == "accounts" || m.data.Kind == "chat ls" { + check = "[ ] " + if m.selectedResults[row.ID] { + check = "[x] " + } + if m.data.Kind == "accounts" && row.Status != "ready" { + check = "[-] " + } + } style := textStyle if i == m.resultSelected { marker = "▸ " style = selectedStyle.Bold(true).Width(width) } - lines = append(lines, style.Render(clip(marker+row.Title, width)), dim.Render(clip(" "+row.Subtitle, width))) + lines = append(lines, style.Render(clip(marker+check+row.Title, width)), dim.Render(clip(" "+row.Subtitle, width))) } if len(rows) == 0 && len(m.data.Metrics) == 0 { message := "No results. Try changing the filters or refreshing." diff --git a/internal/tui/transcript.go b/internal/tui/transcript.go index a10201d..4560b9f 100644 --- a/internal/tui/transcript.go +++ b/internal/tui/transcript.go @@ -19,6 +19,7 @@ type transcript struct { x, y, savedX, savedY int width, height int progress []string + status *taskui.Progress respond func(string) } @@ -35,6 +36,15 @@ func newTranscript(width, height int) *transcript { lines[i] = safeText(lines[i]) } t.progress = lines + return + } + var status taskui.Progress + if json.Unmarshal([]byte(payload[len(taskui.ProgressPrefix):]), &status) == nil && status.Label != "" { + status.Label = safeText(status.Label) + status.Detail = safeText(status.Detail) + status.Summary = safeText(status.Summary) + status.Percent = max(0, min(1, status.Percent)) + t.status = &status } } }, Print: t.print, Execute: t.control, HandleCsi: t.csi, HandleEsc: func(cmd ansi.Cmd) { diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go index fcebb2a..39992ad 100644 --- a/internal/tui/tui_test.go +++ b/internal/tui/tui_test.go @@ -199,7 +199,7 @@ func TestModelSearchEditReviewAndReturn(t *testing.T) { t.Fatal("opened command ran unexpectedly") } m.focus = slices.Index(m.visibleFields(), slices.IndexFunc(m.form.Fields, func(f Field) bool { return f.Name == "output" })) - m = update(m, key(tea.KeyEnter, "")) + m = clickChoiceText(t, m, "[ Type path ]") m = update(m, key('u', "", tea.ModCtrl)) m = update(m, tea.PasteMsg{Content: "آرشیو/Book Club"}) m = update(m, key(tea.KeyEnter, "")) @@ -241,7 +241,7 @@ func TestSearchNoMatchesAndAdvancedOptions(t *testing.T) { t.Fatal(m.screen) } m.open(action) - m = update(m, key('/', "/")) + m = update(m, key('f', "", tea.ModCtrl)) m = update(m, tea.PasteMsg{Content: "proxy"}) if fields := m.visibleFields(); len(fields) != 1 || m.form.Fields[fields[0]].Name != "proxy" { t.Fatal(fields) @@ -260,6 +260,7 @@ func TestSpaceTogglesSwitchesAndCyclesChoices(t *testing.T) { root, action := fixture() m := New(Catalog(root), nil, "default", context.Background()) m.open(action) + m.advanced = true // Resume is an advanced setting; its control still works. focus := func(name string) { m.focus = slices.Index(m.visibleFields(), slices.IndexFunc(m.form.Fields, func(f Field) bool { return f.Name == name })) } @@ -278,7 +279,7 @@ func TestSpaceTogglesSwitchesAndCyclesChoices(t *testing.T) { t.Fatal("field did not reset") } focus("output") - m = update(m, key(tea.KeyEnter, "")) + m = clickChoiceText(t, m, "[ Type path ]") m = update(m, key(' ', " ")) if string(m.input) != "data " { t.Fatal("space should type normally in an editor") diff --git a/internal/tui/usability_test.go b/internal/tui/usability_test.go new file mode 100644 index 0000000..3e32392 --- /dev/null +++ b/internal/tui/usability_test.go @@ -0,0 +1,238 @@ +package tui + +import ( + "bytes" + "context" + "fmt" + "slices" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/mo1ein/TelegramArchive/internal/taskui" +) + +func focusField(m *Model, name string) { + index := slices.IndexFunc(m.form.Fields, func(field Field) bool { return field.Name == name }) + m.focus = slices.Index(m.visibleFields(), index) +} + +func TestFormAcceptsTypingAndPasteWithoutAnEditMode(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + focusField(&m, "output") + m = update(m, key('/', "/")) + if !m.editing || m.searching { + t.Fatal("typing a path should edit the selected field") + } + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: "آرشیو/Book Club"}) + previous := m.focus + m = update(m, key(tea.KeyTab, "")) + if got := m.form.field("output").Value; got != "آرشیو/Book Club" { + t.Fatalf("Tab lost the input: %q", got) + } + if m.editing || (m.focus == previous && !m.buttonsFocused) { + t.Fatal("Tab should save and move to the next setting") + } + m = update(m, key(tea.KeyTab, "", tea.ModShift)) + if m.focus != previous { + t.Fatal("Shift+Tab should return to the previous setting") + } +} + +func TestReviewSavesTheActiveEditorAndRejectsInvalidValues(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + focusField(&m, "output") + m = clickChoiceText(t, m, "[ Type path ]") + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: "exports/Saved Messages"}) + m = update(m, key('r', "", tea.ModCtrl)) + if m.screen != review || !slices.Contains(m.plan.Args, "--output=exports/Saved Messages") { + t.Fatal("Review must include the value still being edited") + } + m = update(m, key(tea.KeyEscape, "")) + m.advanced = true + focusField(&m, "every") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: "tomorrow"}) + focus := m.focus + m = update(m, key(tea.KeyTab, "")) + if !m.editing || m.focus != focus || m.err == "" { + t.Fatal("an invalid duration should keep focus and explain the error") + } + if m.form.field("every").Value == "tomorrow" { + t.Fatal("invalid input overwrote the last valid setting") + } +} + +func TestChoosingAllChatsClearsAnEarlierChatSelection(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + set(&m.form, "chat", "me") + focusField(&m, "all") + m = update(m, key(' ', " ")) + if m.form.field("chat").Value != "" || m.form.field("all").Value != "true" { + t.Fatal("the scope controls left mutually exclusive settings selected") + } + if _, err := m.form.Plan(nil); err != nil { + t.Fatalf("switching the backup scope should remain runnable: %v", err) + } +} + +func TestNativeProgressUsesMeasurementsAndDoesNotInventScanPercentages(t *testing.T) { + var buffer bytes.Buffer + taskui.WriteStatus(&buffer, taskui.Progress{Label: "video.mp4", Detail: "30 MiB / 100 MiB", Summary: "ETA 10s · 3 MiB/s", Percent: .3, Determinate: true, CompletedFiles: 2, TotalFiles: 8}) + tr := newTranscript(80, 24) + tr.write(buffer.Bytes()) + if tr.status == nil || tr.status.Percent != .3 || strings.Contains(tr.text(), "ta-progress") { + t.Fatal("structured progress was not kept separate from activity") + } + root, _ := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.status = tr.status + view := ansi.Strip(m.progressView(74)) + for _, want := range []string{"video.mp4", "30.0%", "2 / 8 files", "3 MiB/s"} { + if !strings.Contains(view, want) { + t.Fatalf("missing transfer measurement %q in %s", want, view) + } + } + m.status = &taskui.Progress{Label: "Scanning history", Detail: "800 files found"} + view = ansi.Strip(m.progressView(74)) + if strings.Contains(view, "%") || !strings.Contains(view, "Discovering") { + t.Fatal("a history scan must show activity without a made-up percentage") + } +} + +func TestAReceivedChatCanBeArchivedBeforeTheBrowserFinishes(t *testing.T) { + root, _ := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.screen, m.loading = result, true + m.plan = Plan{Path: []string{"chat", "ls"}, Title: "Browse your chats"} + rows := []item{{ID: "42", Title: "Synthetic chat"}, {ID: "84", Title: "Another synthetic chat"}} + m.data = resultData{Kind: "chat ls", Items: rows} + cancelled := false + m.job = &job{terminal: newTranscript(80, 24), streamSeen: true, items: rows, cancel: func() { cancelled = true }} + m.activate("archive") + if !cancelled || m.pendingAction != "archive" || m.screen != result { + t.Fatal("the lookup must stop before opening the selected chat") + } + m.resultSelected = 1 // Moving during shutdown must not change the chosen chat. + m.job.done, m.job.ended, m.job.err = true, time.Now(), context.Canceled + m = update(m, pollMsg{}) + if m.screen != configure || m.form.field("chat").Value != "42" || m.source == nil { + t.Fatal("selected chat was lost while stopping the lookup") + } + m.restoreList() + if len(m.data.Items) != 2 || m.data.Items[m.resultSelected].ID != "42" { + t.Fatal("the received list must remain available without another request") + } +} + +func TestActiveSecretInputIsMaskedAndEscapeDiscardsTheEdit(t *testing.T) { + root, action := fixture() + action.Command.Flags().String("passcode", "", "local app passcode") + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + m.advanced = true + focusField(&m, "passcode") + m = update(m, key(tea.KeyEnter, "")) + m = update(m, tea.PasteMsg{Content: "synthetic private phrase"}) + if strings.Contains(ansi.Strip(m.View().Content), "synthetic private phrase") { + t.Fatal("the active input exposed a passcode") + } + m = update(m, key(tea.KeyEscape, "")) + if m.editing || m.form.field("passcode").Value != "" { + t.Fatal("Escape should discard the current secret edit") + } +} + +func TestMouseOpensTheDisplayedWorkflowAfterScrollingANarrowDashboard(t *testing.T) { + _, action := fixture() + var actions []Action + for i := range 12 { + copy := action + copy.Group, copy.Title = "Quick start", fmt.Sprintf("Workflow %d", i) + actions = append(actions, copy) + } + m := New(actions, nil, "default", context.Background()) + m.width, m.height, m.selected = 80, 24, 9 + for y, line := range strings.Split(ansi.Strip(m.View().Content), "\n") { + if strings.Contains(line, "Workflow 7") { + m = update(m, tea.MouseClickMsg{X: 4, Y: y, Button: tea.MouseLeft}) + if m.screen != configure || m.form.Action.Title != "Workflow 7" { + t.Fatal("mouse selection disagreed with the workflow shown under the cursor") + } + return + } + } + t.Fatal("expected workflow was not visible") +} + +func TestTabReachesReviewWithoutEditingAndReturnsToTheLastField(t *testing.T) { + root, action := fixture() + m := New(Catalog(root), nil, "default", context.Background()) + m.open(action) + m.focus = len(m.visibleFields()) - 1 + m = update(m, key(tea.KeyTab, "")) + if !m.buttonsFocused || m.buttons()[m.buttonFocus].ID != "review" { + t.Fatal("Tab from the final field should focus the review action") + } + m = update(m, key(tea.KeyTab, "", tea.ModShift)) + if m.buttonsFocused || m.focus != len(m.visibleFields())-1 { + t.Fatal("Shift+Tab should return to the final field") + } +} + +func TestLongUnicodeInputKeepsTheCursorEndVisibleAndFitsTheTerminal(t *testing.T) { + root, action := fixture() + for _, width := range []int{55, 80, 120} { + m := New(Catalog(root), nil, "default", context.Background()) + m.width, m.height = width, 24 + m.open(action) + focusField(&m, "output") + m = clickChoiceText(t, m, "[ Type path ]") + m = update(m, key('u', "", tea.ModCtrl)) + m = update(m, tea.PasteMsg{Content: strings.Repeat("آرشیو/名字/", 20) + "visible-end"}) + view := ansi.Strip(m.View().Content) + if !strings.Contains(view, "visible-end") { + t.Fatalf("input cursor scrolled out of view at width %d:\n%s", width, view) + } + for _, line := range strings.Split(view, "\n") { + if ansi.StringWidth(line) > width { + t.Fatalf("input overflow at width %d: %q", width, line) + } + } + } +} + +func BenchmarkTaskPolling(b *testing.B) { + for _, changed := range []bool{false, true} { + name := "idle" + if changed { + name = "new-output" + } + b.Run(name, func(b *testing.B) { + m := New(nil, nil, "default", context.Background()) + m.screen = running + m.job = &job{terminal: newTranscript(80, 24)} + m.job.terminal.write([]byte(strings.Repeat("A completed synthetic file\n", 1800))) + m = update(m, pollMsg{}) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if changed { + m.job.revision++ + } + m = update(m, pollMsg{}) + } + }) + } +} diff --git a/internal/tui/view.go b/internal/tui/view.go index d1d4a81..9ab297f 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -38,11 +38,17 @@ func (m Model) View() tea.View { if namespace == "" { namespace = "inherited" } - right := dim.Render("namespace ") + accent.Render(clip(namespace, 18)) + right := dim.Render("account ") + accent.Render(clip(namespace, 18)) header += strings.Repeat(" ", max(1, width-lipgloss.Width(header)-lipgloss.Width(right))) + right } var body string - if m.help { + if m.pathDialog != nil { + body = m.pathDialogView(width, height) + } else if m.calendar != nil && !m.inlineCalendar() { + body = m.datePickerView() + } else if m.picker != nil && !m.inlinePicker() { + body = m.pickerView(width, height) + } else if m.help { body = m.helpView(width, height) } else { switch m.screen { @@ -77,11 +83,17 @@ func (m Model) dashboardView(width, height int) string { } sideWidth := 20 var nav strings.Builder - nav.WriteString(dim.Render("WORKSPACE") + "\n\n") + nav.WriteString(dim.Render("YOUR ARCHIVE") + "\n\n") for i, name := range Groups { - label := " " + name + display := name + if name == "Quick start" { + display = "Start here" + } else if name == "All commands" { + display = "Command library" + } + label := " " + display if i == m.group { - label = "▸ " + name + label = "▸ " + display nav.WriteString(selectedStyle.Width(sideWidth).Render(label)) } else { nav.WriteString(dim.Render(label)) @@ -89,7 +101,7 @@ func (m Model) dashboardView(width, height int) string { nav.WriteString("\n\n") } if height >= 23 { - nav.WriteString("\n" + dim.Render("YOUR NEXT BACKUP,\nA FEW KEYS AWAY.\n\n/ Search everything\n? Keyboard guide")) + nav.WriteString("\n" + dim.Render("/ Search workflows\nTab Change section\nEnter Open selected\n? Keyboard guide")) } mainWidth := width - sideWidth - 3 body := m.actionList(mainWidth, height) @@ -98,124 +110,52 @@ func (m Model) dashboardView(width, height int) string { func (m Model) actionList(width, height int) string { actions := m.filteredActions() - heading := "Choose a workflow" + heading, description := "What would you like to back up?", "Choose a task. We’ll guide you through the settings." if m.search != "" { - heading = "Search results" + heading, description = "Find your next task", "Search matches names and descriptions across every section." } else if Groups[m.group] != "Quick start" { - heading = Groups[m.group] + heading, description = Groups[m.group], "Every command is available here, including installed extensions." } - count := dim.Render(fmt.Sprintf("%d available", len(actions))) - header := titleStyle.Render(heading) + count := dim.Render(fmt.Sprintf("%d tasks", len(actions))) + header := titleStyle.Render(clip(heading, max(1, width-lipgloss.Width(count)-2))) header += strings.Repeat(" ", max(1, width-lipgloss.Width(header)-lipgloss.Width(count))) + count - search := dim.Render("/ Search commands, features and descriptions…") + search := dim.Render("/ Search workflows and commands…") if m.search != "" { search = accent.Render("/ ") + textStyle.Render(m.search) } if m.searching { - search = accent.Render("/ ") + m.inputView(width-4, false) + search = accent.Render("/ ") + m.inputView(width-7, false) } - lines := []string{header, "", clip(search, width), ""} + search = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(line).Padding(0, 1).Width(width).Render(clip(search, width-4)) + lines := []string{header, dim.Render(clip(description, width)), search, ""} if len(actions) == 0 { - return strings.Join(append(lines, dim.Render("No matches. Try “archive”, “cron” or “login”.")), "\n") - } - rowHeight := 3 - if height < 23 { - rowHeight = 2 + return strings.Join(append(lines, dim.Render("No matches. Try archive, login, or schedule.")), "\n") } - page := max(1, (height-6)/rowHeight) - start := max(0, m.selected-page+1) + rowHeight, page, start := m.actionListGeometry(height) for i := start; i < min(len(actions), start+page); i++ { action := actions[i] name := " " + action.Title + style := textStyle if i == m.selected { - name = "▸ " + action.Title - } - if i == m.selected { - lines = append(lines, selectedStyle.Bold(true).Width(width).Render(clip(name, width))) - } else { - lines = append(lines, textStyle.Render(clip(name, width))) + name, style = "▸ "+action.Title, selectedStyle.Bold(true).Width(width) } + lines = append(lines, style.Render(clip(name, width)), dim.Render(clip(" "+action.Description, width))) if rowHeight == 3 { - lines = append(lines, dim.Render(clip(" "+action.Description, width))) + lines = append(lines, "") } - lines = append(lines, "") } - lines = append(lines, dim.Render(fmt.Sprintf("%02d / %02d", m.selected+1, len(actions)))+" "+dim.Render("Enter to open · Review before making changes")) + lines = append(lines, dim.Render(fmt.Sprintf("%d / %d", m.selected+1, len(actions)))+" "+accent.Render("Enter to continue")) return strings.Join(lines, "\n") } -func (m Model) formView(width, height int) string { - fields := m.visibleFields() - top := accent.Render("01 CONFIGURE") + dim.Render(" ─── 02 REVIEW ─── 03 RUN") - heading := titleStyle.Render(m.form.Action.Title) - mode := "Common options" - if m.advanced { - mode = "All options" - } - if m.fieldSearch != "" { - mode = "Matching options" - } - unit := "fields" - if len(fields) == 1 { - unit = "field" - } - status := dim.Render(fmt.Sprintf("%s · %d %s · Ctrl+A to switch", mode, len(fields), unit)) - if m.searching { - status = accent.Render("/ ") + m.inputView(width-3, false) - } - lines := []string{top, "", heading, clip(status, width), ""} - page := max(1, height-11) - start := max(0, m.focus-page+1) - labelWidth := min(25, width/2) - for n := start; n < min(len(fields), start+page); n++ { - field := m.form.Fields[fields[n]] - marker := " " - if n == m.focus { - marker = "▸ " - } - label := field.Label - if field.Required { - label += " *" - } - label = lipgloss.NewStyle().Width(labelWidth).Render(clip(marker+label, labelWidth)) - value := field.Display() - if m.editing && n == m.focus { - value = m.inputView(width-labelWidth-4, field.Secret) - } - change := " " - if field.Dirty { - change = "•" - } - row := label + " " + change + " " + clip(value, width-labelWidth-3) - if n == m.focus { - lines = append(lines, selectedStyle.Width(width).Render(row)) - } else { - lines = append(lines, textStyle.Render(row)) - } - } - if len(fields) == 0 { - lines = append(lines, dim.Render("No matching options. Esc clears the search.")) - } - for len(lines) < height-5 { - lines = append(lines, "") - } - if len(fields) > 0 { - field := m.form.Fields[fields[m.focus]] - help := field.Help - if field.Type == "stringArray" || field.Type == "stringSlice" { - help += " Comma-separated values; quote a value containing a comma." - } - if len(field.Choices) > 0 { - help += " Choices: " + strings.Join(field.Choices, ", ") + "." - } - lines = append(lines, dim.Render(strings.Repeat("─", width))) - lines = append(lines, dim.Render(fit(ansi.Wrap(help, width, ""), width, 2))) - lines = append(lines, dim.Render(fmt.Sprintf("%d / %d", m.focus+1, len(fields)))+" "+accent.Render("Ctrl+R Review command")) - } - if m.err != "" { - lines = append(lines, lipgloss.NewStyle().Foreground(lipgloss.Color("#FFAFB8")).Render(clip("! "+m.err, width))) - } - return strings.Join(lines, "\n") +func (m Model) actionListGeometry(height int) (rowHeight, page, start int) { + rowHeight = 2 + if height >= 25 { + rowHeight = 3 + } + page = max(1, (height-7)/rowHeight) + start = max(0, m.selected-page+1) + return } func (m Model) reviewView(width, height int) string { @@ -224,7 +164,7 @@ func (m Model) reviewView(width, height int) string { if field.Name == "arguments" && field.Value == "" { continue } - if !field.Dirty { + if !field.Dirty && field.Advanced { continue } lines = append(lines, dim.Render(field.Label+" ")+textStyle.Render(clip(field.Display(), max(1, width-len(field.Label)-2)))) @@ -232,6 +172,12 @@ func (m Model) reviewView(width, height int) string { if len(lines) == 4 { lines = append(lines, dim.Render("Using the default settings for this workflow.")) } + if len(m.plan.Tasks) > 0 { + lines = append(lines, "", accent.Render(fmt.Sprintf("%d account backups · one at a time", len(m.plan.Tasks)))) + for _, task := range m.plan.Tasks { + lines = append(lines, textStyle.Render(clip(safeText(task.Account)+" → "+safeText(task.Directory), width))) + } + } if len(m.plan.Path) > 0 && m.plan.Path[0] == "login" { lines = append(lines, "", warning.Render("This replaces the saved login in the selected namespace.")) } @@ -246,23 +192,56 @@ func (m Model) reviewView(width, height int) string { } func (m Model) helpView(width, height int) string { - content := titleStyle.Render("A few keys. Every command.") + "\n\n" + accent.Render("WORKSPACE") + "\n↑/↓ or j/k Choose a command\nTab / ←/→ Change section\n/ Search across every command\nEnter Configure the selected command\n\n" + accent.Render("OPTIONS") + "\n↑/↓ or Tab Move between fields\nEnter Edit text or toggle a switch\nSpace / ←/→ Toggle a switch or cycle choices\nCtrl+A Show or hide advanced options\n/ Find any option, including advanced ones\nCtrl+D Reset a field to its inherited default\nCtrl+R Validate and review the command\n\n" + accent.Render("EDITING") + "\nEnter saves · Esc cancels · Ctrl+U clears\nHome/End · ←/→ · Ctrl+W delete word\nTab completes a unique file or directory path\n\nRESULTS & TASKS\nTab / Shift+Tab Focus action buttons\nEnter / click Activate the focused button\n↑/↓ · / Select or search results\nt / l / d Results / Activity / Details\ni Respond to an active prompt (Esc ends input)\nCtrl+C Cancel active task; keep workspace open\n\nEsc goes back · Ctrl+C exits when idle · ? closes this guide" + content := titleStyle.Render("A few keys. Every command.") + "\n\n" + accent.Render("WORKSPACE") + "\n↑/↓ or j/k Choose a command\nTab / ←/→ Change section\n/ Search across every command\nEnter Configure the selected command\n\n" + accent.Render("OPTIONS") + "\n↑/↓ or Tab Move between fields\nEnter Edit text or toggle a switch\nSpace / ←/→ Toggle a switch or cycle choices\nCtrl+A Show or hide advanced options\nCtrl+F Find any option, including advanced ones\nCtrl+D Reset a field to its inherited default\nCtrl+R Validate and review the command\n\n" + accent.Render("CHOICE DROPDOWNS") + "\nEnter / click Open the list beside the argument\n↑↓ / wheel Scroll the list; Enter/Space toggles items\nType to filter; checked items persist while scrolling\n← saves and closes; Tab saves and moves on; Esc undoes\nCtrl+A / Ctrl+D Select all / clear\nCtrl+L Refresh saved accounts\n\n" + accent.Render("FILES & FOLDERS") + "\nEnter / Browse Open the system file or folder chooser\nAlt+O Browse while editing a path\nType path Enter a destination manually\nEsc Cancel the chooser and keep your input\n\n" + accent.Render("EDITING") + "\nType or paste to edit · Enter saves · Esc undoes\nHome/End · ←/→ · Ctrl+W delete word\nTab saves and moves on · Alt+/ completes a path\n\nRESULTS & TASKS\nTab / Shift+Tab Focus action buttons\nEnter / click Activate the focused button\n↑/↓ · / Select or search results\nt / l / d Results / Activity / Details\ni Respond to an active prompt (Esc ends input)\nCtrl+C Cancel active task; keep workspace open\n\nEsc goes back · Ctrl+C exits when idle · ? closes this guide" return scrolled(content, width, height, m.scroll) } func (m Model) footer() string { + if m.calendar != nil { + return accent.Render("Enter choose · Esc cancel") + dim.Render(" Arrows day PgUp/PgDn month I type") + } + if m.pathDialog != nil { + if m.pathDialog.browser == nil { + return accent.Render("Choose in the system dialog") + dim.Render(" Esc cancel") + } + return accent.Render("Enter open · Space select") + dim.Render(" Tab actions Type to filter Ctrl+H hidden Esc cancel") + } + if m.picker != nil { + if m.inlinePicker() { + if !m.picker.multi { + return accent.Render("Enter select · Tab next") + dim.Render(" ↑↓ / wheel scroll Type to filter Esc undo") + } + if m.picker.custom { + return accent.Render("Enter add/toggle · ← save") + dim.Render(" Add/Done buttons Esc undo") + } + return accent.Render("Enter toggle · ← save") + dim.Render(" Click items/Done ↑↓ scroll Esc undo") + } + return accent.Render("Space select · Enter apply") + dim.Render(" Type to filter ↓ list Ctrl+A all Esc cancel") + } if m.help { return dim.Render("↑↓ scroll Esc / ? close guide") } if m.editing { - return accent.Render("Enter save") + dim.Render(" Esc cancel Ctrl+U clear Tab complete path") + if fields := m.visibleFields(); m.screen == configure && len(fields) > 0 && m.focus < len(fields) && m.form.Fields[fields[m.focus]].PathKind != "" { + return accent.Render("Enter save · Alt+O browse") + dim.Render(" Tab next Esc undo Ctrl+U clear") + } + return accent.Render("Enter save") + dim.Render(" Tab next Esc undo Ctrl+U clear Alt+/ complete path") } if m.searching { return accent.Render("Type to search") + dim.Render(" Enter finish Esc clear") } switch m.screen { case configure: - return accent.Render("Enter edit") + dim.Render(" ↑↓ move Ctrl+A advanced Ctrl+R review F6 buttons Esc back ? help") + if fields := m.visibleFields(); len(fields) > 0 && m.focus < len(fields) && m.form.Fields[fields[m.focus]].PathKind != "" { + return accent.Render("Enter browse · Alt+O chooser") + dim.Render(" Type path Tab next Ctrl+R review Esc back") + } + if fields := m.visibleFields(); len(fields) > 0 && m.focus < len(fields) && choiceField(m.form.Fields[fields[m.focus]]) { + if m.form.Fields[fields[m.focus]].Multi { + return accent.Render("Click to multi-select") + dim.Render(" Tab next Ctrl+R review Esc back") + } + return accent.Render("Enter select · Tab next") + dim.Render(" Click a choice Ctrl+R review Ctrl+F find option Esc back") + } + return accent.Render("Type to edit") + dim.Render(" Tab next Ctrl+R review Ctrl+F find option Esc back ? help") case review: return accent.Render("Enter run") + dim.Render(" Esc edit ↑↓ scroll ? help") case running: @@ -278,18 +257,9 @@ func (m Model) footer() string { } func (m Model) inputView(width int, secret bool) string { - value := string(m.input) - if secret { - value = strings.Repeat("•", len(m.input)) - } - runes := []rune(value) - start := max(0, m.cursor-max(1, width-3)) - before := string(runes[start:m.cursor]) - current, after := " ", "" - if m.cursor < len(runes) { - current, after = string(runes[m.cursor]), string(runes[m.cursor+1:]) - } - return clip(before+lipgloss.NewStyle().Reverse(true).Render(current)+after, width) + editor := m.editor + editor.SetWidth(max(1, width-1)) + return editor.View() } func clip(value string, width int) string { return ansi.Truncate(value, max(1, width), "…") }