component.py 59 KB

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