MCPcopy Index your code
hub / github.com/reactive-python/reactpy / HookCatcher

Class HookCatcher

src/py/reactpy/reactpy/testing/common.py:101–152  ·  view source on GitHub ↗

Utility for capturing a LifeCycleHook from a component Example: .. code-block:: hooks = HookCatcher(index_by_kwarg="thing") @reactpy.component @hooks.capture def MyComponent(thing): ... ... # render the comp

Source from the content-addressed store, hash-verified

99
100
101class HookCatcher:
102 """Utility for capturing a LifeCycleHook from a component
103
104 Example:
105 .. code-block::
106
107 hooks = HookCatcher(index_by_kwarg="thing")
108
109 @reactpy.component
110 @hooks.capture
111 def MyComponent(thing):
112 ...
113
114 ... # render the component
115
116 # grab the last render of where MyComponent(thing='something')
117 hooks.index["something"]
118 # or grab the hook from the component's last render
119 hooks.latest
120
121 After the first render of ``MyComponent`` the ``HookCatcher`` will have
122 captured the component's ``LifeCycleHook``.
123 """
124
125 latest: LifeCycleHook
126
127 def __init__(self, index_by_kwarg: str | None = None):
128 self.index_by_kwarg = index_by_kwarg
129 self.index: dict[Any, LifeCycleHook] = {}
130
131 def capture(self, render_function: Callable[..., Any]) -> Callable[..., Any]:
132 """Decorator for capturing a ``LifeCycleHook`` on each render of a component"""
133
134 # The render function holds a reference to `self` and, via the `LifeCycleHook`,
135 # the component. Some tests check whether components are garbage collected, thus
136 # we must use a `ref` here to ensure these checks pass once the catcher itself
137 # has been collected.
138 self_ref = ref(self)
139
140 @wraps(render_function)
141 def wrapper(*args: Any, **kwargs: Any) -> Any:
142 self = self_ref()
143 if self is None:
144 raise RuntimeError("Hook catcher has been garbage collected")
145
146 hook = current_hook()
147 if self.index_by_kwarg is not None:
148 self.index[kwargs[self.index_by_kwarg]] = hook
149 self.latest = hook
150 return render_function(*args, **kwargs)
151
152 return wrapper
153
154
155class StaticEventHandler:

Calls

no outgoing calls