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

Function _hotswap

src/py/reactpy/reactpy/testing/backend.py:159–227  ·  view source on GitHub ↗

Swap out components from a layout on the fly. Since you can't change the component functions used to create a layout in an imperative manner, you can use ``hotswap`` to do this so long as you set things up ahead of time. Parameters: update_on_change: Whether or not all view

(update_on_change: bool = False)

Source from the content-addressed store, hash-verified

157
158
159def _hotswap(update_on_change: bool = False) -> tuple[_MountFunc, ComponentConstructor]:
160 """Swap out components from a layout on the fly.
161
162 Since you can't change the component functions used to create a layout
163 in an imperative manner, you can use ``hotswap`` to do this so
164 long as you set things up ahead of time.
165
166 Parameters:
167 update_on_change: Whether or not all views of the layout should be updated on a swap.
168
169 Example:
170 .. code-block:: python
171
172 import reactpy
173
174 show, root = reactpy.hotswap()
175 PerClientStateServer(root).run_in_thread("localhost", 8765)
176
177 @reactpy.component
178 def DivOne(self):
179 return {"tagName": "div", "children": [1]}
180
181 show(DivOne)
182
183 # displaying the output now will show DivOne
184
185 @reactpy.component
186 def DivTwo(self):
187 return {"tagName": "div", "children": [2]}
188
189 show(DivTwo)
190
191 # displaying the output now will show DivTwo
192 """
193 constructor_ref: Ref[Callable[[], Any]] = Ref(lambda: None)
194
195 if update_on_change:
196 set_constructor_callbacks: set[Callable[[Callable[[], Any]], None]] = set()
197
198 @component
199 def HotSwap() -> Any:
200 # new displays will adopt the latest constructor and arguments
201 constructor, _set_constructor = use_state(lambda: constructor_ref.current)
202 set_constructor = use_callback(lambda new: _set_constructor(lambda _: new))
203
204 def add_callback() -> Callable[[], None]:
205 set_constructor_callbacks.add(set_constructor)
206 return lambda: set_constructor_callbacks.remove(set_constructor)
207
208 use_effect(add_callback)
209
210 return constructor()
211
212 def swap(constructor: Callable[[], Any] | None) -> None:
213 constructor = constructor_ref.current = constructor or (lambda: None)
214
215 for set_constructor in set_constructor_callbacks:
216 set_constructor(constructor)

Callers 3

ButtonSwapsDivsFunction · 0.90
hotswapFunction · 0.90
__init__Method · 0.85

Calls 1

RefClass · 0.90

Tested by 1

ButtonSwapsDivsFunction · 0.72