component.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  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 pydantic.fields import ModelPrivateAttr
  22. from pydantic_core._pydantic_core import PydanticUndefinedType
  23. from reflex.base import Base
  24. from reflex.compiler.templates import STATEFUL_COMPONENT
  25. from reflex.components.tags import Tag
  26. from reflex.constants import (
  27. Dirs,
  28. EventTriggers,
  29. Hooks,
  30. Imports,
  31. MemoizationDisposition,
  32. MemoizationMode,
  33. PageNames,
  34. )
  35. from reflex.event import (
  36. EventChain,
  37. EventHandler,
  38. EventSpec,
  39. call_event_fn,
  40. call_event_handler,
  41. get_handler_args,
  42. )
  43. from reflex.style import Style, format_as_emotion
  44. from reflex.utils import console, format, imports, types
  45. from reflex.utils.imports import ImportVar
  46. from reflex.utils.serializers import serializer
  47. from reflex.vars import BaseVar, Var, VarData
  48. class BaseComponent(Base, ABC):
  49. """The base class for all Reflex components.
  50. This is something that can be rendered as a Component via the Reflex compiler.
  51. """
  52. # The children nested within the component.
  53. children: List[BaseComponent] = []
  54. # The library that the component is based on.
  55. library: Optional[str] = None
  56. # List here the non-react dependency needed by `library`
  57. lib_dependencies: List[str] = []
  58. # The tag to use when rendering the component.
  59. tag: Optional[str] = None
  60. @abstractmethod
  61. def render(self) -> dict:
  62. """Render the component.
  63. Returns:
  64. The dictionary for template of the component.
  65. """
  66. @abstractmethod
  67. def get_hooks(self) -> set[str]:
  68. """Get the React hooks for this component.
  69. Returns:
  70. The code that should appear just before returning the rendered component.
  71. """
  72. @abstractmethod
  73. def get_imports(self) -> imports.ImportDict:
  74. """Get all the libraries and fields that are used by the component.
  75. Returns:
  76. The import dict with the required imports.
  77. """
  78. @abstractmethod
  79. def get_dynamic_imports(self) -> set[str]:
  80. """Get dynamic imports for the component.
  81. Returns:
  82. The dynamic imports.
  83. """
  84. @abstractmethod
  85. def get_custom_code(self) -> set[str]:
  86. """Get custom code for the component.
  87. Returns:
  88. The custom code.
  89. """
  90. @abstractmethod
  91. def get_refs(self) -> set[str]:
  92. """Get the refs for the children of the component.
  93. Returns:
  94. The refs for the children.
  95. """
  96. class ComponentNamespace(SimpleNamespace):
  97. """A namespace to manage components with subcomponents."""
  98. def __hash__(self) -> int:
  99. """Get the hash of the namespace.
  100. Returns:
  101. The hash of the namespace.
  102. """
  103. return hash(self.__class__.__name__)
  104. def evaluate_style_namespaces(style: ComponentStyle) -> dict:
  105. """Evaluate namespaces in the style.
  106. Args:
  107. style: The style to evaluate.
  108. Returns:
  109. The evaluated style.
  110. """
  111. return {
  112. k.__call__ if isinstance(k, ComponentNamespace) else k: v
  113. for k, v in style.items()
  114. }
  115. # Map from component to styling.
  116. ComponentStyle = Dict[
  117. Union[str, Type[BaseComponent], Callable, ComponentNamespace], Any
  118. ]
  119. ComponentChild = Union[types.PrimitiveType, Var, BaseComponent]
  120. class Component(BaseComponent, ABC):
  121. """A component with style, event trigger and other props."""
  122. # The style of the component.
  123. style: Style = Style()
  124. # A mapping from event triggers to event chains.
  125. event_triggers: Dict[str, Union[EventChain, Var]] = {}
  126. # The alias for the tag.
  127. alias: Optional[str] = None
  128. # Whether the import is default or named.
  129. is_default: Optional[bool] = False
  130. # A unique key for the component.
  131. key: Any = None
  132. # The id for the component.
  133. id: Any = None
  134. # The class name for the component.
  135. class_name: Any = None
  136. # Special component props.
  137. special_props: Set[Var] = set()
  138. # Whether the component should take the focus once the page is loaded
  139. autofocus: bool = False
  140. # components that cannot be children
  141. _invalid_children: List[str] = []
  142. # only components that are allowed as children
  143. _valid_children: List[str] = []
  144. # only components that are allowed as parent
  145. _valid_parents: List[str] = []
  146. # props to change the name of
  147. _rename_props: Dict[str, str] = {}
  148. # custom attribute
  149. custom_attrs: Dict[str, Union[Var, str]] = {}
  150. # When to memoize this component and its children.
  151. _memoization_mode: MemoizationMode = MemoizationMode()
  152. @classmethod
  153. def __init_subclass__(cls, **kwargs):
  154. """Set default properties.
  155. Args:
  156. **kwargs: The kwargs to pass to the superclass.
  157. """
  158. super().__init_subclass__(**kwargs)
  159. # Get all the props for the component.
  160. props = cls.get_props()
  161. # Convert fields to props, setting default values.
  162. for field_name, field in cls.get_fields().items():
  163. # If the field is not a component prop, skip it.
  164. if field_name not in props:
  165. continue
  166. # Set default values for any props.
  167. if types._issubclass(field.annotation, Var):
  168. # TODO: pydantic v2 AttributeError: 'FieldInfo' object attribute 'is_required' is read-only
  169. # field.is_required = False
  170. if not isinstance(field.default, PydanticUndefinedType):
  171. field.default = Var.create(field.default)
  172. # Ensure renamed props from parent classes are applied to the subclass.
  173. if cls._rename_props:
  174. inherited_rename_props = {}
  175. for parent in reversed(cls.mro()):
  176. if issubclass(parent, Component) and parent._rename_props:
  177. if isinstance(parent._rename_props, ModelPrivateAttr):
  178. parent._rename_props = parent._rename_props.default
  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].annotation
  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].annotation.__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].annotation
  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.annotation, 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) -> list[Var]:
  669. """Walk all Vars used in this component.
  670. Returns:
  671. Each var referenced by the component (props, styles, event handlers).
  672. """
  673. vars = getattr(self, "__vars", None)
  674. if vars is not None:
  675. return vars
  676. vars = self.__vars = []
  677. # Get Vars associated with event trigger arguments.
  678. for _, event_vars in self._get_vars_from_event_triggers(self.event_triggers):
  679. vars.extend(event_vars)
  680. # Get Vars associated with component props.
  681. for prop in self.get_props():
  682. prop_var = getattr(self, prop)
  683. if isinstance(prop_var, Var):
  684. vars.append(prop_var)
  685. # Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
  686. if isinstance(self.style, dict) and self.style or isinstance(self.style, Var):
  687. vars.append(
  688. BaseVar(
  689. _var_name="style",
  690. _var_type=str,
  691. _var_data=self.style._var_data,
  692. )
  693. )
  694. # Special props are always Var instances.
  695. vars.extend(self.special_props)
  696. # Get Vars associated with common Component props.
  697. for comp_prop in (
  698. self.class_name,
  699. self.id,
  700. self.key,
  701. self.autofocus,
  702. *self.custom_attrs.values(),
  703. ):
  704. if isinstance(comp_prop, Var):
  705. vars.append(comp_prop)
  706. elif isinstance(comp_prop, str):
  707. # Collapse VarData encoded in f-strings.
  708. var = Var.create_safe(comp_prop)
  709. if var._var_data is not None:
  710. vars.append(var)
  711. return vars
  712. def _get_custom_code(self) -> str | None:
  713. """Get custom code for the component.
  714. Returns:
  715. The custom code.
  716. """
  717. return None
  718. def get_custom_code(self) -> Set[str]:
  719. """Get custom code for the component and its children.
  720. Returns:
  721. The custom code.
  722. """
  723. # Store the code in a set to avoid duplicates.
  724. code = set()
  725. # Add the custom code for this component.
  726. custom_code = self._get_custom_code()
  727. if custom_code is not None:
  728. code.add(custom_code)
  729. # Add the custom code for the children.
  730. for child in self.children:
  731. code |= child.get_custom_code()
  732. # Return the code.
  733. return code
  734. def _get_dynamic_imports(self) -> str | None:
  735. """Get dynamic import for the component.
  736. Returns:
  737. The dynamic import.
  738. """
  739. return None
  740. def get_dynamic_imports(self) -> Set[str]:
  741. """Get dynamic imports for the component and its children.
  742. Returns:
  743. The dynamic imports.
  744. """
  745. # Store the import in a set to avoid duplicates.
  746. dynamic_imports = set()
  747. # Get dynamic import for this component.
  748. dynamic_import = self._get_dynamic_imports()
  749. if dynamic_import:
  750. dynamic_imports.add(dynamic_import)
  751. # Get the dynamic imports from children
  752. for child in self.children:
  753. dynamic_imports |= child.get_dynamic_imports()
  754. for prop in self.get_component_props():
  755. if getattr(self, prop) is not None:
  756. dynamic_imports |= getattr(self, prop).get_dynamic_imports()
  757. # Return the dynamic imports
  758. return dynamic_imports
  759. def _get_props_imports(self) -> List[str]:
  760. """Get the imports needed for components props.
  761. Returns:
  762. The imports for the components props of the component.
  763. """
  764. return [
  765. getattr(self, prop).get_imports()
  766. for prop in self.get_component_props()
  767. if getattr(self, prop) is not None
  768. ]
  769. def _get_dependencies_imports(self) -> imports.ImportDict:
  770. """Get the imports from lib_dependencies for installing.
  771. Returns:
  772. The dependencies imports of the component.
  773. """
  774. return {
  775. dep: [ImportVar(tag=None, render=False)] for dep in self.lib_dependencies
  776. }
  777. def _get_hooks_imports(self) -> imports.ImportDict:
  778. """Get the imports required by certain hooks.
  779. Returns:
  780. The imports required for all selected hooks.
  781. """
  782. _imports = {}
  783. if self._get_ref_hook():
  784. # Handle hooks needed for attaching react refs to DOM nodes.
  785. _imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
  786. _imports.setdefault(f"/{Dirs.STATE_PATH}", set()).add(ImportVar(tag="refs"))
  787. if self._get_mount_lifecycle_hook():
  788. # Handle hooks for `on_mount` / `on_unmount`.
  789. _imports.setdefault("react", set()).add(ImportVar(tag="useEffect"))
  790. if self._get_special_hooks():
  791. # Handle additional internal hooks (autofocus, etc).
  792. _imports.setdefault("react", set()).update(
  793. {
  794. ImportVar(tag="useRef"),
  795. ImportVar(tag="useEffect"),
  796. },
  797. )
  798. return _imports
  799. def _get_imports(self) -> imports.ImportDict:
  800. """Get all the libraries and fields that are used by the component.
  801. Returns:
  802. The imports needed by the component.
  803. """
  804. _imports = {}
  805. # Import this component's tag from the main library.
  806. if self.library is not None and self.tag is not None:
  807. _imports[self.library] = {self.import_var}
  808. # Get static imports required for event processing.
  809. event_imports = Imports.EVENTS if self.event_triggers else {}
  810. # Collect imports from Vars used directly by this component.
  811. var_imports = [
  812. var._var_data.imports for var in self._get_vars() if var._var_data
  813. ]
  814. return imports.merge_imports(
  815. *self._get_props_imports(),
  816. self._get_dependencies_imports(),
  817. self._get_hooks_imports(),
  818. _imports,
  819. event_imports,
  820. *var_imports,
  821. )
  822. def get_imports(self) -> imports.ImportDict:
  823. """Get all the libraries and fields that are used by the component and its children.
  824. Returns:
  825. The import dict with the required imports.
  826. """
  827. return imports.merge_imports(
  828. self._get_imports(), *[child.get_imports() for child in self.children]
  829. )
  830. def _get_mount_lifecycle_hook(self) -> str | None:
  831. """Generate the component lifecycle hook.
  832. Returns:
  833. The useEffect hook for managing `on_mount` and `on_unmount` events.
  834. """
  835. # pop on_mount and on_unmount from event_triggers since these are handled by
  836. # hooks, not as actually props in the component
  837. on_mount = self.event_triggers.get(EventTriggers.ON_MOUNT, None)
  838. on_unmount = self.event_triggers.get(EventTriggers.ON_UNMOUNT, None)
  839. if on_mount is not None:
  840. on_mount = format.format_event_chain(on_mount)
  841. if on_unmount is not None:
  842. on_unmount = format.format_event_chain(on_unmount)
  843. if on_mount is not None or on_unmount is not None:
  844. return f"""
  845. useEffect(() => {{
  846. {on_mount or ""}
  847. return () => {{
  848. {on_unmount or ""}
  849. }}
  850. }}, []);"""
  851. def _get_ref_hook(self) -> str | None:
  852. """Generate the ref hook for the component.
  853. Returns:
  854. The useRef hook for managing refs.
  855. """
  856. ref = self.get_ref()
  857. if ref is not None:
  858. return f"const {ref} = useRef(null); {str(Var.create_safe(ref).as_ref())} = {ref};"
  859. def _get_vars_hooks(self) -> set[str]:
  860. """Get the hooks required by vars referenced in this component.
  861. Returns:
  862. The hooks for the vars.
  863. """
  864. vars_hooks = set()
  865. for var in self._get_vars():
  866. if var._var_data:
  867. vars_hooks.update(var._var_data.hooks)
  868. return vars_hooks
  869. def _get_events_hooks(self) -> set[str]:
  870. """Get the hooks required by events referenced in this component.
  871. Returns:
  872. The hooks for the events.
  873. """
  874. if self.event_triggers:
  875. return {Hooks.EVENTS}
  876. return set()
  877. def _get_special_hooks(self) -> set[str]:
  878. """Get the hooks required by special actions referenced in this component.
  879. Returns:
  880. The hooks for special actions.
  881. """
  882. if self.autofocus:
  883. return {
  884. """
  885. // Set focus to the specified element.
  886. const focusRef = useRef(null)
  887. useEffect(() => {
  888. if (focusRef.current) {
  889. focusRef.current.focus();
  890. }
  891. })""",
  892. }
  893. return set()
  894. def _get_hooks_internal(self) -> Set[str]:
  895. """Get the React hooks for this component managed by the framework.
  896. Downstream components should NOT override this method to avoid breaking
  897. framework functionality.
  898. Returns:
  899. Set of internally managed hooks.
  900. """
  901. return (
  902. set(
  903. hook
  904. for hook in [self._get_mount_lifecycle_hook(), self._get_ref_hook()]
  905. if hook
  906. )
  907. | self._get_vars_hooks()
  908. | self._get_events_hooks()
  909. | self._get_special_hooks()
  910. )
  911. def _get_hooks(self) -> str | None:
  912. """Get the React hooks for this component.
  913. Downstream components should override this method to add their own hooks.
  914. Returns:
  915. The hooks for just this component.
  916. """
  917. return
  918. def get_hooks(self) -> Set[str]:
  919. """Get the React hooks for this component and its children.
  920. Returns:
  921. The code that should appear just before returning the rendered component.
  922. """
  923. # Store the code in a set to avoid duplicates.
  924. code = self._get_hooks_internal()
  925. # Add the hook code for this component.
  926. hooks = self._get_hooks()
  927. if hooks is not None:
  928. code.add(hooks)
  929. # Add the hook code for the children.
  930. for child in self.children:
  931. code |= child.get_hooks()
  932. return code
  933. def get_ref(self) -> str | None:
  934. """Get the name of the ref for the component.
  935. Returns:
  936. The ref name.
  937. """
  938. # do not create a ref if the id is dynamic or unspecified
  939. if self.id is None or isinstance(self.id, BaseVar):
  940. return None
  941. return format.format_ref(self.id)
  942. def get_refs(self) -> Set[str]:
  943. """Get the refs for the children of the component.
  944. Returns:
  945. The refs for the children.
  946. """
  947. refs = set()
  948. ref = self.get_ref()
  949. if ref is not None:
  950. refs.add(ref)
  951. for child in self.children:
  952. refs |= child.get_refs()
  953. return refs
  954. def get_custom_components(
  955. self, seen: set[str] | None = None
  956. ) -> Set[CustomComponent]:
  957. """Get all the custom components used by the component.
  958. Args:
  959. seen: The tags of the components that have already been seen.
  960. Returns:
  961. The set of custom components.
  962. """
  963. custom_components = set()
  964. # Store the seen components in a set to avoid infinite recursion.
  965. if seen is None:
  966. seen = set()
  967. for child in self.children:
  968. # Skip BaseComponent and StatefulComponent children.
  969. if not isinstance(child, Component):
  970. continue
  971. custom_components |= child.get_custom_components(seen=seen)
  972. return custom_components
  973. @property
  974. def import_var(self):
  975. """The tag to import.
  976. Returns:
  977. An import var.
  978. """
  979. # If the tag is dot-qualified, only import the left-most name.
  980. tag = self.tag.partition(".")[0] if self.tag else None
  981. alias = self.alias.partition(".")[0] if self.alias else None
  982. return ImportVar(tag=tag, is_default=self.is_default, alias=alias)
  983. @staticmethod
  984. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  985. """Get the app wrap components for the component.
  986. Returns:
  987. The app wrap components.
  988. """
  989. return {}
  990. def get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  991. """Get the app wrap components for the component and its children.
  992. Returns:
  993. The app wrap components.
  994. """
  995. # Store the components in a set to avoid duplicates.
  996. components = self._get_app_wrap_components()
  997. for component in tuple(components.values()):
  998. components.update(component.get_app_wrap_components())
  999. # Add the app wrap components for the children.
  1000. for child in self.children:
  1001. # Skip BaseComponent and StatefulComponent children.
  1002. if not isinstance(child, Component):
  1003. continue
  1004. components.update(child.get_app_wrap_components())
  1005. # Return the components.
  1006. return components
  1007. class CustomComponent(Component):
  1008. """A custom user-defined component."""
  1009. # Use the components library.
  1010. library = f"/{Dirs.COMPONENTS_PATH}"
  1011. # The function that creates the component.
  1012. component_fn: Callable[..., Component] = Component.create
  1013. # The props of the component.
  1014. props: Dict[str, Any] = {}
  1015. def __init__(self, *args, **kwargs):
  1016. """Initialize the custom component.
  1017. Args:
  1018. *args: The args to pass to the component.
  1019. **kwargs: The kwargs to pass to the component.
  1020. """
  1021. super().__init__(*args, **kwargs)
  1022. # Unset the style.
  1023. self.style = Style()
  1024. # Set the tag to the name of the function.
  1025. self.tag = format.to_title_case(self.component_fn.__name__)
  1026. # Set the props.
  1027. props = typing.get_type_hints(self.component_fn)
  1028. for key, value in kwargs.items():
  1029. # Skip kwargs that are not props.
  1030. if key not in props:
  1031. continue
  1032. # Get the type based on the annotation.
  1033. type_ = props[key]
  1034. # Handle event chains.
  1035. if types._issubclass(type_, EventChain):
  1036. value = self._create_event_chain(key, value)
  1037. self.props[format.to_camel_case(key)] = value
  1038. continue
  1039. # Convert the type to a Var, then get the type of the var.
  1040. if not types._issubclass(type_, Var):
  1041. type_ = Var[type_]
  1042. type_ = types.get_args(type_)[0]
  1043. # Handle subclasses of Base.
  1044. if types._issubclass(type_, Base):
  1045. try:
  1046. value = BaseVar(
  1047. _var_name=value.json(), _var_type=type_, _var_is_local=True
  1048. )
  1049. except Exception:
  1050. value = Var.create(value)
  1051. else:
  1052. value = Var.create(value, _var_is_string=type(value) is str)
  1053. # Set the prop.
  1054. self.props[format.to_camel_case(key)] = value
  1055. def __eq__(self, other: Any) -> bool:
  1056. """Check if the component is equal to another.
  1057. Args:
  1058. other: The other component.
  1059. Returns:
  1060. Whether the component is equal to the other.
  1061. """
  1062. return isinstance(other, CustomComponent) and self.tag == other.tag
  1063. def __hash__(self) -> int:
  1064. """Get the hash of the component.
  1065. Returns:
  1066. The hash of the component.
  1067. """
  1068. return hash(self.tag)
  1069. @classmethod
  1070. def get_props(cls) -> Set[str]:
  1071. """Get the props for the component.
  1072. Returns:
  1073. The set of component props.
  1074. """
  1075. return set()
  1076. def get_custom_components(
  1077. self, seen: set[str] | None = None
  1078. ) -> Set[CustomComponent]:
  1079. """Get all the custom components used by the component.
  1080. Args:
  1081. seen: The tags of the components that have already been seen.
  1082. Returns:
  1083. The set of custom components.
  1084. """
  1085. assert self.tag is not None, "The tag must be set."
  1086. # Store the seen components in a set to avoid infinite recursion.
  1087. if seen is None:
  1088. seen = set()
  1089. custom_components = {self} | super().get_custom_components(seen=seen)
  1090. # Avoid adding the same component twice.
  1091. if self.tag not in seen:
  1092. seen.add(self.tag)
  1093. custom_components |= self.get_component(self).get_custom_components(
  1094. seen=seen
  1095. )
  1096. return custom_components
  1097. def _render(self) -> Tag:
  1098. """Define how to render the component in React.
  1099. Returns:
  1100. The tag to render.
  1101. """
  1102. return super()._render(props=self.props)
  1103. def get_prop_vars(self) -> List[BaseVar]:
  1104. """Get the prop vars.
  1105. Returns:
  1106. The prop vars.
  1107. """
  1108. return [
  1109. BaseVar(
  1110. _var_name=name,
  1111. _var_type=prop._var_type
  1112. if types._isinstance(prop, Var)
  1113. else type(prop),
  1114. )
  1115. for name, prop in self.props.items()
  1116. ]
  1117. @lru_cache(maxsize=None) # noqa
  1118. def get_component(self) -> Component:
  1119. """Render the component.
  1120. Returns:
  1121. The code to render the component.
  1122. """
  1123. return self.component_fn(*self.get_prop_vars())
  1124. def custom_component(
  1125. component_fn: Callable[..., Component]
  1126. ) -> Callable[..., CustomComponent]:
  1127. """Create a custom component from a function.
  1128. Args:
  1129. component_fn: The function that creates the component.
  1130. Returns:
  1131. The decorated function.
  1132. """
  1133. @wraps(component_fn)
  1134. def wrapper(*children, **props) -> CustomComponent:
  1135. # Remove the children from the props.
  1136. props.pop("children", None)
  1137. return CustomComponent(component_fn=component_fn, children=children, **props)
  1138. return wrapper
  1139. # Alias memo to custom_component.
  1140. memo = custom_component
  1141. class NoSSRComponent(Component):
  1142. """A dynamic component that is not rendered on the server."""
  1143. def _get_imports(self) -> imports.ImportDict:
  1144. """Get the imports for the component.
  1145. Returns:
  1146. The imports for dynamically importing the component at module load time.
  1147. """
  1148. # Next.js dynamic import mechanism.
  1149. dynamic_import = {"next/dynamic": [ImportVar(tag="dynamic", is_default=True)]}
  1150. # The normal imports for this component.
  1151. _imports = super()._get_imports()
  1152. # Do NOT import the main library/tag statically.
  1153. if self.library is not None:
  1154. _imports[self.library] = [imports.ImportVar(tag=None, render=False)]
  1155. return imports.merge_imports(
  1156. dynamic_import,
  1157. _imports,
  1158. self._get_dependencies_imports(),
  1159. )
  1160. def _get_dynamic_imports(self) -> str:
  1161. opts_fragment = ", { ssr: false });"
  1162. # extract the correct import name from library name
  1163. if self.library is None:
  1164. raise ValueError("Undefined library for NoSSRComponent")
  1165. import_name_parts = [p for p in self.library.rpartition("@") if p != ""]
  1166. import_name = (
  1167. import_name_parts[0] if import_name_parts[0] != "@" else self.library
  1168. )
  1169. library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
  1170. mod_import = (
  1171. # https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
  1172. f".then((mod) => mod.{self.tag})"
  1173. if not self.is_default
  1174. else ""
  1175. )
  1176. return "".join((library_import, mod_import, opts_fragment))
  1177. @serializer
  1178. def serialize_component(comp: Component):
  1179. """Serialize a component.
  1180. Args:
  1181. comp: The component to serialize.
  1182. Returns:
  1183. The serialized component.
  1184. """
  1185. return str(comp)
  1186. class StatefulComponent(BaseComponent):
  1187. """A component that depends on state and is rendered outside of the page component.
  1188. If a StatefulComponent is used in multiple pages, it will be rendered to a common file and
  1189. imported into each page that uses it.
  1190. A stateful component has a tag name that includes a hash of the code that it renders
  1191. to. This tag name refers to the specific component with the specific props that it
  1192. was created with.
  1193. """
  1194. # A lookup table to caching memoized component instances.
  1195. tag_to_stateful_component: ClassVar[Dict[str, StatefulComponent]] = {}
  1196. # Reference to the original component that was memoized into this component.
  1197. component: Component
  1198. # The rendered (memoized) code that will be emitted.
  1199. code: str
  1200. # How many times this component is referenced in the app.
  1201. references: int = 0
  1202. # Whether the component has already been rendered to a shared file.
  1203. rendered_as_shared: bool = False
  1204. @classmethod
  1205. def create(cls, component: Component) -> StatefulComponent | None:
  1206. """Create a stateful component from a component.
  1207. Args:
  1208. component: The component to memoize.
  1209. Returns:
  1210. The stateful component or None if the component should not be memoized.
  1211. """
  1212. from reflex.components.core.foreach import Foreach
  1213. if component._memoization_mode.disposition == MemoizationDisposition.NEVER:
  1214. # Never memoize this component.
  1215. return None
  1216. if component.tag is None:
  1217. # Only memoize components with a tag.
  1218. return None
  1219. # If _var_data is found in this component, it is a candidate for auto-memoization.
  1220. should_memoize = False
  1221. # If the component requests to be memoized, then ignore other checks.
  1222. if component._memoization_mode.disposition == MemoizationDisposition.ALWAYS:
  1223. should_memoize = True
  1224. if not should_memoize:
  1225. # Determine if any Vars have associated data.
  1226. for prop_var in component._get_vars():
  1227. if prop_var._var_data:
  1228. should_memoize = True
  1229. break
  1230. if not should_memoize:
  1231. # Check for special-cases in child components.
  1232. for child in component.children:
  1233. # Skip BaseComponent and StatefulComponent children.
  1234. if not isinstance(child, Component):
  1235. continue
  1236. # Always consider Foreach something that must be memoized by the parent.
  1237. if isinstance(child, Foreach):
  1238. should_memoize = True
  1239. break
  1240. child = cls._child_var(child)
  1241. if isinstance(child, Var) and child._var_data:
  1242. should_memoize = True
  1243. break
  1244. if should_memoize or component.event_triggers:
  1245. # Render the component to determine tag+hash based on component code.
  1246. tag_name = cls._get_tag_name(component)
  1247. if tag_name is None:
  1248. return None
  1249. # Look up the tag in the cache
  1250. stateful_component = cls.tag_to_stateful_component.get(tag_name)
  1251. if stateful_component is None:
  1252. # Render the component as a string of javascript code.
  1253. code = cls._render_stateful_code(component, tag_name=tag_name)
  1254. # Set the stateful component in the cache for the given tag.
  1255. stateful_component = cls.tag_to_stateful_component.setdefault(
  1256. tag_name,
  1257. cls(
  1258. children=component.children,
  1259. component=component,
  1260. tag=tag_name,
  1261. code=code,
  1262. ),
  1263. )
  1264. # Bump the reference count -- multiple pages referencing the same component
  1265. # will result in writing it to a common file.
  1266. stateful_component.references += 1
  1267. return stateful_component
  1268. # Return None to indicate this component should not be memoized.
  1269. return None
  1270. @staticmethod
  1271. def _child_var(child: Component) -> Var | Component:
  1272. """Get the Var from a child component.
  1273. This method is used for special cases when the StatefulComponent should actually
  1274. wrap the parent component of the child instead of recursing into the children
  1275. and memoizing them independently.
  1276. Args:
  1277. child: The child component.
  1278. Returns:
  1279. The Var from the child component or the child itself (for regular cases).
  1280. """
  1281. from reflex.components.base.bare import Bare
  1282. from reflex.components.core.cond import Cond
  1283. from reflex.components.core.foreach import Foreach
  1284. if isinstance(child, Bare):
  1285. return child.contents
  1286. if isinstance(child, Cond):
  1287. return child.cond
  1288. if isinstance(child, Foreach):
  1289. return child.iterable
  1290. return child
  1291. @classmethod
  1292. def _get_tag_name(cls, component: Component) -> str | None:
  1293. """Get the tag based on rendering the given component.
  1294. Args:
  1295. component: The component to render.
  1296. Returns:
  1297. The tag for the stateful component.
  1298. """
  1299. # Get the render dict for the component.
  1300. rendered_code = component.render()
  1301. if not rendered_code:
  1302. # Never memoize non-visual components.
  1303. return None
  1304. # Compute the hash based on the rendered code.
  1305. code_hash = md5(str(rendered_code).encode("utf-8")).hexdigest()
  1306. # Format the tag name including the hash.
  1307. return format.format_state_name(
  1308. f"{component.tag or 'Comp'}_{code_hash}"
  1309. ).capitalize()
  1310. @classmethod
  1311. def _render_stateful_code(
  1312. cls,
  1313. component: Component,
  1314. tag_name: str,
  1315. ) -> str:
  1316. """Render the code for a stateful component.
  1317. Args:
  1318. component: The component to render.
  1319. tag_name: The tag name for the stateful component (see _get_tag_name).
  1320. Returns:
  1321. The rendered code.
  1322. """
  1323. # Memoize event triggers useCallback to avoid unnecessary re-renders.
  1324. memo_event_triggers = tuple(cls._get_memoized_event_triggers(component).items())
  1325. # Trigger hooks stored separately to write after the normal hooks (see stateful_component.js.jinja2)
  1326. memo_trigger_hooks = []
  1327. if memo_event_triggers:
  1328. # Copy the component to avoid mutating the original.
  1329. component = copy.copy(component)
  1330. for event_trigger, (
  1331. memo_trigger,
  1332. memo_trigger_hook,
  1333. ) in memo_event_triggers:
  1334. # Replace the event trigger with the memoized version.
  1335. memo_trigger_hooks.append(memo_trigger_hook)
  1336. component.event_triggers[event_trigger] = memo_trigger
  1337. # Render the code for this component and hooks.
  1338. return STATEFUL_COMPONENT.render(
  1339. tag_name=tag_name,
  1340. memo_trigger_hooks=memo_trigger_hooks,
  1341. component=component,
  1342. )
  1343. @staticmethod
  1344. def _get_hook_deps(hook: str) -> list[str]:
  1345. """Extract var deps from a hook.
  1346. Args:
  1347. hook: The hook line to extract deps from.
  1348. Returns:
  1349. A list of var names created by the hook declaration.
  1350. """
  1351. var_name = hook.partition("=")[0].strip().split(None, 1)[1].strip()
  1352. if var_name.startswith("["):
  1353. # Break up array destructuring.
  1354. return [v.strip() for v in var_name.strip("[]").split(",")]
  1355. return [var_name]
  1356. @classmethod
  1357. def _get_memoized_event_triggers(
  1358. cls,
  1359. component: Component,
  1360. ) -> dict[str, tuple[Var, str]]:
  1361. """Memoize event handler functions with useCallback to avoid unnecessary re-renders.
  1362. Args:
  1363. component: The component with events to memoize.
  1364. Returns:
  1365. A dict of event trigger name to a tuple of the memoized event trigger Var and
  1366. the hook code that memoizes the event handler.
  1367. """
  1368. trigger_memo = {}
  1369. for event_trigger, event_args in component._get_vars_from_event_triggers(
  1370. component.event_triggers
  1371. ):
  1372. if event_trigger in {
  1373. EventTriggers.ON_MOUNT,
  1374. EventTriggers.ON_UNMOUNT,
  1375. EventTriggers.ON_SUBMIT,
  1376. }:
  1377. # Do not memoize lifecycle or submit events.
  1378. continue
  1379. # Get the actual EventSpec and render it.
  1380. event = component.event_triggers[event_trigger]
  1381. rendered_chain = format.format_prop(event)
  1382. if isinstance(rendered_chain, str):
  1383. rendered_chain = rendered_chain.strip("{}")
  1384. # Hash the rendered EventChain to get a deterministic function name.
  1385. chain_hash = md5(str(rendered_chain).encode("utf-8")).hexdigest()
  1386. memo_name = f"{event_trigger}_{chain_hash}"
  1387. # Calculate Var dependencies accessed by the handler for useCallback dep array.
  1388. var_deps = ["addEvents", "Event"]
  1389. for arg in event_args:
  1390. if arg._var_data is None:
  1391. continue
  1392. for hook in arg._var_data.hooks:
  1393. var_deps.extend(cls._get_hook_deps(hook))
  1394. memo_var_data = VarData.merge(
  1395. *[var._var_data for var in event_args],
  1396. VarData( # type: ignore
  1397. imports={"react": {ImportVar(tag="useCallback")}},
  1398. ),
  1399. )
  1400. # Store the memoized function name and hook code for this event trigger.
  1401. trigger_memo[event_trigger] = (
  1402. Var.create_safe(memo_name)._replace(
  1403. _var_type=EventChain, merge_var_data=memo_var_data
  1404. ),
  1405. f"const {memo_name} = useCallback({rendered_chain}, [{', '.join(var_deps)}])",
  1406. )
  1407. return trigger_memo
  1408. def get_hooks(self) -> set[str]:
  1409. """Get the React hooks for this component.
  1410. Returns:
  1411. The code that should appear just before returning the rendered component.
  1412. """
  1413. return set()
  1414. def get_imports(self) -> imports.ImportDict:
  1415. """Get all the libraries and fields that are used by the component.
  1416. Returns:
  1417. The import dict with the required imports.
  1418. """
  1419. if self.rendered_as_shared:
  1420. return {
  1421. f"/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
  1422. ImportVar(tag=self.tag)
  1423. ]
  1424. }
  1425. return self.component.get_imports()
  1426. def get_dynamic_imports(self) -> set[str]:
  1427. """Get dynamic imports for the component.
  1428. Returns:
  1429. The dynamic imports.
  1430. """
  1431. if self.rendered_as_shared:
  1432. return set()
  1433. return self.component.get_dynamic_imports()
  1434. def get_custom_code(self) -> set[str]:
  1435. """Get custom code for the component.
  1436. Returns:
  1437. The custom code.
  1438. """
  1439. if self.rendered_as_shared:
  1440. return set()
  1441. return self.component.get_custom_code().union({self.code})
  1442. def get_refs(self) -> set[str]:
  1443. """Get the refs for the children of the component.
  1444. Returns:
  1445. The refs for the children.
  1446. """
  1447. if self.rendered_as_shared:
  1448. return set()
  1449. return self.component.get_refs()
  1450. def render(self) -> dict:
  1451. """Define how to render the component in React.
  1452. Returns:
  1453. The tag to render.
  1454. """
  1455. return dict(Tag(name=self.tag))
  1456. @classmethod
  1457. def compile_from(cls, component: BaseComponent) -> BaseComponent:
  1458. """Walk through the component tree and memoize all stateful components.
  1459. Args:
  1460. component: The component to memoize.
  1461. Returns:
  1462. The memoized component tree.
  1463. """
  1464. if isinstance(component, Component):
  1465. if component._memoization_mode.recursive:
  1466. # Recursively memoize stateful children (default).
  1467. component.children = [
  1468. cls.compile_from(child) for child in component.children
  1469. ]
  1470. # Memoize this component if it depends on state.
  1471. stateful_component = cls.create(component)
  1472. if stateful_component is not None:
  1473. return stateful_component
  1474. return component
  1475. class MemoizationLeaf(Component):
  1476. """A component that does not separately memoize its children.
  1477. Any component which depends on finding the exact names of children
  1478. components within it, should be a memoization leaf so the compiler
  1479. does not replace the provided child tags with memoized tags.
  1480. During creation, a memoization leaf will mark itself as wanting to be
  1481. memoized if any of its children return any hooks.
  1482. """
  1483. _memoization_mode = MemoizationMode(recursive=False)
  1484. @classmethod
  1485. def create(cls, *children, **props) -> Component:
  1486. """Create a new memoization leaf component.
  1487. Args:
  1488. *children: The children of the component.
  1489. **props: The props of the component.
  1490. Returns:
  1491. The memoization leaf
  1492. """
  1493. comp = super().create(*children, **props)
  1494. if comp.get_hooks():
  1495. comp._memoization_mode = cls._memoization_mode.copy(
  1496. update={"disposition": MemoizationDisposition.ALWAYS}
  1497. )
  1498. return comp