form.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """Form components."""
  2. from __future__ import annotations
  3. from typing import Any, Callable, Dict, List
  4. from reflex.components.component import Component
  5. from reflex.components.libs.chakra import ChakraComponent
  6. from reflex.constants import EventTriggers
  7. from reflex.event import EventChain, EventHandler, EventSpec
  8. from reflex.vars import Var
  9. class Form(ChakraComponent):
  10. """A form component."""
  11. tag = "Box"
  12. # What the form renders to.
  13. as_: Var[str] = "form" # type: ignore
  14. def _create_event_chain(
  15. self,
  16. event_trigger: str,
  17. value: Var
  18. | EventHandler
  19. | EventSpec
  20. | List[EventHandler | EventSpec]
  21. | Callable[..., Any],
  22. ) -> EventChain | Var:
  23. """Override the event chain creation to preventDefault for on_submit.
  24. Args:
  25. event_trigger: The event trigger.
  26. value: The value of the event trigger.
  27. Returns:
  28. The event chain.
  29. """
  30. chain = super()._create_event_chain(event_trigger, value)
  31. if event_trigger == EventTriggers.ON_SUBMIT and isinstance(chain, EventChain):
  32. return chain.prevent_default
  33. return chain
  34. def get_event_triggers(self) -> Dict[str, Any]:
  35. """Get the event triggers that pass the component's value to the handler.
  36. Returns:
  37. A dict mapping the event trigger to the var that is passed to the handler.
  38. """
  39. # Send all the input refs to the handler.
  40. form_refs = {}
  41. for ref in self.get_refs():
  42. # when ref start with refs_ it's an array of refs, so we need different method
  43. # to collect data
  44. if ref.startswith("refs_"):
  45. form_refs[ref[5:-3]] = Var.create(
  46. f"getRefValues({ref[:-3]})", _var_is_local=False
  47. )
  48. else:
  49. form_refs[ref[4:]] = Var.create(
  50. f"getRefValue({ref})", _var_is_local=False
  51. )
  52. return {
  53. **super().get_event_triggers(),
  54. EventTriggers.ON_SUBMIT: lambda e0: [form_refs],
  55. }
  56. class FormControl(ChakraComponent):
  57. """Provide context to form components."""
  58. tag = "FormControl"
  59. # If true, the form control will be disabled.
  60. is_disabled: Var[bool]
  61. # If true, the form control will be invalid.
  62. is_invalid: Var[bool]
  63. # If true, the form control will be readonly
  64. is_read_only: Var[bool]
  65. # If true, the form control will be required.
  66. is_required: Var[bool]
  67. # The label text used to inform users as to what information is requested for a text field.
  68. label: Var[str]
  69. @classmethod
  70. def create(
  71. cls,
  72. *children,
  73. label=None,
  74. input=None,
  75. help_text=None,
  76. error_message=None,
  77. **props,
  78. ) -> Component:
  79. """Create a form control component.
  80. Args:
  81. *children: The children of the form control.
  82. label: The label of the form control.
  83. input: The input of the form control.
  84. help_text: The help text of the form control.
  85. error_message: The error message of the form control.
  86. **props: The properties of the form control.
  87. Raises:
  88. AttributeError: raise an error if missing required kwargs.
  89. Returns:
  90. The form control component.
  91. """
  92. if len(children) == 0:
  93. children = []
  94. if label:
  95. children.append(FormLabel.create(*label))
  96. if not input:
  97. raise AttributeError("input keyword argument is required")
  98. children.append(input)
  99. if help_text:
  100. children.append(FormHelperText.create(*help_text))
  101. if error_message:
  102. children.append(FormErrorMessage.create(*error_message))
  103. return super().create(*children, **props)
  104. class FormHelperText(ChakraComponent):
  105. """A form helper text component."""
  106. tag = "FormHelperText"
  107. class FormLabel(ChakraComponent):
  108. """A form label component."""
  109. tag = "FormLabel"
  110. # Link
  111. html_for: Var[str]
  112. class FormErrorMessage(ChakraComponent):
  113. """A form error message component."""
  114. tag = "FormErrorMessage"