component.py 58 KB

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