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,685 @@
1
+ """Module contains the class to create a fuzzy prompt."""
2
+
3
+ import asyncio
4
+ import math
5
+ from typing import (
6
+ TYPE_CHECKING,
7
+ Any,
8
+ Callable,
9
+ Dict,
10
+ List,
11
+ Optional,
12
+ Tuple,
13
+ Union,
14
+ cast,
15
+ )
16
+
17
+ from pfzy import fuzzy_match
18
+ from pfzy.score import fzy_scorer, substr_scorer
19
+ from pfzy.types import HAYSTACKS
20
+ from prompt_toolkit.application.application import Application
21
+ from prompt_toolkit.buffer import Buffer
22
+ from prompt_toolkit.filters.cli import IsDone
23
+ from prompt_toolkit.layout.containers import (
24
+ ConditionalContainer,
25
+ FloatContainer,
26
+ HSplit,
27
+ Window,
28
+ )
29
+ from prompt_toolkit.layout.controls import BufferControl, DummyControl
30
+ from prompt_toolkit.layout.dimension import Dimension, LayoutDimension
31
+ from prompt_toolkit.layout.layout import Layout
32
+ from prompt_toolkit.layout.processors import AfterInput, BeforeInput
33
+ from prompt_toolkit.lexers.base import SimpleLexer
34
+ from prompt_toolkit.validation import ValidationError
35
+ from prompt_toolkit.widgets.base import Frame
36
+
37
+ from InquirerPy.base import FakeDocument, InquirerPyUIListControl
38
+ from InquirerPy.base.list import BaseListPrompt
39
+ from InquirerPy.containers.instruction import InstructionWindow
40
+ from InquirerPy.containers.message import MessageWindow
41
+ from InquirerPy.containers.validation import ValidationFloat
42
+ from InquirerPy.enum import INQUIRERPY_POINTER_SEQUENCE
43
+ from InquirerPy.exceptions import InvalidArgument
44
+ from InquirerPy.separator import Separator
45
+ from InquirerPy.utils import (
46
+ InquirerPyDefault,
47
+ InquirerPyKeybindings,
48
+ InquirerPyListChoices,
49
+ InquirerPyMessage,
50
+ InquirerPySessionResult,
51
+ InquirerPyStyle,
52
+ InquirerPyValidate,
53
+ calculate_height,
54
+ )
55
+
56
+ if TYPE_CHECKING:
57
+ from prompt_toolkit.key_binding.key_processor import KeyPressEvent
58
+
59
+ __all__ = ["FuzzyPrompt"]
60
+
61
+
62
+ class InquirerPyFuzzyControl(InquirerPyUIListControl):
63
+ """An :class:`~prompt_toolkit.layout.UIControl` class that displays a list of choices.
64
+
65
+ This only displays the chocies. The actual input buffer will be handled by a separate
66
+ :class:`~prompt_toolkit.layout.BufferControl`.
67
+
68
+ Reference the parameter definition in :class:`.FuzzyPrompt`.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ choices: InquirerPyListChoices,
74
+ pointer: str,
75
+ marker: str,
76
+ current_text: Callable[[], str],
77
+ max_lines: int,
78
+ session_result: Optional[InquirerPySessionResult],
79
+ multiselect: bool,
80
+ marker_pl: str,
81
+ match_exact: bool,
82
+ ) -> None:
83
+ self._pointer = pointer
84
+ self._marker = marker
85
+ self._marker_pl = marker_pl
86
+ self._current_text = current_text
87
+ self._max_lines = max_lines if max_lines > 0 else 1
88
+ self._scorer = fzy_scorer if not match_exact else substr_scorer
89
+ super().__init__(
90
+ choices=choices,
91
+ default=None,
92
+ session_result=session_result,
93
+ multiselect=multiselect,
94
+ )
95
+
96
+ def _format_choices(self) -> None:
97
+ for index, choice in enumerate(self.choices):
98
+ if isinstance(choice["value"], Separator):
99
+ raise InvalidArgument(
100
+ "fuzzy prompt argument choices should not contain Separator"
101
+ )
102
+ choice["index"] = index
103
+ choice["indices"] = []
104
+ self._filtered_choices = self.choices
105
+ self._first_line = 0
106
+ self._last_line = min(self._max_lines, self.choice_count)
107
+ self._height = self._last_line - self._first_line
108
+
109
+ def _get_hover_text(self, choice) -> List[Tuple[str, str]]:
110
+ """Get the current highlighted line of text.
111
+
112
+ If in the middle of filtering, loop through the char and color
113
+ indices matched char into style class `class:fuzzy_match`.
114
+
115
+ Returns:
116
+ FormattedText in list of tuple format.
117
+ """
118
+ display_choices = []
119
+ display_choices.append(("class:pointer", self._pointer))
120
+ display_choices.append(
121
+ (
122
+ "class:marker",
123
+ (
124
+ self._marker
125
+ if self.choices[choice["index"]]["enabled"]
126
+ else self._marker_pl
127
+ ),
128
+ )
129
+ )
130
+ display_choices.append(("[SetCursorPosition]", ""))
131
+ if not choice["indices"]:
132
+ display_choices.append(("class:pointer", choice["name"]))
133
+ else:
134
+ indices = set(choice["indices"])
135
+ for index, char in enumerate(choice["name"]):
136
+ if index in indices:
137
+ display_choices.append(("class:fuzzy_match", char))
138
+ else:
139
+ display_choices.append(("class:pointer", char))
140
+ return display_choices
141
+
142
+ def _get_normal_text(self, choice) -> List[Tuple[str, str]]:
143
+ """Get the line of text in `FormattedText`.
144
+
145
+ If in the middle of filtering, loop through the char and color
146
+ indices matched char into `class:fuzzy_match`.
147
+
148
+ Calculate spaces of pointer to make the choice equally align.
149
+
150
+ Returns:
151
+ FormattedText in list of tuple format.
152
+ """
153
+ display_choices = []
154
+ display_choices.append(("class:pointer", len(self._pointer) * " "))
155
+ display_choices.append(
156
+ (
157
+ "class:marker",
158
+ (
159
+ self._marker
160
+ if self.choices[choice["index"]]["enabled"]
161
+ else self._marker_pl
162
+ ),
163
+ )
164
+ )
165
+ if not choice["indices"]:
166
+ display_choices.append(("", choice["name"]))
167
+ else:
168
+ indices = set(choice["indices"])
169
+ for index, char in enumerate(choice["name"]):
170
+ if index in indices:
171
+ display_choices.append(("class:fuzzy_match", char))
172
+ else:
173
+ display_choices.append(("", char))
174
+ return display_choices
175
+
176
+ def _get_formatted_choices(self) -> List[Tuple[str, str]]:
177
+ """Get all available choices in formatted text format.
178
+
179
+ Overriding this method because `self.choice` will be the
180
+ full choice list. Using `self.filtered_choice` to get
181
+ a list of choice based on current_text.
182
+
183
+ Returns:
184
+ FormattedText in list of tuple format.
185
+ """
186
+ display_choices = []
187
+ if self.choice_count == 0:
188
+ self._selected_choice_index = 0
189
+ return display_choices
190
+
191
+ if self._selected_choice_index < 0:
192
+ self._selected_choice_index = 0
193
+ elif self._selected_choice_index >= self.choice_count:
194
+ self._selected_choice_index = self.choice_count - 1
195
+
196
+ if (self._last_line - self._first_line) < min(self.choice_count, self._height):
197
+ self._last_line = min(self.choice_count, self._height)
198
+ self._first_line = self._last_line - min(self.choice_count, self._height)
199
+
200
+ if self._selected_choice_index <= self._first_line:
201
+ self._first_line = self._selected_choice_index
202
+ self._last_line = self._first_line + min(self._height, self.choice_count)
203
+ elif self._selected_choice_index >= self._last_line:
204
+ self._last_line = self._selected_choice_index + 1
205
+ self._first_line = self._last_line - min(self._height, self.choice_count)
206
+
207
+ if self._last_line > self.choice_count:
208
+ self._last_line = self.choice_count
209
+ self._first_line = self._last_line - min(self._height, self.choice_count)
210
+ if self._first_line < 0:
211
+ self._first_line = 0
212
+ self._last_line = self._first_line + min(self._height, self.choice_count)
213
+
214
+ for index in range(self._first_line, self._last_line):
215
+ if index == self.selected_choice_index:
216
+ display_choices += self._get_hover_text(self._filtered_choices[index])
217
+ else:
218
+ display_choices += self._get_normal_text(self._filtered_choices[index])
219
+ display_choices.append(("", "\n"))
220
+ if display_choices:
221
+ display_choices.pop()
222
+ return display_choices
223
+
224
+ async def _filter_choices(self, wait_time: float) -> List[Dict[str, Any]]:
225
+ """Call to filter choices using fzy fuzzy match.
226
+
227
+ Args:
228
+ wait_time: Additional time to wait before filtering the choice.
229
+
230
+ Returns:
231
+ Filtered choices.
232
+ """
233
+ if not self._current_text():
234
+ for choice in self.choices:
235
+ choice["indices"] = []
236
+ choices = self.choices
237
+ else:
238
+ await asyncio.sleep(wait_time)
239
+ choices = await fuzzy_match(
240
+ self._current_text(),
241
+ cast(HAYSTACKS, self.choices),
242
+ key="name",
243
+ scorer=self._scorer,
244
+ )
245
+ return choices
246
+
247
+ @property
248
+ def selection(self) -> Dict[str, Any]:
249
+ """Override this value since `self.choice` does not indicate the choice displayed.
250
+
251
+ `self.filtered_choice` is the up to date choice displayed.
252
+
253
+ Returns:
254
+ A dictionary of name and value for the current pointed choice.
255
+ """
256
+ return self._filtered_choices[self.selected_choice_index]
257
+
258
+ @property
259
+ def choice_count(self) -> int:
260
+ """int: Filtered choice count."""
261
+ return len(self._filtered_choices)
262
+
263
+
264
+ class FuzzyPrompt(BaseListPrompt):
265
+ """Create a prompt that lists choices while also allowing fuzzy search like fzf.
266
+
267
+ A wrapper class around :class:`~prompt_toolkit.application.Application`.
268
+
269
+ Fuzzy search using :func:`pfzy.match.fuzzy_match` function.
270
+
271
+ Override the default keybindings for up/down as j/k cannot be bind even if `editing_mode` is vim
272
+ due to the input buffer.
273
+
274
+ Args:
275
+ message: The question to ask the user.
276
+ Refer to :ref:`pages/dynamic:message` documentation for more details.
277
+ choices: List of choices to display and select.
278
+ Refer to :ref:`pages/dynamic:choices` documentation for more details.
279
+ style: An :class:`InquirerPyStyle` instance.
280
+ Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
281
+ vi_mode: Use vim keybinding for the prompt.
282
+ Refer to :ref:`pages/kb:Keybindings` documentation for more details.
283
+ default: Set the default value in the search buffer.
284
+ Different than other list type prompts, the `default` parameter tries to replicate what fzf does and
285
+ add the value in `default` to search buffer so it starts searching immediatelly.
286
+ Refer to :ref:`pages/dynamic:default` documentation for more details.
287
+ qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
288
+ amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
289
+ pointer: Pointer symbol. Customer symbol that will be used to indicate the current choice selection.
290
+ instruction: Short instruction to display next to the question.
291
+ long_instruction: Long instructions to display at the bottom of the prompt.
292
+ validate: Add validation to user input.
293
+ The main use case for this prompt would be when `multiselect` is True, you can enforce a min/max selection.
294
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
295
+ invalid_message: Error message to display when user input is invalid.
296
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
297
+ transformer: A function which performs additional transformation on the value that gets printed to the terminal.
298
+ Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
299
+ Refer to :ref:`pages/dynamic:transformer` documentation for more details.
300
+ filter: A function which performs additional transformation on the result.
301
+ This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
302
+ Refer to :ref:`pages/dynamic:filter` documentation for more details.
303
+ height: Preferred height of the prompt.
304
+ Refer to :ref:`pages/height:Height` documentation for more details.
305
+ max_height: Max height of the prompt.
306
+ Refer to :ref:`pages/height:Height` documentation for more details.
307
+ multiselect: Enable multi-selection on choices.
308
+ You can use `validate` parameter to control min/max selections.
309
+ Setting to True will also change the result from a single value to a list of values.
310
+ prompt: Input prompt symbol. Custom symbol to display infront of the input buffer to indicate for input.
311
+ border: Create border around the choice window.
312
+ info: Display choice information similar to fzf --info=inline next to the prompt.
313
+ match_exact: Use exact sub-string match instead of using fzy fuzzy match algorithm.
314
+ exact_symbol: Custom symbol to display in the info section when `info=True`.
315
+ marker: Marker Symbol. Custom symbol to indicate if a choice is selected.
316
+ This will take effects when `multiselect` is True.
317
+ marker_pl: Marker place holder when the choice is not selected.
318
+ This is empty space by default.
319
+ keybindings: Customise the builtin keybindings.
320
+ Refer to :ref:`pages/kb:Keybindings` for more details.
321
+ cycle: Return to top item if hit bottom during navigation or vice versa.
322
+ wrap_lines: Soft wrap question lines when question exceeds the terminal width.
323
+ raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
324
+ will be `None` and the question is skiped.
325
+ mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
326
+ mandatory_message: Error message to show when user attempts to skip mandatory prompt.
327
+ session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
328
+
329
+ Examples:
330
+ >>> from InquirerPy import inquirer
331
+ >>> result = inquirer.fuzzy(message="Select one:", choices=[1, 2, 3]).execute()
332
+ >>> print(result)
333
+ 1
334
+ """
335
+
336
+ def __init__(
337
+ self,
338
+ message: InquirerPyMessage,
339
+ choices: InquirerPyListChoices,
340
+ default: InquirerPyDefault = "",
341
+ pointer: str = INQUIRERPY_POINTER_SEQUENCE,
342
+ style: Optional[InquirerPyStyle] = None,
343
+ vi_mode: bool = False,
344
+ qmark: str = "?",
345
+ amark: str = "?",
346
+ transformer: Optional[Callable[[Any], Any]] = None,
347
+ filter: Optional[Callable[[Any], Any]] = None,
348
+ instruction: str = "",
349
+ long_instruction: str = "",
350
+ multiselect: bool = False,
351
+ prompt: str = INQUIRERPY_POINTER_SEQUENCE,
352
+ marker: str = INQUIRERPY_POINTER_SEQUENCE,
353
+ marker_pl: str = " ",
354
+ border: bool = False,
355
+ info: bool = True,
356
+ match_exact: bool = False,
357
+ exact_symbol: str = " E",
358
+ height: Optional[Union[str, int]] = None,
359
+ max_height: Optional[Union[str, int]] = None,
360
+ validate: Optional[InquirerPyValidate] = None,
361
+ invalid_message: str = "Invalid input",
362
+ keybindings: Optional[InquirerPyKeybindings] = None,
363
+ cycle: bool = True,
364
+ wrap_lines: bool = True,
365
+ raise_keyboard_interrupt: bool = True,
366
+ mandatory: bool = True,
367
+ mandatory_message: str = "Mandatory prompt",
368
+ session_result: Optional[InquirerPySessionResult] = None,
369
+ ) -> None:
370
+ if not keybindings:
371
+ keybindings = {}
372
+ self._prompt = prompt
373
+ self._info = info
374
+ self._task = None
375
+ self._rendered = False
376
+ self._exact_symbol = exact_symbol
377
+
378
+ keybindings = {
379
+ "up": [{"key": "up"}, {"key": "c-p"}],
380
+ "down": [{"key": "down"}, {"key": "c-n"}],
381
+ "toggle": [],
382
+ "toggle-exact": [],
383
+ **keybindings,
384
+ }
385
+ super().__init__(
386
+ message=message,
387
+ style=style,
388
+ border=border,
389
+ vi_mode=vi_mode,
390
+ qmark=qmark,
391
+ amark=amark,
392
+ transformer=transformer,
393
+ filter=filter,
394
+ validate=validate,
395
+ invalid_message=invalid_message,
396
+ multiselect=multiselect,
397
+ instruction=instruction,
398
+ long_instruction=long_instruction,
399
+ keybindings=keybindings,
400
+ cycle=cycle,
401
+ wrap_lines=wrap_lines,
402
+ raise_keyboard_interrupt=raise_keyboard_interrupt,
403
+ mandatory=mandatory,
404
+ mandatory_message=mandatory_message,
405
+ session_result=session_result,
406
+ )
407
+ self.kb_func_lookup = {"toggle-exact": [{"func": self._toggle_exact}]}
408
+ self._default = (
409
+ default
410
+ if not isinstance(default, Callable)
411
+ else cast(Callable, default)(self._result)
412
+ )
413
+ self._height_offset += 1 # search input
414
+ self._dimmension_height, self._dimmension_max_height = calculate_height(
415
+ height, max_height, height_offset=self.height_offset
416
+ )
417
+
418
+ self._content_control: InquirerPyFuzzyControl = InquirerPyFuzzyControl(
419
+ choices=choices,
420
+ pointer=pointer,
421
+ marker=marker,
422
+ current_text=self._get_current_text,
423
+ max_lines=self._dimmension_max_height,
424
+ session_result=session_result,
425
+ multiselect=multiselect,
426
+ marker_pl=marker_pl,
427
+ match_exact=match_exact,
428
+ )
429
+
430
+ self._buffer = Buffer(on_text_changed=self._on_text_changed)
431
+ input_window = Window(
432
+ height=LayoutDimension.exact(1),
433
+ content=BufferControl(
434
+ self._buffer,
435
+ [
436
+ AfterInput(self._generate_after_input),
437
+ BeforeInput(self._generate_before_input),
438
+ ],
439
+ lexer=SimpleLexer("class:input"),
440
+ ),
441
+ )
442
+
443
+ choice_height_dimmension = lambda: Dimension(
444
+ max=self._dimmension_max_height,
445
+ preferred=self._dimmension_height,
446
+ min=self.content_control._height if self.content_control._height > 0 else 1,
447
+ )
448
+ self.choice_window = Window(
449
+ content=self.content_control,
450
+ height=choice_height_dimmension,
451
+ dont_extend_height=True,
452
+ )
453
+
454
+ main_content_window = HSplit([input_window, self.choice_window])
455
+ if self._border:
456
+ main_content_window = Frame(main_content_window)
457
+ self._layout = Layout(
458
+ FloatContainer(
459
+ content=HSplit(
460
+ [
461
+ MessageWindow(
462
+ message=self._get_prompt_message,
463
+ filter=True,
464
+ wrap_lines=self._wrap_lines,
465
+ show_cursor=True,
466
+ ),
467
+ ConditionalContainer(
468
+ main_content_window,
469
+ filter=~IsDone(),
470
+ ),
471
+ ConditionalContainer(
472
+ Window(content=DummyControl()),
473
+ filter=~IsDone() & self._is_displaying_long_instruction,
474
+ ),
475
+ InstructionWindow(
476
+ message=self._long_instruction,
477
+ filter=~IsDone() & self._is_displaying_long_instruction,
478
+ wrap_lines=self._wrap_lines,
479
+ ),
480
+ ],
481
+ ),
482
+ floats=[
483
+ ValidationFloat(
484
+ invalid_message=self._get_error_message,
485
+ filter=self._is_invalid & ~IsDone(),
486
+ wrap_lines=self._wrap_lines,
487
+ left=0,
488
+ bottom=self._validation_window_bottom_offset,
489
+ ),
490
+ ],
491
+ )
492
+ )
493
+ self._layout.focus(input_window)
494
+
495
+ self._application = Application(
496
+ layout=self._layout,
497
+ style=self._style,
498
+ key_bindings=self._kb,
499
+ editing_mode=self._editing_mode,
500
+ after_render=self._after_render,
501
+ )
502
+
503
+ def _toggle_exact(self, _, value: Optional[bool] = None) -> None:
504
+ """Toggle matching algorithm.
505
+
506
+ Switch between fzy fuzzy match or sub-string exact match.
507
+
508
+ Args:
509
+ value: Specify the value to toggle.
510
+ """
511
+ if value is not None:
512
+ self.content_control._scorer = fzy_scorer if not value else substr_scorer
513
+ else:
514
+ self.content_control._scorer = (
515
+ fzy_scorer
516
+ if self.content_control._scorer == substr_scorer
517
+ else substr_scorer
518
+ )
519
+
520
+ def _on_rendered(self, _) -> None:
521
+ """Render callable choices and set the buffer default text.
522
+
523
+ Setting buffer default text has to be after application is rendered and choice are loaded,
524
+ because `self._filter_choices` will use the event loop from `Application`.
525
+ """
526
+ if self._default:
527
+ default_text = str(self._default)
528
+ self._buffer.text = default_text
529
+ self._buffer.cursor_position = len(default_text)
530
+
531
+ def _handle_toggle_all(self, _, value: Optional[bool] = None) -> None:
532
+ """Toggle all choice `enabled` status.
533
+
534
+ Args:
535
+ value: Specify the value to toggle.
536
+ """
537
+ if not self._multiselect:
538
+ return
539
+ for choice in self.content_control._filtered_choices:
540
+ raw_choice = self.content_control.choices[choice["index"]]
541
+ if isinstance(raw_choice["value"], Separator):
542
+ continue
543
+ raw_choice["enabled"] = value if value else not raw_choice["enabled"]
544
+
545
+ def _generate_after_input(self) -> List[Tuple[str, str]]:
546
+ """Virtual text displayed after the user input."""
547
+ display_message = []
548
+ if self._info:
549
+ display_message.append(("", " "))
550
+ display_message.append(
551
+ (
552
+ "class:fuzzy_info",
553
+ f"{self.content_control.choice_count}/{len(self.content_control.choices)}",
554
+ )
555
+ )
556
+ if self._multiselect:
557
+ display_message.append(
558
+ ("class:fuzzy_info", f" ({len(self.selected_choices)})")
559
+ )
560
+ if self.content_control._scorer == substr_scorer:
561
+ display_message.append(("class:fuzzy_info", self._exact_symbol))
562
+ return display_message
563
+
564
+ def _generate_before_input(self) -> List[Tuple[str, str]]:
565
+ """Display prompt symbol as virtual text before user input."""
566
+ display_message = []
567
+ display_message.append(("class:fuzzy_prompt", "%s " % self._prompt))
568
+ return display_message
569
+
570
+ def _filter_callback(self, task):
571
+ """Redraw `self._application` when the filter task is finished."""
572
+ if task.cancelled():
573
+ return
574
+ self.content_control._filtered_choices = task.result()
575
+ self._application.invalidate()
576
+
577
+ def _calculate_wait_time(self) -> float:
578
+ """Calculate wait time to smoother the application on big data set.
579
+
580
+ Using digit of the choices lengeth to get wait time.
581
+ For digit greater than 6, using formula 2^(digit - 5) * 0.3 to increase the wait_time.
582
+
583
+ Returns:
584
+ Desired wait time before running the filter.
585
+ """
586
+ wait_table = {
587
+ 2: 0.05,
588
+ 3: 0.1,
589
+ 4: 0.2,
590
+ 5: 0.3,
591
+ }
592
+ digit = 1
593
+ if len(self.content_control.choices) > 0:
594
+ digit = int(math.log10(len(self.content_control.choices))) + 1
595
+
596
+ if digit < 2:
597
+ return 0.0
598
+ if digit in wait_table:
599
+ return wait_table[digit]
600
+ return wait_table[5] * (2 ** (digit - 5))
601
+
602
+ def _on_text_changed(self, _) -> None:
603
+ """Handle buffer text change event.
604
+
605
+ 1. Check if there is current task running.
606
+ 2. Cancel if already has task, increase wait_time
607
+ 3. Create a filtered_choice task in asyncio event loop
608
+ 4. Add callback
609
+
610
+ 1. Run a new filter on all choices.
611
+ 2. Re-calculate current selected_choice_index
612
+ if it exceeds the total filtered_choice.
613
+ 3. Avoid selected_choice_index less than zero,
614
+ this fix the issue of cursor lose when:
615
+ choice -> empty choice -> choice
616
+
617
+ Don't need to create or check asyncio event loop, `prompt_toolkit`
618
+ application already has a event loop running.
619
+ """
620
+ if self._invalid:
621
+ self._invalid = False
622
+ wait_time = self._calculate_wait_time()
623
+ if self._task and not self._task.done():
624
+ self._task.cancel()
625
+ self._task = asyncio.create_task(
626
+ self.content_control._filter_choices(wait_time)
627
+ )
628
+ self._task.add_done_callback(self._filter_callback)
629
+
630
+ def _handle_toggle_choice(self, _) -> None:
631
+ """Handle tab event, alter the `selected` state of the choice."""
632
+ if not self._multiselect:
633
+ return
634
+ current_selected_index = self.content_control.selection["index"]
635
+ self.content_control.choices[current_selected_index]["enabled"] = (
636
+ not self.content_control.choices[current_selected_index]["enabled"]
637
+ )
638
+
639
+ def _handle_enter(self, event: "KeyPressEvent") -> None:
640
+ """Handle enter event.
641
+
642
+ Validate the result first.
643
+
644
+ In multiselect scenario, if no TAB is entered, then capture the current
645
+ highlighted choice and return the value in a list.
646
+ Otherwise, return all TAB choices as a list.
647
+
648
+ In normal scenario, reutrn the current highlighted choice.
649
+
650
+ If current UI contains no choice due to filter, return None.
651
+ """
652
+ try:
653
+ fake_document = FakeDocument(self.result_value)
654
+ self._validator.validate(fake_document) # type: ignore
655
+ if self._multiselect:
656
+ self.status["answered"] = True
657
+ if not self.selected_choices:
658
+ self.status["result"] = [self.content_control.selection["name"]]
659
+ event.app.exit(result=[self.content_control.selection["value"]])
660
+ else:
661
+ self.status["result"] = self.result_name
662
+ event.app.exit(result=self.result_value)
663
+ else:
664
+ self.status["answered"] = True
665
+ self.status["result"] = self.content_control.selection["name"]
666
+ event.app.exit(result=self.content_control.selection["value"])
667
+ except ValidationError as e:
668
+ self._set_error(str(e))
669
+ except IndexError:
670
+ self.status["answered"] = True
671
+ self.status["result"] = None if not self._multiselect else []
672
+ event.app.exit(result=None if not self._multiselect else [])
673
+
674
+ @property
675
+ def content_control(self) -> InquirerPyFuzzyControl:
676
+ """InquirerPyFuzzyControl: Override for type-hinting."""
677
+ return cast(InquirerPyFuzzyControl, super().content_control)
678
+
679
+ @content_control.setter
680
+ def content_control(self, value: InquirerPyFuzzyControl) -> None:
681
+ self._content_control = value
682
+
683
+ def _get_current_text(self) -> str:
684
+ """Get current input buffer text."""
685
+ return self._buffer.text