feat(tui): App skeleton with mode machine, async navigation and effects (6.1.5)

The new UI's root model: Screen x viewer focus x native selection x
filter edit x modal stack, one inputOwner, keys resolved through the
registry, an action table that features extend from register_*.go.
Directory reads and previews run in Cmds with tickets: Update never
blocks (N-P1-1), stale results are dropped (U-P1-13), failed navigation
keeps the panel and a vanished directory climbs up (U-P1-8). q closes
layers before asking to quit (U-P1-16), PgDn pages (U-P1-6), the theme
list previews live and saves with config.SetKey. Mouse mode is
reconciled after every Update; View only reads state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-11-01 09:11:39 +03:00
parent bb7f98016b
commit 40b8722d58
22 changed files with 2567 additions and 0 deletions

148
internal/tui/actions.go Normal file
View file

@ -0,0 +1,148 @@
package tui
import (
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/keys"
"vcom/internal/tui/notify"
"vcom/internal/tui/panel"
)
// actionDef is the handler of one action.
type actionDef struct {
Run func(a *App) tea.Cmd
// Enabled is checked before Run; an error is shown ("Unavailable: …")
// and Run is skipped. nil means always enabled.
Enabled func(a *App) error
}
// actionTable maps actions to handlers. Features fill it in register_*.go.
type actionTable map[keys.ActionID]actionDef
func (t actionTable) add(id keys.ActionID, run func(*App) tea.Cmd, enabled func(*App) error) {
t[id] = actionDef{Run: run, Enabled: enabled}
}
// dispatch runs action id.
func (a *App) dispatch(id keys.ActionID) tea.Cmd {
def, ok := a.actions[id]
if !ok || def.Run == nil {
return a.notify(notify.Info, a.actionHelp(id)+": not available yet")
}
if def.Enabled != nil {
if err := def.Enabled(a); err != nil {
return a.notify(notify.Warn, "Unavailable: "+err.Error())
}
}
return def.Run(a)
}
func (a *App) actionHelp(id keys.ActionID) string {
for _, ctx := range keys.Contexts() {
for _, s := range a.keys.Help(ctx) {
for _, it := range s.Items {
if it.Action == id {
return it.Help
}
}
}
}
return string(id)
}
// registerCore installs the actions of the 6.1 skeleton.
func registerCore(t actionTable) {
move := func(f func(p *panel.Model)) func(*App) tea.Cmd {
return func(a *App) tea.Cmd {
f(a.Active())
return a.selectionChanged()
}
}
t.add(keys.NavUp, move(func(p *panel.Model) { p.MoveCursor(-1) }), nil)
t.add(keys.NavDown, move(func(p *panel.Model) { p.MoveCursor(1) }), nil)
t.add(keys.NavPageUp, move(func(p *panel.Model) { p.Page(-1, false) }), nil)
t.add(keys.NavPageDown, move(func(p *panel.Model) { p.Page(1, false) }), nil)
t.add(keys.NavHalfUp, move(func(p *panel.Model) { p.Page(-1, true) }), nil)
t.add(keys.NavHalfDown, move(func(p *panel.Model) { p.Page(1, true) }), nil)
t.add(keys.NavHome, move(func(p *panel.Model) { p.SetCursor(0) }), nil)
t.add(keys.NavEnd, move(func(p *panel.Model) { p.SetCursor(p.VisibleLen() - 1) }), nil)
t.add(keys.MarkToggle, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(1) }), nil)
t.add(keys.MarkUp, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(-1) }), nil)
t.add(keys.MarkDown, move(func(p *panel.Model) { p.ToggleMark(); p.MoveCursor(1) }), nil)
t.add(keys.NavOpen, (*App).openSelected, nil)
t.add(keys.NavEnter, (*App).enterSelected, nil)
t.add(keys.NavParent, (*App).goParent, nil)
t.add(keys.NavBack, func(a *App) tea.Cmd { return a.history(false) }, nil)
t.add(keys.NavForward, func(a *App) tea.Cmd { return a.history(true) }, nil)
t.add(keys.PaneSwitch, func(a *App) tea.Cmd {
a.active = 1 - a.active
a.relayout()
return a.selectionChanged()
}, nil)
t.add(keys.PanesReload, func(a *App) tea.Cmd { return tea.Batch(a.reload(0), a.reload(1)) }, nil)
t.add(keys.ToggleHidden, func(a *App) tea.Cmd {
a.deps.Config.Browser.ShowHidden = !a.deps.Config.Browser.ShowHidden
o := a.panelOptions()
for _, p := range a.panels {
p.SetOptions(o)
}
if o.ShowHidden {
return a.notify(notify.Info, "Hidden files shown")
}
return a.notify(notify.Info, "Hidden files hidden")
}, nil)
t.add(keys.BrowseEscape, func(a *App) tea.Cmd { a.escapeLayer(); return a.selectionChanged() }, nil)
t.add(keys.BrowseCtrlC, func(a *App) tea.Cmd {
if a.escapeLayer() {
return a.selectionChanged()
}
return a.askQuit()
}, nil)
t.add(keys.FilterStart, (*App).startFilter, nil)
t.add(keys.ScreenInfo, func(a *App) tea.Cmd { return a.setScreen(ScreenInfo) }, nil)
t.add(keys.InfoClose, func(a *App) tea.Cmd { return a.setScreen(ScreenBrowse) }, nil)
t.add(keys.ScreenView, (*App).openView, nil)
t.add(keys.ThemeSelect, (*App).openThemeSelect, nil)
t.add(keys.HelpShow, (*App).openHelp, nil)
t.add(keys.LogShow, (*App).openLog, nil)
t.add(keys.AppQuit, (*App).askQuit, nil)
// Viewer focus machine (the motions themselves are refined in 6.3).
t.add(keys.ViewerFocus, (*App).viewerFocus, nil)
t.add(keys.ViewerCaret, (*App).viewerCaret, nil)
t.add(keys.ViewerVisual, (*App).viewerVisual, nil)
t.add(keys.ViewerBack, (*App).viewerBack, nil)
t.add(keys.ViewerClose, (*App).viewerClose, nil)
t.add(keys.NativeSelect, (*App).toggleNativeSelect, nil)
t.add(keys.PreviewDown, func(a *App) tea.Cmd { a.viewer.Scroll(1); return nil }, nil)
t.add(keys.PreviewUp, func(a *App) tea.Cmd { a.viewer.Scroll(-1); return nil }, nil)
t.add(keys.ViewerLineUp, func(a *App) tea.Cmd { a.viewer.Scroll(-1); return nil }, nil)
t.add(keys.ViewerLineDown, func(a *App) tea.Cmd { a.viewer.Scroll(1); return nil }, nil)
t.add(keys.ViewerPageUp, func(a *App) tea.Cmd { a.viewer.Page(-1); return nil }, nil)
t.add(keys.ViewerPageDown, func(a *App) tea.Cmd { a.viewer.Page(1); return nil }, nil)
t.add(keys.ViewerTop, func(a *App) tea.Cmd { a.viewer.Jump(false); return nil }, nil)
t.add(keys.ViewerBottom, func(a *App) tea.Cmd { a.viewer.Jump(true); return nil }, nil)
}
// escapeLayer drops the filter, then the marks of the active panel; it
// reports whether something was dropped (Esc never quits).
func (a *App) escapeLayer() bool {
p := a.Active()
if p.Filter() != "" {
p.SetFilter("")
return true
}
return p.ClearMarks()
}
// notify pushes a note and schedules its expiry.
func (a *App) notify(l notify.Level, text string) tea.Cmd {
n := a.notes.Push(l, text, a.now())
id := n.ID
return tea.Tick(notify.TTL(l), func(time.Time) tea.Msg { return noteExpiredMsg{id} })
}
type noteExpiredMsg struct{ id uint64 }

180
internal/tui/app.go Normal file
View file

@ -0,0 +1,180 @@
// Package tui is the new user interface (design §7), enabled with
// --ui=next. The App is a tea.Model with an explicit mode machine (Screen ×
// viewer focus × native selection × filter edit × modal stack); one
// function decides who owns the keyboard (inputOwner), keys resolve through
// the keys.Registry, every async result carries a Ticket and is dropped
// when stale, and View only reads state.
//
// Extension points for stages 6.2–6.6 (each feature in its own files):
// - actions: registerOps/registerViewer/registerSSH/registerArchive/
// registerMisc add handlers to the action table (register_*.go);
// - messages: a.handle(fn) for the feature's own message types;
// - job events: a.onJob(fn) for jobs.Event;
// - key bindings: keys/bindings_<feature>.go;
// - modals: internal/tui/modal.
//
// Rules: Cmd functions never capture *App (only immutable inputs: Target,
// Ticket, options, leases); no file I/O outside vfs.FS (TestImportsGuard).
package tui
import (
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/theme"
"vcom/internal/tui/keys"
"vcom/internal/tui/modal"
"vcom/internal/tui/notify"
"vcom/internal/tui/panel"
"vcom/internal/tui/style"
"vcom/internal/tui/viewer"
)
// Screen is the main screen.
type Screen uint8
const (
ScreenBrowse Screen = iota
ScreenInfo
ScreenView
)
func (s Screen) String() string {
return [...]string{"browse", "info", "view"}[s]
}
// App is the root model.
type App struct {
deps Deps
keys *keys.Registry
styles *style.Styles
theme string
screen Screen
viewBack Screen
panels [2]*panel.Model
active int
filter *textinput.Model // non-nil while the filter line is edited
viewer viewer.Model
nativeSelect bool
modals modal.Stack
notes notify.Center
req Tracker
w, h int
layout Layout
applied effects
actions actionTable
handlers []func(*App, tea.Msg) (tea.Cmd, bool)
jobHooks []func(*App, jobEvent) tea.Cmd
jobSnaps map[uint64]jobSnap
// openFile handles Enter on a non-directory entry; set by stage 6.5
// (archives) and 6.6 (edit / run menu / xdg-open) in their hooks.
openFile func(*App, panel.Entry) tea.Cmd
previewFor string // what the viewer shows / is loading (location + name)
lastClick click
quitting bool
}
type click struct {
at time.Time
pane, row int
}
// New builds the App. Call Init (Bubble Tea does) to load the panels.
func New(d Deps) *App {
d.fill()
a := &App{deps: d, keys: keys.MustDefault(), jobSnaps: map[uint64]jobSnap{}}
a.setTheme(d.Config.UI.Theme)
opts := a.panelOptions()
for i := range a.panels {
m := panel.NewMount(d.LocalFS, "/", nil, "", nil, nil)
a.panels[i] = panel.New(i, opts, []panel.Mount{m}, d.StartDirs[i])
}
a.actions = actionTable{}
registerCore(a.actions)
registerOps(a.actions)
registerViewer(a.actions)
registerSSH(a.actions)
registerArchive(a.actions)
registerMisc(a.actions)
registerOpsHooks(a)
registerViewerHooks(a)
registerSSHHooks(a)
registerArchiveHooks(a)
registerMiscHooks(a)
return a
}
func (a *App) panelOptions() panel.Options {
b := a.deps.Config.Browser
return panel.Options{
ShowHidden: b.ShowHidden,
DirsFirst: b.DirsFirst,
SortBy: b.Sort.By,
Reverse: b.Sort.Reverse,
ShowSize: b.Columns.Size,
ShowTime: b.Columns.Modified,
HumanSize: b.HumanReadableSize,
}
}
// setTheme switches the palette (unknown names fall back to the default).
func (a *App) setTheme(name string) {
p, err := theme.Resolve(name)
if err != nil {
p, _ = theme.Resolve("catppuccin-mocha")
name = p.Name
}
a.theme = name
a.styles = style.New(p)
}
// Init loads both panels.
func (a *App) Init() tea.Cmd {
var cmds []tea.Cmd
if a.deps.Notice != "" {
cmds = append(cmds, a.notify(notify.Warn, a.deps.Notice))
}
for i, p := range a.panels {
cmds = append(cmds, a.navigate(i, p.Here(), "", panel.NavReplace))
}
cmds = append(cmds, a.reconcile())
return tea.Batch(cmds...)
}
// Active returns the active panel.
func (a *App) Active() *panel.Model { return a.panels[a.active] }
// Passive returns the other panel.
func (a *App) Passive() *panel.Model { return a.panels[1-a.active] }
// Panel returns panel i.
func (a *App) Panel(i int) *panel.Model { return a.panels[i] }
// Screen returns the current screen.
func (a *App) Screen() Screen { return a.screen }
// ThemeName is the theme in use.
func (a *App) ThemeName() string { return a.theme }
// Viewer exposes the viewer model (tests, stage 6.3).
func (a *App) Viewer() *viewer.Model { return &a.viewer }
// Quitting reports whether the user confirmed quitting.
func (a *App) Quitting() bool { return a.quitting }
// handle registers a handler for feature messages; it returns true when it
// consumed the message.
func (a *App) handle(fn func(*App, tea.Msg) (tea.Cmd, bool)) { a.handlers = append(a.handlers, fn) }
// onJob registers a job-event hook.
func (a *App) onJob(fn func(*App, jobEvent) tea.Cmd) { a.jobHooks = append(a.jobHooks, fn) }
// now is the clock.
func (a *App) now() time.Time { return a.deps.Clock() }

533
internal/tui/app_test.go Normal file
View file

@ -0,0 +1,533 @@
package tui
import (
"context"
"fmt"
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/config"
"vcom/internal/testutil/fstree"
"vcom/internal/testutil/teadriver"
"vcom/internal/tui/keys"
"vcom/internal/tui/viewer"
"vcom/internal/vfs"
"vcom/internal/vfs/localfs"
"vcom/internal/vfs/vfstest"
)
const settle = 3 * time.Second
type harness struct {
t *testing.T
d *teadriver.Driver
app *App
dir string
}
type opt func(*Deps)
func newHarness(t *testing.T, fsys vfs.FS, dir string, opts ...opt) *harness {
t.Helper()
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
d := Deps{
Config: cfg,
LocalFS: fsys,
StartDirs: [2]string{dir, dir},
SetConfigKey: func(string, string, string, any) (string, error) { return "test.toml", nil },
}
for _, o := range opts {
o(&d)
}
app := New(d)
h := &harness{t: t, app: app, dir: dir}
h.d = teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(150*time.Millisecond))
h.d.Settle(settle)
h.check()
return h
}
func (h *harness) check() {
h.t.Helper()
if err := h.app.Invariants(); err != nil {
h.t.Fatalf("invariants: %v\n%s", err, h.d.Screen())
}
}
// press sends keys, settling and checking invariants after each.
func (h *harness) press(ks ...string) {
h.t.Helper()
for _, k := range ks {
h.d.Press(k)
h.d.Settle(settle)
h.check()
}
}
func (h *harness) typ(s string) {
h.t.Helper()
h.d.Type(s)
h.d.Settle(settle)
h.check()
}
func (h *harness) selected() string {
e, _ := h.app.Active().Selected()
return e.Name
}
// cursorTo moves the active panel's cursor onto name.
func (h *harness) cursorTo(name string) {
h.t.Helper()
p := h.app.Active()
for i := 0; i < p.VisibleLen(); i++ {
if e, _ := p.Visible(i); e.Name == name {
p.SetCursor(i)
return
}
}
h.t.Fatalf("%s not in panel: %s", name, h.d.Screen())
}
func tree(t *testing.T, spec fstree.Spec) string {
t.Helper()
dir := t.TempDir()
fstree.Build(t, dir, spec)
return dir
}
// gate blocks hooks until released.
type gate struct {
once sync.Once
ch chan struct{}
}
func newGate(t *testing.T) *gate {
g := &gate{ch: make(chan struct{})}
t.Cleanup(g.open)
return g
}
func (g *gate) open() { g.once.Do(func() { close(g.ch) }) }
// N-P1-1, U-P1-9: a hung ReadDir must not block Update; Esc and q work.
func TestUpdateNeverBlocks(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("f", "x")})
g := newGate(t)
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir {
<-g.ch
}
return nil
}}
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
app := New(Deps{Config: cfg, LocalFS: fsys, StartDirs: [2]string{dir, dir}})
d := teadriver.New(t, app, 100, 30, teadriver.WithLongCmd(50*time.Millisecond))
d.Settle(time.Second) // the listings hang
for _, k := range []string{"esc", "j", "tab", "o", "o", "q"} {
start := time.Now()
d.Press(k)
if el := time.Since(start); el > 10*time.Millisecond {
t.Errorf("Update(%s) took %v", k, el)
}
}
if !strings.Contains(d.Screen(), "Quit vcom?") {
t.Fatalf("quit dialog not shown while a listing hangs:\n%s", d.Screen())
}
d.Press("q")
d.Settle(time.Second)
if !d.Quit() {
t.Fatal("q q did not quit while a listing hangs")
}
g.open()
}
// U-P1-13: a listing that arrives after a newer navigation is dropped.
func TestStaleListingIgnored(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("a"), fstree.File("a/in-a", ""), fstree.Dir("b"), fstree.File("b/in-b", "")})
g := newGate(t)
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir && filepath.Base(p) == "a" {
<-g.ch
}
return nil
}}
h := newHarness(t, fsys, dir)
h.cursorTo("a")
h.press("enter") // hangs
if h.app.Active().Path() != dir {
t.Fatal("panel changed before its listing arrived")
}
h.cursorTo("b")
h.press("enter")
if got := h.app.Active().Path(); got != filepath.Join(dir, "b") {
t.Fatalf("path = %s", got)
}
g.open()
h.d.Settle(settle)
if got := h.app.Active().Path(); got != filepath.Join(dir, "b") {
t.Fatalf("stale listing of a applied: path = %s", got)
}
if h.selected() != "in-b" && !h.d.ScreenContains("in-b") {
t.Fatalf("b's content not shown:\n%s", h.d.Screen())
}
}
// U-P1-13: a stale preview (Image) must not knock the viewer out of Caret.
func TestStalePreviewDoesNotExitCaret(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a.txt", "line1\nline2"), fstree.File("b.png", "img")})
g := newGate(t)
prev := func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, _ int64) (viewer.Content, error) {
if fi.Name == "b.png" {
<-g.ch // ignores ctx on purpose: the result arrives late
return viewer.Content{Kind: viewer.Image, Title: "b.png"}, nil
}
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: []string{"line1", "line2"}}, nil
}
h := newHarness(t, localfs.New(), dir, func(d *Deps) { d.Preview = prev })
h.cursorTo("a.txt")
h.press("o")
if h.app.Viewer().Kind != viewer.Text {
t.Fatalf("preview of a.txt not loaded: %v", h.app.Viewer().Kind)
}
h.press("j") // b.png: its preview hangs
h.press("k") // back to a.txt
h.press("i")
if h.app.InputOwner() != keys.CtxCaret {
t.Fatalf("not in caret: %s", h.app.InputOwner())
}
g.open()
h.d.Settle(settle)
h.check()
if h.app.InputOwner() != keys.CtxCaret || h.app.Viewer().Kind != viewer.Text {
t.Fatalf("stale preview changed the viewer: owner %s kind %v", h.app.InputOwner(), h.app.Viewer().Kind)
}
}
func lockedFS(dir string) vfs.FS {
return &vfstest.FaultFS{FS: localfs.New(), Hook: func(op vfstest.Op, p string) error {
if op == vfstest.OpReadDir && filepath.Base(p) == "locked" {
return &os.PathError{Op: "open", Path: p, Err: vfs.ErrPermission}
}
return nil
}}
}
// U-P1-8: a failed navigation leaves the panel as it was.
func TestNavErrorKeepsPanel(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("locked"), fstree.File("other", "")})
h := newHarness(t, lockedFS(dir), dir)
h.cursorTo("locked")
before := h.app.Active().VisibleLen()
h.press("enter")
p := h.app.Active()
if p.Path() != dir || p.VisibleLen() != before || h.selected() != "locked" || p.Loading {
t.Fatalf("panel changed: path %s, %d entries, on %q", p.Path(), p.VisibleLen(), h.selected())
}
}
// U-P1-1: errors are visible in the status line.
func TestStatusLineShowsError(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("locked")})
h := newHarness(t, lockedFS(dir), dir)
h.cursorTo("locked")
h.press("enter")
scr := h.d.Screen()
last := strings.Split(scr, "\n")
status := last[len(last)-2]
if !strings.Contains(status, "Cannot open") || !strings.Contains(status, "permission") {
t.Fatalf("status line = %q", status)
}
// It stays at least until a key is pressed.
h.d.Settle(settle)
if !h.d.ScreenContains("Cannot open") {
t.Fatal("error vanished without a key press")
}
}
// U-P1-8: if the current directory vanishes, a refresh climbs to the
// nearest existing parent.
func TestVanishedDirClimbsUp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("x/y/z"), fstree.File("x/keep", "")})
deep := filepath.Join(dir, "x", "y", "z")
h := newHarness(t, localfs.New(), deep)
if err := os.RemoveAll(filepath.Join(dir, "x", "y")); err != nil {
t.Fatal(err)
}
h.press("ctrl+r")
if got := h.app.Active().Path(); got != filepath.Join(dir, "x") {
t.Fatalf("path = %s, want %s", got, filepath.Join(dir, "x"))
}
if got := h.app.Passive().Path(); got != filepath.Join(dir, "x") {
t.Fatalf("passive path = %s", got)
}
if !h.d.ScreenContains("vanished") {
t.Fatalf("no notice:\n%s", h.d.Screen())
}
}
// U-P1-16: q closes layers first; quitting needs confirmation; q q is fast.
func TestQClosesLayersThenConfirmsQuit(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("apple", ""), fstree.File("banana", "")})
h := newHarness(t, localfs.New(), dir)
h.press("o")
if h.app.Screen() != ScreenInfo {
t.Fatal("o did not open Info")
}
h.press("q")
if h.app.Screen() != ScreenBrowse || h.d.Quit() {
t.Fatal("q in Info did not just close Info")
}
h.press("/")
h.typ("an")
h.press("enter")
if h.app.Active().Filter() != "an" {
t.Fatalf("filter = %q", h.app.Active().Filter())
}
h.press("q")
if h.d.Quit() || !h.d.ScreenContains("Quit vcom?") {
t.Fatal("q in Browse quit without asking")
}
h.press("esc")
if h.d.Quit() || h.d.ScreenContains("Quit vcom?") {
t.Fatal("Esc in the quit dialog did not just close it")
}
h.press("esc") // drops the filter, never quits
if h.app.Active().Filter() != "" || h.d.Quit() {
t.Fatal("Esc did not drop the filter")
}
h.press("q", "q")
if !h.d.Quit() || !h.app.Quitting() {
t.Fatal("q q did not quit")
}
}
// U-P1-6: PgDn moves a page.
func TestPgDn(t *testing.T) {
var spec fstree.Spec
for i := 0; i < 200; i++ {
spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), ""))
}
h := newHarness(t, localfs.New(), tree(t, spec))
rows := h.app.Active().Rows()
if rows < 10 {
t.Fatalf("rows = %d", rows)
}
h.press("pgdown")
if c := h.app.Active().Cursor(); c != rows-1 {
t.Fatalf("cursor after PgDn = %d, want %d", c, rows-1)
}
h.press("pgdown", "pgup")
if c := h.app.Active().Cursor(); c != rows-1 {
t.Fatalf("cursor after PgDn PgUp = %d", c)
}
h.press("G")
if c := h.app.Active().Cursor(); c != 200 { // ".." + 200 files
t.Fatalf("G: cursor %d", c)
}
}
func TestInvariantsAfterEachStep(t *testing.T) {
dir := tree(t, fstree.Spec{
fstree.File("a.txt", "hello\nworld"), fstree.File("b.bin", "\x00\x01"), fstree.Dir("sub"),
fstree.File("sub/c.txt", "c"), fstree.Symlink("link", "sub"),
})
seed := time.Now().UnixNano()
t.Logf("seed %d", seed)
rng := rand.New(rand.NewSource(seed))
pool := []string{"j", "k", "o", "i", "v", "esc", "q", "/", "a", "enter", "tab", "ctrl+t", "f3",
"pgdown", "g", "G", "?", "t", "h", "l", "n", "y", "insert", "ctrl+c", "backspace", "W", "й", "п"}
cfg := config.Default()
cfg.Behavior.ConfirmQuit = true
app := New(Deps{Config: cfg, LocalFS: localfs.New(), StartDirs: [2]string{dir, dir},
SetConfigKey: func(string, string, string, any) (string, error) { return "x", nil }})
d := teadriver.New(t, app, 80, 24, teadriver.WithLongCmd(20*time.Millisecond))
d.Settle(settle)
for i := 0; i < 400; i++ {
k := pool[rng.Intn(len(pool))]
d.Press(k)
d.Settle(settle)
if err := app.Invariants(); err != nil {
t.Fatalf("step %d (%q): %v", i, k, err)
}
_ = d.Screen()
}
}
// Design §9.2: the theme is saved with config.SetKey (comments kept).
func TestThemeSelectPreservesConfigComments(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("f", "")})
cfgPath := filepath.Join(t.TempDir(), "vcom.toml")
orig := "# my settings\n[ui]\n# the look\ntheme = \"nord\"\nshow_footer = true\n"
if err := os.WriteFile(cfgPath, []byte(orig), 0o600); err != nil {
t.Fatal(err)
}
h := newHarness(t, localfs.New(), dir, func(d *Deps) {
d.Config.UI.Theme = "nord"
d.ConfigPath = cfgPath
d.SetConfigKey = config.SetKey
})
h.press("t", "down")
next := h.app.ThemeName()
if next == "nord" {
t.Fatal("no live preview")
}
h.press("enter")
data, _ := os.ReadFile(cfgPath)
got := string(data)
if !strings.Contains(got, "theme = \""+next+"\"") || !strings.Contains(got, "# my settings") ||
!strings.Contains(got, "# the look") || !strings.Contains(got, "show_footer = true") {
t.Fatalf("config after save:\n%s", got)
}
// Esc reverts the live preview and writes nothing.
h.press("t", "down", "esc")
if h.app.ThemeName() != next {
t.Fatalf("Esc kept %s", h.app.ThemeName())
}
if data2, _ := os.ReadFile(cfgPath); string(data2) != got {
t.Fatal("Esc wrote the config")
}
}
// Crutch #10/#14: under a modal, the mouse does nothing to the panels.
func TestMouseUnderModalIgnored(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", ""), fstree.File("c", "")})
h := newHarness(t, localfs.New(), dir)
h.press("q")
cur := h.app.Active().Cursor()
lr := h.app.listRect(0)
h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonLeft)
h.d.Mouse(lr.X+1, lr.Y+2, tea.MouseButtonWheelDown)
h.d.Settle(settle)
if h.app.Active().Cursor() != cur || h.app.active != 0 || !h.d.ScreenContains("Quit vcom?") {
t.Fatal("click under the modal acted")
}
}
func TestMarksKeptOnTab(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a", ""), fstree.File("b", "")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("a")
h.press("insert")
h.press("tab", "tab")
if h.app.Active().MarkCount() != 1 || !h.app.Active().Marked("a") {
t.Fatal("marks lost on Tab")
}
h.press("esc")
if h.app.Active().MarkCount() != 0 {
t.Fatal("Esc did not clear marks")
}
}
// U-P1-4 through the App: a click picks the visible row under the mouse.
func TestFilterVisibleIndexAndMouseApp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("abc", ""), fstree.File("bcd", ""), fstree.File("xyz", ""), fstree.File("xbz", "")})
h := newHarness(t, localfs.New(), dir)
h.press("/")
h.typ("b")
h.press("enter")
lr := h.app.listRect(0)
h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft) // third row: "..", abc, bcd
h.d.Settle(settle)
if got := h.selected(); got != "bcd" {
t.Fatalf("clicked %q, want bcd\n%s", got, h.d.Screen())
}
// A double click opens like Enter (here: a file → not available yet, no crash).
h.d.Mouse(lr.X+2, lr.Y+2, tea.MouseButtonLeft)
h.d.Settle(settle)
h.check()
}
// U-P1-5 through the App: Cyrillic goes into the filter as typed.
func TestTextContextPassesRunesApp(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("папка"), fstree.File("quit", "")})
h := newHarness(t, localfs.New(), dir)
h.press("/")
h.typ("папка")
if got := h.app.Active().Filter(); got != "папка" {
t.Fatalf("filter = %q", got)
}
h.press("enter")
h.press("/")
h.typ("q") // a letter here, not quit
if h.d.Quit() || h.d.ScreenContains("Quit vcom?") {
t.Fatal("q in the filter line acted as a command")
}
}
func TestNavigationHistoryAndParent(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.Dir("sub/deeper"), fstree.File("top", "")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("sub")
h.press("l")
h.cursorTo("deeper")
h.press("enter")
if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") {
t.Fatal("enter failed")
}
h.press("h")
if h.app.Active().Path() != filepath.Join(dir, "sub") || h.selected() != "deeper" {
t.Fatalf("parent: %s on %q", h.app.Active().Path(), h.selected())
}
h.press("[")
if h.app.Active().Path() != filepath.Join(dir, "sub", "deeper") {
t.Fatalf("back: %s", h.app.Active().Path())
}
h.press("]")
if h.app.Active().Path() != filepath.Join(dir, "sub") {
t.Fatalf("forward: %s", h.app.Active().Path())
}
h.press("?")
if !h.d.ScreenContains("Help") || !h.d.ScreenContains("history back") {
t.Fatalf("help:\n%s", h.d.Screen())
}
h.press("esc")
h.press("f5") // not implemented in 6.1: a note, no crash
if !h.d.ScreenContains("not available yet") {
t.Fatalf("no note for an unimplemented action:\n%s", h.d.Screen())
}
}
func TestViewScreenAndBack(t *testing.T) {
dir := tree(t, fstree.Spec{fstree.File("a.txt", "one\ntwo\nthree"), fstree.Dir("d")})
h := newHarness(t, localfs.New(), dir)
h.cursorTo("d")
h.press("f3")
if h.app.Screen() != ScreenBrowse {
t.Fatal("F3 on a directory opened View")
}
h.cursorTo("a.txt")
h.press("f3")
if h.app.Screen() != ScreenView || !h.d.ScreenContains("three") {
t.Fatalf("View:\n%s", h.d.Screen())
}
h.press("i", "v")
if h.app.InputOwner() != keys.CtxVisual {
t.Fatalf("owner %s", h.app.InputOwner())
}
h.press("esc", "esc")
if h.app.InputOwner() != keys.CtxViewScroll {
t.Fatalf("owner %s", h.app.InputOwner())
}
h.press("ctrl+t")
if !h.app.nativeSelect {
t.Fatal("ctrl+t")
}
h.press("esc")
if h.app.nativeSelect || h.app.Screen() != ScreenView {
t.Fatal("Esc must end native selection first")
}
h.press("q")
if h.app.Screen() != ScreenBrowse {
t.Fatal("q did not close View")
}
}

124
internal/tui/deps.go Normal file
View file

@ -0,0 +1,124 @@
package tui
import (
"context"
"io"
"os"
"strings"
"time"
"unicode/utf8"
"vcom/internal/config"
"vcom/internal/jobs"
"vcom/internal/ssh/conn"
"vcom/internal/ssh/sshconfig"
"vcom/internal/tui/viewer"
"vcom/internal/vfs"
"vcom/internal/vfs/localfs"
)
// PreviewFunc builds the preview of an entry. Stage 5B/6.3 plug
// preview.Build in here; the default reads the head of text files.
type PreviewFunc func(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxBytes int64) (viewer.Content, error)
// Deps are the App's outside world. Everything the UI touches goes through
// them, so tests substitute fakes (FaultFS, a fixed clock, a fake preview).
// This file and external.go are the only ones in internal/tui allowed to
// import os (TestImportsGuard).
type Deps struct {
Config config.Config
ConfigPath string // file the theme choice is written to ("" = default XDG path)
// SetConfigKey edits one key of the config file (default config.SetKey).
SetConfigKey func(path, section, key string, value any) (string, error)
LocalFS vfs.FS
StartDirs [2]string // initial directories of the left and right panel
Jobs *jobs.Manager
Pool *conn.Pool
Resolver *sshconfig.Resolver
Preview PreviewFunc
Clock func() time.Time
// Notice is shown in the status line at start (config warnings).
Notice string
}
// DefaultDeps fills Deps for the real program.
func DefaultDeps(cfg config.Config, configPath string) Deps {
wd, err := os.Getwd()
if err != nil {
wd, _ = os.UserHomeDir()
}
left, right := wd, wd
if cfg.Startup.LeftPath != "" {
left = expandHome(cfg.Startup.LeftPath)
}
if cfg.Startup.RightPath != "" {
right = expandHome(cfg.Startup.RightPath)
}
return Deps{
Config: cfg,
ConfigPath: configPath,
LocalFS: localfs.New(),
StartDirs: [2]string{left, right},
}
}
func expandHome(p string) string {
if p == "~" || strings.HasPrefix(p, "~/") {
if h, err := os.UserHomeDir(); err == nil {
return h + p[1:]
}
}
return p
}
func (d *Deps) fill() {
if d.SetConfigKey == nil {
d.SetConfigKey = config.SetKey
}
if d.Clock == nil {
d.Clock = time.Now
}
if d.Preview == nil {
d.Preview = defaultPreview
}
if d.LocalFS == nil {
d.LocalFS = localfs.New()
}
for i, p := range d.StartDirs {
if p == "" {
d.StartDirs[i] = "/"
}
}
}
// defaultPreview shows the head of a text file, metadata otherwise.
func defaultPreview(ctx context.Context, loc vfs.Location, fi vfs.FileInfo, maxBytes int64) (viewer.Content, error) {
p := loc.FS.Paths().Join(loc.Path, fi.Name)
meta := viewer.Content{Kind: viewer.Other, Title: fi.Name, Lines: []string{
fi.Name,
fi.Mode.String(),
fi.ModTime.Format("2006-01-02 15:04:05"),
}}
if !fi.IsRegularLike() {
return meta, nil
}
if maxBytes <= 0 {
maxBytes = 64 << 10
}
f, err := loc.FS.Open(ctx, p)
if err != nil {
return viewer.Content{}, err
}
defer f.Close()
buf, err := io.ReadAll(io.LimitReader(f, maxBytes))
if err != nil {
return viewer.Content{}, err
}
if !utf8.Valid(buf) || strings.ContainsRune(string(buf), 0) {
return meta, nil
}
return viewer.Content{Kind: viewer.Text, Title: fi.Name, Lines: strings.Split(strings.TrimRight(string(buf), "\n"), "\n")}, nil
}

44
internal/tui/effects.go Normal file
View file

@ -0,0 +1,44 @@
package tui
import tea "github.com/charmbracelet/bubbletea"
// Terminal side effects (mouse mode, image overlay) are not done in View or
// scattered in handlers: after every Update the desired state is compared
// with what was applied and one command fixes the difference (design §7.9).
const (
mouseUnknown int8 = iota
mouseOn
mouseOff
)
type effects struct {
mouse int8
// overlay: imgview.Desired once stage 5C/6.3 lands.
}
type desiredEffects struct {
Mouse bool
}
func (a *App) desired() desiredEffects {
return desiredEffects{Mouse: !a.nativeSelect}
}
// reconcile returns the command that brings the terminal to the desired
// state, or nil.
func (a *App) reconcile() tea.Cmd {
d := a.desired()
want := mouseOff
if d.Mouse {
want = mouseOn
}
if a.applied.mouse == want {
return nil
}
a.applied.mouse = want
if want == mouseOn {
return tea.EnableMouseCellMotion
}
return tea.DisableMouse
}

61
internal/tui/help.go Normal file
View file

@ -0,0 +1,61 @@
package tui
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/keys"
"vcom/internal/tui/modal"
)
// openHelp shows the bindings of the context that owned input, generated
// from the registry (design §7.4).
func (a *App) openHelp() tea.Cmd {
ctx := a.inputOwner()
var lines []string
for i, s := range a.keys.Help(ctx) {
if i > 0 {
lines = append(lines, "")
}
lines = append(lines, "── "+s.Title+" ──")
w := 0
for _, it := range s.Items {
w = max(w, ansi.StringWidth(it.Keys))
}
for _, it := range s.Items {
lines = append(lines, fmt.Sprintf(" %s%s %s", it.Keys, strings.Repeat(" ", w-ansi.StringWidth(it.Keys)), it.Help))
}
}
a.openModal(modal.NewText("Help: "+contextTitle(ctx), lines), nil)
return nil
}
func contextTitle(c keys.Context) string {
switch c {
case keys.CtxBrowse:
return "panels"
case keys.CtxInfo:
return "info"
case keys.CtxViewScroll:
return "viewer"
}
return c.String()
}
// openLog is "L": the message log, newest last.
func (a *App) openLog() tea.Cmd {
var lines []string
for _, n := range a.notes.Log() {
lines = append(lines, fmt.Sprintf("%s %-5s %s", n.At.Format("15:04:05"), n.Level, n.Text))
}
if len(lines) == 0 {
lines = []string{"(no messages)"}
}
l := modal.NewText("Messages", lines)
a.openModal(l, nil)
l.Key(keys.ModalEnd, tea.KeyMsg{})
return nil
}

87
internal/tui/jobs.go Normal file
View file

@ -0,0 +1,87 @@
package tui
import (
"fmt"
"sort"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/jobs"
"vcom/internal/tui/notify"
)
// JobEvent wraps a jobs.Event for the program: main passes
// func(e jobs.Event) { program.Send(tui.JobEvent(e)) } as the jobs notify
// callback.
func JobEvent(e jobs.Event) tea.Msg { return jobEventMsg{E: e} }
type jobEventMsg struct{ E jobs.Event }
// jobEvent is what feature hooks receive.
type jobEvent = jobEventMsg
type jobSnap = jobs.Snapshot
// onJobEvent keeps snapshots for the status line and runs feature hooks
// (stage 6.2 opens progress/conflict modals there). Without a hook a
// finished job is reported in the status line.
func (a *App) onJobEvent(m jobEventMsg) tea.Cmd {
var cmds []tea.Cmd
switch e := m.E.(type) {
case jobs.Started:
a.jobSnaps[uint64(e.Snapshot.ID)] = e.Snapshot
case jobs.ProgressTick:
for _, s := range e.Snapshots {
a.jobSnaps[uint64(s.ID)] = s
}
case jobs.Finished:
delete(a.jobSnaps, uint64(e.Snapshot.ID))
if len(a.jobHooks) == 0 {
cmds = append(cmds, a.reportJob(e.Snapshot))
}
case jobs.Asked:
if len(a.jobHooks) == 0 {
cmds = append(cmds, a.notify(notify.Warn, fmt.Sprintf("Job %q is waiting for an answer", a.jobTitle(e.Question.Job))))
}
}
for _, h := range a.jobHooks {
cmds = append(cmds, h(a, m))
}
return tea.Batch(cmds...)
}
func (a *App) jobTitle(id jobs.ID) string {
if s, ok := a.jobSnaps[uint64(id)]; ok {
return s.Title
}
return fmt.Sprint(id)
}
func (a *App) reportJob(s jobs.Snapshot) tea.Cmd {
switch s.State {
case jobs.Done:
return a.notify(notify.Success, s.Title+": done")
case jobs.Cancelled:
return a.notify(notify.Warn, s.Title+": cancelled")
default:
return a.notify(notify.Error, fmt.Sprintf("%s: %v", s.Title, s.Err))
}
}
// activeJobs returns running/queued snapshots by ID.
func (a *App) activeJobs() []jobs.Snapshot {
out := make([]jobs.Snapshot, 0, len(a.jobSnaps))
for _, s := range a.jobSnaps {
out = append(out, s)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// activeJobCount prefers the manager (authoritative) over snapshots.
func (a *App) activeJobCount() int {
if a.deps.Jobs != nil {
return a.deps.Jobs.Active()
}
return len(a.jobSnaps)
}

92
internal/tui/layout.go Normal file
View file

@ -0,0 +1,92 @@
package tui
import (
"vcom/internal/tui/geom"
"vcom/internal/tui/panel"
)
// Layout holds every screen rectangle. Rendering, mouse hit-tests and the
// image overlay use the same values (design §7.3).
type Layout struct {
W, H int
Panes [2]geom.Rect // empty when the pane is hidden (Info shows only the active one)
Preview geom.Rect // Info: the preview box (with border)
PreviewBody geom.Rect // inside the preview border
Viewer geom.Rect // View screen: full content area
Status geom.Rect
Footer geom.Rect
Screen geom.Rect // whole terminal (modals center in it)
}
// computeLayout splits the terminal for the current screen.
func computeLayout(w, h int, screen Screen, active int, footer bool, previewPct, gap int) Layout {
l := Layout{W: w, H: h, Screen: geom.Rect{W: w, H: h}}
bottom := 1
if footer && h >= 8 {
bottom = 2
}
l.Status = geom.Rect{X: 0, Y: h - bottom, W: w, H: 1}
if bottom == 2 {
l.Footer = geom.Rect{X: 0, Y: h - 1, W: w, H: 1}
}
body := geom.Rect{W: w, H: max(0, h-bottom)}
switch screen {
case ScreenView:
l.Viewer = body
case ScreenInfo:
pct := previewPct
if pct < 20 || pct > 80 {
pct = 50
}
pw := body.W * pct / 100
lw := body.W - pw
l.Panes[active] = geom.Rect{X: 0, Y: 0, W: lw, H: body.H}
l.Preview = geom.Rect{X: lw, Y: 0, W: pw, H: body.H}
l.PreviewBody = geom.Rect{X: lw + 1, Y: 2, W: max(0, pw-2), H: max(0, body.H-3)}
default:
gap = max(0, min(gap, 4))
lw := (body.W - gap) / 2
l.Panes[0] = geom.Rect{X: 0, Y: 0, W: lw, H: body.H}
l.Panes[1] = geom.Rect{X: lw + gap, Y: 0, W: body.W - lw - gap, H: body.H}
}
return l
}
// paneAt returns the pane whose rectangle contains (x, y).
func (l Layout) paneAt(x, y int) (int, bool) {
for i, r := range l.Panes {
if !r.Empty() && r.Contains(x, y) {
return i, true
}
}
return 0, false
}
// listRect is the rows area of pane i given its filter state.
func (a *App) listRect(i int) geom.Rect {
return panel.ListRect(a.layout.Panes[i], a.filterRow(i))
}
func (a *App) filterRow(i int) bool {
return a.panels[i].Filter() != "" || (a.filter != nil && i == a.active)
}
// relayout recomputes the layout and tells panels and the viewer their
// sizes. Called after every Update (cheap) so View stays pure.
func (a *App) relayout() {
c := a.deps.Config.UI
a.layout = computeLayout(a.w, a.h, a.screen, a.active, c.ShowFooter, c.PreviewWidthPercent, c.PaneGap)
for i, p := range a.panels {
r := a.layout.Panes[i]
if r.Empty() {
r = a.layout.Panes[a.active]
}
p.SetRows(panel.ListRect(r, a.filterRow(i)).H)
}
switch a.screen {
case ScreenView:
a.viewer.SetRows(a.layout.Viewer.H - 1)
case ScreenInfo:
a.viewer.SetRows(a.layout.PreviewBody.H)
}
}

321
internal/tui/modes.go Normal file
View file

@ -0,0 +1,321 @@
package tui
import (
"context"
"errors"
"fmt"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/keys"
"vcom/internal/tui/notify"
"vcom/internal/tui/viewer"
"vcom/internal/vfs"
)
// inputOwner decides who gets the keyboard — the one place that does
// (design §7.3).
func (a *App) inputOwner() keys.Context {
switch {
case a.modals.Len() > 0:
return a.modals.Top().Context()
case a.filter != nil:
return keys.CtxFilterEdit
case a.screen == ScreenView:
return viewerCtx(a.viewer.Focus)
case a.screen == ScreenInfo && a.viewer.Focus != viewer.Scroll:
return viewerCtx(a.viewer.Focus)
case a.screen == ScreenInfo:
return keys.CtxInfo
}
return keys.CtxBrowse
}
// InputOwner is inputOwner for tests and features.
func (a *App) InputOwner() keys.Context { return a.inputOwner() }
func viewerCtx(f viewer.Focus) keys.Context {
switch f {
case viewer.Caret:
return keys.CtxCaret
case viewer.Visual:
return keys.CtxVisual
}
return keys.CtxViewScroll
}
// Invariants checks the allowed state combinations (design §7.2); tests
// call it after every step.
func (a *App) Invariants() error {
var errs []error
if a.viewer.Focus != viewer.Scroll && (a.screen == ScreenBrowse || a.viewer.Kind != viewer.Text) {
errs = append(errs, fmt.Errorf("viewer focus %d on screen %s with kind %d", a.viewer.Focus, a.screen, a.viewer.Kind))
}
if a.nativeSelect && a.screen == ScreenBrowse {
errs = append(errs, errors.New("native selection in Browse"))
}
if a.filter != nil && (a.screen == ScreenView || a.modals.Len() > 0) {
errs = append(errs, fmt.Errorf("filter edited on %s with %d modals", a.screen, a.modals.Len()))
}
if a.active != 0 && a.active != 1 {
errs = append(errs, fmt.Errorf("active pane %d", a.active))
}
for i, p := range a.panels {
if n := p.VisibleLen(); n > 0 && (p.Cursor() < 0 || p.Cursor() >= n) {
errs = append(errs, fmt.Errorf("pane %d cursor %d of %d", i, p.Cursor(), n))
}
}
return errors.Join(errs...)
}
// setScreen switches the screen; leaving Info/View resets the viewer focus
// and native selection.
func (a *App) setScreen(s Screen) tea.Cmd {
if s == a.screen {
return nil
}
prev := a.screen
a.screen = s
if s == ScreenBrowse || (prev == ScreenView && s == ScreenInfo) {
a.viewer.Focus = viewer.Scroll
a.nativeSelect = false
}
if s == ScreenView && a.filter != nil {
a.commitFilter()
}
a.relayout()
switch s {
case ScreenInfo:
a.previewFor = ""
return a.requestPreview(false)
case ScreenBrowse:
a.req.Cancel(ReqKey{Kind: ReqPreview})
a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce})
a.previewFor = ""
}
return nil
}
// openView is F3/v: the selected file full screen.
func (a *App) openView() tea.Cmd {
e, ok := a.Active().Selected()
if !ok || e.Parent || e.Navigable() {
return a.notify(notify.Info, "Not a file")
}
a.viewBack = a.screen
a.screen = ScreenView
a.viewer.Focus = viewer.Scroll
if a.filter != nil {
a.commitFilter()
}
a.relayout()
a.previewFor = ""
return a.requestPreview(true)
}
// Viewer focus transitions (design §7.2).
func (a *App) viewerFocus() tea.Cmd {
if !a.viewer.EnterCaret() {
return a.notify(notify.Info, "Preview is not text")
}
return nil
}
func (a *App) viewerCaret() tea.Cmd {
switch a.viewer.Focus {
case viewer.Visual:
a.viewer.Focus = viewer.Caret
case viewer.Scroll:
if !a.viewer.EnterCaret() {
return a.notify(notify.Info, "Not text")
}
}
return nil
}
func (a *App) viewerVisual() tea.Cmd {
if !a.viewer.EnterVisual() {
return a.notify(notify.Info, "Not text")
}
return nil
}
// viewerBack is Esc: one focus step back, then close.
func (a *App) viewerBack() tea.Cmd {
if a.nativeSelect {
return a.toggleNativeSelect()
}
switch a.viewer.Focus {
case viewer.Visual:
a.viewer.Focus = viewer.Caret
return nil
case viewer.Caret:
a.viewer.Focus = viewer.Scroll
return nil
}
return a.viewerClose()
}
// viewerClose is q/F3: close View, or drop the focus in Info.
func (a *App) viewerClose() tea.Cmd {
a.nativeSelect = false
if a.screen == ScreenView {
a.viewer.Focus = viewer.Scroll
back := a.viewBack
a.screen = back
a.relayout()
a.previewFor = ""
if back == ScreenInfo {
return a.requestPreview(false)
}
return nil
}
a.viewer.Focus = viewer.Scroll
return nil
}
func (a *App) toggleNativeSelect() tea.Cmd {
if a.screen == ScreenBrowse {
return nil
}
a.nativeSelect = !a.nativeSelect
if a.nativeSelect {
return a.notify(notify.Info, "Terminal mouse selection: Ctrl+T or Esc to end")
}
return nil
}
// Filter line.
func (a *App) startFilter() tea.Cmd {
ti := textinput.New()
ti.Prompt = "/"
ti.SetValue(a.Active().Filter())
ti.CursorEnd()
ti.Focus()
a.filter = &ti
a.relayout()
return nil
}
func (a *App) commitFilter() {
a.filter = nil
a.relayout()
}
// filterKey handles a key while the filter line owns input.
func (a *App) filterKey(act keys.ActionID, ok bool, k tea.KeyMsg) tea.Cmd {
p := a.Active()
if ok {
switch act {
case keys.FilterCommit:
a.commitFilter()
case keys.FilterCancel:
p.SetFilter("")
a.commitFilter()
case keys.FilterClearAll:
a.filter.SetValue("")
p.SetFilter("")
case keys.NavUp:
p.MoveCursor(-1)
case keys.NavDown:
p.MoveCursor(1)
}
return a.selectionChanged()
}
ti, cmd := a.filter.Update(k)
a.filter = &ti
p.SetFilter(ti.Value())
return tea.Batch(cmd, a.selectionChanged())
}
// Preview requests (design §7.7): cursor moves are debounced 100 ms, one
// preview in flight per app, stale results dropped.
const previewDebounce = 100 * time.Millisecond
type previewTickMsg struct{ Ticket Ticket }
type previewMsg struct {
Ticket Ticket
For string
Content viewer.Content
Err error
}
// selectionChanged is called after anything that may move the cursor.
func (a *App) selectionChanged() tea.Cmd {
if a.screen != ScreenInfo {
return nil
}
return a.requestPreview(false)
}
func (a *App) previewKey() (string, vfs.Location, vfs.FileInfo, bool) {
p := a.Active()
e, ok := p.Selected()
if !ok || e.Parent {
return "", vfs.Location{}, vfs.FileInfo{}, false
}
loc := p.Location()
return fmt.Sprintf("%s\x00%s\x00%s", loc.FS.Volume(), loc.Path, e.Name), loc, e.FileInfo, true
}
func (a *App) requestPreview(now bool) tea.Cmd {
key, loc, fi, ok := a.previewKey()
if !ok {
a.req.Cancel(ReqKey{Kind: ReqPreview})
a.req.Cancel(ReqKey{Kind: ReqPreviewDebounce})
a.previewFor = ""
a.viewer.Clear()
return nil
}
if key == a.previewFor {
return nil
}
a.previewFor = key
if !now {
tk, _ := a.req.Begin(ReqKey{Kind: ReqPreviewDebounce})
return tea.Tick(previewDebounce, func(time.Time) tea.Msg { return previewTickMsg{tk} })
}
return a.startPreview(key, loc, fi)
}
func (a *App) startPreview(key string, loc vfs.Location, fi vfs.FileInfo) tea.Cmd {
tk, ctx := a.req.Begin(ReqKey{Kind: ReqPreview})
build := a.deps.Preview
limit := a.deps.Config.Preview.MaxPreviewBytes
return func() tea.Msg {
c, err := build(ctx, loc, fi, limit)
return previewMsg{Ticket: tk, For: key, Content: c, Err: err}
}
}
func (a *App) onPreviewTick(m previewTickMsg) tea.Cmd {
if !a.req.Accept(m.Ticket) {
return nil
}
key, loc, fi, ok := a.previewKey()
if !ok || key != a.previewFor {
return nil
}
return a.startPreview(key, loc, fi)
}
func (a *App) onPreview(m previewMsg) tea.Cmd {
if !a.req.Accept(m.Ticket) {
return nil // stale: must not touch the viewer (U-P1-13)
}
if m.Err != nil {
if errors.Is(m.Err, context.Canceled) {
return nil
}
a.viewer.SetContent(viewer.Content{Kind: viewer.Other, Lines: []string{"Preview failed: " + cleanErr(m.Err).Error()}})
return nil
}
a.viewer.SetContent(m.Content)
return nil
}

184
internal/tui/nav.go Normal file
View file

@ -0,0 +1,184 @@
package tui
import (
"context"
"errors"
"fmt"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/notify"
"vcom/internal/tui/panel"
"vcom/internal/vfs"
)
// listingMsg is the result of a directory read for pane.
type listingMsg struct {
Ticket Ticket
Pane int
Target panel.Target
Infos []vfs.FileInfo
Err error
Focus string
Mode panel.NavMode
Reload bool // refresh of the current directory (keep cursor, filter)
Climb bool // a refresh whose directory vanished: walking up
}
// readDir is the Cmd reading t; it captures only immutable inputs.
func readDir(ctx context.Context, tk Ticket, pane int, t panel.Target, focus string, mode panel.NavMode, reload, climb bool) tea.Cmd {
return func() tea.Msg {
infos, err := t.FS().ReadDir(ctx, t.Path)
return listingMsg{Ticket: tk, Pane: pane, Target: t, Infos: infos, Err: err, Focus: focus, Mode: mode, Reload: reload, Climb: climb}
}
}
// navigate starts the transaction "show t in pane". The panel changes only
// when the listing arrives and succeeds (U-P1-8); a newer navigation of the
// same pane makes this one stale (U-P1-13).
func (a *App) navigate(pane int, t panel.Target, focus string, mode panel.NavMode) tea.Cmd {
tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: pane})
a.panels[pane].Loading = true
return readDir(ctx, tk, pane, t, focus, mode, false, false)
}
// reload re-reads the current directory of pane.
func (a *App) reload(pane int) tea.Cmd {
p := a.panels[pane]
if p.Source != panel.SourceDir {
return nil
}
tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: pane})
p.Loading = true
return readDir(ctx, tk, pane, p.Here(), "", panel.NavReplace, true, false)
}
// invalidate reloads every panel showing one of locs (after an operation:
// each panel keeps its own cursor; U-P1-7, N-P1-11).
func (a *App) invalidate(locs []vfs.Location) tea.Cmd {
var cmds []tea.Cmd
for i, p := range a.panels {
for _, l := range locs {
if p.Location().Same(l) {
cmds = append(cmds, a.reload(i))
break
}
}
}
return tea.Batch(cmds...)
}
func (a *App) onListing(m listingMsg) tea.Cmd {
if !a.req.Accept(m.Ticket) {
return nil // stale: a newer navigation of this pane won
}
p := a.panels[m.Pane]
p.Loading = false
if m.Err != nil {
if (m.Reload || m.Climb) && errors.Is(m.Err, vfs.ErrNotExist) {
// The directory vanished: walk up to the nearest existing parent.
tmp := panel.New(-1, p.Opts, m.Target.Mounts, m.Target.Path)
if t, _, _, ok := tmp.ParentTarget(); ok {
tk, ctx := a.req.Begin(ReqKey{Kind: ReqList, Pane: m.Pane})
p.Loading = true
return readDir(ctx, tk, m.Pane, t, "", panel.NavReplace, false, true)
}
}
if errors.Is(m.Err, context.Canceled) {
return nil
}
return a.notify(notify.Error, fmt.Sprintf("Cannot open %s: %v", displayPath(m.Target.Location()), cleanErr(m.Err)))
}
if m.Reload {
p.Reload(m.Infos)
} else {
p.Apply(m.Target, m.Infos, m.Focus, m.Mode)
}
var cmd tea.Cmd
if m.Climb {
cmd = a.notify(notify.Warn, "Directory vanished, moved up to "+displayPath(p.Location()))
}
if m.Pane == a.active {
return tea.Batch(cmd, a.selectionChanged())
}
return cmd
}
// openSelected is Enter: go into directories (and links to them), up on
// "..". Files are dispatched by stage 6.6 (edit / run menu / xdg-open).
func (a *App) openSelected() tea.Cmd {
e, ok := a.Active().Selected()
if !ok {
return nil
}
if e.Parent {
return a.goParent()
}
if e.Navigable() {
return a.enterSelected()
}
if a.openFile != nil {
return a.openFile(a, e)
}
return a.notify(notify.Info, "Opening files: not available yet")
}
// enterSelected is l/→: enter a directory; nothing on files.
func (a *App) enterSelected() tea.Cmd {
p := a.Active()
e, ok := p.Selected()
if !ok {
return nil
}
if e.Parent {
return a.goParent()
}
if !e.Navigable() {
return nil
}
return a.navigate(a.active, p.ChildTarget(e.Name), "", panel.NavPush)
}
// goParent is h/←/Backspace and Enter on "..".
func (a *App) goParent() tea.Cmd {
p := a.Active()
t, focus, _, ok := p.ParentTarget()
if !ok {
return nil
}
return a.navigate(a.active, t, focus, panel.NavPush)
}
// history goes back (or forward) in the active panel.
func (a *App) history(forward bool) tea.Cmd {
p := a.Active()
snap, ok := p.BackTarget()
mode := panel.NavBack
if forward {
snap, ok = p.ForwardTarget()
mode = panel.NavForward
}
if !ok {
return nil
}
return a.navigate(a.active, snap.Target, snap.Focus, mode)
}
// displayPath renders a location for messages and titles.
func displayPath(l vfs.Location) string {
if l.FS == nil || l.FS.Kind() == vfs.KindLocal {
return l.Path
}
return l.FS.Label() + ":" + l.Path
}
// cleanErr drops the "op path:" prefix of a path error (the message
// already names the path).
func cleanErr(err error) error {
if u, ok := err.(interface{ Unwrap() error }); ok {
if in := u.Unwrap(); in != nil {
return in
}
}
return err
}

45
internal/tui/quit.go Normal file
View file

@ -0,0 +1,45 @@
package tui
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/modal"
)
// askQuit is q/F10 in Browse (and Ctrl+C with nothing to clear). With
// confirm_quit or running jobs it asks; "q q" quits fast because the Quit
// button's hotkey is q (U-P1-16). Running jobs are cancelled and cleaned
// up by main's teardown (jobs.Shutdown).
func (a *App) askQuit() tea.Cmd {
n := a.activeJobCount()
if !a.deps.Config.Behavior.ConfirmQuit && n == 0 {
return a.quit()
}
d := &modal.Dialog{
Title: "Quit vcom?",
Buttons: []modal.Button{
{Label: "Quit", Key: "q", Value: true, Default: true},
{Label: "Back", Key: "n", Cancel: true},
},
}
if n > 0 {
d.Title = "Quit and cancel operations?"
d.Warnings = []string{fmt.Sprintf("%d operation(s) running: they will be cancelled and their temp files removed", n)}
d.Buttons[0].Label = "Cancel them and quit"
d.Buttons[0].Danger = true
}
a.openModal(d, func(o modal.Outcome) tea.Cmd {
if o.Cancelled {
return nil
}
return a.quit()
})
return nil
}
func (a *App) quit() tea.Cmd {
a.quitting = true
return tea.Quit
}

View file

@ -0,0 +1,7 @@
package tui
// registerArchive adds the action handlers of stage 6.5 (stub until then).
func registerArchive(t actionTable) {}
// registerArchiveHooks adds message and job-event handlers of stage 6.5.
func registerArchiveHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerMisc adds the action handlers of stage 6.6 (stub until then).
func registerMisc(t actionTable) {}
// registerMiscHooks adds message and job-event handlers of stage 6.6.
func registerMiscHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerOps adds the action handlers of stage 6.2 (stub until then).
func registerOps(t actionTable) {}
// registerOpsHooks adds message and job-event handlers of stage 6.2.
func registerOpsHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerSSH adds the action handlers of stage 6.4 (stub until then).
func registerSSH(t actionTable) {}
// registerSSHHooks adds message and job-event handlers of stage 6.4.
func registerSSHHooks(a *App) {}

View file

@ -0,0 +1,7 @@
package tui
// registerViewer adds the action handlers of stage 6.3 (stub until then).
func registerViewer(t actionTable) {}
// registerViewerHooks adds message and job-event handlers of stage 6.3.
func registerViewerHooks(a *App) {}

98
internal/tui/status.go Normal file
View file

@ -0,0 +1,98 @@
package tui
import (
"fmt"
"strings"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/notify"
"vcom/internal/tui/viewer"
)
// modeBadge names the mode shown at the left of the status line.
func (a *App) modeBadge() string {
switch {
case a.nativeSelect:
return "SELECT"
case a.filter != nil:
return "FILTER"
case a.viewer.Focus == viewer.Visual && a.screen != ScreenBrowse:
return "VISUAL"
case a.viewer.Focus == viewer.Caret && a.screen != ScreenBrowse:
return "CARET"
case a.screen == ScreenView:
return "VIEW"
case a.screen == ScreenInfo:
return "INFO"
}
return ""
}
// statusLine: mode badge and current note on the left; jobs and the
// connection state of the active panel on the right (design §7.6).
func (a *App) statusLine() string {
st := a.styles
w := a.layout.Status.W
var left strings.Builder
if b := a.modeBadge(); b != "" {
left.WriteString(st.Badge.Render(b))
left.WriteString(st.Status.Render(" "))
}
if n, ok := a.notes.Current(); ok {
s := st.NoteInfo
switch n.Level {
case notify.Success:
s = st.NoteOK
case notify.Warn:
s = st.NoteWarn
case notify.Error:
s = st.NoteError
}
left.WriteString(s.Render(n.Text))
} else if e, ok := a.Active().Selected(); ok && !e.Parent {
left.WriteString(st.Status.Render(e.Name))
}
var right []string
if jobs := a.activeJobs(); len(jobs) > 0 {
j := jobs[0]
pct := ""
if t := j.Progress.BytesTotal; t > 0 {
pct = fmt.Sprintf(" %d%%", j.Progress.BytesDone*100/t)
}
r := fmt.Sprintf("⟳ %s%s", j.Title, pct)
if len(jobs) > 1 {
r += fmt.Sprintf(" · +%d", len(jobs)-1)
}
right = append(right, r)
}
if b := a.Active().Badge; b != "" {
right = append(right, b)
}
r := st.Status.Render(strings.Join(right, " "))
rw := ansi.StringWidth(r)
l := ansi.Truncate(left.String(), max(0, w-rw-1), "…")
gap := max(0, w-ansi.StringWidth(l)-rw)
return l + st.Status.Render(strings.Repeat(" ", gap)) + r
}
// footerLine lists the footer bindings of the context owning input.
func (a *App) footerLine() string {
st := a.styles
w := a.layout.Footer.W
var b strings.Builder
used := 0
for _, it := range a.keys.Footer(a.inputOwner()) {
k := st.FooterKey.Render(it.Keys)
h := st.Footer.Render(" " + it.Help + " ")
n := ansi.StringWidth(k) + ansi.StringWidth(h)
if used+n > w {
break
}
b.WriteString(k)
b.WriteString(h)
used += n
}
return b.String() + st.Footer.Render(strings.Repeat(" ", max(0, w-used)))
}

View file

@ -0,0 +1,54 @@
package tui
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/theme"
"vcom/internal/tui/modal"
"vcom/internal/tui/notify"
)
type themeSavedMsg struct {
Theme string
Path string
Err error
}
// openThemeSelect is "t": a list with live preview; Enter keeps and saves
// the theme with config.SetKey (comments kept, design §9.2), Esc reverts.
func (a *App) openThemeSelect() tea.Cmd {
orig := a.theme
var items []modal.Item
for _, n := range theme.Names() {
items = append(items, modal.Item{Label: n, Value: n})
}
l := modal.NewList("Theme", items, orig)
l.OnMove = func(it modal.Item) tea.Cmd {
a.setTheme(it.Value.(string)) // runs in Update: no I/O
return nil
}
a.openModal(l, func(o modal.Outcome) tea.Cmd {
if o.Cancelled {
a.setTheme(orig)
return nil
}
name := o.Value.(string)
a.setTheme(name)
a.deps.Config.UI.Theme = name
set, path := a.deps.SetConfigKey, a.deps.ConfigPath
return func() tea.Msg {
p, err := set(path, "ui", "theme", name)
return themeSavedMsg{Theme: name, Path: p, Err: err}
}
})
return nil
}
func (a *App) onThemeSaved(m themeSavedMsg) tea.Cmd {
if m.Err != nil {
return a.notify(notify.Error, fmt.Sprintf("Theme %s not saved: %v", m.Theme, m.Err))
}
return a.notify(notify.Success, fmt.Sprintf("Theme %s saved to %s", m.Theme, m.Path))
}

95
internal/tui/tracker.go Normal file
View file

@ -0,0 +1,95 @@
package tui
import "context"
// ReqKind is a kind of async request.
type ReqKind uint8
const (
ReqList ReqKind = iota
ReqPreview
ReqPreviewDebounce
ReqDirSize
ReqMount
ReqConnect
ReqFeature // features (6.2–6.6) use ReqKey.Extra to tell their requests apart
)
// ReqKey identifies a request slot: a newer request with the same key
// supersedes the older one.
type ReqKey struct {
Kind ReqKind
Pane int
Extra string
}
// Ticket travels with every async message. Update accepts a message only if
// its ticket is still current (design §7.7, U-P1-13).
type Ticket struct {
Key ReqKey
Gen uint64
}
type slot struct {
gen uint64
cancel context.CancelFunc
live bool
}
// Tracker hands out tickets. UI goroutine only.
type Tracker struct {
gen uint64
slots map[ReqKey]*slot
}
// Begin starts a request for k: the previous one with the same key is
// cancelled and its ticket becomes stale.
func (t *Tracker) Begin(k ReqKey) (Ticket, context.Context) {
if t.slots == nil {
t.slots = map[ReqKey]*slot{}
}
if s := t.slots[k]; s != nil && s.cancel != nil {
s.cancel()
}
t.gen++
ctx, cancel := context.WithCancel(context.Background())
t.slots[k] = &slot{gen: t.gen, cancel: cancel, live: true}
return Ticket{Key: k, Gen: t.gen}, ctx
}
// Accept reports whether tk is the current ticket of its key; if so the
// request is finished (its context released) and the slot freed.
func (t *Tracker) Accept(tk Ticket) bool {
s := t.slots[tk.Key]
if s == nil || !s.live || s.gen != tk.Gen {
return false
}
s.live = false
s.cancel()
delete(t.slots, tk.Key)
return true
}
// Pending reports whether a request for k is in flight.
func (t *Tracker) Pending(k ReqKey) bool {
s := t.slots[k]
return s != nil && s.live
}
// Cancel cancels the request for k (its ticket becomes stale).
func (t *Tracker) Cancel(k ReqKey) {
if s := t.slots[k]; s != nil {
s.cancel()
delete(t.slots, k)
}
}
// CancelAll cancels every request of kind.
func (t *Tracker) CancelAll(kind ReqKind) {
for k, s := range t.slots {
if k.Kind == kind {
s.cancel()
delete(t.slots, k)
}
}
}

154
internal/tui/update.go Normal file
View file

@ -0,0 +1,154 @@
package tui
import (
"time"
tea "github.com/charmbracelet/bubbletea"
"vcom/internal/tui/keys"
"vcom/internal/tui/modal"
)
// doubleClick is the max interval between clicks of a double click.
const doubleClick = 400 * time.Millisecond
// Update is the single entry point of the model. It never blocks: all I/O
// runs in Cmds (N-P1-1).
func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmd := a.update(msg)
a.relayout()
return a, tea.Batch(cmd, a.reconcile())
}
func (a *App) update(msg tea.Msg) tea.Cmd {
switch m := msg.(type) {
case tea.WindowSizeMsg:
a.w, a.h = m.Width, m.Height
return nil
case tea.KeyMsg:
return a.key(m)
case tea.MouseMsg:
return a.mouse(m)
case listingMsg:
return a.onListing(m)
case previewTickMsg:
return a.onPreviewTick(m)
case previewMsg:
return a.onPreview(m)
case noteExpiredMsg:
a.notes.Expire(m.id)
return nil
case themeSavedMsg:
return a.onThemeSaved(m)
case jobEventMsg:
return a.onJobEvent(m)
case execDoneMsg:
a.applied.mouse = mouseUnknown // the external program may have reset it (U-P1-3)
return nil
}
for _, h := range a.handlers {
if cmd, ok := h(a, msg); ok {
return cmd
}
}
return nil
}
func (a *App) key(k tea.KeyMsg) tea.Cmd {
a.notes.KeyPressed()
if a.nativeSelect && k.Type == tea.KeyEsc && a.modals.Len() == 0 {
return a.toggleNativeSelect()
}
ctx := a.inputOwner()
act, ok := a.keys.Resolve(ctx, k)
if ok && act == keys.Pending {
return nil
}
switch {
case a.modals.Len() > 0:
return a.modals.Key(act, k)
case ctx == keys.CtxFilterEdit:
return a.filterKey(act, ok, k)
case ok:
return a.dispatch(act)
}
return nil
}
// mouse routes mouse events: everything to the top modal while one is open
// (clicks outside it are ignored); otherwise by Layout hit-test.
func (a *App) mouse(m tea.MouseMsg) tea.Cmd {
if a.modals.Len() > 0 {
return a.modals.Mouse(m, a.layout.Screen, a.styles)
}
if a.nativeSelect {
return nil
}
switch m.Button {
case tea.MouseButtonWheelUp, tea.MouseButtonWheelDown:
d := 3
if m.Button == tea.MouseButtonWheelUp {
d = -3
}
if a.screen == ScreenView || (a.screen == ScreenInfo && a.layout.Preview.Contains(m.X, m.Y)) {
a.viewer.Scroll(d)
return nil
}
if i, ok := a.layout.paneAt(m.X, m.Y); ok {
a.panels[i].Scroll(d)
if i == a.active {
return a.selectionChanged()
}
}
return nil
}
if m.Action != tea.MouseActionPress || a.screen == ScreenView {
return nil
}
i, ok := a.layout.paneAt(m.X, m.Y)
if !ok {
return nil
}
if m.Button == tea.MouseButtonRight {
if a.screen == ScreenInfo {
return a.setScreen(ScreenBrowse)
}
return a.setScreen(ScreenInfo)
}
if m.Button != tea.MouseButtonLeft || a.filter != nil && i != a.active {
return nil
}
if i != a.active {
a.active = i
}
lr := a.listRect(i)
if !lr.Contains(m.X, m.Y) {
return a.selectionChanged()
}
row, ok := a.panels[i].RowAt(m.Y - lr.Y)
if !ok {
return a.selectionChanged()
}
now := a.now()
double := a.lastClick.pane == i && a.lastClick.row == row && now.Sub(a.lastClick.at) <= doubleClick
a.lastClick = click{at: now, pane: i, row: row}
a.panels[i].SetCursor(row)
if double {
a.lastClick = click{}
return a.dispatch(keys.NavOpen)
}
return a.selectionChanged()
}
// openModal pushes m; a filter being edited is committed first (the filter
// line never coexists with a modal).
func (a *App) openModal(m modal.Modal, onClose func(modal.Outcome) tea.Cmd) uint64 {
if a.filter != nil {
a.commitFilter()
}
a.keys.Reset()
return a.modals.Push(m, onClose)
}
// execDoneMsg is sent after an external program (editor, run) returns.
type execDoneMsg struct{ Err error }

133
internal/tui/view.go Normal file
View file

@ -0,0 +1,133 @@
package tui
import (
"strconv"
"strings"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/geom"
"vcom/internal/tui/panel"
"vcom/internal/vfs"
)
// View renders the screen. It only reads state (design §7.9): sizes were
// set in Update (relayout), effects are applied by reconcile.
func (a *App) View() string {
if a.w <= 0 || a.h <= 0 {
return ""
}
canvas := make([]string, a.h)
blank := strings.Repeat(" ", a.w)
for i := range canvas {
canvas[i] = blank
}
draw := func(r geom.Rect, s string) {
if r.Empty() || s == "" {
return
}
for i, line := range strings.Split(s, "\n") {
y := r.Y + i
if i >= r.H || y >= len(canvas) {
break
}
canvas[y] = place(canvas[y], ansi.Truncate(line, r.W, ""), r.X, a.w)
}
}
switch a.screen {
case ScreenView:
draw(a.layout.Viewer, a.renderViewer())
default:
for i, p := range a.panels {
r := a.layout.Panes[i]
if r.Empty() {
continue
}
draw(r, p.Render(panel.View{
Rect: r,
Active: i == a.active,
FilterLine: a.filterLine(i),
Title: a.paneTitle(p),
Styles: a.styles,
}))
}
if a.screen == ScreenInfo {
draw(a.layout.Preview, a.renderPreview())
}
}
draw(a.layout.Status, a.statusLine())
if !a.layout.Footer.Empty() {
draw(a.layout.Footer, a.footerLine())
}
out := strings.Join(canvas, "\n")
return a.modals.Render(out, a.layout.Screen, a.styles)
}
// place writes s into line at column x.
func place(line, s string, x, w int) string {
left := ansi.Truncate(line, x, "")
if n := ansi.StringWidth(left); n < x {
left += strings.Repeat(" ", x-n)
}
right := ansi.TruncateLeft(line, x+ansi.StringWidth(s), "")
out := left + s + right
if n := ansi.StringWidth(out); n < w {
out += strings.Repeat(" ", w-n)
}
return out
}
func (a *App) filterLine(i int) string {
if a.filter == nil || i != a.active {
return ""
}
return a.filter.View()
}
func (a *App) paneTitle(p *panel.Model) string {
if p.Source == panel.SourceHosts {
return "SSH hosts"
}
t := displayPath(p.Location())
if n := p.MarkCount(); n > 0 {
t += " [" + strconv.Itoa(n) + " marked]"
}
return t
}
func (a *App) renderPreview() string {
r := a.layout.Preview
if r.W < 4 || r.H < 3 {
return ""
}
inner := r.W - 2
title := a.viewer.Title()
if title == "" {
if e, ok := a.Active().Selected(); ok && !e.Parent {
title = e.Name
}
}
body := a.viewer.Render(inner, a.layout.PreviewBody.H, a.styles)
content := a.styles.PaneTitle.Render(pad(ansi.Truncate(title, inner, "…"), inner)) + "\n" + body
return a.styles.PaneBorder.Width(inner).Render(content)
}
func (a *App) renderViewer() string {
r := a.layout.Viewer
title := a.viewer.Title()
if title == "" {
title = "View"
}
head := a.styles.PaneTitleActive.Render(pad(ansi.Truncate(title, r.W, "…"), r.W))
return head + "\n" + a.viewer.Render(r.W, max(0, r.H-1), a.styles)
}
func pad(s string, w int) string {
if n := ansi.StringWidth(s); n < w {
return s + strings.Repeat(" ", w-n)
}
return s
}
// locationOf is a helper for features: the active panel's location.
func (a *App) locationOf(i int) vfs.Location { return a.panels[i].Location() }

View file

@ -0,0 +1,179 @@
// Package viewer shows file content in the Info preview and the View
// screen. Stage 6.1 provides the model the App's state machine needs
// (Kind, Focus, Gen, scrolling, a line caret); stage 6.3 replaces the
// rendering with the real TextViewer (cell-accurate caret/visual, wrap,
// yank) and images through imgview.
package viewer
import (
"strings"
"github.com/charmbracelet/x/ansi"
"vcom/internal/tui/style"
)
// Kind of content.
type Kind uint8
const (
None Kind = iota
Text // lines of text: caret and visual are possible
Image // drawn by imgview (stage 6.3)
Other // metadata only (binary, directory, error)
)
// Focus of the viewer.
type Focus uint8
const (
Scroll Focus = iota // keys scroll
Caret // a cursor in the text
Visual // a selection
)
// Content is what a preview produced.
type Content struct {
Kind Kind
Title string
Lines []string
Image any // preview.ImageRef in stage 6.3
}
// Model is the viewer state.
type Model struct {
Focus Focus
Kind Kind
Gen uint64 // bumps with every SetContent (overlay effects key on it)
Image any
title string
lines []string
offset int
caret int // line of the caret
anchor int // line where Visual started
rows int
}
// SetContent shows c. Non-text content drops the focus back to Scroll.
func (m *Model) SetContent(c Content) {
m.Gen++
m.Kind = c.Kind
m.title = c.Title
m.lines = c.Lines
m.Image = c.Image
m.offset, m.caret, m.anchor = 0, 0, 0
if m.Kind != Text {
m.Focus = Scroll
}
}
// Clear drops the content.
func (m *Model) Clear() { m.SetContent(Content{}) }
// Lines returns the text lines.
func (m *Model) Lines() []string { return m.lines }
// Offset is the first line on screen.
func (m *Model) Offset() int { return m.offset }
// CaretLine is the caret line.
func (m *Model) CaretLine() int { return m.caret }
// SetRows tells the viewer how many lines fit.
func (m *Model) SetRows(n int) { m.rows = max(1, n) }
// Scroll moves the view (Scroll focus) or the caret (Caret/Visual).
func (m *Model) Scroll(delta int) {
if m.Focus == Scroll {
m.offset = max(0, min(m.offset+delta, max(0, len(m.lines)-m.rows)))
return
}
m.caret = max(0, min(m.caret+delta, max(0, len(m.lines)-1)))
if m.caret < m.offset {
m.offset = m.caret
}
if m.caret >= m.offset+m.rows {
m.offset = m.caret - m.rows + 1
}
}
// Page scrolls by a screen.
func (m *Model) Page(dir int) { m.Scroll(dir * max(1, m.rows-1)) }
// Jump goes to the top or the bottom.
func (m *Model) Jump(end bool) {
if end {
m.Scroll(len(m.lines))
} else {
m.Scroll(-len(m.lines))
}
}
// EnterCaret puts the caret on the first visible line (text only).
func (m *Model) EnterCaret() bool {
if m.Kind != Text {
return false
}
m.Focus = Caret
m.caret = min(m.offset, max(0, len(m.lines)-1))
return true
}
// EnterVisual starts a selection at the caret (from Scroll: at the first
// visible line).
func (m *Model) EnterVisual() bool {
if m.Kind != Text {
return false
}
if m.Focus == Scroll {
m.caret = min(m.offset, max(0, len(m.lines)-1))
}
m.Focus = Visual
m.anchor = m.caret
return true
}
// Selection returns the selected lines (Visual) or the caret line.
func (m *Model) Selection() []string {
if len(m.lines) == 0 {
return nil
}
a, b := m.caret, m.caret
if m.Focus == Visual {
a, b = min(m.anchor, m.caret), max(m.anchor, m.caret)
}
return m.lines[a : b+1]
}
// Render draws the visible window into w×h.
func (m *Model) Render(w, h int, st *style.Styles) string {
var b strings.Builder
lo, hi := m.caret, m.caret
if m.Focus == Visual {
lo, hi = min(m.anchor, m.caret), max(m.anchor, m.caret)
}
for row := 0; row < h; row++ {
if row > 0 {
b.WriteByte('\n')
}
i := m.offset + row
line := ""
if i < len(m.lines) {
line = ansi.Truncate(strings.ReplaceAll(m.lines[i], "\t", " "), w, "")
} else if i == 0 && m.Kind == None {
line = st.Muted.Render("(no preview)")
}
if n := ansi.StringWidth(line); n < w {
line += strings.Repeat(" ", w-n)
}
if m.Focus != Scroll && i >= lo && i <= hi && i < len(m.lines) {
line = st.ListCursor.Render(ansi.Strip(line))
}
b.WriteString(line)
}
return b.String()
}
// Title of the content.
func (m *Model) Title() string { return m.title }