formcontrol.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """Form components."""
  2. from typing import Set
  3. from pynecone.components.component import Component
  4. from pynecone.components.libs.chakra import ChakraComponent
  5. from pynecone.vars import Var
  6. class Form(ChakraComponent):
  7. """A form component."""
  8. tag = "Box"
  9. as_: Var[str] = "form" # type: ignore
  10. @classmethod
  11. def get_triggers(cls) -> Set[str]:
  12. """Get the event triggers for the component.
  13. Returns:
  14. The event triggers.
  15. """
  16. return super().get_triggers() | {"on_submit"}
  17. class FormControl(ChakraComponent):
  18. """Provide context to form components."""
  19. tag = "FormControl"
  20. # If true, the form control will be disabled.
  21. is_disabled: Var[bool]
  22. # If true, the form control will be invalid.
  23. is_invalid: Var[bool]
  24. # If true, the form control will be readonly
  25. is_read_only: Var[bool]
  26. # If true, the form control will be required.
  27. is_required: Var[bool]
  28. # The label text used to inform users as to what information is requested for a text field.
  29. label: Var[str]
  30. @classmethod
  31. def create(
  32. cls,
  33. *children,
  34. label=None,
  35. input=None,
  36. help_text=None,
  37. error_message=None,
  38. **props
  39. ) -> Component:
  40. """Create a form control component.
  41. Args:
  42. children: The children of the form control.
  43. label: The label of the form control.
  44. input: The input of the form control.
  45. help_text: The help text of the form control.
  46. error_message: The error message of the form control.
  47. props: The properties of the form control.
  48. Raises:
  49. AttributeError: raise an error if missing required kwargs.
  50. Returns:
  51. The form control component.
  52. """
  53. if len(children) == 0:
  54. children = []
  55. if label:
  56. children.append(FormLabel.create(*label))
  57. if not input:
  58. raise AttributeError("input keyword argument is required")
  59. children.append(input)
  60. if help_text:
  61. children.append(FormHelperText.create(*help_text))
  62. if error_message:
  63. children.append(FormErrorMessage.create(*error_message))
  64. return super().create(*children, **props)
  65. class FormHelperText(ChakraComponent):
  66. """A form helper text component."""
  67. tag = "FormHelperText"
  68. class FormLabel(ChakraComponent):
  69. """A form label component."""
  70. tag = "FormLabel"
  71. # Link
  72. html_for: Var[str]
  73. class FormErrorMessage(ChakraComponent):
  74. """A form error message component."""
  75. tag = "FormErrorMessage"