diff --git a/internal/tui/keys/bindings_archive.go b/internal/tui/keys/bindings_archive.go new file mode 100644 index 0000000..47319c1 --- /dev/null +++ b/internal/tui/keys/bindings_archive.go @@ -0,0 +1,4 @@ +package keys + +// archiveBindings holds the extra bindings of archives (stage 6.5). +func archiveBindings() []Binding { return nil } diff --git a/internal/tui/keys/bindings_browse.go b/internal/tui/keys/bindings_browse.go new file mode 100644 index 0000000..66b265c --- /dev/null +++ b/internal/tui/keys/bindings_browse.go @@ -0,0 +1,139 @@ +package keys + +// Browse/Info actions (design §8.1). +const ( + NavUp ActionID = "nav.up" + NavDown ActionID = "nav.down" + NavPageUp ActionID = "nav.pageUp" + NavPageDown ActionID = "nav.pageDown" + NavHalfUp ActionID = "nav.halfUp" + NavHalfDown ActionID = "nav.halfDown" + NavHome ActionID = "nav.home" + NavEnd ActionID = "nav.end" + NavOpen ActionID = "nav.open" // Enter: dispatch by entry type + NavEnter ActionID = "nav.enter" // l/→: enter directory or archive + NavParent ActionID = "nav.parent" // h/←/Backspace + NavBack ActionID = "nav.back" + NavForward ActionID = "nav.forward" + PaneSwitch ActionID = "pane.switch" + PaneMirror ActionID = "pane.mirror" + PanesReload ActionID = "panes.reload" + MarkToggle ActionID = "mark.toggle" // Insert: mark and move down + MarkUp ActionID = "mark.up" + MarkDown ActionID = "mark.down" + BrowseEscape ActionID = "browse.escape" // Esc: drop filter, then marks + BrowseCtrlC ActionID = "browse.ctrlC" // like Esc; quits from a clean Browse + DirSize ActionID = "dir.size" + FilterStart ActionID = "filter.start" + ToggleHidden ActionID = "view.hidden" + SortMenu ActionID = "sort.menu" + ScreenInfo ActionID = "screen.info" + ScreenView ActionID = "screen.view" + FileRename ActionID = "file.rename" + FileEdit ActionID = "file.edit" + FileCopy ActionID = "file.copy" + FileMove ActionID = "file.move" + FileMkdir ActionID = "file.mkdir" + FileTrash ActionID = "file.trash" + FileDelete ActionID = "file.delete" // permanent + ArchiveNew ActionID = "archive.create" + ArchiveUnzip ActionID = "archive.extract" + PathYank ActionID = "path.yank" + SSHHosts ActionID = "ssh.hosts" + ThemeSelect ActionID = "theme.select" + JobsList ActionID = "jobs.list" + LogShow ActionID = "log.show" + HelpShow ActionID = "help.show" + AppQuit ActionID = "app.quit" + + // Info only. + ViewerFocus ActionID = "viewer.focus" + PreviewDown ActionID = "preview.scrollDown" + PreviewUp ActionID = "preview.scrollUp" + NativeSelect ActionID = "viewer.nativeSelect" + InfoClose ActionID = "screen.infoClose" + FilterCommit ActionID = "filter.commit" + FilterCancel ActionID = "filter.cancel" + FilterClearAll ActionID = "filter.clear" +) + +// browseCommon is shared by Browse and Info (Info adds its own keys and +// closes on q/Esc instead of quitting). +func browseCommon() []Binding { + return []Binding{ + {Action: NavUp, Keys: []string{"up", "k"}, Help: "cursor up", Group: "Navigation"}, + {Action: NavDown, Keys: []string{"down", "j"}, Help: "cursor down", Group: "Navigation"}, + {Action: NavPageUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "Navigation"}, + {Action: NavPageDown, Keys: []string{"pgdown", "ctrl+f"}, Help: "page down", Group: "Navigation"}, + {Action: NavHalfUp, Keys: []string{"ctrl+u"}, Help: "half page up", Group: "Navigation"}, + {Action: NavHalfDown, Keys: []string{"ctrl+d"}, Help: "half page down", Group: "Navigation"}, + {Action: NavHome, Keys: []string{"home", "g"}, Help: "first entry", Group: "Navigation"}, + {Action: NavEnd, Keys: []string{"end", "G"}, Help: "last entry", Group: "Navigation"}, + {Action: NavOpen, Keys: []string{"enter"}, Help: "open", Group: "Navigation", Footer: true}, + {Action: NavEnter, Keys: []string{"right", "l"}, Help: "enter directory", Group: "Navigation"}, + {Action: NavParent, Keys: []string{"left", "h", "backspace"}, Help: "parent directory", Group: "Navigation"}, + {Action: NavBack, Keys: []string{"alt+left", "["}, Help: "history back", Group: "Navigation"}, + {Action: NavForward, Keys: []string{"alt+right", "]"}, Help: "history forward", Group: "Navigation"}, + {Action: PaneSwitch, Keys: []string{"tab"}, Help: "switch pane", Group: "Panels", Footer: true}, + {Action: PaneMirror, Keys: []string{"p"}, Help: "mirror: other pane to this place", Group: "Panels"}, + {Action: PanesReload, Keys: []string{"ctrl+r"}, Help: "reload panes", Group: "Panels"}, + {Action: MarkToggle, Keys: []string{"insert"}, Help: "mark and move down", Group: "Marks"}, + {Action: MarkUp, Keys: []string{"shift+up", "K"}, Help: "mark moving up", Group: "Marks"}, + {Action: MarkDown, Keys: []string{"shift+down", "J"}, Help: "mark moving down", Group: "Marks"}, + {Action: DirSize, Keys: []string{" "}, Help: "directory size", Group: "Files"}, + {Action: FilterStart, Keys: []string{"/"}, Help: "filter", Group: "Panels", Footer: true}, + {Action: ToggleHidden, Keys: []string{"."}, Help: "show hidden files", Group: "Panels"}, + {Action: SortMenu, Keys: []string{"S"}, Help: "sort menu", Group: "Panels"}, + {Action: ScreenView, Keys: []string{"f3", "v"}, Help: "view file", Group: "Files", Footer: true}, + {Action: FileRename, Keys: []string{"f2", "r"}, Help: "rename", Group: "Files"}, + {Action: FileEdit, Keys: []string{"f4"}, Help: "edit", Group: "Files", Footer: true}, + {Action: FileCopy, Keys: []string{"f5", "c"}, Help: "copy", Group: "Files", Footer: true}, + {Action: FileMove, Keys: []string{"f6", "m"}, Help: "move", Group: "Files", Footer: true}, + {Action: FileMkdir, Keys: []string{"f7", "n"}, Help: "make directory", Group: "Files", Footer: true}, + {Action: FileTrash, Keys: []string{"f8", "delete", "x"}, Help: "move to trash", Group: "Files", Footer: true}, + {Action: FileDelete, Keys: []string{"f20", "X"}, Help: "delete permanently", Group: "Files"}, + {Action: ArchiveNew, Keys: []string{"a"}, Help: "create archive", Group: "Files"}, + {Action: ArchiveUnzip, Keys: []string{"e", "f11"}, Help: "extract archive", Group: "Files"}, + {Action: PathYank, Keys: []string{"y"}, Help: "copy path to clipboard", Group: "Files"}, + {Action: SSHHosts, Keys: []string{"s", "f12"}, Help: "SSH hosts", Group: "Panels"}, + {Action: ThemeSelect, Keys: []string{"t"}, Help: "choose theme", Group: "Other"}, + {Action: JobsList, Keys: []string{"B"}, Help: "background jobs", Group: "Other"}, + {Action: LogShow, Keys: []string{"L"}, Help: "message log", Group: "Other"}, + {Action: HelpShow, Keys: []string{"f1", "?"}, Help: "help", Group: "Other", Footer: true}, + } +} + +func browseBindings() []Binding { + var out []Binding + for _, b := range browseCommon() { + b.Context = CtxBrowse + out = append(out, b) + } + out = append(out, + Binding{Context: CtxBrowse, Action: BrowseEscape, Keys: []string{"esc"}, Help: "clear filter, then marks", Group: "Marks"}, + Binding{Context: CtxBrowse, Action: BrowseCtrlC, Keys: []string{"ctrl+c"}}, + Binding{Context: CtxBrowse, Action: ScreenInfo, Keys: []string{"o", "f9"}, Help: "info / preview", Group: "Panels", Footer: true}, + Binding{Context: CtxBrowse, Action: AppQuit, Keys: []string{"q", "f10"}, Help: "quit", Group: "Other", Footer: true}, + ) + for _, b := range browseCommon() { + b.Context = CtxInfo + b.Footer = false + out = append(out, b) + } + out = append(out, + Binding{Context: CtxInfo, Action: InfoClose, Keys: []string{"o", "f9", "q", "f10", "esc", "ctrl+c"}, Help: "close info", Group: "Info", Footer: true}, + Binding{Context: CtxInfo, Action: ViewerFocus, Keys: []string{"i"}, Help: "cursor in preview", Group: "Info", Footer: true}, + Binding{Context: CtxInfo, Action: PreviewDown, Keys: []string{"ctrl+e"}, Help: "scroll preview down", Group: "Info"}, + Binding{Context: CtxInfo, Action: PreviewUp, Keys: []string{"ctrl+y"}, Help: "scroll preview up", Group: "Info"}, + Binding{Context: CtxInfo, Action: NativeSelect, Keys: []string{"ctrl+t"}, Help: "select with the terminal mouse", Group: "Info"}, + ) + // Filter line (text context): only control keys. + out = append(out, + Binding{Context: CtxFilterEdit, Action: FilterCommit, Keys: []string{"enter"}, Help: "keep filter", Group: "Filter", Footer: true}, + Binding{Context: CtxFilterEdit, Action: FilterCancel, Keys: []string{"esc", "ctrl+c"}, Help: "drop filter", Group: "Filter", Footer: true}, + Binding{Context: CtxFilterEdit, Action: FilterClearAll, Keys: []string{"ctrl+u"}, Help: "clear text", Group: "Filter"}, + Binding{Context: CtxFilterEdit, Action: NavUp, Keys: []string{"up"}, Help: "cursor up", Group: "Filter"}, + Binding{Context: CtxFilterEdit, Action: NavDown, Keys: []string{"down"}, Help: "cursor down", Group: "Filter"}, + ) + return out +} diff --git a/internal/tui/keys/bindings_misc.go b/internal/tui/keys/bindings_misc.go new file mode 100644 index 0000000..b9e2ed0 --- /dev/null +++ b/internal/tui/keys/bindings_misc.go @@ -0,0 +1,4 @@ +package keys + +// miscBindings holds the extra bindings of stage 6.6 (sort menu, run menu). +func miscBindings() []Binding { return nil } diff --git a/internal/tui/keys/bindings_modal.go b/internal/tui/keys/bindings_modal.go new file mode 100644 index 0000000..2b26699 --- /dev/null +++ b/internal/tui/keys/bindings_modal.go @@ -0,0 +1,42 @@ +package keys + +// Actions shared by modal contexts (design §8.4). Dialog button hotkeys are +// not in the table: a Dialog matches them itself (see Translate). +const ( + ModalConfirm ActionID = "modal.confirm" + ModalCancel ActionID = "modal.cancel" + ModalNext ActionID = "modal.next" + ModalPrev ActionID = "modal.prev" + ModalUp ActionID = "modal.up" + ModalDown ActionID = "modal.down" + ModalPgUp ActionID = "modal.pageUp" + ModalPgDown ActionID = "modal.pageDown" + ModalHome ActionID = "modal.home" + ModalEnd ActionID = "modal.end" + ModalClear ActionID = "modal.clear" +) + +func modalBindings() []Binding { + d, in, l := CtxModalDialog, CtxModalInput, CtxModalList + return []Binding{ + {Context: d, Action: ModalConfirm, Keys: []string{"enter"}, Help: "press focused button", Group: "Dialog", Footer: true}, + {Context: d, Action: ModalNext, Keys: []string{"tab", "right", "l"}, Help: "next button", Group: "Dialog"}, + {Context: d, Action: ModalPrev, Keys: []string{"shift+tab", "left", "h"}, Help: "previous button", Group: "Dialog"}, + {Context: d, Action: ModalCancel, Keys: []string{"esc", "ctrl+c", "q"}, Help: "cancel", Group: "Dialog", Footer: true}, + + {Context: in, Action: ModalConfirm, Keys: []string{"enter"}, Help: "OK", Group: "Input", Footer: true}, + {Context: in, Action: ModalCancel, Keys: []string{"esc", "ctrl+c"}, Help: "cancel", Group: "Input", Footer: true}, + {Context: in, Action: ModalNext, Keys: []string{"tab", "down"}, Help: "next field", Group: "Input"}, + {Context: in, Action: ModalPrev, Keys: []string{"shift+tab", "up"}, Help: "previous field", Group: "Input"}, + {Context: in, Action: ModalClear, Keys: []string{"ctrl+u"}, Help: "clear field", Group: "Input"}, + + {Context: l, Action: ModalUp, Keys: []string{"up", "k"}, Help: "up", Group: "List"}, + {Context: l, Action: ModalDown, Keys: []string{"down", "j"}, Help: "down", Group: "List"}, + {Context: l, Action: ModalPgUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "List"}, + {Context: l, Action: ModalPgDown, Keys: []string{"pgdown", "ctrl+f", " "}, Help: "page down", Group: "List"}, + {Context: l, Action: ModalHome, Keys: []string{"home", "g"}, Help: "first", Group: "List"}, + {Context: l, Action: ModalEnd, Keys: []string{"end", "G"}, Help: "last", Group: "List"}, + {Context: l, Action: ModalConfirm, Keys: []string{"enter"}, Help: "choose", Group: "List", Footer: true}, + {Context: l, Action: ModalCancel, Keys: []string{"esc", "q", "ctrl+c", "f1", "?"}, Help: "close", Group: "List", Footer: true}, + } +} diff --git a/internal/tui/keys/bindings_ops.go b/internal/tui/keys/bindings_ops.go new file mode 100644 index 0000000..631fbe5 --- /dev/null +++ b/internal/tui/keys/bindings_ops.go @@ -0,0 +1,5 @@ +package keys + +// opsBindings holds the extra bindings of file operations (stage 6.2: +// progress and conflict modals). Browse keys live in bindings_browse.go. +func opsBindings() []Binding { return nil } diff --git a/internal/tui/keys/bindings_ssh.go b/internal/tui/keys/bindings_ssh.go new file mode 100644 index 0000000..0736138 --- /dev/null +++ b/internal/tui/keys/bindings_ssh.go @@ -0,0 +1,5 @@ +package keys + +// sshBindings holds the extra bindings of SSH (stage 6.4: host list, +// prompts). Browse keys live in bindings_browse.go. +func sshBindings() []Binding { return nil } diff --git a/internal/tui/keys/bindings_viewer.go b/internal/tui/keys/bindings_viewer.go new file mode 100644 index 0000000..1788e20 --- /dev/null +++ b/internal/tui/keys/bindings_viewer.go @@ -0,0 +1,54 @@ +package keys + +// Viewer actions (design §8.2). Stage 6.1 binds scrolling and the focus +// transitions; stage 6.3 adds the caret/visual motions (w/b/e, 0/^/$, ...) +// to this file. +const ( + ViewerLineUp ActionID = "viewer.lineUp" + ViewerLineDown ActionID = "viewer.lineDown" + ViewerPageUp ActionID = "viewer.pageUp" + ViewerPageDown ActionID = "viewer.pageDown" + ViewerTop ActionID = "viewer.top" + ViewerBottom ActionID = "viewer.bottom" + ViewerCaret ActionID = "viewer.caret" + ViewerVisual ActionID = "viewer.visual" + ViewerYank ActionID = "viewer.yank" + ViewerYankLine ActionID = "viewer.yankLine" + ViewerWrap ActionID = "viewer.wrap" + ViewerBack ActionID = "viewer.back" // Esc: one focus step back + ViewerClose ActionID = "viewer.close" // q/F3: close View / unfocus Info +) + +func viewerBindings() []Binding { + motion := func(ctx Context) []Binding { + return []Binding{ + {Context: ctx, Action: ViewerLineUp, Keys: []string{"up", "k"}, Help: "up", Group: "Viewer"}, + {Context: ctx, Action: ViewerLineDown, Keys: []string{"down", "j"}, Help: "down", Group: "Viewer"}, + {Context: ctx, Action: ViewerPageUp, Keys: []string{"pgup", "ctrl+b"}, Help: "page up", Group: "Viewer"}, + {Context: ctx, Action: ViewerPageDown, Keys: []string{"pgdown", "ctrl+f"}, Help: "page down", Group: "Viewer"}, + {Context: ctx, Action: ViewerTop, Keys: []string{"home", "g"}, Help: "top", Group: "Viewer"}, + {Context: ctx, Action: ViewerBottom, Keys: []string{"end", "G"}, Help: "bottom", Group: "Viewer"}, + {Context: ctx, Action: ViewerWrap, Keys: []string{"W"}, Help: "wrap lines", Group: "Viewer"}, + {Context: ctx, Action: NativeSelect, Keys: []string{"ctrl+t"}, Help: "select with the terminal mouse", Group: "Viewer"}, + {Context: ctx, Action: ViewerBack, Keys: []string{"esc"}, Help: "back", Group: "Viewer", Footer: true}, + {Context: ctx, Action: ViewerClose, Keys: []string{"q", "f3", "ctrl+c"}, Help: "close", Group: "Viewer", Footer: true}, + } + } + var out []Binding + out = append(out, motion(CtxViewScroll)...) + out = append(out, + Binding{Context: CtxViewScroll, Action: ViewerCaret, Keys: []string{"i"}, Help: "cursor mode", Group: "Viewer", Footer: true}, + Binding{Context: CtxViewScroll, Action: ViewerVisual, Keys: []string{"v"}, Help: "visual selection", Group: "Viewer"}, + ) + out = append(out, motion(CtxCaret)...) + out = append(out, + Binding{Context: CtxCaret, Action: ViewerVisual, Keys: []string{"v"}, Help: "visual selection", Group: "Viewer", Footer: true}, + Binding{Context: CtxCaret, Action: ViewerYankLine, Keys: []string{"y y"}, Help: "copy line", Group: "Viewer", Footer: true}, + ) + out = append(out, motion(CtxVisual)...) + out = append(out, + Binding{Context: CtxVisual, Action: ViewerCaret, Keys: []string{"v"}, Help: "end selection", Group: "Viewer"}, + Binding{Context: CtxVisual, Action: ViewerYank, Keys: []string{"y"}, Help: "copy selection", Group: "Viewer", Footer: true}, + ) + return out +} diff --git a/internal/tui/keys/defaults.go b/internal/tui/keys/defaults.go new file mode 100644 index 0000000..840198d --- /dev/null +++ b/internal/tui/keys/defaults.go @@ -0,0 +1,34 @@ +package keys + +import "unicode" + +// DefaultBindings collects the bindings of every feature file. Features add +// their own bindings_.go so parallel work does not touch one file. +func DefaultBindings() []Binding { + var out []Binding + for _, part := range [][]Binding{ + browseBindings(), modalBindings(), viewerBindings(), + opsBindings(), sshBindings(), archiveBindings(), miscBindings(), + } { + out = append(out, part...) + } + return out +} + +// Translate maps a key typed in the ЙЦУКЕН layout to its QWERTY name, for +// matching per-modal hotkeys (dialog buttons) the same way Resolve does. +// Other keys are returned unchanged. +func Translate(k string) string { + rs := []rune(k) + if len(rs) != 1 { + return k + } + q, ok := jcuken[unicode.ToLower(rs[0])] + if !ok { + return k + } + if unicode.IsUpper(rs[0]) { + q = unicode.ToUpper(q) + } + return string(q) +} diff --git a/internal/tui/keys/keys.go b/internal/tui/keys/keys.go new file mode 100644 index 0000000..b21f93e --- /dev/null +++ b/internal/tui/keys/keys.go @@ -0,0 +1,308 @@ +// Package keys is the single key-routing table of the new UI (design §7.4, +// §8): actions are named by ActionID, bound per input Context, and resolved +// from tea.KeyMsg in one place. Help and the footer are generated from the +// same table, so they cannot drift from what the keys do. +// +// Command contexts also accept keys typed in the Russian ЙЦУКЕН layout +// (й→q, …); text contexts (filter line, input fields) never translate and +// let everything except a few control keys through to the text field +// (U-P1-5: "папка" stays "папка"). +package keys + +import ( + "fmt" + "sort" + "strings" + + tea "github.com/charmbracelet/bubbletea" +) + +// ActionID names an action: "nav.down", "file.copy", "viewer.visual", ... +type ActionID string + +// Pending is returned by Resolve when the key started a chord ("y" of +// "y y"); the caller does nothing and waits for the next key. +const Pending ActionID = "keys.pending" + +// Context is who owns the keyboard right now (see App.inputOwner). +type Context uint8 + +const ( + CtxBrowse Context = iota + CtxInfo + CtxFilterEdit + CtxViewScroll + CtxCaret + CtxVisual + CtxModalDialog + CtxModalInput + CtxModalList + CtxModalProgress + CtxModalConflict + CtxModalPrompt + numContexts +) + +// Contexts lists every context (for tests and help). +func Contexts() []Context { + out := make([]Context, numContexts) + for i := range out { + out[i] = Context(i) + } + return out +} + +var ctxNames = [...]string{ + "browse", "info", "filter", "view", "caret", "visual", + "dialog", "input", "list", "progress", "conflict", "prompt", +} + +func (c Context) String() string { + if int(c) < len(ctxNames) { + return ctxNames[c] + } + return fmt.Sprintf("Context(%d)", uint8(c)) +} + +// IsText reports whether c edits text: only a few control keys are bound, +// everything else goes to the text field untranslated. +func (c Context) IsText() bool { + return c == CtxFilterEdit || c == CtxModalInput || c == CtxModalPrompt +} + +// textKeys are the only keys a text context may bind. +var textKeys = map[string]bool{ + "enter": true, "esc": true, "tab": true, "shift+tab": true, + "up": true, "down": true, "ctrl+c": true, "ctrl+u": true, +} + +// Binding binds keys to an action in one context. +type Binding struct { + Context Context + Action ActionID + // Keys in tea.KeyMsg.String() form ("j", "ctrl+f", "f5", "shift+up"). + // A chord is space separated: "y y". + Keys []string + Help string // one line for help; "" hides the binding from help + Group string // help section ("Navigation", "Files", ...) + Footer bool // shown in the footer +} + +// Registry resolves keys. It keeps a small chord buffer per context; it is +// not safe for concurrent use (it lives in the UI goroutine). +type Registry struct { + byCtx [numContexts]map[string]ActionID // key or chord → action + prefixes [numContexts]map[string]bool // chord prefixes + bindings []Binding + + pendingCtx Context + pending string +} + +// New builds a registry from bindings. It fails on a key bound twice in one +// context or a text context binding a non-control key. +func New(bindings []Binding) (*Registry, error) { + r := &Registry{bindings: bindings} + for i := range r.byCtx { + r.byCtx[i] = map[string]ActionID{} + r.prefixes[i] = map[string]bool{} + } + var errs []string + for _, b := range bindings { + if b.Context >= numContexts { + errs = append(errs, fmt.Sprintf("%s: bad context %d", b.Action, b.Context)) + continue + } + for _, k := range b.Keys { + if b.Context.IsText() && !textKeys[k] { + errs = append(errs, fmt.Sprintf("%s: %q binds a typing key in text context %s", b.Action, k, b.Context)) + continue + } + if prev, dup := r.byCtx[b.Context][k]; dup && prev != b.Action { + errs = append(errs, fmt.Sprintf("%s: %q in %s already bound to %s", b.Action, k, b.Context, prev)) + continue + } + r.byCtx[b.Context][k] = b.Action + parts := strings.Fields(k) + for i := 1; i < len(parts); i++ { + r.prefixes[b.Context][strings.Join(parts[:i], " ")] = true + } + } + } + if len(errs) > 0 { + return r, fmt.Errorf("keys: %s", strings.Join(errs, "; ")) + } + return r, nil +} + +// MustDefault returns the registry of DefaultBindings and panics on a +// conflict (a programming error caught by TestNoDuplicateKeysPerContext). +func MustDefault() *Registry { + r, err := New(DefaultBindings()) + if err != nil { + panic(err) + } + return r +} + +// Resolve maps a key in ctx to an action. ok is false when the key is not +// bound (in a text context: when it must go to the text field). A chord +// prefix yields (Pending, true). Changing context drops a pending chord. +func (r *Registry) Resolve(ctx Context, msg tea.KeyMsg) (ActionID, bool) { + key := msg.String() + if ctx != r.pendingCtx { + r.pending = "" + r.pendingCtx = ctx + } + if ctx.IsText() { + if !textKeys[key] { + return "", false + } + a, ok := r.byCtx[ctx][key] + return a, ok + } + cands := []string{key} + if t, ok := translate(msg); ok { + cands = append(cands, t) + } + if r.pending != "" { + prefix := r.pending + r.pending = "" + for _, k := range cands { + chord := prefix + " " + k + if a, ok := r.byCtx[ctx][chord]; ok { + return a, true + } + if r.prefixes[ctx][chord] { + r.pending = chord + return Pending, true + } + } + // Not a continuation: fall through and treat the key on its own. + } + for _, k := range cands { + if r.prefixes[ctx][k] { + r.pending = k + return Pending, true + } + if a, ok := r.byCtx[ctx][k]; ok { + return a, true + } + } + return "", false +} + +// Reset drops a pending chord. +func (r *Registry) Reset() { r.pending = "" } + +// Keys returns the keys bound to action in ctx, in declaration order. +func (r *Registry) Keys(ctx Context, a ActionID) []string { + for _, b := range r.bindings { + if b.Context == ctx && b.Action == a { + return b.Keys + } + } + return nil +} + +// HelpItem is one line of help or footer. +type HelpItem struct { + Action ActionID + Keys string // "F5/c" + Help string +} + +// Section is a group of help items. +type Section struct { + Title string + Items []HelpItem +} + +// Help lists the bindings of ctx grouped by section, in declaration order. +func (r *Registry) Help(ctx Context) []Section { + var out []Section + idx := map[string]int{} + for _, b := range r.bindings { + if b.Context != ctx || b.Help == "" { + continue + } + g := b.Group + if g == "" { + g = "Keys" + } + i, ok := idx[g] + if !ok { + i = len(out) + idx[g] = i + out = append(out, Section{Title: g}) + } + out[i].Items = append(out[i].Items, HelpItem{Action: b.Action, Keys: KeyLabel(b.Keys), Help: b.Help}) + } + return out +} + +// Footer lists the footer bindings of ctx. +func (r *Registry) Footer(ctx Context) []HelpItem { + var out []HelpItem + for _, b := range r.bindings { + if b.Context == ctx && b.Footer { + out = append(out, HelpItem{Action: b.Action, Keys: KeyLabel(b.Keys[:1]), Help: b.Help}) + } + } + return out +} + +// Actions lists every action bound in ctx (sorted). +func (r *Registry) Actions(ctx Context) []ActionID { + seen := map[ActionID]bool{} + for _, a := range r.byCtx[ctx] { + seen[a] = true + } + out := make([]ActionID, 0, len(seen)) + for a := range seen { + out = append(out, a) + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// KeyLabel renders keys for humans: "F5/c", "Shift+↓/J", "y y". +func KeyLabel(ks []string) string { + parts := make([]string, len(ks)) + for i, k := range ks { + parts[i] = label(k) + } + return strings.Join(parts, "/") +} + +var keyLabels = map[string]string{ + "up": "↑", "down": "↓", "left": "←", "right": "→", "enter": "Enter", "esc": "Esc", + "tab": "Tab", "shift+tab": "Shift+Tab", "backspace": "Backspace", "delete": "Del", + "insert": "Ins", "pgup": "PgUp", "pgdown": "PgDn", "home": "Home", "end": "End", + " ": "Space", "f20": "Shift+F8", +} + +func label(k string) string { + if strings.Contains(k, " ") && k != " " { + ps := strings.Fields(k) + for i, p := range ps { + ps[i] = label(p) + } + return strings.Join(ps, " ") + } + if l, ok := keyLabels[k]; ok { + return l + } + if len(k) >= 2 && k[0] == 'f' && k[1] >= '0' && k[1] <= '9' { + return "F" + k[1:] + } + out := k + for _, mod := range []string{"ctrl+", "alt+", "shift+"} { + if strings.HasPrefix(out, mod) { + rest := strings.TrimPrefix(out, mod) + out = strings.ToUpper(mod[:1]) + mod[1:] + label(rest) + break + } + } + return out +} diff --git a/internal/tui/keys/keys_test.go b/internal/tui/keys/keys_test.go new file mode 100644 index 0000000..9ed259b --- /dev/null +++ b/internal/tui/keys/keys_test.go @@ -0,0 +1,141 @@ +package keys + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" +) + +func runeKey(s string) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} } + +// U-P1-16: one key in one context = one action. +func TestNoDuplicateKeysPerContext(t *testing.T) { + if _, err := New(DefaultBindings()); err != nil { + t.Fatal(err) + } + r, err := New([]Binding{ + {Context: CtxBrowse, Action: "a", Keys: []string{"x"}}, + {Context: CtxBrowse, Action: "b", Keys: []string{"x"}}, + }) + if err == nil || r == nil { + t.Fatal("duplicate key not reported") + } + if _, err := New([]Binding{{Context: CtxFilterEdit, Action: "a", Keys: []string{"q"}}}); err == nil { + t.Fatal("text context binding a typing key not reported") + } +} + +// U-P1-5: ЙЦУКЕН is translated for commands only. +func TestLayoutTranslationCommandsOnly(t *testing.T) { + r := MustDefault() + if a, ok := r.Resolve(CtxBrowse, runeKey("й")); !ok || a != AppQuit { + t.Errorf("Browse й = %q %v, want %s", a, ok, AppQuit) + } + if a, ok := r.Resolve(CtxBrowse, runeKey("с")); !ok || a != FileCopy { + t.Errorf("Browse с = %q %v, want %s", a, ok, FileCopy) + } + if a, ok := r.Resolve(CtxBrowse, runeKey("Р")); ok { + t.Errorf("Browse Р (H) resolved to %q", a) + } + if a, ok := r.Resolve(CtxBrowse, runeKey("П")); !ok || a != NavEnd { + t.Errorf("Browse П (G) = %q %v, want %s", a, ok, NavEnd) + } + for _, ctx := range []Context{CtxFilterEdit, CtxModalInput} { + if a, ok := r.Resolve(ctx, runeKey("й")); ok { + t.Errorf("%s: й resolved to %q", ctx, a) + } + if a, ok := r.Resolve(ctx, runeKey("q")); ok { + t.Errorf("%s: q resolved to %q (must be typable)", ctx, a) + } + } + if got := Translate("н"); got != "y" { + t.Errorf("Translate(н) = %q", got) + } +} + +func TestTextContextPassesRunes(t *testing.T) { + r := MustDefault() + for _, ctx := range []Context{CtxFilterEdit, CtxModalInput} { + for _, ch := range "папка q/j" { + k := runeKey(string(ch)) + if ch == ' ' { + k = tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}} + } + if a, ok := r.Resolve(ctx, k); ok { + t.Errorf("%s: %q resolved to %q", ctx, ch, a) + } + } + if a, ok := r.Resolve(ctx, tea.KeyMsg{Type: tea.KeyEnter}); !ok || a == "" { + t.Errorf("%s: enter not resolved", ctx) + } + } +} + +func TestChordYY(t *testing.T) { + r := MustDefault() + if a, ok := r.Resolve(CtxCaret, runeKey("y")); !ok || a != Pending { + t.Fatalf("first y = %q %v, want Pending", a, ok) + } + if a, ok := r.Resolve(CtxCaret, runeKey("y")); !ok || a != ViewerYankLine { + t.Fatalf("y y = %q %v, want %s", a, ok, ViewerYankLine) + } + // A non-continuing key drops the chord and acts on its own. + r.Resolve(CtxCaret, runeKey("y")) + if a, ok := r.Resolve(CtxCaret, runeKey("j")); !ok || a != ViewerLineDown { + t.Fatalf("y j = %q %v, want %s", a, ok, ViewerLineDown) + } + if a, _ := r.Resolve(CtxCaret, runeKey("y")); a != Pending { + t.Fatal("chord did not restart") + } + // A context change drops it too. + if a, ok := r.Resolve(CtxVisual, runeKey("y")); !ok || a != ViewerYank { + t.Fatalf("visual y = %q %v", a, ok) + } + if a, _ := r.Resolve(CtxCaret, runeKey("y")); a != Pending { + t.Fatal("chord survived a context change") + } + // In the ЙЦУКЕН layout too. + r.Reset() + r.Resolve(CtxCaret, runeKey("н")) + if a, _ := r.Resolve(CtxCaret, runeKey("н")); a != ViewerYankLine { + t.Fatalf("н н = %q", a) + } +} + +func TestHelpGeneratedFromRegistry(t *testing.T) { + r := MustDefault() + var found bool + for _, s := range r.Help(CtxBrowse) { + for _, it := range s.Items { + if it.Action == FileCopy { + found = true + if it.Keys != "F5/c" || it.Help != "copy" || s.Title != "Files" { + t.Errorf("copy help = %+v in %q", it, s.Title) + } + } + } + } + if !found { + t.Fatal("file.copy missing from help") + } + var foot []string + for _, it := range r.Footer(CtxBrowse) { + foot = append(foot, it.Keys+" "+it.Help) + } + if !strings.Contains(strings.Join(foot, "|"), "F5 copy") { + t.Errorf("footer = %v", foot) + } + if got := KeyLabel([]string{"f20", "X", "shift+up", "y y", " "}); got != "Shift+F8/X/Shift+↑/y y/Space" { + t.Errorf("KeyLabel = %q", got) + } + for _, ctx := range Contexts() { + for _, s := range r.Help(ctx) { + for _, it := range s.Items { + if it.Keys == "" { + t.Errorf("%s: %s has no keys", ctx, it.Action) + } + } + } + } +} diff --git a/internal/tui/keys/layout.go b/internal/tui/keys/layout.go new file mode 100644 index 0000000..4dad2d4 --- /dev/null +++ b/internal/tui/keys/layout.go @@ -0,0 +1,35 @@ +package keys + +import ( + "unicode" + + tea "github.com/charmbracelet/bubbletea" +) + +// jcuken maps the Russian ЙЦУКЕН layout to the US QWERTY key in the same +// position (lower case; upper case is derived). +var jcuken = map[rune]rune{ + 'й': 'q', 'ц': 'w', 'у': 'e', 'к': 'r', 'е': 't', 'н': 'y', 'г': 'u', 'ш': 'i', 'щ': 'o', 'з': 'p', + 'х': '[', 'ъ': ']', 'ф': 'a', 'ы': 's', 'в': 'd', 'а': 'f', 'п': 'g', 'р': 'h', 'о': 'j', 'л': 'k', + 'д': 'l', 'ж': ';', 'э': '\'', 'я': 'z', 'ч': 'x', 'с': 'c', 'м': 'v', 'и': 'b', 'т': 'n', 'ь': 'm', + 'б': ',', 'ю': '.', 'ё': '`', +} + +// translate returns the QWERTY key name for a single Cyrillic rune key +// (with alt preserved). Only command contexts use it. +func translate(msg tea.KeyMsg) (string, bool) { + if msg.Type != tea.KeyRunes || len(msg.Runes) != 1 { + return "", false + } + r := msg.Runes[0] + upper := unicode.IsUpper(r) + q, ok := jcuken[unicode.ToLower(r)] + if !ok { + return "", false + } + if upper { + q = unicode.ToUpper(q) + } + k := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{q}, Alt: msg.Alt} + return k.String(), true +}