debounce.py 4.5 KB

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