debounce.py 4.8 KB

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