component.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  1. """Base component definitions."""
  2. from __future__ import annotations
  3. import copy
  4. import typing
  5. from abc import ABC, abstractmethod
  6. from functools import lru_cache, wraps
  7. from hashlib import md5
  8. from typing import (
  9. Any,
  10. Callable,
  11. ClassVar,
  12. Dict,
  13. Iterator,
  14. List,
  15. Optional,
  16. Set,
  17. Type,
  18. Union,
  19. )
  20. from reflex.base import Base
  21. from reflex.compiler.templates import STATEFUL_COMPONENT
  22. from reflex.components.tags import Tag
  23. from reflex.constants import Dirs, EventTriggers, Hooks, Imports, PageNames
  24. from reflex.event import (
  25. EventChain,
  26. EventHandler,
  27. EventSpec,
  28. call_event_fn,
  29. call_event_handler,
  30. get_handler_args,
  31. )
  32. from reflex.style import Style
  33. from reflex.utils import console, format, imports, types
  34. from reflex.utils.imports import ImportVar
  35. from reflex.utils.serializers import serializer
  36. from reflex.vars import BaseVar, Var, VarData
  37. class BaseComponent(Base, ABC):
  38. """The base class for all Reflex components.
  39. This is something that can be rendered as a Component via the Reflex compiler.
  40. """
  41. # The children nested within the component.
  42. children: List[BaseComponent] = []
  43. # The library that the component is based on.
  44. library: Optional[str] = None
  45. # List here the non-react dependency needed by `library`
  46. lib_dependencies: List[str] = []
  47. # The tag to use when rendering the component.
  48. tag: Optional[str] = None
  49. @abstractmethod
  50. def render(self) -> dict:
  51. """Render the component.
  52. Returns:
  53. The dictionary for template of the component.
  54. """
  55. @abstractmethod
  56. def get_hooks(self) -> set[str]:
  57. """Get the React hooks for this component.
  58. Returns:
  59. The code that should appear just before returning the rendered component.
  60. """
  61. @abstractmethod
  62. def get_imports(self) -> imports.ImportDict:
  63. """Get all the libraries and fields that are used by the component.
  64. Returns:
  65. The import dict with the required imports.
  66. """
  67. @abstractmethod
  68. def get_dynamic_imports(self) -> set[str]:
  69. """Get dynamic imports for the component.
  70. Returns:
  71. The dynamic imports.
  72. """
  73. @abstractmethod
  74. def get_custom_code(self) -> set[str]:
  75. """Get custom code for the component.
  76. Returns:
  77. The custom code.
  78. """
  79. @abstractmethod
  80. def get_refs(self) -> set[str]:
  81. """Get the refs for the children of the component.
  82. Returns:
  83. The refs for the children.
  84. """
  85. # Map from component to styling.
  86. ComponentStyle = Dict[Union[str, Type[BaseComponent]], Any]
  87. ComponentChild = Union[types.PrimitiveType, Var, BaseComponent]
  88. class Component(BaseComponent, ABC):
  89. """A component with style, event trigger and other props."""
  90. # The style of the component.
  91. style: Style = Style()
  92. # A mapping from event triggers to event chains.
  93. event_triggers: Dict[str, Union[EventChain, Var]] = {}
  94. # The alias for the tag.
  95. alias: Optional[str] = None
  96. # Whether the import is default or named.
  97. is_default: Optional[bool] = False
  98. # A unique key for the component.
  99. key: Any = None
  100. # The id for the component.
  101. id: Any = None
  102. # The class name for the component.
  103. class_name: Any = None
  104. # Special component props.
  105. special_props: Set[Var] = set()
  106. # Whether the component should take the focus once the page is loaded
  107. autofocus: bool = False
  108. # components that cannot be children
  109. _invalid_children: List[str] = []
  110. # only components that are allowed as children
  111. _valid_children: List[str] = []
  112. # custom attribute
  113. custom_attrs: Dict[str, Union[Var, str]] = {}
  114. @classmethod
  115. def __init_subclass__(cls, **kwargs):
  116. """Set default properties.
  117. Args:
  118. **kwargs: The kwargs to pass to the superclass.
  119. """
  120. super().__init_subclass__(**kwargs)
  121. # Get all the props for the component.
  122. props = cls.get_props()
  123. # Convert fields to props, setting default values.
  124. for field in cls.get_fields().values():
  125. # If the field is not a component prop, skip it.
  126. if field.name not in props:
  127. continue
  128. # Set default values for any props.
  129. if types._issubclass(field.type_, Var):
  130. field.required = False
  131. field.default = Var.create(field.default)
  132. def __init__(self, *args, **kwargs):
  133. """Initialize the component.
  134. Args:
  135. *args: Args to initialize the component.
  136. **kwargs: Kwargs to initialize the component.
  137. Raises:
  138. TypeError: If an invalid prop is passed.
  139. ValueError: If a prop value is invalid.
  140. """
  141. # Set the id and children initially.
  142. children = kwargs.get("children", [])
  143. initial_kwargs = {
  144. "id": kwargs.get("id"),
  145. "children": children,
  146. **{
  147. prop: Var.create(kwargs[prop])
  148. for prop in self.get_initial_props()
  149. if prop in kwargs
  150. },
  151. }
  152. super().__init__(**initial_kwargs)
  153. self._validate_component_children(children)
  154. # Get the component fields, triggers, and props.
  155. fields = self.get_fields()
  156. triggers = self.get_event_triggers().keys()
  157. props = self.get_props()
  158. # Add any events triggers.
  159. if "event_triggers" not in kwargs:
  160. kwargs["event_triggers"] = {}
  161. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  162. # Iterate through the kwargs and set the props.
  163. for key, value in kwargs.items():
  164. if key in triggers:
  165. # Event triggers are bound to event chains.
  166. field_type = EventChain
  167. elif key in props:
  168. # Set the field type.
  169. field_type = fields[key].type_
  170. else:
  171. continue
  172. # Check whether the key is a component prop.
  173. if types._issubclass(field_type, Var):
  174. try:
  175. # Try to create a var from the value.
  176. kwargs[key] = Var.create(value)
  177. # Check that the var type is not None.
  178. if kwargs[key] is None:
  179. raise TypeError
  180. expected_type = fields[key].outer_type_.__args__[0]
  181. if (
  182. types.is_literal(expected_type)
  183. and value not in expected_type.__args__
  184. ):
  185. allowed_values = expected_type.__args__
  186. if value not in allowed_values:
  187. raise ValueError(
  188. f"prop value for {key} of the `{type(self).__name__}` component should be one of the following: {','.join(allowed_values)}. Got '{value}' instead"
  189. )
  190. # Get the passed type and the var type.
  191. passed_type = kwargs[key]._var_type
  192. expected_type = (
  193. type(expected_type.__args__[0])
  194. if types.is_literal(expected_type)
  195. else expected_type
  196. )
  197. except TypeError:
  198. # If it is not a valid var, check the base types.
  199. passed_type = type(value)
  200. expected_type = fields[key].outer_type_
  201. if not types._issubclass(passed_type, expected_type):
  202. raise TypeError(
  203. f"Invalid var passed for prop {key}, expected type {expected_type}, got value {value} of type {passed_type}."
  204. )
  205. # Check if the key is an event trigger.
  206. if key in triggers:
  207. # Temporarily disable full control for event triggers.
  208. kwargs["event_triggers"][key] = self._create_event_chain(key, value)
  209. # Remove any keys that were added as events.
  210. for key in kwargs["event_triggers"]:
  211. del kwargs[key]
  212. # Add style props to the component.
  213. style = kwargs.get("style", {})
  214. if isinstance(style, List):
  215. # Merge styles, the later ones overriding keys in the earlier ones.
  216. style = {k: v for style_dict in style for k, v in style_dict.items()}
  217. kwargs["style"] = Style(
  218. {
  219. **style,
  220. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  221. }
  222. )
  223. if "custom_attrs" not in kwargs:
  224. kwargs["custom_attrs"] = {}
  225. # Convert class_name to str if it's list
  226. class_name = kwargs.get("class_name", "")
  227. if isinstance(class_name, (List, tuple)):
  228. kwargs["class_name"] = " ".join(class_name)
  229. # Construct the component.
  230. super().__init__(*args, **kwargs)
  231. def _create_event_chain(
  232. self,
  233. event_trigger: str,
  234. value: Union[
  235. Var, EventHandler, EventSpec, List[Union[EventHandler, EventSpec]], Callable
  236. ],
  237. ) -> Union[EventChain, Var]:
  238. """Create an event chain from a variety of input types.
  239. Args:
  240. event_trigger: The event trigger to bind the chain to.
  241. value: The value to create the event chain from.
  242. Returns:
  243. The event chain.
  244. Raises:
  245. ValueError: If the value is not a valid event chain.
  246. """
  247. # Check if the trigger is a controlled event.
  248. triggers = self.get_event_triggers()
  249. # If it's an event chain var, return it.
  250. if isinstance(value, Var):
  251. if value._var_type is not EventChain:
  252. raise ValueError(f"Invalid event chain: {value}")
  253. return value
  254. elif isinstance(value, EventChain):
  255. # Trust that the caller knows what they're doing passing an EventChain directly
  256. return value
  257. arg_spec = triggers.get(event_trigger, lambda: [])
  258. wrapped = False
  259. # If the input is a single event handler, wrap it in a list.
  260. if isinstance(value, (EventHandler, EventSpec)):
  261. wrapped = True
  262. value = [value]
  263. # If the input is a list of event handlers, create an event chain.
  264. if isinstance(value, List):
  265. if not wrapped:
  266. console.deprecate(
  267. feature_name="EventChain",
  268. reason="to avoid confusion, only use yield API",
  269. deprecation_version="0.2.8",
  270. removal_version="0.4.0",
  271. )
  272. events: list[EventSpec] = []
  273. for v in value:
  274. if isinstance(v, EventHandler):
  275. # Call the event handler to get the event.
  276. try:
  277. event = call_event_handler(v, arg_spec) # type: ignore
  278. except ValueError as err:
  279. raise ValueError(
  280. f" {err} defined in the `{type(self).__name__}` component"
  281. ) from err
  282. # Add the event to the chain.
  283. events.append(event)
  284. elif isinstance(v, EventSpec):
  285. # Add the event to the chain.
  286. events.append(v)
  287. elif isinstance(v, Callable):
  288. # Call the lambda to get the event chain.
  289. events.extend(call_event_fn(v, arg_spec)) # type: ignore
  290. else:
  291. raise ValueError(f"Invalid event: {v}")
  292. # If the input is a callable, create an event chain.
  293. elif isinstance(value, Callable):
  294. events = call_event_fn(value, arg_spec) # type: ignore
  295. # Otherwise, raise an error.
  296. else:
  297. raise ValueError(f"Invalid event chain: {value}")
  298. # Add args to the event specs if necessary.
  299. events = [e.with_args(get_handler_args(e)) for e in events]
  300. # Collect event_actions from each spec
  301. event_actions = {}
  302. for e in events:
  303. event_actions.update(e.event_actions)
  304. # Return the event chain.
  305. if isinstance(arg_spec, Var):
  306. return EventChain(
  307. events=events,
  308. args_spec=None,
  309. event_actions=event_actions,
  310. )
  311. else:
  312. return EventChain(
  313. events=events,
  314. args_spec=arg_spec, # type: ignore
  315. event_actions=event_actions,
  316. )
  317. def get_event_triggers(self) -> Dict[str, Any]:
  318. """Get the event triggers for the component.
  319. Returns:
  320. The event triggers.
  321. """
  322. return {
  323. EventTriggers.ON_FOCUS: lambda: [],
  324. EventTriggers.ON_BLUR: lambda: [],
  325. EventTriggers.ON_CLICK: lambda: [],
  326. EventTriggers.ON_CONTEXT_MENU: lambda: [],
  327. EventTriggers.ON_DOUBLE_CLICK: lambda: [],
  328. EventTriggers.ON_MOUSE_DOWN: lambda: [],
  329. EventTriggers.ON_MOUSE_ENTER: lambda: [],
  330. EventTriggers.ON_MOUSE_LEAVE: lambda: [],
  331. EventTriggers.ON_MOUSE_MOVE: lambda: [],
  332. EventTriggers.ON_MOUSE_OUT: lambda: [],
  333. EventTriggers.ON_MOUSE_OVER: lambda: [],
  334. EventTriggers.ON_MOUSE_UP: lambda: [],
  335. EventTriggers.ON_SCROLL: lambda: [],
  336. EventTriggers.ON_MOUNT: lambda: [],
  337. EventTriggers.ON_UNMOUNT: lambda: [],
  338. }
  339. def __repr__(self) -> str:
  340. """Represent the component in React.
  341. Returns:
  342. The code to render the component.
  343. """
  344. return format.json_dumps(self.render())
  345. def __str__(self) -> str:
  346. """Represent the component in React.
  347. Returns:
  348. The code to render the component.
  349. """
  350. from reflex.compiler.compiler import _compile_component
  351. return _compile_component(self)
  352. def _render(self, props: dict[str, Any] | None = None) -> Tag:
  353. """Define how to render the component in React.
  354. Args:
  355. props: The props to render (if None, then use get_props).
  356. Returns:
  357. The tag to render.
  358. """
  359. # Create the base tag.
  360. tag = Tag(
  361. name=self.tag if not self.alias else self.alias,
  362. special_props=self.special_props,
  363. )
  364. if props is None:
  365. # Add component props to the tag.
  366. props = {
  367. attr[:-1] if attr.endswith("_") else attr: getattr(self, attr)
  368. for attr in self.get_props()
  369. }
  370. # Add ref to element if `id` is not None.
  371. ref = self.get_ref()
  372. if ref is not None:
  373. props["ref"] = Var.create(ref, _var_is_local=False)
  374. else:
  375. props = props.copy()
  376. props.update(
  377. **{
  378. trigger: handler
  379. for trigger, handler in self.event_triggers.items()
  380. if trigger not in {EventTriggers.ON_MOUNT, EventTriggers.ON_UNMOUNT}
  381. },
  382. key=self.key,
  383. id=self.id,
  384. class_name=self.class_name,
  385. )
  386. props.update(self._get_style())
  387. props.update(self.custom_attrs)
  388. return tag.add_props(**props)
  389. @classmethod
  390. @lru_cache(maxsize=None)
  391. def get_props(cls) -> Set[str]:
  392. """Get the unique fields for the component.
  393. Returns:
  394. The unique fields.
  395. """
  396. return set(cls.get_fields()) - set(Component.get_fields())
  397. @classmethod
  398. @lru_cache(maxsize=None)
  399. def get_initial_props(cls) -> Set[str]:
  400. """Get the initial props to set for the component.
  401. Returns:
  402. The initial props to set.
  403. """
  404. return set()
  405. @classmethod
  406. @lru_cache(maxsize=None)
  407. def get_component_props(cls) -> set[str]:
  408. """Get the props that expected a component as value.
  409. Returns:
  410. The components props.
  411. """
  412. return {
  413. name
  414. for name, field in cls.get_fields().items()
  415. if name in cls.get_props()
  416. and types._issubclass(field.outer_type_, Component)
  417. }
  418. @classmethod
  419. def create(cls, *children, **props) -> Component:
  420. """Create the component.
  421. Args:
  422. *children: The children of the component.
  423. **props: The props of the component.
  424. Returns:
  425. The component.
  426. Raises:
  427. TypeError: If an invalid child is passed.
  428. """
  429. # Import here to avoid circular imports.
  430. from reflex.components.base.bare import Bare
  431. # Validate all the children.
  432. for child in children:
  433. # Make sure the child is a valid type.
  434. if not types._isinstance(child, ComponentChild):
  435. raise TypeError(
  436. "Children of Reflex components must be other components, "
  437. "state vars, or primitive Python types. "
  438. f"Got child {child} of type {type(child)}.",
  439. )
  440. children = [
  441. child
  442. if isinstance(child, Component)
  443. else Bare.create(contents=Var.create(child, _var_is_string=True))
  444. for child in children
  445. ]
  446. return cls(children=children, **props)
  447. def _add_style(self, style: dict):
  448. """Add additional style to the component.
  449. Args:
  450. style: A style dict to apply.
  451. """
  452. self.style.update(style)
  453. def add_style(self, style: ComponentStyle) -> Component:
  454. """Add additional style to the component and its children.
  455. Args:
  456. style: A dict from component to styling.
  457. Returns:
  458. The component with the additional style.
  459. """
  460. if type(self) in style:
  461. # Extract the style for this component.
  462. component_style = Style(style[type(self)])
  463. # Only add style props that are not overridden.
  464. component_style = {
  465. k: v for k, v in component_style.items() if k not in self.style
  466. }
  467. # Add the style to the component.
  468. self._add_style(component_style)
  469. # Recursively add style to the children.
  470. for child in self.children:
  471. # Skip BaseComponent and StatefulComponent children.
  472. if not isinstance(child, Component):
  473. continue
  474. child.add_style(style)
  475. return self
  476. def _get_style(self) -> dict:
  477. """Get the style for the component.
  478. Returns:
  479. The dictionary of the component style as value and the style notation as key.
  480. """
  481. return {"style": self.style}
  482. def render(self) -> Dict:
  483. """Render the component.
  484. Returns:
  485. The dictionary for template of component.
  486. """
  487. tag = self._render()
  488. rendered_dict = dict(
  489. tag.set(
  490. children=[child.render() for child in self.children],
  491. contents=str(tag.contents),
  492. props=tag.format_props(),
  493. ),
  494. autofocus=self.autofocus,
  495. )
  496. return rendered_dict
  497. def _validate_component_children(self, children: List[Component]):
  498. """Validate the children components.
  499. Args:
  500. children: The children of the component.
  501. """
  502. if not self._invalid_children and not self._valid_children:
  503. return
  504. comp_name = type(self).__name__
  505. def validate_invalid_child(child_name):
  506. if child_name in self._invalid_children:
  507. raise ValueError(
  508. f"The component `{comp_name}` cannot have `{child_name}` as a child component"
  509. )
  510. def validate_valid_child(child_name):
  511. if child_name not in self._valid_children:
  512. valid_child_list = ", ".join(
  513. [f"`{v_child}`" for v_child in self._valid_children]
  514. )
  515. raise ValueError(
  516. f"The component `{comp_name}` only allows the components: {valid_child_list} as children. Got `{child_name}` instead."
  517. )
  518. for child in children:
  519. name = type(child).__name__
  520. if self._invalid_children:
  521. validate_invalid_child(name)
  522. if self._valid_children:
  523. validate_valid_child(name)
  524. @staticmethod
  525. def _get_vars_from_event_triggers(
  526. event_triggers: dict[str, EventChain | Var],
  527. ) -> Iterator[tuple[str, list[Var]]]:
  528. """Get the Vars associated with each event trigger.
  529. Args:
  530. event_triggers: The event triggers from the component instance.
  531. Yields:
  532. tuple of (event_name, event_vars)
  533. """
  534. for event_trigger, event in event_triggers.items():
  535. if isinstance(event, Var):
  536. yield event_trigger, [event]
  537. elif isinstance(event, EventChain):
  538. event_args = []
  539. for spec in event.events:
  540. for args in spec.args:
  541. event_args.extend(args)
  542. yield event_trigger, event_args
  543. def _get_vars(self) -> list[Var]:
  544. """Walk all Vars used in this component.
  545. Returns:
  546. Each var referenced by the component (props, styles, event handlers).
  547. """
  548. vars = getattr(self, "__vars", None)
  549. if vars is not None:
  550. return vars
  551. vars = self.__vars = []
  552. # Get Vars associated with event trigger arguments.
  553. for _, event_vars in self._get_vars_from_event_triggers(self.event_triggers):
  554. vars.extend(event_vars)
  555. # Get Vars associated with component props.
  556. for prop in self.get_props():
  557. prop_var = getattr(self, prop)
  558. if isinstance(prop_var, Var):
  559. vars.append(prop_var)
  560. # Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
  561. if self.style:
  562. vars.append(
  563. BaseVar(
  564. _var_name="style",
  565. _var_type=str,
  566. _var_data=self.style._var_data,
  567. )
  568. )
  569. # Special props are always Var instances.
  570. vars.extend(self.special_props)
  571. # Get Vars associated with common Component props.
  572. for comp_prop in (
  573. self.class_name,
  574. self.id,
  575. self.key,
  576. self.autofocus,
  577. *self.custom_attrs.values(),
  578. ):
  579. if isinstance(comp_prop, Var):
  580. vars.append(comp_prop)
  581. elif isinstance(comp_prop, str):
  582. # Collapse VarData encoded in f-strings.
  583. var = Var.create_safe(comp_prop)
  584. if var._var_data is not None:
  585. vars.append(var)
  586. return vars
  587. def _get_custom_code(self) -> str | None:
  588. """Get custom code for the component.
  589. Returns:
  590. The custom code.
  591. """
  592. return None
  593. def get_custom_code(self) -> Set[str]:
  594. """Get custom code for the component and its children.
  595. Returns:
  596. The custom code.
  597. """
  598. # Store the code in a set to avoid duplicates.
  599. code = set()
  600. # Add the custom code for this component.
  601. custom_code = self._get_custom_code()
  602. if custom_code is not None:
  603. code.add(custom_code)
  604. # Add the custom code for the children.
  605. for child in self.children:
  606. code |= child.get_custom_code()
  607. # Return the code.
  608. return code
  609. def _get_dynamic_imports(self) -> str | None:
  610. """Get dynamic import for the component.
  611. Returns:
  612. The dynamic import.
  613. """
  614. return None
  615. def get_dynamic_imports(self) -> Set[str]:
  616. """Get dynamic imports for the component and its children.
  617. Returns:
  618. The dynamic imports.
  619. """
  620. # Store the import in a set to avoid duplicates.
  621. dynamic_imports = set()
  622. # Get dynamic import for this component.
  623. dynamic_import = self._get_dynamic_imports()
  624. if dynamic_import:
  625. dynamic_imports.add(dynamic_import)
  626. # Get the dynamic imports from children
  627. for child in self.children:
  628. dynamic_imports |= child.get_dynamic_imports()
  629. # Return the dynamic imports
  630. return dynamic_imports
  631. def _get_props_imports(self) -> List[str]:
  632. """Get the imports needed for components props.
  633. Returns:
  634. The imports for the components props of the component.
  635. """
  636. return [
  637. getattr(self, prop).get_imports()
  638. for prop in self.get_component_props()
  639. if getattr(self, prop) is not None
  640. ]
  641. def _get_dependencies_imports(self) -> imports.ImportDict:
  642. """Get the imports from lib_dependencies for installing.
  643. Returns:
  644. The dependencies imports of the component.
  645. """
  646. return {
  647. dep: [ImportVar(tag=None, render=False)] for dep in self.lib_dependencies
  648. }
  649. def _get_hooks_imports(self) -> imports.ImportDict:
  650. """Get the imports required by certain hooks.
  651. Returns:
  652. The imports required for all selected hooks.
  653. """
  654. _imports = {}
  655. if self._get_ref_hook():
  656. # Handle hooks needed for attaching react refs to DOM nodes.
  657. _imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
  658. _imports.setdefault(f"/{Dirs.STATE_PATH}", set()).add(ImportVar(tag="refs"))
  659. if self._get_mount_lifecycle_hook():
  660. # Handle hooks for `on_mount` / `on_unmount`.
  661. _imports.setdefault("react", set()).add(ImportVar(tag="useEffect"))
  662. if self._get_special_hooks():
  663. # Handle additional internal hooks (autofocus, etc).
  664. _imports.setdefault("react", set()).update(
  665. {
  666. ImportVar(tag="useRef"),
  667. ImportVar(tag="useEffect"),
  668. },
  669. )
  670. return _imports
  671. def _get_imports(self) -> imports.ImportDict:
  672. """Get all the libraries and fields that are used by the component.
  673. Returns:
  674. The imports needed by the component.
  675. """
  676. _imports = {}
  677. # Import this component's tag from the main library.
  678. if self.library is not None and self.tag is not None:
  679. _imports[self.library] = {self.import_var}
  680. # Get static imports required for event processing.
  681. event_imports = Imports.EVENTS if self.event_triggers else {}
  682. # Collect imports from Vars used directly by this component.
  683. var_imports = [
  684. var._var_data.imports for var in self._get_vars() if var._var_data
  685. ]
  686. return imports.merge_imports(
  687. *self._get_props_imports(),
  688. self._get_dependencies_imports(),
  689. self._get_hooks_imports(),
  690. _imports,
  691. event_imports,
  692. *var_imports,
  693. )
  694. def get_imports(self) -> imports.ImportDict:
  695. """Get all the libraries and fields that are used by the component and its children.
  696. Returns:
  697. The import dict with the required imports.
  698. """
  699. return imports.merge_imports(
  700. self._get_imports(), *[child.get_imports() for child in self.children]
  701. )
  702. def _get_mount_lifecycle_hook(self) -> str | None:
  703. """Generate the component lifecycle hook.
  704. Returns:
  705. The useEffect hook for managing `on_mount` and `on_unmount` events.
  706. """
  707. # pop on_mount and on_unmount from event_triggers since these are handled by
  708. # hooks, not as actually props in the component
  709. on_mount = self.event_triggers.get(EventTriggers.ON_MOUNT, None)
  710. on_unmount = self.event_triggers.get(EventTriggers.ON_UNMOUNT, None)
  711. if on_mount is not None:
  712. on_mount = format.format_event_chain(on_mount)
  713. if on_unmount is not None:
  714. on_unmount = format.format_event_chain(on_unmount)
  715. if on_mount is not None or on_unmount is not None:
  716. return f"""
  717. useEffect(() => {{
  718. {on_mount or ""}
  719. return () => {{
  720. {on_unmount or ""}
  721. }}
  722. }}, []);"""
  723. def _get_ref_hook(self) -> str | None:
  724. """Generate the ref hook for the component.
  725. Returns:
  726. The useRef hook for managing refs.
  727. """
  728. ref = self.get_ref()
  729. if ref is not None:
  730. return f"const {ref} = useRef(null); {str(Var.create_safe(ref).as_ref())} = {ref};"
  731. def _get_vars_hooks(self) -> set[str]:
  732. """Get the hooks required by vars referenced in this component.
  733. Returns:
  734. The hooks for the vars.
  735. """
  736. vars_hooks = set()
  737. for var in self._get_vars():
  738. if var._var_data:
  739. vars_hooks.update(var._var_data.hooks)
  740. return vars_hooks
  741. def _get_events_hooks(self) -> set[str]:
  742. """Get the hooks required by events referenced in this component.
  743. Returns:
  744. The hooks for the events.
  745. """
  746. if self.event_triggers:
  747. return {Hooks.EVENTS}
  748. return set()
  749. def _get_special_hooks(self) -> set[str]:
  750. """Get the hooks required by special actions referenced in this component.
  751. Returns:
  752. The hooks for special actions.
  753. """
  754. if self.autofocus:
  755. return {
  756. """
  757. // Set focus to the specified element.
  758. const focusRef = useRef(null)
  759. useEffect(() => {
  760. if (focusRef.current) {
  761. focusRef.current.focus();
  762. }
  763. })""",
  764. }
  765. return set()
  766. def _get_hooks_internal(self) -> Set[str]:
  767. """Get the React hooks for this component managed by the framework.
  768. Downstream components should NOT override this method to avoid breaking
  769. framework functionality.
  770. Returns:
  771. Set of internally managed hooks.
  772. """
  773. return (
  774. set(
  775. hook
  776. for hook in [self._get_mount_lifecycle_hook(), self._get_ref_hook()]
  777. if hook
  778. )
  779. | self._get_vars_hooks()
  780. | self._get_events_hooks()
  781. | self._get_special_hooks()
  782. )
  783. def _get_hooks(self) -> str | None:
  784. """Get the React hooks for this component.
  785. Downstream components should override this method to add their own hooks.
  786. Returns:
  787. The hooks for just this component.
  788. """
  789. return
  790. def get_hooks(self) -> Set[str]:
  791. """Get the React hooks for this component and its children.
  792. Returns:
  793. The code that should appear just before returning the rendered component.
  794. """
  795. # Store the code in a set to avoid duplicates.
  796. code = self._get_hooks_internal()
  797. # Add the hook code for this component.
  798. hooks = self._get_hooks()
  799. if hooks is not None:
  800. code.add(hooks)
  801. # Add the hook code for the children.
  802. for child in self.children:
  803. code |= child.get_hooks()
  804. return code
  805. def get_ref(self) -> str | None:
  806. """Get the name of the ref for the component.
  807. Returns:
  808. The ref name.
  809. """
  810. # do not create a ref if the id is dynamic or unspecified
  811. if self.id is None or isinstance(self.id, BaseVar):
  812. return None
  813. return format.format_ref(self.id)
  814. def get_refs(self) -> Set[str]:
  815. """Get the refs for the children of the component.
  816. Returns:
  817. The refs for the children.
  818. """
  819. refs = set()
  820. ref = self.get_ref()
  821. if ref is not None:
  822. refs.add(ref)
  823. for child in self.children:
  824. refs |= child.get_refs()
  825. return refs
  826. def get_custom_components(
  827. self, seen: set[str] | None = None
  828. ) -> Set[CustomComponent]:
  829. """Get all the custom components used by the component.
  830. Args:
  831. seen: The tags of the components that have already been seen.
  832. Returns:
  833. The set of custom components.
  834. """
  835. custom_components = set()
  836. # Store the seen components in a set to avoid infinite recursion.
  837. if seen is None:
  838. seen = set()
  839. for child in self.children:
  840. # Skip BaseComponent and StatefulComponent children.
  841. if not isinstance(child, Component):
  842. continue
  843. custom_components |= child.get_custom_components(seen=seen)
  844. return custom_components
  845. @property
  846. def import_var(self):
  847. """The tag to import.
  848. Returns:
  849. An import var.
  850. """
  851. # If the tag is dot-qualified, only import the left-most name.
  852. tag = self.tag.partition(".")[0] if self.tag else None
  853. alias = self.alias.partition(".")[0] if self.alias else None
  854. return ImportVar(tag=tag, is_default=self.is_default, alias=alias)
  855. @staticmethod
  856. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  857. """Get the app wrap components for the component.
  858. Returns:
  859. The app wrap components.
  860. """
  861. return {}
  862. def get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  863. """Get the app wrap components for the component and its children.
  864. Returns:
  865. The app wrap components.
  866. """
  867. # Store the components in a set to avoid duplicates.
  868. components = self._get_app_wrap_components()
  869. for component in tuple(components.values()):
  870. components.update(component.get_app_wrap_components())
  871. # Add the app wrap components for the children.
  872. for child in self.children:
  873. # Skip BaseComponent and StatefulComponent children.
  874. if not isinstance(child, Component):
  875. continue
  876. components.update(child.get_app_wrap_components())
  877. # Return the components.
  878. return components
  879. class CustomComponent(Component):
  880. """A custom user-defined component."""
  881. # Use the components library.
  882. library = f"/{Dirs.COMPONENTS_PATH}"
  883. # The function that creates the component.
  884. component_fn: Callable[..., Component] = Component.create
  885. # The props of the component.
  886. props: Dict[str, Any] = {}
  887. def __init__(self, *args, **kwargs):
  888. """Initialize the custom component.
  889. Args:
  890. *args: The args to pass to the component.
  891. **kwargs: The kwargs to pass to the component.
  892. """
  893. super().__init__(*args, **kwargs)
  894. # Unset the style.
  895. self.style = Style()
  896. # Set the tag to the name of the function.
  897. self.tag = format.to_title_case(self.component_fn.__name__)
  898. # Set the props.
  899. props = typing.get_type_hints(self.component_fn)
  900. for key, value in kwargs.items():
  901. # Skip kwargs that are not props.
  902. if key not in props:
  903. continue
  904. # Get the type based on the annotation.
  905. type_ = props[key]
  906. # Handle event chains.
  907. if types._issubclass(type_, EventChain):
  908. value = self._create_event_chain(key, value)
  909. self.props[format.to_camel_case(key)] = value
  910. continue
  911. # Convert the type to a Var, then get the type of the var.
  912. if not types._issubclass(type_, Var):
  913. type_ = Var[type_]
  914. type_ = types.get_args(type_)[0]
  915. # Handle subclasses of Base.
  916. if types._issubclass(type_, Base):
  917. try:
  918. value = BaseVar(
  919. _var_name=value.json(), _var_type=type_, _var_is_local=True
  920. )
  921. except Exception:
  922. value = Var.create(value)
  923. else:
  924. value = Var.create(value, _var_is_string=type(value) is str)
  925. # Set the prop.
  926. self.props[format.to_camel_case(key)] = value
  927. def __eq__(self, other: Any) -> bool:
  928. """Check if the component is equal to another.
  929. Args:
  930. other: The other component.
  931. Returns:
  932. Whether the component is equal to the other.
  933. """
  934. return isinstance(other, CustomComponent) and self.tag == other.tag
  935. def __hash__(self) -> int:
  936. """Get the hash of the component.
  937. Returns:
  938. The hash of the component.
  939. """
  940. return hash(self.tag)
  941. @classmethod
  942. def get_props(cls) -> Set[str]:
  943. """Get the props for the component.
  944. Returns:
  945. The set of component props.
  946. """
  947. return set()
  948. def get_custom_components(
  949. self, seen: set[str] | None = None
  950. ) -> Set[CustomComponent]:
  951. """Get all the custom components used by the component.
  952. Args:
  953. seen: The tags of the components that have already been seen.
  954. Returns:
  955. The set of custom components.
  956. """
  957. assert self.tag is not None, "The tag must be set."
  958. # Store the seen components in a set to avoid infinite recursion.
  959. if seen is None:
  960. seen = set()
  961. custom_components = {self} | super().get_custom_components(seen=seen)
  962. # Avoid adding the same component twice.
  963. if self.tag not in seen:
  964. seen.add(self.tag)
  965. custom_components |= self.get_component(self).get_custom_components(
  966. seen=seen
  967. )
  968. return custom_components
  969. def _render(self) -> Tag:
  970. """Define how to render the component in React.
  971. Returns:
  972. The tag to render.
  973. """
  974. return super()._render(props=self.props)
  975. def get_prop_vars(self) -> List[BaseVar]:
  976. """Get the prop vars.
  977. Returns:
  978. The prop vars.
  979. """
  980. return [
  981. BaseVar(
  982. _var_name=name,
  983. _var_type=prop._var_type
  984. if types._isinstance(prop, Var)
  985. else type(prop),
  986. )
  987. for name, prop in self.props.items()
  988. ]
  989. @lru_cache(maxsize=None) # noqa
  990. def get_component(self) -> Component:
  991. """Render the component.
  992. Returns:
  993. The code to render the component.
  994. """
  995. return self.component_fn(*self.get_prop_vars())
  996. def custom_component(
  997. component_fn: Callable[..., Component]
  998. ) -> Callable[..., CustomComponent]:
  999. """Create a custom component from a function.
  1000. Args:
  1001. component_fn: The function that creates the component.
  1002. Returns:
  1003. The decorated function.
  1004. """
  1005. @wraps(component_fn)
  1006. def wrapper(*children, **props) -> CustomComponent:
  1007. # Remove the children from the props.
  1008. props.pop("children", None)
  1009. return CustomComponent(component_fn=component_fn, children=children, **props)
  1010. return wrapper
  1011. # Alias memo to custom_component.
  1012. memo = custom_component
  1013. class NoSSRComponent(Component):
  1014. """A dynamic component that is not rendered on the server."""
  1015. def _get_imports(self) -> imports.ImportDict:
  1016. """Get the imports for the component.
  1017. Returns:
  1018. The imports for dynamically importing the component at module load time.
  1019. """
  1020. # Next.js dynamic import mechanism.
  1021. dynamic_import = {"next/dynamic": [ImportVar(tag="dynamic", is_default=True)]}
  1022. # The normal imports for this component.
  1023. _imports = super()._get_imports()
  1024. # Do NOT import the main library/tag statically.
  1025. if self.library is not None:
  1026. _imports[self.library] = [imports.ImportVar(tag=None, render=False)]
  1027. return imports.merge_imports(
  1028. dynamic_import,
  1029. _imports,
  1030. self._get_dependencies_imports(),
  1031. )
  1032. def _get_dynamic_imports(self) -> str:
  1033. opts_fragment = ", { ssr: false });"
  1034. # extract the correct import name from library name
  1035. if self.library is None:
  1036. raise ValueError("Undefined library for NoSSRComponent")
  1037. import_name_parts = [p for p in self.library.rpartition("@") if p != ""]
  1038. import_name = (
  1039. import_name_parts[0] if import_name_parts[0] != "@" else self.library
  1040. )
  1041. library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
  1042. mod_import = (
  1043. # https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
  1044. f".then((mod) => mod.{self.tag})"
  1045. if not self.is_default
  1046. else ""
  1047. )
  1048. return "".join((library_import, mod_import, opts_fragment))
  1049. @serializer
  1050. def serialize_component(comp: Component):
  1051. """Serialize a component.
  1052. Args:
  1053. comp: The component to serialize.
  1054. Returns:
  1055. The serialized component.
  1056. """
  1057. return str(comp)
  1058. class StatefulComponent(BaseComponent):
  1059. """A component that depends on state and is rendered outside of the page component.
  1060. If a StatefulComponent is used in multiple pages, it will be rendered to a common file and
  1061. imported into each page that uses it.
  1062. A stateful component has a tag name that includes a hash of the code that it renders
  1063. to. This tag name refers to the specific component with the specific props that it
  1064. was created with.
  1065. """
  1066. # A lookup table to caching memoized component instances.
  1067. tag_to_stateful_component: ClassVar[Dict[str, StatefulComponent]] = {}
  1068. # Reference to the original component that was memoized into this component.
  1069. component: Component
  1070. # The rendered (memoized) code that will be emitted.
  1071. code: str
  1072. # How many times this component is referenced in the app.
  1073. references: int = 0
  1074. # Whether the component has already been rendered to a shared file.
  1075. rendered_as_shared: bool = False
  1076. @classmethod
  1077. def create(cls, component: Component) -> StatefulComponent | None:
  1078. """Create a stateful component from a component.
  1079. Args:
  1080. component: The component to memoize.
  1081. Returns:
  1082. The stateful component or None if the component should not be memoized.
  1083. """
  1084. from reflex.components.layout.foreach import Foreach
  1085. if component.tag is None:
  1086. # Only memoize components with a tag.
  1087. return None
  1088. # If _var_data is found in this component, it is a candidate for auto-memoization.
  1089. has_var_data = False
  1090. # Determine if any Vars have associated data.
  1091. for prop_var in component._get_vars():
  1092. if prop_var._var_data:
  1093. has_var_data = True
  1094. break
  1095. if not has_var_data:
  1096. # Check for special-cases in child components.
  1097. for child in component.children:
  1098. # Skip BaseComponent and StatefulComponent children.
  1099. if not isinstance(child, Component):
  1100. continue
  1101. # Always consider Foreach something that must be memoized by the parent.
  1102. if isinstance(child, Foreach):
  1103. has_var_data = True
  1104. break
  1105. child = cls._child_var(child)
  1106. if isinstance(child, Var) and child._var_data:
  1107. has_var_data = True
  1108. break
  1109. if has_var_data or component.event_triggers:
  1110. # Render the component to determine tag+hash based on component code.
  1111. tag_name = cls._get_tag_name(component)
  1112. if tag_name is None:
  1113. return None
  1114. # Look up the tag in the cache
  1115. stateful_component = cls.tag_to_stateful_component.get(tag_name)
  1116. if stateful_component is None:
  1117. # Render the component as a string of javascript code.
  1118. code = cls._render_stateful_code(component, tag_name=tag_name)
  1119. # Set the stateful component in the cache for the given tag.
  1120. stateful_component = cls.tag_to_stateful_component.setdefault(
  1121. tag_name,
  1122. cls(
  1123. children=component.children,
  1124. component=component,
  1125. tag=tag_name,
  1126. code=code,
  1127. ),
  1128. )
  1129. # Bump the reference count -- multiple pages referencing the same component
  1130. # will result in writing it to a common file.
  1131. stateful_component.references += 1
  1132. return stateful_component
  1133. # Return None to indicate this component should not be memoized.
  1134. return None
  1135. @staticmethod
  1136. def _child_var(child: Component) -> Var | Component:
  1137. """Get the Var from a child component.
  1138. This method is used for special cases when the StatefulComponent should actually
  1139. wrap the parent component of the child instead of recursing into the children
  1140. and memoizing them independently.
  1141. Args:
  1142. child: The child component.
  1143. Returns:
  1144. The Var from the child component or the child itself (for regular cases).
  1145. """
  1146. from reflex.components.base.bare import Bare
  1147. from reflex.components.layout.cond import Cond
  1148. from reflex.components.layout.foreach import Foreach
  1149. if isinstance(child, Bare):
  1150. return child.contents
  1151. if isinstance(child, Cond):
  1152. return child.cond
  1153. if isinstance(child, Foreach):
  1154. return child.iterable
  1155. return child
  1156. @classmethod
  1157. def _get_tag_name(cls, component: Component) -> str | None:
  1158. """Get the tag based on rendering the given component.
  1159. Args:
  1160. component: The component to render.
  1161. Returns:
  1162. The tag for the stateful component.
  1163. """
  1164. # Get the render dict for the component.
  1165. rendered_code = component.render()
  1166. if not rendered_code:
  1167. # Never memoize non-visual components.
  1168. return None
  1169. # Compute the hash based on the rendered code.
  1170. code_hash = md5(str(rendered_code).encode("utf-8")).hexdigest()
  1171. # Format the tag name including the hash.
  1172. return format.format_state_name(f"{component.tag or 'Comp'}_{code_hash}")
  1173. @classmethod
  1174. def _render_stateful_code(
  1175. cls,
  1176. component: Component,
  1177. tag_name: str,
  1178. ) -> str:
  1179. """Render the code for a stateful component.
  1180. Args:
  1181. component: The component to render.
  1182. tag_name: The tag name for the stateful component (see _get_tag_name).
  1183. Returns:
  1184. The rendered code.
  1185. """
  1186. # Memoize event triggers useCallback to avoid unnecessary re-renders.
  1187. memo_event_triggers = tuple(cls._get_memoized_event_triggers(component).items())
  1188. # Trigger hooks stored separately to write after the normal hooks (see stateful_component.js.jinja2)
  1189. memo_trigger_hooks = []
  1190. if memo_event_triggers:
  1191. # Copy the component to avoid mutating the original.
  1192. component = copy.copy(component)
  1193. for event_trigger, (
  1194. memo_trigger,
  1195. memo_trigger_hook,
  1196. ) in memo_event_triggers:
  1197. # Replace the event trigger with the memoized version.
  1198. memo_trigger_hooks.append(memo_trigger_hook)
  1199. component.event_triggers[event_trigger] = memo_trigger
  1200. # Render the code for this component and hooks.
  1201. return STATEFUL_COMPONENT.render(
  1202. tag_name=tag_name,
  1203. memo_trigger_hooks=memo_trigger_hooks,
  1204. component=component,
  1205. )
  1206. @staticmethod
  1207. def _get_hook_deps(hook: str) -> list[str]:
  1208. """Extract var deps from a hook.
  1209. Args:
  1210. hook: The hook line to extract deps from.
  1211. Returns:
  1212. A list of var names created by the hook declaration.
  1213. """
  1214. var_name = hook.partition("=")[0].strip().split(None, 1)[1].strip()
  1215. if var_name.startswith("["):
  1216. # Break up array destructuring.
  1217. return [v.strip() for v in var_name.strip("[]").split(",")]
  1218. return [var_name]
  1219. @classmethod
  1220. def _get_memoized_event_triggers(
  1221. cls,
  1222. component: Component,
  1223. ) -> dict[str, tuple[Var, str]]:
  1224. """Memoize event handler functions with useCallback to avoid unnecessary re-renders.
  1225. Args:
  1226. component: The component with events to memoize.
  1227. Returns:
  1228. A dict of event trigger name to a tuple of the memoized event trigger Var and
  1229. the hook code that memoizes the event handler.
  1230. """
  1231. trigger_memo = {}
  1232. for event_trigger, event_args in component._get_vars_from_event_triggers(
  1233. component.event_triggers
  1234. ):
  1235. if event_trigger in {
  1236. EventTriggers.ON_MOUNT,
  1237. EventTriggers.ON_UNMOUNT,
  1238. EventTriggers.ON_SUBMIT,
  1239. }:
  1240. # Do not memoize lifecycle or submit events.
  1241. continue
  1242. # Get the actual EventSpec and render it.
  1243. event = component.event_triggers[event_trigger]
  1244. rendered_chain = format.format_prop(event)
  1245. if isinstance(rendered_chain, str):
  1246. rendered_chain = rendered_chain.strip("{}")
  1247. # Hash the rendered EventChain to get a deterministic function name.
  1248. chain_hash = md5(str(rendered_chain).encode("utf-8")).hexdigest()
  1249. memo_name = f"{event_trigger}_{chain_hash}"
  1250. # Calculate Var dependencies accessed by the handler for useCallback dep array.
  1251. var_deps = ["addEvents", "Event"]
  1252. for arg in event_args:
  1253. if arg._var_data is None:
  1254. continue
  1255. for hook in arg._var_data.hooks:
  1256. var_deps.extend(cls._get_hook_deps(hook))
  1257. memo_var_data = VarData.merge(
  1258. *[var._var_data for var in event_args],
  1259. VarData( # type: ignore
  1260. imports={"react": {ImportVar(tag="useCallback")}},
  1261. ),
  1262. )
  1263. # Store the memoized function name and hook code for this event trigger.
  1264. trigger_memo[event_trigger] = (
  1265. Var.create_safe(memo_name)._replace(
  1266. _var_type=EventChain, merge_var_data=memo_var_data
  1267. ),
  1268. f"const {memo_name} = useCallback({rendered_chain}, [{', '.join(var_deps)}])",
  1269. )
  1270. return trigger_memo
  1271. def get_hooks(self) -> set[str]:
  1272. """Get the React hooks for this component.
  1273. Returns:
  1274. The code that should appear just before returning the rendered component.
  1275. """
  1276. return set()
  1277. def get_imports(self) -> imports.ImportDict:
  1278. """Get all the libraries and fields that are used by the component.
  1279. Returns:
  1280. The import dict with the required imports.
  1281. """
  1282. if self.rendered_as_shared:
  1283. return {
  1284. f"/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
  1285. ImportVar(tag=self.tag)
  1286. ]
  1287. }
  1288. return self.component.get_imports()
  1289. def get_dynamic_imports(self) -> set[str]:
  1290. """Get dynamic imports for the component.
  1291. Returns:
  1292. The dynamic imports.
  1293. """
  1294. if self.rendered_as_shared:
  1295. return set()
  1296. return self.component.get_dynamic_imports()
  1297. def get_custom_code(self) -> set[str]:
  1298. """Get custom code for the component.
  1299. Returns:
  1300. The custom code.
  1301. """
  1302. if self.rendered_as_shared:
  1303. return set()
  1304. return self.component.get_custom_code().union({self.code})
  1305. def get_refs(self) -> set[str]:
  1306. """Get the refs for the children of the component.
  1307. Returns:
  1308. The refs for the children.
  1309. """
  1310. if self.rendered_as_shared:
  1311. return set()
  1312. return self.component.get_refs()
  1313. def render(self) -> dict:
  1314. """Define how to render the component in React.
  1315. Returns:
  1316. The tag to render.
  1317. """
  1318. return dict(Tag(name=self.tag))
  1319. @classmethod
  1320. def compile_from(cls, component: BaseComponent) -> BaseComponent:
  1321. """Walk through the component tree and memoize all stateful components.
  1322. Args:
  1323. component: The component to memoize.
  1324. Returns:
  1325. The memoized component tree.
  1326. """
  1327. from reflex.components.layout.foreach import Foreach
  1328. # Foreach must be memoized as a single component to retain index Var context.
  1329. if not isinstance(component, Foreach):
  1330. component.children = [
  1331. cls.compile_from(child) for child in component.children
  1332. ]
  1333. if isinstance(component, Component):
  1334. stateful_component = cls.create(component)
  1335. if stateful_component is not None:
  1336. return stateful_component
  1337. return component