form.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from typing import Any, Callable, Optional
  2. from rich_toolkit.element import Element
  3. from rich_toolkit.spacer import Spacer
  4. from rich_toolkit.styles import BaseStyle
  5. from .button import Button
  6. from .container import Container
  7. from .input import Input
  8. class Form(Container):
  9. def __init__(self, title: str, style: BaseStyle):
  10. super().__init__(style)
  11. self.title = title
  12. def _append_element(self, element: Element):
  13. if len(self.elements) > 0:
  14. self.elements.append(Spacer())
  15. self.elements.append(element)
  16. def add_input(
  17. self,
  18. name: str,
  19. label: str,
  20. placeholder: Optional[str] = None,
  21. password: bool = False,
  22. inline: bool = False,
  23. required: bool = False,
  24. **metadata: Any,
  25. ):
  26. input = Input(
  27. label=label,
  28. placeholder=placeholder,
  29. name=name,
  30. password=password,
  31. inline=inline,
  32. required=required,
  33. **metadata,
  34. )
  35. self._append_element(input)
  36. def add_button(
  37. self,
  38. name: str,
  39. label: str,
  40. callback: Optional[Callable] = None,
  41. **metadata: Any,
  42. ):
  43. button = Button(name=name, label=label, callback=callback, **metadata)
  44. self._append_element(button)
  45. def run(self):
  46. super().run()
  47. return self._collect_data()
  48. def handle_enter_key(self) -> bool:
  49. all_valid = True
  50. for element in self.elements:
  51. if isinstance(element, Input):
  52. element.on_validate()
  53. if element.valid is False:
  54. all_valid = False
  55. return all_valid
  56. def _collect_data(self) -> dict:
  57. return {
  58. input.name: input.text
  59. for input in self.elements
  60. if isinstance(input, Input)
  61. }