component.py 60 KB

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