Interactive selection using arrow keys with Rich Live display. Args: options: Dict with keys as option keys and values as descriptions prompt_text: Text to show above the options default_key: Default option key to start with Returns: Selected option key
(
options: dict[str, str],
prompt_text: str = "Select an option",
default_key: str | None = None,
)
| 145 | return key |
| 146 | |
| 147 | def select_with_arrows( |
| 148 | options: dict[str, str], |
| 149 | prompt_text: str = "Select an option", |
| 150 | default_key: str | None = None, |
| 151 | ) -> str: |
| 152 | """ |
| 153 | Interactive selection using arrow keys with Rich Live display. |
| 154 | |
| 155 | Args: |
| 156 | options: Dict with keys as option keys and values as descriptions |
| 157 | prompt_text: Text to show above the options |
| 158 | default_key: Default option key to start with |
| 159 | |
| 160 | Returns: |
| 161 | Selected option key |
| 162 | """ |
| 163 | if not options: |
| 164 | raise ValueError("select_with_arrows() requires at least one option.") |
| 165 | |
| 166 | option_keys = list(options.keys()) |
| 167 | if default_key and default_key in option_keys: |
| 168 | selected_index = option_keys.index(default_key) |
| 169 | else: |
| 170 | selected_index = 0 |
| 171 | |
| 172 | selected_key = None |
| 173 | |
| 174 | def create_selection_panel(): |
| 175 | """Create the selection panel with current selection highlighted.""" |
| 176 | table = Table.grid(padding=(0, 2)) |
| 177 | table.add_column(style="cyan", justify="left", width=3) |
| 178 | table.add_column(style="white", justify="left") |
| 179 | |
| 180 | for i, key in enumerate(option_keys): |
| 181 | if i == selected_index: |
| 182 | table.add_row("▶", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]") |
| 183 | else: |
| 184 | table.add_row(" ", f"[cyan]{key}[/cyan] [dim]({options[key]})[/dim]") |
| 185 | |
| 186 | table.add_row("", "") |
| 187 | table.add_row("", "[dim]Use ↑/↓ to navigate, Enter to select, Esc to cancel[/dim]") |
| 188 | |
| 189 | return Panel( |
| 190 | table, |
| 191 | title=f"[bold]{prompt_text}[/bold]", |
| 192 | border_style="cyan", |
| 193 | padding=(1, 2) |
| 194 | ) |
| 195 | |
| 196 | console.print() |
| 197 | |
| 198 | def run_selection_loop(): |
| 199 | nonlocal selected_key, selected_index |
| 200 | _transient = sys.platform != "win32" |
| 201 | with Live(create_selection_panel(), console=console, transient=_transient, auto_refresh=False) as live: |
| 202 | while True: |
| 203 | try: |
| 204 | key = get_key() |