debounce.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """Wrapper around react-debounce-input."""
  2. from __future__ import annotations
  3. from typing import Any, Type
  4. from reflex.components import Component
  5. from reflex.constants import EventTriggers
  6. from reflex.vars import Var, VarData
  7. class DebounceInput(Component):
  8. """The DebounceInput component is used to buffer input events on the client side.
  9. It is intended to wrap various form controls and should be used whenever a
  10. fully-controlled input is needed to prevent lost input data when the backend
  11. is experiencing high latency.
  12. """
  13. library = "react-debounce-input@3.3.0"
  14. tag = "DebounceInput"
  15. # Minimum input characters before triggering the on_change event
  16. min_length: Var[int]
  17. # Time to wait between end of input and triggering on_change
  18. debounce_timeout: Var[int]
  19. # If true, notify when Enter key is pressed
  20. force_notify_by_enter: Var[bool]
  21. # If true, notify when form control loses focus
  22. force_notify_on_blur: Var[bool]
  23. # If provided, create a fully-controlled input
  24. value: Var[str]
  25. # The ref to attach to the created input
  26. input_ref: Var[str]
  27. # The element to wrap
  28. element: Var[Type[Component]]
  29. @classmethod
  30. def create(cls, *children: Component, **props: Any) -> Component:
  31. """Create a DebounceInput component.
  32. Carry first child props directly on this tag.
  33. Since react-debounce-input wants to create and manage the underlying
  34. input component itself, we carry all props, events, and styles from
  35. the child, and then neuter the child's render method so it produces no output.
  36. Args:
  37. children: The child component to wrap.
  38. props: The component props.
  39. Returns:
  40. The DebounceInput component.
  41. Raises:
  42. RuntimeError: unless exactly one child element is provided.
  43. ValueError: if the child element does not have an on_change handler.
  44. """
  45. if len(children) != 1:
  46. raise RuntimeError(
  47. "Provide a single child for DebounceInput, such as rx.input() or "
  48. "rx.text_area()",
  49. )
  50. child = children[0]
  51. if "on_change" not in child.event_triggers:
  52. raise ValueError("DebounceInput child requires an on_change handler")
  53. # Carry known props and event_triggers from the child.
  54. props_from_child = {
  55. p: getattr(child, p)
  56. for p in cls.get_props()
  57. if getattr(child, p, None) is not None
  58. }
  59. props_from_child.update(child.event_triggers)
  60. props = {**props_from_child, **props}
  61. # Carry all other child props directly via custom_attrs
  62. other_props = {
  63. p: getattr(child, p)
  64. for p in child.get_props()
  65. if p not in props_from_child and getattr(child, p) is not None
  66. }
  67. props.setdefault("custom_attrs", {}).update(other_props, **child.custom_attrs)
  68. # Carry base Component props.
  69. props.setdefault("style", {}).update(child.style)
  70. if child.class_name is not None:
  71. props["class_name"] = f"{props.get('class_name', '')} {child.class_name}"
  72. child_ref = child.get_ref()
  73. if not props.get("input_ref") and child_ref:
  74. props["input_ref"] = Var.create_safe(child_ref, _var_is_local=False)
  75. props["id"] = child.id
  76. # Set the child element to wrap, including any imports/hooks from the child.
  77. props.setdefault(
  78. "element",
  79. Var.create_safe(
  80. "{%s}" % (child.alias or child.tag),
  81. _var_is_local=False,
  82. _var_is_string=False,
  83. )._replace(
  84. _var_type=Type[Component],
  85. merge_var_data=VarData( # type: ignore
  86. imports=child._get_imports(),
  87. hooks=child._get_hooks_internal(),
  88. ),
  89. ),
  90. )
  91. return super().create(**props)
  92. def get_event_triggers(self) -> dict[str, Any]:
  93. """Get the event triggers that pass the component's value to the handler.
  94. Returns:
  95. A dict mapping the event trigger to the var that is passed to the handler.
  96. """
  97. return {
  98. **super().get_event_triggers(),
  99. EventTriggers.ON_CHANGE: lambda e0: [e0.value],
  100. }
  101. def _render(self):
  102. return super()._render().remove_props("ref")