InquirerPrompt 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+ """Module contains the class to create a confirm prompt."""
2
+
3
+ from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple
4
+
5
+ from prompt_toolkit.buffer import ValidationState
6
+ from prompt_toolkit.keys import Keys
7
+ from prompt_toolkit.shortcuts import PromptSession
8
+ from prompt_toolkit.validation import ValidationError
9
+
10
+ from InquirerPy.base import BaseSimplePrompt
11
+ from InquirerPy.exceptions import InvalidArgument
12
+ from InquirerPy.utils import (
13
+ InquirerPyDefault,
14
+ InquirerPyKeybindings,
15
+ InquirerPyMessage,
16
+ InquirerPySessionResult,
17
+ InquirerPyStyle,
18
+ )
19
+
20
+ if TYPE_CHECKING:
21
+ from prompt_toolkit.input.base import Input
22
+ from prompt_toolkit.key_binding.key_processor import KeyPressEvent
23
+ from prompt_toolkit.output.base import Output
24
+
25
+ __all__ = ["ConfirmPrompt"]
26
+
27
+
28
+ class ConfirmPrompt(BaseSimplePrompt):
29
+ """Create a prompt that provides 2 options (confirm/deny) and controlled via single keypress.
30
+
31
+ A wrapper class around :class:`~prompt_toolkit.shortcuts.PromptSession`.
32
+
33
+ Args:
34
+ message: The question to ask the user.
35
+ Refer to :ref:`pages/dynamic:message` documentation for more details.
36
+ style: An :class:`InquirerPyStyle` instance.
37
+ Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
38
+ vi_mode: Used for compatibility .
39
+ default: Set the default value of the prompt, should be either `True` or `False`.
40
+ This affects the value returned when user directly hit `enter` key.
41
+ Refer to :ref:`pages/dynamic:default` documentation for more details.
42
+ qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
43
+ amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
44
+ instruction: Short instruction to display next to the question.
45
+ long_instruction: Long instructions to display at the bottom of the prompt.
46
+ transformer: A function which performs additional transformation on the value that gets printed to the terminal.
47
+ Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
48
+ Refer to :ref:`pages/dynamic:transformer` documentation for more details.
49
+ filter: A function which performs additional transformation on the result.
50
+ This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
51
+ Refer to :ref:`pages/dynamic:filter` documentation for more details.
52
+ keybindings: Customise the builtin keybindings.
53
+ Refer to :ref:`pages/kb:Keybindings` for more details.
54
+ wrap_lines: Soft wrap question lines when question exceeds the terminal width.
55
+ confirm_letter: Letter used to confirm the prompt. A keybinding will be created for this letter.
56
+ Default is `y` and pressing `y` will answer the prompt with value `True`.
57
+ reject_letter: Letter used to reject the prompt. A keybinding will be created for this letter.
58
+ Default is `n` and pressing `n` will answer the prompt with value `False`.
59
+ raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
60
+ will be `None` and the question is skiped.
61
+ mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
62
+ mandatory_message: Error message to show when user attempts to skip mandatory prompt.
63
+ session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
64
+ input: Used internally and will be removed in future updates.
65
+ output: Used internally and will be removed in future updates.
66
+
67
+ Examples:
68
+ >>> from InquirerPy import inquirer
69
+ >>> result = inquirer.confirm(message="Confirm?").execute()
70
+ >>> print(result)
71
+ True
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ message: InquirerPyMessage,
77
+ style: Optional[InquirerPyStyle] = None,
78
+ default: InquirerPyDefault = False,
79
+ vi_mode: bool = False,
80
+ qmark: str = "?",
81
+ amark: str = "?",
82
+ instruction: str = "",
83
+ long_instruction: str = "",
84
+ transformer: Optional[Callable[[bool], Any]] = None,
85
+ filter: Optional[Callable[[bool], Any]] = None,
86
+ keybindings: Optional[InquirerPyKeybindings] = None,
87
+ wrap_lines: bool = True,
88
+ confirm_letter: str = "y",
89
+ reject_letter: str = "n",
90
+ raise_keyboard_interrupt: bool = True,
91
+ mandatory: bool = True,
92
+ mandatory_message: str = "Mandatory prompt",
93
+ session_result: Optional[InquirerPySessionResult] = None,
94
+ input: Optional["Input"] = None,
95
+ output: Optional["Output"] = None,
96
+ ) -> None:
97
+ vi_mode = False
98
+ super().__init__(
99
+ message=message,
100
+ style=style,
101
+ vi_mode=vi_mode,
102
+ qmark=qmark,
103
+ amark=amark,
104
+ instruction=instruction,
105
+ transformer=transformer,
106
+ filter=filter,
107
+ default=default,
108
+ wrap_lines=wrap_lines,
109
+ raise_keyboard_interrupt=raise_keyboard_interrupt,
110
+ mandatory=mandatory,
111
+ mandatory_message=mandatory_message,
112
+ session_result=session_result,
113
+ )
114
+ if not isinstance(self._default, bool):
115
+ raise InvalidArgument(
116
+ f"{type(self).__name__} argument default should be type of bool"
117
+ )
118
+ self._confirm_letter = confirm_letter
119
+ self._reject_letter = reject_letter
120
+
121
+ if not keybindings:
122
+ keybindings = {}
123
+ self.kb_maps = {
124
+ "confirm": [
125
+ {"key": self._confirm_letter},
126
+ {"key": self._confirm_letter.upper()},
127
+ ],
128
+ "reject": [
129
+ {"key": self._reject_letter},
130
+ {"key": self._reject_letter.upper()},
131
+ ],
132
+ "any": [{"key": Keys.Any}],
133
+ **keybindings,
134
+ }
135
+ self.kb_func_lookup = {
136
+ "confirm": [{"func": self._handle_confirm}],
137
+ "reject": [{"func": self._handle_reject}],
138
+ "any": [{"func": lambda _: None}],
139
+ }
140
+ self._keybinding_factory()
141
+
142
+ self._session = PromptSession(
143
+ message=self._get_prompt_message,
144
+ key_bindings=self._kb,
145
+ style=self._style,
146
+ wrap_lines=self._wrap_lines,
147
+ bottom_toolbar=(
148
+ [("class:long_instruction", long_instruction)]
149
+ if long_instruction
150
+ else None
151
+ ),
152
+ input=input,
153
+ output=output,
154
+ )
155
+
156
+ def _set_error(self, message: str) -> None:
157
+ self._session.default_buffer.validation_state = ValidationState.INVALID
158
+ self._session.default_buffer.validation_error = ValidationError(message=message)
159
+
160
+ def _handle_reject(self, event) -> None:
161
+ self._session.default_buffer.text = ""
162
+ self.status["answered"] = True
163
+ self.status["result"] = False
164
+ event.app.exit(result=False)
165
+
166
+ def _handle_confirm(self, event) -> None:
167
+ self._session.default_buffer.text = ""
168
+ self.status["answered"] = True
169
+ self.status["result"] = True
170
+ event.app.exit(result=True)
171
+
172
+ def _handle_enter(self, event: "KeyPressEvent") -> None:
173
+ self.status["answered"] = True
174
+ self.status["result"] = self._default
175
+ event.app.exit(result=self._default)
176
+
177
+ def _get_prompt_message(self) -> List[Tuple[str, str]]:
178
+ """Get message to display infront of the input buffer.
179
+
180
+ Returns:
181
+ Formatted text in list of tuple format.
182
+ """
183
+ if not self.instruction:
184
+ pre_answer = (
185
+ "class:instruction",
186
+ (
187
+ " (%s/%s) " % (self._confirm_letter.upper(), self._reject_letter)
188
+ if self._default
189
+ else " (%s/%s) "
190
+ % (self._confirm_letter, self._reject_letter.upper())
191
+ ),
192
+ )
193
+ else:
194
+ pre_answer = ("class:instruction", " %s " % self.instruction)
195
+ post_answer = ("class:answer", " Yes" if self.status["result"] else " No")
196
+ return super()._get_prompt_message(pre_answer, post_answer)
197
+
198
+ def _run(self) -> bool:
199
+ return self._session.prompt()
200
+
201
+ async def _run_async(self) -> Any:
202
+ return await self._session.prompt_async()
@@ -0,0 +1,459 @@
1
+ """Module contains the class to create an expand prompt."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Callable, List, Optional, Tuple, Union
5
+
6
+ from InquirerPy.base import BaseListPrompt, InquirerPyUIListControl
7
+ from InquirerPy.base.control import Choice
8
+ from InquirerPy.enum import INQUIRERPY_POINTER_SEQUENCE
9
+ from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFound
10
+ from InquirerPy.prompts.list import ListPrompt
11
+ from InquirerPy.separator import Separator
12
+ from InquirerPy.utils import (
13
+ InquirerPyDefault,
14
+ InquirerPyKeybindings,
15
+ InquirerPyListChoices,
16
+ InquirerPyMessage,
17
+ InquirerPySessionResult,
18
+ InquirerPyStyle,
19
+ InquirerPyValidate,
20
+ )
21
+
22
+ __all__ = ["ExpandPrompt", "ExpandHelp", "ExpandChoice"]
23
+
24
+
25
+ @dataclass
26
+ class ExpandHelp:
27
+ """Help choice for the :class:`.ExpandPrompt`.
28
+
29
+ Args:
30
+ key: The key to bind to toggle the expansion of the prompt.
31
+ message: The help message.
32
+ """
33
+
34
+ key: str = "h"
35
+ message: str = "Help, list all choices"
36
+
37
+
38
+ @dataclass
39
+ class ExpandChoice(Choice):
40
+ """Choice class for :class:`.ExpandPrompt`.
41
+
42
+ See Also:
43
+ :class:`~InquirerPy.base.control.Choice`
44
+
45
+ Args:
46
+ value: The value of the choice when user selects this choice.
47
+ name: The value that should be presented to the user prior/after selection of the choice.
48
+ This value is optional, if not provided, it will fallback to the string representation of `value`.
49
+ enabled: Indicates if the choice should be pre-selected.
50
+ This only has effects when the prompt has `multiselect` enabled.
51
+ key: Char to bind to the choice. Pressing this value will jump to the choice,
52
+ If this value is missing, the first char of the `str(value)` will be used as the key.
53
+ """
54
+
55
+ key: Optional[str] = None
56
+
57
+ def __post_init__(self):
58
+ """Assign stringify value to name and also create key using the first char of the value if not present."""
59
+ super().__post_init__()
60
+ if self.key is None:
61
+ self.key = str(self.value)[0].lower()
62
+
63
+
64
+ class InquirerPyExpandControl(InquirerPyUIListControl):
65
+ """An :class:`~prompt_toolkit.layout.UIControl` class that displays a list of choices.
66
+
67
+ Reference the parameter definition in :class:`.ExpandPrompt`.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ choices: InquirerPyListChoices,
73
+ default: Any,
74
+ pointer: str,
75
+ separator: str,
76
+ expand_help: ExpandHelp,
77
+ expand_pointer: str,
78
+ marker: str,
79
+ session_result: Optional[InquirerPySessionResult],
80
+ multiselect: bool,
81
+ marker_pl: str,
82
+ ) -> None:
83
+ self._pointer = pointer
84
+ self._separator = separator
85
+ self._expanded = False
86
+ self._expand_pointer = expand_pointer
87
+ self._marker = marker
88
+ self._marker_pl = marker_pl
89
+ self._expand_help = expand_help
90
+ super().__init__(
91
+ choices=choices,
92
+ default=default,
93
+ session_result=session_result,
94
+ multiselect=multiselect,
95
+ )
96
+
97
+ def _format_choices(self) -> None:
98
+ self._key_maps = {}
99
+ try:
100
+ count = 0
101
+ separator_count = 0
102
+ for raw_choice, choice in zip(self._raw_choices, self.choices): # type: ignore
103
+ if (
104
+ not isinstance(raw_choice, dict)
105
+ and not isinstance(raw_choice, Separator)
106
+ and not isinstance(raw_choice, ExpandChoice)
107
+ ):
108
+ raise InvalidArgument(
109
+ "expand prompt argument choices requires each choice to be type of dictionary or Separator or ExpandChoice"
110
+ )
111
+ if isinstance(raw_choice, Separator):
112
+ separator_count += 1
113
+ else:
114
+ choice["key"] = (
115
+ raw_choice.key
116
+ if isinstance(raw_choice, ExpandChoice)
117
+ else raw_choice["key"]
118
+ )
119
+ self._key_maps[choice["key"]] = count
120
+ count += 1
121
+ except KeyError:
122
+ raise RequiredKeyNotFound(
123
+ "expand prompt choice requires a key 'key' to exists"
124
+ )
125
+
126
+ self.choices.append(
127
+ {
128
+ "key": self._expand_help.key,
129
+ "value": self._expand_help,
130
+ "name": self._expand_help.message,
131
+ "enabled": False,
132
+ }
133
+ )
134
+ self._key_maps[self._expand_help.key] = len(self.choices) - 1
135
+
136
+ first_valid_choice_index = 0
137
+ while isinstance(self.choices[first_valid_choice_index]["value"], Separator):
138
+ first_valid_choice_index += 1
139
+ if self.selected_choice_index == first_valid_choice_index:
140
+ for index, choice in enumerate(self.choices):
141
+ if isinstance(choice["value"], Separator):
142
+ continue
143
+ if choice["key"] == self._default:
144
+ self.selected_choice_index = index
145
+ break
146
+
147
+ def _get_formatted_choices(self) -> List[Tuple[str, str]]:
148
+ """Override this parent class method as expand require visual switch of content.
149
+
150
+ Two types of mode:
151
+ * non expand mode
152
+ * expand mode
153
+ """
154
+ if self._expanded:
155
+ return super()._get_formatted_choices()
156
+ else:
157
+ display_choices = []
158
+ display_choices.append(("class:pointer", self._expand_pointer))
159
+ display_choices.append(
160
+ ("", self.choices[self.selected_choice_index]["name"])
161
+ )
162
+ return display_choices
163
+
164
+ def _get_hover_text(self, choice) -> List[Tuple[str, str]]:
165
+ display_choices = []
166
+ display_choices.append(("class:pointer", self._pointer))
167
+ display_choices.append(
168
+ (
169
+ "class:marker",
170
+ self._marker if choice["enabled"] else self._marker_pl,
171
+ )
172
+ )
173
+ if not isinstance(choice["value"], Separator):
174
+ display_choices.append(
175
+ ("class:pointer", "%s%s" % (choice["key"], self._separator))
176
+ )
177
+ display_choices.append(("[SetCursorPosition]", ""))
178
+ display_choices.append(("class:pointer", choice["name"]))
179
+ return display_choices
180
+
181
+ def _get_normal_text(self, choice) -> List[Tuple[str, str]]:
182
+ display_choices = []
183
+ display_choices.append(("", len(self._pointer) * " "))
184
+ display_choices.append(
185
+ (
186
+ "class:marker",
187
+ self._marker if choice["enabled"] else self._marker_pl,
188
+ )
189
+ )
190
+ if not isinstance(choice["value"], Separator):
191
+ display_choices.append(("", "%s%s" % (choice["key"], self._separator)))
192
+ display_choices.append(("", choice["name"]))
193
+ else:
194
+ display_choices.append(("class:separator", choice["name"]))
195
+ return display_choices
196
+
197
+
198
+ class ExpandPrompt(ListPrompt):
199
+ """Create a compact prompt with the ability to expand.
200
+
201
+ A wrapper class around :class:`~prompt_toolkit.application.Application`.
202
+
203
+ Contains a list of chocies binded to a shortcut letter.
204
+ The prompt can be expanded using `h` key.
205
+
206
+ Args:
207
+ message: The question to ask the user.
208
+ Refer to :ref:`pages/dynamic:message` documentation for more details.
209
+ choices: List of choices to display and select.
210
+ Refer to :ref:`pages/prompts/expand:Choices` documentation for more details.
211
+ style: An :class:`InquirerPyStyle` instance.
212
+ Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
213
+ vi_mode: Use vim keybinding for the prompt.
214
+ Refer to :ref:`pages/kb:Keybindings` documentation for more details.
215
+ default: Set the default value of the prompt.
216
+ This will be used to determine which choice is highlighted (current selection),
217
+ The default value should the value of one of the choices.
218
+ For :class:`.ExpandPrompt` specifically, default value can also be a `choice["key"]` which is the shortcut key for the choice.
219
+ Refer to :ref:`pages/dynamic:default` documentation for more details.
220
+ separator: Separator symbol. Custom symbol that will be used as a separator between the choice index number and the choices.
221
+ help_msg: This parameter is DEPRECATED. Use expand_help instead.
222
+ expand_help: The help configuration for the prompt. Must be an instance of :class:`.ExpandHelp`.
223
+ If this value is None, the default help key will be binded to `h` and the default help message would be
224
+ "Help, List all choices."
225
+ expand_pointer: Pointer symbol before prompt expansion. Custom symbol that will be displayed to indicate the prompt is not expanded.
226
+ qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
227
+ amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
228
+ pointer: Pointer symbol. Customer symbol that will be used to indicate the current choice selection.
229
+ instruction: Short instruction to display next to the question.
230
+ long_instruction: Long instructions to display at the bottom of the prompt.
231
+ validate: Add validation to user input.
232
+ The main use case for this prompt would be when `multiselect` is True, you can enforce a min/max selection.
233
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
234
+ invalid_message: Error message to display when user input is invalid.
235
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
236
+ transformer: A function which performs additional transformation on the value that gets printed to the terminal.
237
+ Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
238
+ Refer to :ref:`pages/dynamic:transformer` documentation for more details.
239
+ filter: A function which performs additional transformation on the result.
240
+ This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
241
+ Refer to :ref:`pages/dynamic:filter` documentation for more details.
242
+ height: Preferred height of the prompt.
243
+ Refer to :ref:`pages/height:Height` documentation for more details.
244
+ max_height: Max height of the prompt.
245
+ Refer to :ref:`pages/height:Height` documentation for more details.
246
+ multiselect: Enable multi-selection on choices.
247
+ You can use `validate` parameter to control min/max selections.
248
+ Setting to True will also change the result from a single value to a list of values.
249
+ marker: Marker Symbol. Custom symbol to indicate if a choice is selected.
250
+ This will take effects when `multiselect` is True.
251
+ marker_pl: Marker place holder when the choice is not selected.
252
+ This is empty space by default.
253
+ border: Create border around the choice window.
254
+ keybindings: Customise the builtin keybindings.
255
+ Refer to :ref:`pages/kb:Keybindings` for more details.
256
+ show_cursor: Display cursor at the end of the prompt.
257
+ Set to False to hide the cursor.
258
+ cycle: Return to top item if hit bottom during navigation or vice versa.
259
+ wrap_lines: Soft wrap question lines when question exceeds the terminal width.
260
+ raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
261
+ will be `None` and the question is skiped.
262
+ mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
263
+ mandatory_message: Error message to show when user attempts to skip mandatory prompt.
264
+ session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
265
+
266
+ Examples:
267
+ >>> from InquirerPy import inquirer
268
+ >>> result = inquirer.expand(message="Select one:", choices[{"name": "1", "value": "1", "key": "a"}]).execute()
269
+ >>> print(result)
270
+ "1"
271
+ """
272
+
273
+ def __init__(
274
+ self,
275
+ message: InquirerPyMessage,
276
+ choices: InquirerPyListChoices,
277
+ default: InquirerPyDefault = "",
278
+ style: Optional[InquirerPyStyle] = None,
279
+ vi_mode: bool = False,
280
+ qmark: str = "?",
281
+ amark: str = "?",
282
+ pointer: str = " ",
283
+ separator: str = ") ",
284
+ help_msg: str = "Help, list all choices",
285
+ expand_help: Optional[ExpandHelp] = None,
286
+ expand_pointer: str = "%s " % INQUIRERPY_POINTER_SEQUENCE,
287
+ instruction: str = "",
288
+ long_instruction: str = "",
289
+ transformer: Optional[Callable[[Any], Any]] = None,
290
+ filter: Optional[Callable[[Any], Any]] = None,
291
+ height: Optional[Union[int, str]] = None,
292
+ max_height: Optional[Union[int, str]] = None,
293
+ multiselect: bool = False,
294
+ marker: str = INQUIRERPY_POINTER_SEQUENCE,
295
+ marker_pl: str = " ",
296
+ border: bool = False,
297
+ validate: Optional[InquirerPyValidate] = None,
298
+ invalid_message: str = "Invalid input",
299
+ keybindings: Optional[InquirerPyKeybindings] = None,
300
+ show_cursor: bool = True,
301
+ cycle: bool = True,
302
+ wrap_lines: bool = True,
303
+ raise_keyboard_interrupt: bool = True,
304
+ mandatory: bool = True,
305
+ mandatory_message: str = "Mandatory prompt",
306
+ session_result: Optional[InquirerPySessionResult] = None,
307
+ ) -> None:
308
+ if expand_help is None:
309
+ expand_help = ExpandHelp(message=help_msg)
310
+ self._expand_help = expand_help
311
+ self.content_control: InquirerPyExpandControl = InquirerPyExpandControl(
312
+ choices=choices,
313
+ default=default,
314
+ pointer=pointer,
315
+ separator=separator,
316
+ expand_help=expand_help,
317
+ expand_pointer=expand_pointer,
318
+ marker=marker,
319
+ marker_pl=marker_pl,
320
+ session_result=session_result,
321
+ multiselect=multiselect,
322
+ )
323
+ super().__init__(
324
+ message=message,
325
+ choices=choices,
326
+ style=style,
327
+ border=border,
328
+ vi_mode=vi_mode,
329
+ qmark=qmark,
330
+ amark=amark,
331
+ instruction=instruction,
332
+ long_instruction=long_instruction,
333
+ transformer=transformer,
334
+ filter=filter,
335
+ height=height,
336
+ max_height=max_height,
337
+ validate=validate,
338
+ invalid_message=invalid_message,
339
+ multiselect=multiselect,
340
+ keybindings=keybindings,
341
+ show_cursor=show_cursor,
342
+ cycle=cycle,
343
+ wrap_lines=wrap_lines,
344
+ raise_keyboard_interrupt=raise_keyboard_interrupt,
345
+ mandatory=mandatory,
346
+ mandatory_message=mandatory_message,
347
+ session_result=session_result,
348
+ )
349
+
350
+ def _on_rendered(self, _) -> None:
351
+ """Override this method to apply custom keybindings.
352
+
353
+ Needs to creat these kb in the callback due to `after_render`
354
+ retrieve the choices asynchronously.
355
+ """
356
+
357
+ def keybinding_factory(key):
358
+ @self.register_kb(key.lower())
359
+ def keybinding(_) -> None:
360
+ if key == self._expand_help.key:
361
+ self.content_control._expanded = not self.content_control._expanded
362
+ else:
363
+ self.content_control.selected_choice_index = (
364
+ self.content_control._key_maps[key]
365
+ )
366
+
367
+ return keybinding
368
+
369
+ for choice in self.content_control.choices:
370
+ if not isinstance(choice["value"], Separator):
371
+ keybinding_factory(choice["key"])
372
+
373
+ def _handle_up(self, event) -> None:
374
+ """Handle the event when user attempt to move up.
375
+
376
+ Overriding this method to skip the help choice.
377
+ """
378
+ if not self.content_control._expanded:
379
+ return
380
+ while True:
381
+ cap = BaseListPrompt._handle_up(self, event)
382
+ if not isinstance(
383
+ self.content_control.selection["value"], Separator
384
+ ) and not isinstance(self.content_control.selection["value"], ExpandHelp):
385
+ break
386
+ else:
387
+ if cap and not self._cycle:
388
+ self._handle_down(event)
389
+ break
390
+
391
+ def _handle_down(self, event) -> None:
392
+ """Handle the event when user attempt to move down.
393
+
394
+ Overriding this method to skip the help choice.
395
+ """
396
+ if not self.content_control._expanded:
397
+ return
398
+ while True:
399
+ cap = BaseListPrompt._handle_down(self, event)
400
+ if not isinstance(
401
+ self.content_control.selection["value"], Separator
402
+ ) and not isinstance(self.content_control.selection["value"], ExpandHelp):
403
+ break
404
+ elif (
405
+ isinstance(self.content_control.selection["value"], ExpandHelp)
406
+ and not self._cycle
407
+ ):
408
+ self._handle_up(event)
409
+ break
410
+ else:
411
+ if cap and not self._cycle:
412
+ self._handle_up(event)
413
+ break
414
+
415
+ @property
416
+ def instruction(self) -> str:
417
+ """Construct the instruction behind the question.
418
+
419
+ If _instruction exists, use that.
420
+
421
+ :return: The instruction text.
422
+ """
423
+ return (
424
+ "(%s)" % "".join(self.content_control._key_maps.keys())
425
+ if not self._instruction
426
+ else self._instruction
427
+ )
428
+
429
+ def _get_prompt_message(self) -> List[Tuple[str, str]]:
430
+ """Return the formatted text to display in the prompt.
431
+
432
+ Overriding this method to allow multiple formatted class to be displayed.
433
+ """
434
+ display_message = super()._get_prompt_message()
435
+ if not self.status["answered"]:
436
+ display_message.append(
437
+ ("class:input", self.content_control.selection["key"])
438
+ )
439
+ return display_message
440
+
441
+ def _handle_toggle_all(self, _, value: Optional[bool] = None) -> None:
442
+ """Override this method to ignore `ExpandHelp`.
443
+
444
+ :param value: Specify a value to toggle.
445
+ """
446
+ if not self.content_control._expanded:
447
+ return
448
+ for choice in self.content_control.choices:
449
+ if isinstance(choice["value"], Separator) or isinstance(
450
+ choice["value"], ExpandHelp
451
+ ):
452
+ continue
453
+ choice["enabled"] = value if value else not choice["enabled"]
454
+
455
+ def _handle_toggle_choice(self, event) -> None:
456
+ """Override this method to ignore keypress when not expanded."""
457
+ if not self.content_control._expanded:
458
+ return
459
+ super()._handle_toggle_choice(event)