pininput.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. """A pin input component."""
  2. from __future__ import annotations
  3. from typing import Any, Optional, Union
  4. from reflex.components.component import Component
  5. from reflex.components.layout import Foreach
  6. from reflex.components.libs.chakra import ChakraComponent, LiteralInputVariant
  7. from reflex.constants import EventTriggers
  8. from reflex.utils import format
  9. from reflex.vars import Var
  10. class PinInput(ChakraComponent):
  11. """The component that provides context to all the pin-input fields."""
  12. tag = "PinInput"
  13. # State var to bind the the input.
  14. value: Var[str]
  15. # If true, the pin input receives focus on mount
  16. auto_focus: Var[bool]
  17. # The default value of the pin input
  18. default_value: Var[str]
  19. # The border color when the input is invalid.
  20. error_border_color: Var[str]
  21. # The border color when the input is focused.
  22. focus_border_color: Var[str]
  23. # The top-level id string that will be applied to the input fields. The index of the input will be appended to this top-level id.
  24. id_: Var[str]
  25. # The length of the number input.
  26. length: Var[int]
  27. # If true, the pin input component is put in the disabled state
  28. is_disabled: Var[bool]
  29. # If true, the pin input component is put in the invalid state
  30. is_invalid: Var[bool]
  31. # If true, focus will move automatically to the next input once filled
  32. manage_focus: Var[bool]
  33. # If true, the input's value will be masked just like `type=password`
  34. mask: Var[bool]
  35. # The placeholder for the pin input
  36. placeholder: Var[str]
  37. # The type of values the pin-input should allow ("number" | "alphanumeric").
  38. type_: Var[str]
  39. # "outline" | "flushed" | "filled" | "unstyled"
  40. variant: Var[LiteralInputVariant]
  41. def get_event_triggers(self) -> dict[str, Union[Var, Any]]:
  42. """Get the event triggers that pass the component's value to the handler.
  43. Returns:
  44. A dict mapping the event trigger to the var that is passed to the handler.
  45. """
  46. return {
  47. **super().get_event_triggers(),
  48. EventTriggers.ON_CHANGE: lambda e0: [e0],
  49. EventTriggers.ON_COMPLETE: lambda e0: [e0],
  50. }
  51. def get_ref(self):
  52. """Return a reference because we actually attached the ref to the PinInputFields.
  53. Returns:
  54. None.
  55. """
  56. return None
  57. def _get_ref_hook(self) -> Optional[str]:
  58. """Override the base _get_ref_hook to handle array refs.
  59. Returns:
  60. The overrided hooks.
  61. """
  62. if self.id:
  63. ref = format.format_array_ref(self.id, None)
  64. if ref:
  65. return f"const {ref} = Array.from({{length:{self.length}}}, () => useRef(null));"
  66. return super()._get_ref_hook()
  67. @classmethod
  68. def create(cls, *children, **props) -> Component:
  69. """Create a pin input component.
  70. If no children are passed in, the component will create a default pin input
  71. based on the length prop.
  72. Args:
  73. *children: The children of the component.
  74. **props: The props of the component.
  75. Returns:
  76. The pin input component.
  77. """
  78. if not children and "length" in props:
  79. _id = props.get("id", None)
  80. length = props["length"]
  81. if _id:
  82. children = [
  83. Foreach.create(
  84. list(range(length)), # type: ignore
  85. lambda ref, i: PinInputField.create(
  86. key=i,
  87. id=_id,
  88. index=i,
  89. ),
  90. )
  91. ]
  92. else:
  93. children = [PinInputField()] * length
  94. return super().create(*children, **props)
  95. class PinInputField(ChakraComponent):
  96. """The text field that user types in - must be a direct child of PinInput."""
  97. tag = "PinInputField"
  98. # the position of the PinInputField inside the PinInput.
  99. # Default to None because it is assigned by PinInput when created.
  100. index: Optional[Var[int]] = None
  101. def _get_ref_hook(self) -> Optional[str]:
  102. return None
  103. def get_ref(self):
  104. """Get the array ref for the pin input.
  105. Returns:
  106. The array ref.
  107. """
  108. if self.id:
  109. return format.format_array_ref(self.id, self.index)