xref: /aosp_15_r20/external/pigweed/pw_cli/py/pw_cli/interactive_prompts.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2024 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Interactive input prompts with up/down navigation and validation."""
15
16import sys
17
18from prompt_toolkit import PromptSession
19from prompt_toolkit.history import InMemoryHistory
20from prompt_toolkit.validation import Validator
21
22
23def interactive_index_select(
24    selection_lines: list[str],
25    prompt_text: str = (
26        '\nEnter an item index or press up/down (Ctrl-C to cancel)\n> '
27    ),
28) -> tuple[int, str]:
29    """Display an interactive prompt to the user with up down navigation.
30
31    Presents an interactive prompt to the user on the terminal where
32    the index of and item can be typed in or items selected with the
33    up & down keys. If the user enters Ctrl-c or Ctrl-d the process
34    will exit with sys.exit(1).
35
36    Args:
37      selection_lines: List of strings to present to the user for
38          selection. Indexes will be prepended to each line starting
39          from 1 before displaying to the user.
40      prompt_text: String to display before the prompt cursor.
41
42    Returns: a tuple containing the index of the item selected and the
43      selected item text.
44    """
45
46    lines_with_indexes = list(
47        f'{i+1} - {line}' for i, line in enumerate(selection_lines)
48    )
49
50    # Add the items to a prompt_toolkit history so they can be
51    # selected with up and down.
52    history = InMemoryHistory()
53    # Add in reverse order so pressing up selects the first item
54    # followed by the second. Otherwise pressing up selects the last
55    # item in the printed list.
56    for line in reversed(lines_with_indexes):
57        history.append_string(line)
58
59    for line in lines_with_indexes:
60        print(' ', line)
61
62    def input_index(text: str) -> int:
63        """Convert input to a single index.
64
65        Args:
66            text: str beginning a single integer followed by whitespace.
67
68        Returns:
69            The single integer as an int minus 1 for use as a list index.
70        """
71        parts = text.split()
72        index = int(parts[0].strip())
73        return index - 1
74
75    def is_valid_item(text: str) -> bool:
76        """Returns true if the input line is a valid entry."""
77        return (
78            bool(text)
79            and any(line.startswith(text) for line in lines_with_indexes)
80            and input_index(text) < len(lines_with_indexes)
81        )
82
83    validator = Validator.from_callable(
84        is_valid_item,
85        error_message="Not a valid item.",
86        move_cursor_to_end=True,
87    )
88
89    session: PromptSession = PromptSession(
90        history=history,
91        enable_history_search=True,
92        validator=validator,
93        validate_while_typing=False,
94    )
95
96    try:
97        selected_text = session.prompt(prompt_text)
98    except (EOFError, KeyboardInterrupt):
99        # Cancel with Ctrl-c or Ctrl-d
100        sys.exit(1)
101
102    selected_index = input_index(selected_text)
103    original_text = selection_lines[selected_index]
104
105    return (selected_index, original_text)
106