component.py 62 KB

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