component.py 65 KB

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