forked from vhaudiquet/weekly-activity
refactor(wizard): replace hand-rolled arrow-key menu with questionary
The reviewer asked for a known-good interactive-menu library instead of the custom termios/select key reader; arrow keys had failed in their terminal. The TTY path now delegates to questionary.select (pointer ">", bold highlight via pointer/selected styles), keeping choice values mapped to list indices. Cancellable menus graft an eager Escape binding onto the prompt's own key-binding registry so Esc backs out while Ctrl-C still aborts fixed menus and backs out of cancellable ones. The non-TTY numbered fallback is untouched, and hand-rolled internals (_arrow_menu/_read_keypress/_option_line/_draw_menu_rows) are gone.
This commit is contained in:
1 parent
12ca06ba0d
commit
daf0a203a0
4 files changed
+277
-212
No files matched your search
+33
-105
@@ -18,6 +18,7 @@ import os
|
||||
import sys
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from weekly_activity.aggregate import source_label
|
||||
from weekly_activity.config import (
|
||||
@@ -32,6 +33,10 @@ from weekly_activity.config import (
|
||||
)
|
||||
from weekly_activity.sources.launchpad import LaunchpadSource
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
|
||||
|
||||
|
||||
_APPLICATION_NAME = "weekly-activity"
|
||||
|
||||
# Stable processing order, shared by menus and summaries: (config attr, menu text).
|
||||
@@ -291,7 +296,7 @@ def _menu(title: str, options: Sequence[str], *, cancellable: bool = False) -> i
|
||||
Returns the selected index, or None when backed out of a cancellable menu.
|
||||
"""
|
||||
if sys.stdin.isatty() and sys.stdout.isatty():
|
||||
return _arrow_menu(title, options, cancellable=cancellable)
|
||||
return _tty_menu(title, options, cancellable=cancellable)
|
||||
return _numbered_menu(title, options, cancellable=cancellable)
|
||||
|
||||
|
||||
@@ -320,119 +325,42 @@ def _numbered_menu(title: str, options: Sequence[str], *, cancellable: bool = Fa
|
||||
# --- Arrow-key menu (interactive TTYs only) ---
|
||||
|
||||
|
||||
_BOLD = "\x1b[1m"
|
||||
_RESET = "\x1b[0m"
|
||||
|
||||
_ERASE_LINE = "\x1b[2K"
|
||||
_CURSOR_DOWN = "\x1b[1B"
|
||||
_CURSOR_UP_TEMPLATE = "\x1b[{}A"
|
||||
|
||||
# Key classifications shared by the reader and the menu loop.
|
||||
_KEY_UP = "up"
|
||||
_KEY_DOWN = "down"
|
||||
_KEY_HOME = "home"
|
||||
_KEY_END = "end"
|
||||
_KEY_ENTER = "enter"
|
||||
_KEY_ESCAPE = "escape"
|
||||
_KEY_OTHER = "other"
|
||||
|
||||
_CSI_KEYS = {"[A": _KEY_UP, "[B": _KEY_DOWN, "[H": _KEY_HOME, "[F": _KEY_END}
|
||||
# Sentinel handed back through the prompt when Esc backs out; it can never
|
||||
# collide with a real choice because every choice's value is its list index.
|
||||
_CANCELLED = object()
|
||||
|
||||
|
||||
def _read_keypress() -> str:
|
||||
"""Read one keystroke from stdin (cbreak mode); classify it."""
|
||||
import select
|
||||
def _tty_menu(title: str, options: Sequence[str], *, cancellable: bool = False) -> int | None:
|
||||
"""Arrow-key menu rendered by questionary instead of hand-rolled ANSI.
|
||||
|
||||
fd = sys.stdin.fileno()
|
||||
# Read raw bytes from the fd: a buffered text read would pull the whole
|
||||
# escape sequence into its own buffer, leaving nothing for select to see.
|
||||
first = os.read(fd, 1)
|
||||
if first == b"\x1b":
|
||||
# A bare Esc is not followed by more bytes; CSI sequences are. Peek briefly.
|
||||
readable, _, _ = select.select([fd], [], [], 0.05)
|
||||
if not readable:
|
||||
return _KEY_ESCAPE
|
||||
tail = os.read(fd, 2)
|
||||
return _CSI_KEYS.get(tail.decode("ascii", "replace"), _KEY_OTHER)
|
||||
if first in (b"\r", b"\n"):
|
||||
return _KEY_ENTER
|
||||
if first == b"\x01": # Ctrl-A
|
||||
return _KEY_HOME
|
||||
if first == b"\x05": # Ctrl-E
|
||||
return _KEY_END
|
||||
if first == b"k":
|
||||
return _KEY_UP
|
||||
if first == b"j":
|
||||
return _KEY_DOWN
|
||||
return _KEY_OTHER
|
||||
|
||||
|
||||
def _option_line(option: str, selected: bool) -> str:
|
||||
"""One rendered row: bold with a '>' marker on the selected line."""
|
||||
prefix = "> " if selected else " "
|
||||
if selected:
|
||||
return f"{_BOLD}{prefix}{option}{_RESET}"
|
||||
return f"{prefix}{option}"
|
||||
|
||||
|
||||
def _draw_menu_rows(options: Sequence[str], selected: int | None) -> None:
|
||||
"""Redraw or clear the option rows.
|
||||
|
||||
On entry the cursor sits at column 0 of the blank row just below the
|
||||
block; writes move up and repaint each row so the title above stays
|
||||
untouched. With ``selected=None`` every row is erased instead,
|
||||
clearing the menu before trailing prompts run.
|
||||
Up/Down (plus j/k) move the bold ``>``-marked highlight and Enter
|
||||
accepts; Esc or Ctrl-C backs out of a cancellable menu while Ctrl-C
|
||||
alone aborts fixed ones. questionary is imported lazily so
|
||||
non-interactive commands never pay for prompt-toolkit.
|
||||
"""
|
||||
out = sys.stdout
|
||||
out.write(_CURSOR_UP_TEMPLATE.format(len(options)))
|
||||
for index, option in enumerate(options):
|
||||
out.write(_ERASE_LINE + "\r")
|
||||
if selected is not None:
|
||||
out.write(_option_line(option, index == selected))
|
||||
out.write(_CURSOR_DOWN)
|
||||
out.flush()
|
||||
import questionary
|
||||
|
||||
choices = [questionary.Choice(title=text, value=index) for index, text in enumerate(options)]
|
||||
style = questionary.Style([("pointer", "bold"), ("selected", "bold")])
|
||||
question = questionary.select(title, choices, pointer=">", style=style)
|
||||
if cancellable:
|
||||
# questionary wires arrows, Enter and Ctrl-C itself but leaves Esc as
|
||||
# a no-op; graft back-out onto this prompt's own key-binding registry.
|
||||
registry = cast("KeyBindings", question.application.key_bindings)
|
||||
|
||||
def _arrow_menu(title: str, options: Sequence[str], *, cancellable: bool = False) -> int | None:
|
||||
"""Inline re-rendered menu driven by raw-mode keypresses."""
|
||||
import termios
|
||||
import tty
|
||||
@registry.add("escape", eager=True)
|
||||
def _back_out(event: KeyPressEvent) -> None:
|
||||
event.app.exit(result=_CANCELLED)
|
||||
|
||||
print(title)
|
||||
selected = 0
|
||||
for index, option in enumerate(options): # fresh draw lands one row per option
|
||||
print(_option_line(option, index == selected))
|
||||
fd = sys.stdin.fileno()
|
||||
saved_state = termios.tcgetattr(fd)
|
||||
choice: int | None = None
|
||||
try:
|
||||
tty.setcbreak(fd)
|
||||
while True:
|
||||
key = _read_keypress()
|
||||
if key == _KEY_ENTER:
|
||||
choice = selected
|
||||
break
|
||||
if key == _KEY_UP:
|
||||
selected = (selected - 1) % len(options)
|
||||
elif key == _KEY_DOWN:
|
||||
selected = (selected + 1) % len(options)
|
||||
elif key == _KEY_HOME:
|
||||
selected = 0
|
||||
elif key == _KEY_END:
|
||||
selected = len(options) - 1
|
||||
elif cancellable and key in (_KEY_ESCAPE, "q"):
|
||||
break
|
||||
else: # Esc/q on fixed menus, or any unrecognised key: no-op.
|
||||
continue
|
||||
_draw_menu_rows(options, selected)
|
||||
except KeyboardInterrupt:
|
||||
# ISIG stays enabled under cbreak, so Ctrl-C raises SIGINT here.
|
||||
picked = question.unsafe_ask()
|
||||
except (KeyboardInterrupt, EOFError):
|
||||
if not cancellable:
|
||||
raise
|
||||
finally:
|
||||
termios.tcsetattr(fd, termios.TCSADRAIN, saved_state)
|
||||
_draw_menu_rows(options, None)
|
||||
return choice
|
||||
raise # Ctrl-C aborts fixed menus, like every other wizard input
|
||||
return None
|
||||
if not isinstance(picked, int): # the Esc sentinel, or any surprise value
|
||||
return None
|
||||
return picked
|
||||
|
||||
|
||||
def _ask(prompt: str, default: str = "") -> str:
|
||||
|
||||
Reference in new issue
Block a user