component.py 60 KB

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