component.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  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.core.breakpoints import Breakpoints
  25. from reflex.components.dynamic import load_dynamic_serializer
  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.constants.compiler import SpecialAttributes
  37. from reflex.event import (
  38. EventCallback,
  39. EventChain,
  40. EventChainVar,
  41. EventHandler,
  42. EventSpec,
  43. EventVar,
  44. call_event_fn,
  45. call_event_handler,
  46. empty_event,
  47. get_handler_args,
  48. )
  49. from reflex.style import Style, format_as_emotion
  50. from reflex.utils import format, imports, types
  51. from reflex.utils.imports import (
  52. ImmutableParsedImportDict,
  53. ImportDict,
  54. ImportVar,
  55. ParsedImportDict,
  56. parse_imports,
  57. )
  58. from reflex.vars import VarData
  59. from reflex.vars.base import LiteralVar, Var
  60. from reflex.vars.sequence import LiteralArrayVar
  61. class BaseComponent(Base, ABC):
  62. """The base class for all Reflex components.
  63. This is something that can be rendered as a Component via the Reflex compiler.
  64. """
  65. # The children nested within the component.
  66. children: List[BaseComponent] = []
  67. # The library that the component is based on.
  68. library: Optional[str] = None
  69. # List here the non-react dependency needed by `library`
  70. lib_dependencies: List[str] = []
  71. # List here the dependencies that need to be transpiled by Next.js
  72. transpile_packages: List[str] = []
  73. # The tag to use when rendering the component.
  74. tag: Optional[str] = None
  75. @abstractmethod
  76. def render(self) -> dict:
  77. """Render the component.
  78. Returns:
  79. The dictionary for template of the component.
  80. """
  81. @abstractmethod
  82. def _get_all_hooks_internal(self) -> dict[str, None]:
  83. """Get the reflex internal hooks for the component and its children.
  84. Returns:
  85. The code that should appear just before user-defined hooks.
  86. """
  87. @abstractmethod
  88. def _get_all_hooks(self) -> dict[str, None]:
  89. """Get the React hooks for this component.
  90. Returns:
  91. The code that should appear just before returning the rendered component.
  92. """
  93. @abstractmethod
  94. def _get_all_imports(self) -> ParsedImportDict:
  95. """Get all the libraries and fields that are used by the component.
  96. Returns:
  97. The import dict with the required imports.
  98. """
  99. @abstractmethod
  100. def _get_all_dynamic_imports(self) -> set[str]:
  101. """Get dynamic imports for the component.
  102. Returns:
  103. The dynamic imports.
  104. """
  105. @abstractmethod
  106. def _get_all_custom_code(self) -> set[str]:
  107. """Get custom code for the component.
  108. Returns:
  109. The custom code.
  110. """
  111. @abstractmethod
  112. def _get_all_refs(self) -> set[str]:
  113. """Get the refs for the children of the component.
  114. Returns:
  115. The refs for the children.
  116. """
  117. class ComponentNamespace(SimpleNamespace):
  118. """A namespace to manage components with subcomponents."""
  119. def __hash__(self) -> int:
  120. """Get the hash of the namespace.
  121. Returns:
  122. The hash of the namespace.
  123. """
  124. return hash(self.__class__.__name__)
  125. def evaluate_style_namespaces(style: ComponentStyle) -> dict:
  126. """Evaluate namespaces in the style.
  127. Args:
  128. style: The style to evaluate.
  129. Returns:
  130. The evaluated style.
  131. """
  132. return {
  133. k.__call__ if isinstance(k, ComponentNamespace) else k: v
  134. for k, v in style.items()
  135. }
  136. # Map from component to styling.
  137. ComponentStyle = Dict[
  138. Union[str, Type[BaseComponent], Callable, ComponentNamespace], Any
  139. ]
  140. ComponentChild = Union[types.PrimitiveType, Var, BaseComponent]
  141. class Component(BaseComponent, ABC):
  142. """A component with style, event trigger and other props."""
  143. # The style of the component.
  144. style: Style = Style()
  145. # A mapping from event triggers to event chains.
  146. event_triggers: Dict[str, Union[EventChain, Var]] = {}
  147. # The alias for the tag.
  148. alias: Optional[str] = None
  149. # Whether the import is default or named.
  150. is_default: Optional[bool] = False
  151. # A unique key for the component.
  152. key: Any = None
  153. # The id for the component.
  154. id: Any = None
  155. # The class name for the component.
  156. class_name: Any = None
  157. # Special component props.
  158. special_props: List[Var] = []
  159. # Whether the component should take the focus once the page is loaded
  160. autofocus: bool = False
  161. # components that cannot be children
  162. _invalid_children: List[str] = []
  163. # only components that are allowed as children
  164. _valid_children: List[str] = []
  165. # only components that are allowed as parent
  166. _valid_parents: List[str] = []
  167. # props to change the name of
  168. _rename_props: Dict[str, str] = {}
  169. # custom attribute
  170. custom_attrs: Dict[str, Union[Var, str]] = {}
  171. # When to memoize this component and its children.
  172. _memoization_mode: MemoizationMode = MemoizationMode()
  173. # State class associated with this component instance
  174. State: Optional[Type[reflex.state.State]] = None
  175. def add_imports(self) -> ImportDict | list[ImportDict]:
  176. """Add imports for the component.
  177. This method should be implemented by subclasses to add new imports for the component.
  178. Implementations do NOT need to call super(). The result of calling
  179. add_imports in each parent class will be merged internally.
  180. Returns:
  181. The additional imports for this component subclass.
  182. The format of the return value is a dictionary where the keys are the
  183. library names (with optional npm-style version specifications) mapping
  184. to a single name to be imported, or a list names to be imported.
  185. For advanced use cases, the values can be ImportVar instances (for
  186. example, to provide an alias or mark that an import is the default
  187. export from the given library).
  188. ```python
  189. return {
  190. "react": "useEffect",
  191. "react-draggable": ["DraggableCore", rx.ImportVar(tag="Draggable", is_default=True)],
  192. }
  193. ```
  194. """
  195. return {}
  196. def add_hooks(self) -> list[str | Var]:
  197. """Add hooks inside the component function.
  198. Hooks are pieces of literal Javascript code that is inserted inside the
  199. React component function.
  200. Each logical hook should be a separate string in the list.
  201. Common strings will be deduplicated and inserted into the component
  202. function only once, so define const variables and other identical code
  203. in their own strings to avoid defining the same const or hook multiple
  204. times.
  205. If a hook depends on specific data from the component instance, be sure
  206. to use unique values inside the string to _avoid_ deduplication.
  207. Implementations do NOT need to call super(). The result of calling
  208. add_hooks in each parent class will be merged and deduplicated internally.
  209. Returns:
  210. The additional hooks for this component subclass.
  211. ```python
  212. return [
  213. "const [count, setCount] = useState(0);",
  214. "useEffect(() => { setCount((prev) => prev + 1); console.log(`mounted ${count} times`); }, []);",
  215. ]
  216. ```
  217. """
  218. return []
  219. def add_custom_code(self) -> list[str]:
  220. """Add custom Javascript code into the page that contains this component.
  221. Custom code is inserted at module level, after any imports.
  222. Each string of custom code is deduplicated per-page, so take care to
  223. avoid defining the same const or function differently from different
  224. component instances.
  225. Custom code is useful for defining global functions or constants which
  226. can then be referenced inside hooks or used by component vars.
  227. Implementations do NOT need to call super(). The result of calling
  228. add_custom_code in each parent class will be merged and deduplicated internally.
  229. Returns:
  230. The additional custom code for this component subclass.
  231. ```python
  232. return [
  233. "const translatePoints = (event) => { return { x: event.clientX, y: event.clientY }; };",
  234. ]
  235. ```
  236. """
  237. return []
  238. @classmethod
  239. def __init_subclass__(cls, **kwargs):
  240. """Set default properties.
  241. Args:
  242. **kwargs: The kwargs to pass to the superclass.
  243. """
  244. super().__init_subclass__(**kwargs)
  245. # Get all the props for the component.
  246. props = cls.get_props()
  247. # Convert fields to props, setting default values.
  248. for field in cls.get_fields().values():
  249. # If the field is not a component prop, skip it.
  250. if field.name not in props:
  251. continue
  252. # Set default values for any props.
  253. if types._issubclass(field.type_, Var):
  254. field.required = False
  255. if field.default is not None:
  256. field.default = LiteralVar.create(field.default)
  257. elif types._issubclass(field.type_, EventHandler):
  258. field.required = False
  259. # Ensure renamed props from parent classes are applied to the subclass.
  260. if cls._rename_props:
  261. inherited_rename_props = {}
  262. for parent in reversed(cls.mro()):
  263. if issubclass(parent, Component) and parent._rename_props:
  264. inherited_rename_props.update(parent._rename_props)
  265. cls._rename_props = inherited_rename_props
  266. def __init__(self, *args, **kwargs):
  267. """Initialize the component.
  268. Args:
  269. *args: Args to initialize the component.
  270. **kwargs: Kwargs to initialize the component.
  271. Raises:
  272. TypeError: If an invalid prop is passed.
  273. ValueError: If an event trigger passed is not valid.
  274. """
  275. # Set the id and children initially.
  276. children = kwargs.get("children", [])
  277. initial_kwargs = {
  278. "id": kwargs.get("id"),
  279. "children": children,
  280. **{
  281. prop: LiteralVar.create(kwargs[prop])
  282. for prop in self.get_initial_props()
  283. if prop in kwargs
  284. },
  285. }
  286. super().__init__(**initial_kwargs)
  287. self._validate_component_children(children)
  288. # Get the component fields, triggers, and props.
  289. fields = self.get_fields()
  290. component_specific_triggers = self.get_event_triggers()
  291. props = self.get_props()
  292. # Add any events triggers.
  293. if "event_triggers" not in kwargs:
  294. kwargs["event_triggers"] = {}
  295. kwargs["event_triggers"] = kwargs["event_triggers"].copy()
  296. # Iterate through the kwargs and set the props.
  297. for key, value in kwargs.items():
  298. if (
  299. key.startswith("on_")
  300. and key not in component_specific_triggers
  301. and key not in props
  302. ):
  303. raise ValueError(
  304. f"The {(comp_name := type(self).__name__)} does not take in an `{key}` event trigger. If {comp_name}"
  305. f" is a third party component make sure to add `{key}` to the component's event triggers. "
  306. f"visit https://reflex.dev/docs/wrapping-react/guide/#event-triggers for more info."
  307. )
  308. if key in component_specific_triggers:
  309. # Event triggers are bound to event chains.
  310. field_type = EventChain
  311. elif key in props:
  312. # Set the field type.
  313. field_type = fields[key].type_
  314. else:
  315. continue
  316. # Check whether the key is a component prop.
  317. if types._issubclass(field_type, Var):
  318. # Used to store the passed types if var type is a union.
  319. passed_types = None
  320. try:
  321. # Try to create a var from the value.
  322. if isinstance(value, Var):
  323. kwargs[key] = value
  324. else:
  325. kwargs[key] = LiteralVar.create(value)
  326. # Check that the var type is not None.
  327. if kwargs[key] is None:
  328. raise TypeError
  329. expected_type = fields[key].outer_type_.__args__[0]
  330. # validate literal fields.
  331. types.validate_literal(
  332. key, value, expected_type, type(self).__name__
  333. )
  334. # Get the passed type and the var type.
  335. passed_type = kwargs[key]._var_type
  336. expected_type = (
  337. type(expected_type.__args__[0])
  338. if types.is_literal(expected_type)
  339. else expected_type
  340. )
  341. except TypeError:
  342. # If it is not a valid var, check the base types.
  343. passed_type = type(value)
  344. expected_type = fields[key].outer_type_
  345. if types.is_union(passed_type):
  346. # We need to check all possible types in the union.
  347. passed_types = (
  348. arg
  349. for arg in passed_type.__args__ # type: ignore
  350. if arg is not type(None)
  351. )
  352. if (
  353. # If the passed var is a union, check if all possible types are valid.
  354. passed_types
  355. and not all(
  356. types._issubclass(pt, expected_type) for pt in passed_types
  357. )
  358. ) or (
  359. # Else just check if the passed var type is valid.
  360. not passed_types
  361. and not types._issubclass(passed_type, expected_type, value)
  362. ):
  363. value_name = value._js_expr if isinstance(value, Var) else value
  364. additional_info = (
  365. " You can call `.bool()` on the value to convert it to a boolean."
  366. if expected_type is bool and isinstance(value, Var)
  367. else ""
  368. )
  369. raise TypeError(
  370. f"Invalid var passed for prop {type(self).__name__}.{key}, expected type {expected_type}, got value {value_name} of type {passed_type}."
  371. + additional_info
  372. )
  373. # Check if the key is an event trigger.
  374. if key in component_specific_triggers:
  375. # Temporarily disable full control for event triggers.
  376. kwargs["event_triggers"][key] = self._create_event_chain(
  377. value=value, # type: ignore
  378. args_spec=component_specific_triggers[key],
  379. )
  380. # Remove any keys that were added as events.
  381. for key in kwargs["event_triggers"]:
  382. del kwargs[key]
  383. # Place data_ and aria_ attributes into custom_attrs
  384. special_attributes = tuple(
  385. key
  386. for key in kwargs
  387. if key not in fields and SpecialAttributes.is_special(key)
  388. )
  389. if special_attributes:
  390. custom_attrs = kwargs.setdefault("custom_attrs", {})
  391. for key in special_attributes:
  392. custom_attrs[format.to_kebab_case(key)] = kwargs.pop(key)
  393. # Add style props to the component.
  394. style = kwargs.get("style", {})
  395. if isinstance(style, List):
  396. # Merge styles, the later ones overriding keys in the earlier ones.
  397. style = {k: v for style_dict in style for k, v in style_dict.items()}
  398. if isinstance(style, (Breakpoints, Var)):
  399. style = {
  400. # Assign the Breakpoints to the self-referential selector to avoid squashing down to a regular dict.
  401. "&": style,
  402. }
  403. kwargs["style"] = Style(
  404. {
  405. **self.get_fields()["style"].default,
  406. **style,
  407. **{attr: value for attr, value in kwargs.items() if attr not in fields},
  408. }
  409. )
  410. # Convert class_name to str if it's list
  411. class_name = kwargs.get("class_name", "")
  412. if isinstance(class_name, (List, tuple)):
  413. if any(isinstance(c, Var) for c in class_name):
  414. kwargs["class_name"] = LiteralArrayVar.create(
  415. class_name, _var_type=List[str]
  416. ).join(" ")
  417. else:
  418. kwargs["class_name"] = " ".join(class_name)
  419. # Construct the component.
  420. super().__init__(*args, **kwargs)
  421. def _create_event_chain(
  422. self,
  423. args_spec: Any,
  424. value: Union[
  425. Var,
  426. EventHandler,
  427. EventSpec,
  428. List[Union[EventHandler, EventSpec, EventVar]],
  429. Callable,
  430. ],
  431. ) -> Union[EventChain, Var]:
  432. """Create an event chain from a variety of input types.
  433. Args:
  434. args_spec: The args_spec of the event trigger being bound.
  435. value: The value to create the event chain from.
  436. Returns:
  437. The event chain.
  438. Raises:
  439. ValueError: If the value is not a valid event chain.
  440. """
  441. # If it's an event chain var, return it.
  442. if isinstance(value, Var):
  443. if isinstance(value, EventChainVar):
  444. return value
  445. elif isinstance(value, EventVar):
  446. value = [value]
  447. elif issubclass(value._var_type, (EventChain, EventSpec)):
  448. return self._create_event_chain(args_spec, value.guess_type())
  449. else:
  450. raise ValueError(
  451. f"Invalid event chain: {str(value)} of type {value._var_type}"
  452. )
  453. elif isinstance(value, EventChain):
  454. # Trust that the caller knows what they're doing passing an EventChain directly
  455. return value
  456. # If the input is a single event handler, wrap it in a list.
  457. if isinstance(value, (EventHandler, EventSpec)):
  458. value = [value]
  459. # If the input is a list of event handlers, create an event chain.
  460. if isinstance(value, List):
  461. events: List[Union[EventSpec, EventVar]] = []
  462. for v in value:
  463. if isinstance(v, (EventHandler, EventSpec)):
  464. # Call the event handler to get the event.
  465. events.append(call_event_handler(v, args_spec))
  466. elif isinstance(v, Callable):
  467. # Call the lambda to get the event chain.
  468. result = call_event_fn(v, args_spec)
  469. if isinstance(result, Var):
  470. raise ValueError(
  471. f"Invalid event chain: {v}. Cannot use a Var-returning "
  472. "lambda inside an EventChain list."
  473. )
  474. events.extend(result)
  475. elif isinstance(v, EventVar):
  476. events.append(v)
  477. else:
  478. raise ValueError(f"Invalid event: {v}")
  479. # If the input is a callable, create an event chain.
  480. elif isinstance(value, Callable):
  481. result = call_event_fn(value, args_spec)
  482. if isinstance(result, Var):
  483. # Recursively call this function if the lambda returned an EventChain Var.
  484. return self._create_event_chain(args_spec, result)
  485. events = [*result]
  486. # Otherwise, raise an error.
  487. else:
  488. raise ValueError(f"Invalid event chain: {value}")
  489. # Add args to the event specs if necessary.
  490. events = [
  491. (e.with_args(get_handler_args(e)) if isinstance(e, EventSpec) else e)
  492. for e in events
  493. ]
  494. # Return the event chain.
  495. if isinstance(args_spec, Var):
  496. return EventChain(
  497. events=events,
  498. args_spec=None,
  499. event_actions={},
  500. )
  501. else:
  502. return EventChain(
  503. events=events,
  504. args_spec=args_spec,
  505. event_actions={},
  506. )
  507. def get_event_triggers(self) -> Dict[str, Any]:
  508. """Get the event triggers for the component.
  509. Returns:
  510. The event triggers.
  511. """
  512. default_triggers = {
  513. EventTriggers.ON_FOCUS: empty_event,
  514. EventTriggers.ON_BLUR: empty_event,
  515. EventTriggers.ON_CLICK: empty_event,
  516. EventTriggers.ON_CONTEXT_MENU: empty_event,
  517. EventTriggers.ON_DOUBLE_CLICK: empty_event,
  518. EventTriggers.ON_MOUSE_DOWN: empty_event,
  519. EventTriggers.ON_MOUSE_ENTER: empty_event,
  520. EventTriggers.ON_MOUSE_LEAVE: empty_event,
  521. EventTriggers.ON_MOUSE_MOVE: empty_event,
  522. EventTriggers.ON_MOUSE_OUT: empty_event,
  523. EventTriggers.ON_MOUSE_OVER: empty_event,
  524. EventTriggers.ON_MOUSE_UP: empty_event,
  525. EventTriggers.ON_SCROLL: empty_event,
  526. EventTriggers.ON_MOUNT: empty_event,
  527. EventTriggers.ON_UNMOUNT: empty_event,
  528. }
  529. # Look for component specific triggers,
  530. # e.g. variable declared as EventHandler types.
  531. for field in self.get_fields().values():
  532. if types._issubclass(field.outer_type_, EventHandler):
  533. args_spec = None
  534. annotation = field.annotation
  535. if (metadata := getattr(annotation, "__metadata__", None)) is not None:
  536. args_spec = metadata[0]
  537. default_triggers[field.name] = args_spec or (empty_event) # type: ignore
  538. return default_triggers
  539. def __repr__(self) -> str:
  540. """Represent the component in React.
  541. Returns:
  542. The code to render the component.
  543. """
  544. return format.json_dumps(self.render())
  545. def __str__(self) -> str:
  546. """Represent the component in React.
  547. Returns:
  548. The code to render the component.
  549. """
  550. from reflex.compiler.compiler import _compile_component
  551. return _compile_component(self)
  552. def _exclude_props(self) -> list[str]:
  553. """Props to exclude when adding the component props to the Tag.
  554. Returns:
  555. A list of component props to exclude.
  556. """
  557. return []
  558. def _render(self, props: dict[str, Any] | None = None) -> Tag:
  559. """Define how to render the component in React.
  560. Args:
  561. props: The props to render (if None, then use get_props).
  562. Returns:
  563. The tag to render.
  564. """
  565. # Create the base tag.
  566. tag = Tag(
  567. name=(self.tag if not self.alias else self.alias) or "",
  568. special_props=self.special_props,
  569. )
  570. if props is None:
  571. # Add component props to the tag.
  572. props = {
  573. attr[:-1] if attr.endswith("_") else attr: getattr(self, attr)
  574. for attr in self.get_props()
  575. }
  576. # Add ref to element if `id` is not None.
  577. ref = self.get_ref()
  578. if ref is not None:
  579. props["ref"] = Var(_js_expr=ref)
  580. else:
  581. props = props.copy()
  582. props.update(
  583. **{
  584. trigger: handler
  585. for trigger, handler in self.event_triggers.items()
  586. if trigger not in {EventTriggers.ON_MOUNT, EventTriggers.ON_UNMOUNT}
  587. },
  588. key=self.key,
  589. id=self.id,
  590. class_name=self.class_name,
  591. )
  592. props.update(self._get_style())
  593. props.update(self.custom_attrs)
  594. # remove excluded props from prop dict before adding to tag.
  595. for prop_to_exclude in self._exclude_props():
  596. props.pop(prop_to_exclude, None)
  597. return tag.add_props(**props)
  598. @classmethod
  599. @lru_cache(maxsize=None)
  600. def get_props(cls) -> Set[str]:
  601. """Get the unique fields for the component.
  602. Returns:
  603. The unique fields.
  604. """
  605. return set(cls.get_fields()) - set(Component.get_fields())
  606. @classmethod
  607. @lru_cache(maxsize=None)
  608. def get_initial_props(cls) -> Set[str]:
  609. """Get the initial props to set for the component.
  610. Returns:
  611. The initial props to set.
  612. """
  613. return set()
  614. @classmethod
  615. @lru_cache(maxsize=None)
  616. def get_component_props(cls) -> set[str]:
  617. """Get the props that expected a component as value.
  618. Returns:
  619. The components props.
  620. """
  621. return {
  622. name
  623. for name, field in cls.get_fields().items()
  624. if name in cls.get_props()
  625. and types._issubclass(field.outer_type_, Component)
  626. }
  627. @classmethod
  628. def create(cls, *children, **props) -> Component:
  629. """Create the component.
  630. Args:
  631. *children: The children of the component.
  632. **props: The props of the component.
  633. Returns:
  634. The component.
  635. """
  636. # Import here to avoid circular imports.
  637. from reflex.components.base.bare import Bare
  638. from reflex.components.base.fragment import Fragment
  639. from reflex.utils.exceptions import ComponentTypeError
  640. # Filter out None props
  641. props = {key: value for key, value in props.items() if value is not None}
  642. def validate_children(children):
  643. for child in children:
  644. if isinstance(child, tuple):
  645. validate_children(child)
  646. # Make sure the child is a valid type.
  647. if not types._isinstance(child, ComponentChild):
  648. raise ComponentTypeError(
  649. "Children of Reflex components must be other components, "
  650. "state vars, or primitive Python types. "
  651. f"Got child {child} of type {type(child)}.",
  652. )
  653. # Validate all the children.
  654. validate_children(children)
  655. children = [
  656. (
  657. child
  658. if isinstance(child, Component)
  659. else (
  660. Fragment.create(*child)
  661. if isinstance(child, tuple)
  662. else Bare.create(contents=LiteralVar.create(child))
  663. )
  664. )
  665. for child in children
  666. ]
  667. return cls(children=children, **props)
  668. def add_style(self) -> dict[str, Any] | None:
  669. """Add style to the component.
  670. Downstream components can override this method to return a style dict
  671. that will be applied to the component.
  672. Returns:
  673. The style to add.
  674. """
  675. return None
  676. def _add_style(self) -> Style:
  677. """Call add_style for all bases in the MRO.
  678. Downstream components should NOT override. Use add_style instead.
  679. Returns:
  680. The style to add.
  681. """
  682. styles = []
  683. # Walk the MRO to call all `add_style` methods.
  684. for base in self._iter_parent_classes_with_method("add_style"):
  685. s = base.add_style(self) # type: ignore
  686. if s is not None:
  687. styles.append(s)
  688. _style = Style()
  689. for s in reversed(styles):
  690. _style.update(s)
  691. return _style
  692. def _get_component_style(self, styles: ComponentStyle) -> Style | None:
  693. """Get the style to the component from `App.style`.
  694. Args:
  695. styles: The style to apply.
  696. Returns:
  697. The style of the component.
  698. """
  699. component_style = None
  700. if type(self) in styles:
  701. component_style = Style(styles[type(self)])
  702. if self.create in styles:
  703. component_style = Style(styles[self.create])
  704. return component_style
  705. def _add_style_recursive(
  706. self, style: ComponentStyle, theme: Optional[Component] = None
  707. ) -> Component:
  708. """Add additional style to the component and its children.
  709. Apply order is as follows (with the latest overriding the earliest):
  710. 1. Default style from `_add_style`/`add_style`.
  711. 2. User-defined style from `App.style`.
  712. 3. User-defined style from `Component.style`.
  713. 4. style dict and css props passed to the component instance.
  714. Args:
  715. style: A dict from component to styling.
  716. theme: The theme to apply. (for retro-compatibility with deprecated _apply_theme API)
  717. Raises:
  718. UserWarning: If `_add_style` has been overridden.
  719. Returns:
  720. The component with the additional style.
  721. """
  722. # 1. Default style from `_add_style`/`add_style`.
  723. if type(self)._add_style != Component._add_style:
  724. raise UserWarning(
  725. "Do not override _add_style directly. Use add_style instead."
  726. )
  727. new_style = self._add_style()
  728. style_vars = [new_style._var_data]
  729. # 2. User-defined style from `App.style`.
  730. component_style = self._get_component_style(style)
  731. if component_style:
  732. new_style.update(component_style)
  733. style_vars.append(component_style._var_data)
  734. # 4. style dict and css props passed to the component instance.
  735. new_style.update(self.style)
  736. style_vars.append(self.style._var_data)
  737. new_style._var_data = VarData.merge(*style_vars)
  738. # Assign the new style
  739. self.style = new_style
  740. # Recursively add style to the children.
  741. for child in self.children:
  742. # Skip BaseComponent and StatefulComponent children.
  743. if not isinstance(child, Component):
  744. continue
  745. child._add_style_recursive(style, theme)
  746. return self
  747. def _get_style(self) -> dict:
  748. """Get the style for the component.
  749. Returns:
  750. The dictionary of the component style as value and the style notation as key.
  751. """
  752. if isinstance(self.style, Var):
  753. return {"css": self.style}
  754. emotion_style = format_as_emotion(self.style)
  755. return (
  756. {"css": LiteralVar.create(emotion_style)}
  757. if emotion_style is not None
  758. else {}
  759. )
  760. def render(self) -> Dict:
  761. """Render the component.
  762. Returns:
  763. The dictionary for template of component.
  764. """
  765. tag = self._render()
  766. rendered_dict = dict(
  767. tag.set(
  768. children=[child.render() for child in self.children],
  769. contents=str(tag.contents),
  770. props=tag.format_props(),
  771. ),
  772. autofocus=self.autofocus,
  773. )
  774. self._replace_prop_names(rendered_dict)
  775. return rendered_dict
  776. def _replace_prop_names(self, rendered_dict) -> None:
  777. """Replace the prop names in the render dictionary.
  778. Args:
  779. rendered_dict: The render dictionary with all the component props and event handlers.
  780. """
  781. # fast path
  782. if not self._rename_props:
  783. return
  784. for ix, prop in enumerate(rendered_dict["props"]):
  785. for old_prop, new_prop in self._rename_props.items():
  786. if prop.startswith(old_prop):
  787. rendered_dict["props"][ix] = prop.replace(old_prop, new_prop, 1)
  788. def _validate_component_children(self, children: List[Component]):
  789. """Validate the children components.
  790. Args:
  791. children: The children of the component.
  792. """
  793. from reflex.components.base.fragment import Fragment
  794. from reflex.components.core.cond import Cond
  795. from reflex.components.core.foreach import Foreach
  796. from reflex.components.core.match import Match
  797. no_valid_parents_defined = all(child._valid_parents == [] for child in children)
  798. if (
  799. not self._invalid_children
  800. and not self._valid_children
  801. and no_valid_parents_defined
  802. ):
  803. return
  804. comp_name = type(self).__name__
  805. allowed_components = [
  806. comp.__name__ for comp in (Fragment, Foreach, Cond, Match)
  807. ]
  808. def validate_child(child):
  809. child_name = type(child).__name__
  810. # Iterate through the immediate children of fragment
  811. if isinstance(child, Fragment):
  812. for c in child.children:
  813. validate_child(c)
  814. if isinstance(child, Cond):
  815. validate_child(child.comp1)
  816. validate_child(child.comp2)
  817. if isinstance(child, Match):
  818. for cases in child.match_cases:
  819. validate_child(cases[-1])
  820. validate_child(child.default)
  821. if self._invalid_children and child_name in self._invalid_children:
  822. raise ValueError(
  823. f"The component `{comp_name}` cannot have `{child_name}` as a child component"
  824. )
  825. if self._valid_children and child_name not in [
  826. *self._valid_children,
  827. *allowed_components,
  828. ]:
  829. valid_child_list = ", ".join(
  830. [f"`{v_child}`" for v_child in self._valid_children]
  831. )
  832. raise ValueError(
  833. f"The component `{comp_name}` only allows the components: {valid_child_list} as children. Got `{child_name}` instead."
  834. )
  835. if child._valid_parents and all(
  836. clz_name not in [*child._valid_parents, *allowed_components]
  837. for clz_name in self._iter_parent_classes_names()
  838. ):
  839. valid_parent_list = ", ".join(
  840. [f"`{v_parent}`" for v_parent in child._valid_parents]
  841. )
  842. raise ValueError(
  843. f"The component `{child_name}` can only be a child of the components: {valid_parent_list}. Got `{comp_name}` instead."
  844. )
  845. for child in children:
  846. validate_child(child)
  847. @staticmethod
  848. def _get_vars_from_event_triggers(
  849. event_triggers: dict[str, EventChain | Var],
  850. ) -> Iterator[tuple[str, list[Var]]]:
  851. """Get the Vars associated with each event trigger.
  852. Args:
  853. event_triggers: The event triggers from the component instance.
  854. Yields:
  855. tuple of (event_name, event_vars)
  856. """
  857. for event_trigger, event in event_triggers.items():
  858. if isinstance(event, Var):
  859. yield event_trigger, [event]
  860. elif isinstance(event, EventChain):
  861. event_args = []
  862. for spec in event.events:
  863. if isinstance(spec, EventSpec):
  864. for args in spec.args:
  865. event_args.extend(args)
  866. else:
  867. event_args.append(spec)
  868. yield event_trigger, event_args
  869. def _get_vars(self, include_children: bool = False) -> list[Var]:
  870. """Walk all Vars used in this component.
  871. Args:
  872. include_children: Whether to include Vars from children.
  873. Returns:
  874. Each var referenced by the component (props, styles, event handlers).
  875. """
  876. vars = getattr(self, "__vars", None)
  877. if vars is not None:
  878. return vars
  879. vars = self.__vars = []
  880. # Get Vars associated with event trigger arguments.
  881. for _, event_vars in self._get_vars_from_event_triggers(self.event_triggers):
  882. vars.extend(event_vars)
  883. # Get Vars associated with component props.
  884. for prop in self.get_props():
  885. prop_var = getattr(self, prop)
  886. if isinstance(prop_var, Var):
  887. vars.append(prop_var)
  888. # Style keeps track of its own VarData instance, so embed in a temp Var that is yielded.
  889. if isinstance(self.style, dict) and self.style or isinstance(self.style, Var):
  890. vars.append(
  891. Var(
  892. _js_expr="style",
  893. _var_type=str,
  894. _var_data=VarData.merge(self.style._var_data),
  895. )
  896. )
  897. # Special props are always Var instances.
  898. vars.extend(self.special_props)
  899. # Get Vars associated with common Component props.
  900. for comp_prop in (
  901. self.class_name,
  902. self.id,
  903. self.key,
  904. self.autofocus,
  905. *self.custom_attrs.values(),
  906. ):
  907. if isinstance(comp_prop, Var):
  908. vars.append(comp_prop)
  909. elif isinstance(comp_prop, str):
  910. # Collapse VarData encoded in f-strings.
  911. var = LiteralVar.create(comp_prop)
  912. if var._get_all_var_data() is not None:
  913. vars.append(var)
  914. # Get Vars associated with children.
  915. if include_children:
  916. for child in self.children:
  917. if not isinstance(child, Component):
  918. continue
  919. child_vars = child._get_vars(include_children=include_children)
  920. vars.extend(child_vars)
  921. return vars
  922. def _event_trigger_values_use_state(self) -> bool:
  923. """Check if the values of a component's event trigger use state.
  924. Returns:
  925. True if any of the component's event trigger values uses State.
  926. """
  927. for trigger in self.event_triggers.values():
  928. if isinstance(trigger, EventChain):
  929. for event in trigger.events:
  930. if isinstance(event, EventCallback):
  931. continue
  932. if isinstance(event, EventSpec):
  933. if event.handler.state_full_name:
  934. return True
  935. else:
  936. if event._var_state:
  937. return True
  938. elif isinstance(trigger, Var) and trigger._var_state:
  939. return True
  940. return False
  941. def _has_stateful_event_triggers(self):
  942. """Check if component or children have any event triggers that use state.
  943. Returns:
  944. True if the component or children have any event triggers that uses state.
  945. """
  946. if self.event_triggers and self._event_trigger_values_use_state():
  947. return True
  948. else:
  949. for child in self.children:
  950. if (
  951. isinstance(child, Component)
  952. and child._has_stateful_event_triggers()
  953. ):
  954. return True
  955. return False
  956. @classmethod
  957. def _iter_parent_classes_names(cls) -> Iterator[str]:
  958. for clz in cls.mro():
  959. if clz is Component:
  960. break
  961. yield clz.__name__
  962. @classmethod
  963. def _iter_parent_classes_with_method(cls, method: str) -> Iterator[Type[Component]]:
  964. """Iterate through parent classes that define a given method.
  965. Used for handling the `add_*` API functions that internally simulate a super() call chain.
  966. Args:
  967. method: The method to look for.
  968. Yields:
  969. The parent classes that define the method (differently than the base).
  970. """
  971. seen_methods = set([getattr(Component, method)])
  972. for clz in cls.mro():
  973. if clz is Component:
  974. break
  975. if not issubclass(clz, Component):
  976. continue
  977. method_func = getattr(clz, method, None)
  978. if not callable(method_func) or method_func in seen_methods:
  979. continue
  980. seen_methods.add(method_func)
  981. yield clz
  982. def _get_custom_code(self) -> str | None:
  983. """Get custom code for the component.
  984. Returns:
  985. The custom code.
  986. """
  987. return None
  988. def _get_all_custom_code(self) -> set[str]:
  989. """Get custom code for the component and its children.
  990. Returns:
  991. The custom code.
  992. """
  993. # Store the code in a set to avoid duplicates.
  994. code = set()
  995. # Add the custom code for this component.
  996. custom_code = self._get_custom_code()
  997. if custom_code is not None:
  998. code.add(custom_code)
  999. # Add the custom code from add_custom_code method.
  1000. for clz in self._iter_parent_classes_with_method("add_custom_code"):
  1001. for item in clz.add_custom_code(self):
  1002. code.add(item)
  1003. # Add the custom code for the children.
  1004. for child in self.children:
  1005. code |= child._get_all_custom_code()
  1006. # Return the code.
  1007. return code
  1008. def _get_dynamic_imports(self) -> str | None:
  1009. """Get dynamic import for the component.
  1010. Returns:
  1011. The dynamic import.
  1012. """
  1013. return None
  1014. def _get_all_dynamic_imports(self) -> Set[str]:
  1015. """Get dynamic imports for the component and its children.
  1016. Returns:
  1017. The dynamic imports.
  1018. """
  1019. # Store the import in a set to avoid duplicates.
  1020. dynamic_imports = set()
  1021. # Get dynamic import for this component.
  1022. dynamic_import = self._get_dynamic_imports()
  1023. if dynamic_import:
  1024. dynamic_imports.add(dynamic_import)
  1025. # Get the dynamic imports from children
  1026. for child in self.children:
  1027. dynamic_imports |= child._get_all_dynamic_imports()
  1028. for prop in self.get_component_props():
  1029. if getattr(self, prop) is not None:
  1030. dynamic_imports |= getattr(self, prop)._get_all_dynamic_imports()
  1031. # Return the dynamic imports
  1032. return dynamic_imports
  1033. def _get_props_imports(self) -> List[ParsedImportDict]:
  1034. """Get the imports needed for components props.
  1035. Returns:
  1036. The imports for the components props of the component.
  1037. """
  1038. return [
  1039. getattr(self, prop)._get_all_imports()
  1040. for prop in self.get_component_props()
  1041. if getattr(self, prop) is not None
  1042. ]
  1043. def _should_transpile(self, dep: str | None) -> bool:
  1044. """Check if a dependency should be transpiled.
  1045. Args:
  1046. dep: The dependency to check.
  1047. Returns:
  1048. True if the dependency should be transpiled.
  1049. """
  1050. return (
  1051. dep in self.transpile_packages
  1052. or format.format_library_name(dep or "") in self.transpile_packages
  1053. )
  1054. def _get_dependencies_imports(self) -> ParsedImportDict:
  1055. """Get the imports from lib_dependencies for installing.
  1056. Returns:
  1057. The dependencies imports of the component.
  1058. """
  1059. return {
  1060. dep: [
  1061. ImportVar(
  1062. tag=None,
  1063. render=False,
  1064. transpile=self._should_transpile(dep),
  1065. )
  1066. ]
  1067. for dep in self.lib_dependencies
  1068. }
  1069. def _get_hooks_imports(self) -> ParsedImportDict:
  1070. """Get the imports required by certain hooks.
  1071. Returns:
  1072. The imports required for all selected hooks.
  1073. """
  1074. _imports = {}
  1075. if self._get_ref_hook():
  1076. # Handle hooks needed for attaching react refs to DOM nodes.
  1077. _imports.setdefault("react", set()).add(ImportVar(tag="useRef"))
  1078. _imports.setdefault(f"$/{Dirs.STATE_PATH}", set()).add(
  1079. ImportVar(tag="refs")
  1080. )
  1081. if self._get_mount_lifecycle_hook():
  1082. # Handle hooks for `on_mount` / `on_unmount`.
  1083. _imports.setdefault("react", set()).add(ImportVar(tag="useEffect"))
  1084. if self._get_special_hooks():
  1085. # Handle additional internal hooks (autofocus, etc).
  1086. _imports.setdefault("react", set()).update(
  1087. {
  1088. ImportVar(tag="useRef"),
  1089. ImportVar(tag="useEffect"),
  1090. },
  1091. )
  1092. other_imports = []
  1093. user_hooks = self._get_hooks()
  1094. user_hooks_data = (
  1095. VarData.merge(user_hooks._get_all_var_data())
  1096. if user_hooks is not None and isinstance(user_hooks, Var)
  1097. else None
  1098. )
  1099. if user_hooks_data is not None:
  1100. other_imports.append(user_hooks_data.imports)
  1101. other_imports.extend(
  1102. hook_imports for hook_imports in self._get_added_hooks().values()
  1103. )
  1104. return imports.merge_imports(_imports, *other_imports)
  1105. def _get_imports(self) -> ParsedImportDict:
  1106. """Get all the libraries and fields that are used by the component.
  1107. Returns:
  1108. The imports needed by the component.
  1109. """
  1110. _imports = {}
  1111. # Import this component's tag from the main library.
  1112. if self.library is not None and self.tag is not None:
  1113. _imports[self.library] = {self.import_var}
  1114. # Get static imports required for event processing.
  1115. event_imports = Imports.EVENTS if self.event_triggers else {}
  1116. # Collect imports from Vars used directly by this component.
  1117. var_datas = [var._get_all_var_data() for var in self._get_vars()]
  1118. var_imports: List[ImmutableParsedImportDict] = list(
  1119. map(
  1120. lambda var_data: var_data.imports,
  1121. filter(
  1122. None,
  1123. var_datas,
  1124. ),
  1125. )
  1126. )
  1127. added_import_dicts: list[ParsedImportDict] = []
  1128. for clz in self._iter_parent_classes_with_method("add_imports"):
  1129. list_of_import_dict = clz.add_imports(self)
  1130. if not isinstance(list_of_import_dict, list):
  1131. list_of_import_dict = [list_of_import_dict]
  1132. for import_dict in list_of_import_dict:
  1133. added_import_dicts.append(parse_imports(import_dict))
  1134. return imports.merge_imports(
  1135. *self._get_props_imports(),
  1136. self._get_dependencies_imports(),
  1137. self._get_hooks_imports(),
  1138. _imports,
  1139. event_imports,
  1140. *var_imports,
  1141. *added_import_dicts,
  1142. )
  1143. def _get_all_imports(self, collapse: bool = False) -> ParsedImportDict:
  1144. """Get all the libraries and fields that are used by the component and its children.
  1145. Args:
  1146. collapse: Whether to collapse the imports by removing duplicates.
  1147. Returns:
  1148. The import dict with the required imports.
  1149. """
  1150. _imports = imports.merge_imports(
  1151. self._get_imports(), *[child._get_all_imports() for child in self.children]
  1152. )
  1153. return imports.collapse_imports(_imports) if collapse else _imports
  1154. def _get_mount_lifecycle_hook(self) -> str | None:
  1155. """Generate the component lifecycle hook.
  1156. Returns:
  1157. The useEffect hook for managing `on_mount` and `on_unmount` events.
  1158. """
  1159. # pop on_mount and on_unmount from event_triggers since these are handled by
  1160. # hooks, not as actually props in the component
  1161. on_mount = self.event_triggers.get(EventTriggers.ON_MOUNT, None)
  1162. on_unmount = self.event_triggers.get(EventTriggers.ON_UNMOUNT, None)
  1163. if on_mount is not None:
  1164. on_mount = str(LiteralVar.create(on_mount)) + "()"
  1165. if on_unmount is not None:
  1166. on_unmount = str(LiteralVar.create(on_unmount)) + "()"
  1167. if on_mount is not None or on_unmount is not None:
  1168. return f"""
  1169. useEffect(() => {{
  1170. {on_mount or ""}
  1171. return () => {{
  1172. {on_unmount or ""}
  1173. }}
  1174. }}, []);"""
  1175. def _get_ref_hook(self) -> str | None:
  1176. """Generate the ref hook for the component.
  1177. Returns:
  1178. The useRef hook for managing refs.
  1179. """
  1180. ref = self.get_ref()
  1181. if ref is not None:
  1182. return f"const {ref} = useRef(null); {str(Var(_js_expr=ref).as_ref())} = {ref};"
  1183. def _get_vars_hooks(self) -> dict[str, None]:
  1184. """Get the hooks required by vars referenced in this component.
  1185. Returns:
  1186. The hooks for the vars.
  1187. """
  1188. vars_hooks = {}
  1189. for var in self._get_vars():
  1190. var_data = var._get_all_var_data()
  1191. if var_data is not None:
  1192. vars_hooks.update(
  1193. var_data.hooks
  1194. if isinstance(var_data.hooks, dict)
  1195. else {k: None for k in var_data.hooks}
  1196. )
  1197. return vars_hooks
  1198. def _get_events_hooks(self) -> dict[str, None]:
  1199. """Get the hooks required by events referenced in this component.
  1200. Returns:
  1201. The hooks for the events.
  1202. """
  1203. return {Hooks.EVENTS: None} if self.event_triggers else {}
  1204. def _get_special_hooks(self) -> dict[str, None]:
  1205. """Get the hooks required by special actions referenced in this component.
  1206. Returns:
  1207. The hooks for special actions.
  1208. """
  1209. return {Hooks.AUTOFOCUS: None} if self.autofocus else {}
  1210. def _get_hooks_internal(self) -> dict[str, None]:
  1211. """Get the React hooks for this component managed by the framework.
  1212. Downstream components should NOT override this method to avoid breaking
  1213. framework functionality.
  1214. Returns:
  1215. The internally managed hooks.
  1216. """
  1217. return {
  1218. **{
  1219. hook: None
  1220. for hook in [self._get_ref_hook(), self._get_mount_lifecycle_hook()]
  1221. if hook is not None
  1222. },
  1223. **self._get_vars_hooks(),
  1224. **self._get_events_hooks(),
  1225. **self._get_special_hooks(),
  1226. }
  1227. def _get_added_hooks(self) -> dict[str, ImportDict]:
  1228. """Get the hooks added via `add_hooks` method.
  1229. Returns:
  1230. The deduplicated hooks and imports added by the component and parent components.
  1231. """
  1232. code = {}
  1233. def extract_var_hooks(hook: Var):
  1234. _imports = {}
  1235. var_data = VarData.merge(hook._get_all_var_data())
  1236. if var_data is not None:
  1237. for sub_hook in var_data.hooks:
  1238. code[sub_hook] = {}
  1239. if var_data.imports:
  1240. _imports = var_data.imports
  1241. if str(hook) in code:
  1242. code[str(hook)] = imports.merge_imports(code[str(hook)], _imports)
  1243. else:
  1244. code[str(hook)] = _imports
  1245. # Add the hook code from add_hooks for each parent class (this is reversed to preserve
  1246. # the order of the hooks in the final output)
  1247. for clz in reversed(tuple(self._iter_parent_classes_with_method("add_hooks"))):
  1248. for hook in clz.add_hooks(self):
  1249. if isinstance(hook, Var):
  1250. extract_var_hooks(hook)
  1251. else:
  1252. code[hook] = {}
  1253. return code
  1254. def _get_hooks(self) -> str | None:
  1255. """Get the React hooks for this component.
  1256. Downstream components should override this method to add their own hooks.
  1257. Returns:
  1258. The hooks for just this component.
  1259. """
  1260. return
  1261. def _get_all_hooks_internal(self) -> dict[str, None]:
  1262. """Get the reflex internal hooks for the component and its children.
  1263. Returns:
  1264. The code that should appear just before user-defined hooks.
  1265. """
  1266. # Store the code in a set to avoid duplicates.
  1267. code = self._get_hooks_internal()
  1268. # Add the hook code for the children.
  1269. for child in self.children:
  1270. code = {**code, **child._get_all_hooks_internal()}
  1271. return code
  1272. def _get_all_hooks(self) -> dict[str, None]:
  1273. """Get the React hooks for this component and its children.
  1274. Returns:
  1275. The code that should appear just before returning the rendered component.
  1276. """
  1277. code = {}
  1278. # Add the hook code for this component.
  1279. hooks = self._get_hooks()
  1280. if hooks is not None:
  1281. code[hooks] = None
  1282. for hook in self._get_added_hooks():
  1283. code[hook] = None
  1284. # Add the hook code for the children.
  1285. for child in self.children:
  1286. code = {**code, **child._get_all_hooks()}
  1287. return code
  1288. def get_ref(self) -> str | None:
  1289. """Get the name of the ref for the component.
  1290. Returns:
  1291. The ref name.
  1292. """
  1293. # do not create a ref if the id is dynamic or unspecified
  1294. if self.id is None or isinstance(self.id, Var):
  1295. return None
  1296. return format.format_ref(self.id)
  1297. def _get_all_refs(self) -> set[str]:
  1298. """Get the refs for the children of the component.
  1299. Returns:
  1300. The refs for the children.
  1301. """
  1302. refs = set()
  1303. ref = self.get_ref()
  1304. if ref is not None:
  1305. refs.add(ref)
  1306. for child in self.children:
  1307. refs |= child._get_all_refs()
  1308. return refs
  1309. def _get_all_custom_components(
  1310. self, seen: set[str] | None = None
  1311. ) -> Set[CustomComponent]:
  1312. """Get all the custom components used by the component.
  1313. Args:
  1314. seen: The tags of the components that have already been seen.
  1315. Returns:
  1316. The set of custom components.
  1317. """
  1318. custom_components = set()
  1319. # Store the seen components in a set to avoid infinite recursion.
  1320. if seen is None:
  1321. seen = set()
  1322. for child in self.children:
  1323. # Skip BaseComponent and StatefulComponent children.
  1324. if not isinstance(child, Component):
  1325. continue
  1326. custom_components |= child._get_all_custom_components(seen=seen)
  1327. return custom_components
  1328. @property
  1329. def import_var(self):
  1330. """The tag to import.
  1331. Returns:
  1332. An import var.
  1333. """
  1334. # If the tag is dot-qualified, only import the left-most name.
  1335. tag = self.tag.partition(".")[0] if self.tag else None
  1336. alias = self.alias.partition(".")[0] if self.alias else None
  1337. return ImportVar(
  1338. tag=tag,
  1339. is_default=self.is_default,
  1340. alias=alias,
  1341. transpile=self._should_transpile(self.library),
  1342. )
  1343. @staticmethod
  1344. def _get_app_wrap_components() -> dict[tuple[int, str], Component]:
  1345. """Get the app wrap components for the component.
  1346. Returns:
  1347. The app wrap components.
  1348. """
  1349. return {}
  1350. def _get_all_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  1351. """Get the app wrap components for the component and its children.
  1352. Returns:
  1353. The app wrap components.
  1354. """
  1355. # Store the components in a set to avoid duplicates.
  1356. components = self._get_app_wrap_components()
  1357. for component in tuple(components.values()):
  1358. components.update(component._get_all_app_wrap_components())
  1359. # Add the app wrap components for the children.
  1360. for child in self.children:
  1361. # Skip BaseComponent and StatefulComponent children.
  1362. if not isinstance(child, Component):
  1363. continue
  1364. components.update(child._get_all_app_wrap_components())
  1365. # Return the components.
  1366. return components
  1367. class CustomComponent(Component):
  1368. """A custom user-defined component."""
  1369. # Use the components library.
  1370. library = f"$/{Dirs.COMPONENTS_PATH}"
  1371. # The function that creates the component.
  1372. component_fn: Callable[..., Component] = Component.create
  1373. # The props of the component.
  1374. props: Dict[str, Any] = {}
  1375. # Props that reference other components.
  1376. component_props: Dict[str, Component] = {}
  1377. def __init__(self, *args, **kwargs):
  1378. """Initialize the custom component.
  1379. Args:
  1380. *args: The args to pass to the component.
  1381. **kwargs: The kwargs to pass to the component.
  1382. """
  1383. super().__init__(*args, **kwargs)
  1384. # Unset the style.
  1385. self.style = Style()
  1386. # Set the tag to the name of the function.
  1387. self.tag = format.to_title_case(self.component_fn.__name__)
  1388. # Get the event triggers defined in the component declaration.
  1389. event_triggers_in_component_declaration = self.get_event_triggers()
  1390. # Set the props.
  1391. props = typing.get_type_hints(self.component_fn)
  1392. for key, value in kwargs.items():
  1393. # Skip kwargs that are not props.
  1394. if key not in props:
  1395. continue
  1396. # Get the type based on the annotation.
  1397. type_ = props[key]
  1398. # Handle event chains.
  1399. if types._issubclass(type_, EventChain):
  1400. value = self._create_event_chain(
  1401. value=value,
  1402. args_spec=event_triggers_in_component_declaration.get(
  1403. key, empty_event
  1404. ),
  1405. )
  1406. self.props[format.to_camel_case(key)] = value
  1407. continue
  1408. # Handle subclasses of Base.
  1409. if isinstance(value, Base):
  1410. base_value = LiteralVar.create(value)
  1411. # Track hooks and imports associated with Component instances.
  1412. if base_value is not None and isinstance(value, Component):
  1413. self.component_props[key] = value
  1414. value = base_value._replace(
  1415. merge_var_data=VarData( # type: ignore
  1416. imports=value._get_all_imports(),
  1417. hooks=value._get_all_hooks(),
  1418. )
  1419. )
  1420. else:
  1421. value = base_value
  1422. else:
  1423. value = LiteralVar.create(value)
  1424. # Set the prop.
  1425. self.props[format.to_camel_case(key)] = value
  1426. def __eq__(self, other: Any) -> bool:
  1427. """Check if the component is equal to another.
  1428. Args:
  1429. other: The other component.
  1430. Returns:
  1431. Whether the component is equal to the other.
  1432. """
  1433. return isinstance(other, CustomComponent) and self.tag == other.tag
  1434. def __hash__(self) -> int:
  1435. """Get the hash of the component.
  1436. Returns:
  1437. The hash of the component.
  1438. """
  1439. return hash(self.tag)
  1440. @classmethod
  1441. def get_props(cls) -> Set[str]:
  1442. """Get the props for the component.
  1443. Returns:
  1444. The set of component props.
  1445. """
  1446. return set()
  1447. def _get_all_custom_components(
  1448. self, seen: set[str] | None = None
  1449. ) -> Set[CustomComponent]:
  1450. """Get all the custom components used by the component.
  1451. Args:
  1452. seen: The tags of the components that have already been seen.
  1453. Raises:
  1454. ValueError: If the tag is not set.
  1455. Returns:
  1456. The set of custom components.
  1457. """
  1458. if self.tag is None:
  1459. raise ValueError("The tag must be set.")
  1460. # Store the seen components in a set to avoid infinite recursion.
  1461. if seen is None:
  1462. seen = set()
  1463. custom_components = {self} | super()._get_all_custom_components(seen=seen)
  1464. # Avoid adding the same component twice.
  1465. if self.tag not in seen:
  1466. seen.add(self.tag)
  1467. custom_components |= self.get_component(self)._get_all_custom_components(
  1468. seen=seen
  1469. )
  1470. # Fetch custom components from props as well.
  1471. for child_component in self.component_props.values():
  1472. if child_component.tag is None:
  1473. continue
  1474. if child_component.tag not in seen:
  1475. seen.add(child_component.tag)
  1476. if isinstance(child_component, CustomComponent):
  1477. custom_components |= {child_component}
  1478. custom_components |= child_component._get_all_custom_components(
  1479. seen=seen
  1480. )
  1481. return custom_components
  1482. def _render(self) -> Tag:
  1483. """Define how to render the component in React.
  1484. Returns:
  1485. The tag to render.
  1486. """
  1487. return super()._render(props=self.props)
  1488. def get_prop_vars(self) -> List[Var]:
  1489. """Get the prop vars.
  1490. Returns:
  1491. The prop vars.
  1492. """
  1493. return [
  1494. Var(
  1495. _js_expr=name,
  1496. _var_type=(
  1497. prop._var_type if types._isinstance(prop, Var) else type(prop)
  1498. ),
  1499. ).guess_type()
  1500. for name, prop in self.props.items()
  1501. ]
  1502. def _get_vars(self, include_children: bool = False) -> list[Var]:
  1503. """Walk all Vars used in this component.
  1504. Args:
  1505. include_children: Whether to include Vars from children.
  1506. Returns:
  1507. Each var referenced by the component (props, styles, event handlers).
  1508. """
  1509. return (
  1510. super()._get_vars(include_children=include_children)
  1511. + [prop for prop in self.props.values() if isinstance(prop, Var)]
  1512. + self.get_component(self)._get_vars(include_children=include_children)
  1513. )
  1514. @lru_cache(maxsize=None) # noqa
  1515. def get_component(self) -> Component:
  1516. """Render the component.
  1517. Returns:
  1518. The code to render the component.
  1519. """
  1520. return self.component_fn(*self.get_prop_vars())
  1521. def custom_component(
  1522. component_fn: Callable[..., Component],
  1523. ) -> Callable[..., CustomComponent]:
  1524. """Create a custom component from a function.
  1525. Args:
  1526. component_fn: The function that creates the component.
  1527. Returns:
  1528. The decorated function.
  1529. """
  1530. @wraps(component_fn)
  1531. def wrapper(*children, **props) -> CustomComponent:
  1532. # Remove the children from the props.
  1533. props.pop("children", None)
  1534. return CustomComponent(component_fn=component_fn, children=children, **props)
  1535. return wrapper
  1536. # Alias memo to custom_component.
  1537. memo = custom_component
  1538. class NoSSRComponent(Component):
  1539. """A dynamic component that is not rendered on the server."""
  1540. def _get_imports(self) -> ParsedImportDict:
  1541. """Get the imports for the component.
  1542. Returns:
  1543. The imports for dynamically importing the component at module load time.
  1544. """
  1545. # Next.js dynamic import mechanism.
  1546. dynamic_import = {"next/dynamic": [ImportVar(tag="dynamic", is_default=True)]}
  1547. # The normal imports for this component.
  1548. _imports = super()._get_imports()
  1549. # Do NOT import the main library/tag statically.
  1550. if self.library is not None:
  1551. _imports[self.library] = [
  1552. imports.ImportVar(
  1553. tag=None,
  1554. render=False,
  1555. transpile=self._should_transpile(self.library),
  1556. ),
  1557. ]
  1558. return imports.merge_imports(
  1559. dynamic_import,
  1560. _imports,
  1561. self._get_dependencies_imports(),
  1562. )
  1563. def _get_dynamic_imports(self) -> str:
  1564. opts_fragment = ", { ssr: false });"
  1565. # extract the correct import name from library name
  1566. if self.library is None:
  1567. raise ValueError("Undefined library for NoSSRComponent")
  1568. import_name = format.format_library_name(self.library)
  1569. library_import = f"const {self.alias if self.alias else self.tag} = dynamic(() => import('{import_name}')"
  1570. mod_import = (
  1571. # https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-named-exports
  1572. f".then((mod) => mod.{self.tag})" if not self.is_default else ""
  1573. )
  1574. return "".join((library_import, mod_import, opts_fragment))
  1575. class StatefulComponent(BaseComponent):
  1576. """A component that depends on state and is rendered outside of the page component.
  1577. If a StatefulComponent is used in multiple pages, it will be rendered to a common file and
  1578. imported into each page that uses it.
  1579. A stateful component has a tag name that includes a hash of the code that it renders
  1580. to. This tag name refers to the specific component with the specific props that it
  1581. was created with.
  1582. """
  1583. # A lookup table to caching memoized component instances.
  1584. tag_to_stateful_component: ClassVar[Dict[str, StatefulComponent]] = {}
  1585. # Reference to the original component that was memoized into this component.
  1586. component: Component
  1587. # The rendered (memoized) code that will be emitted.
  1588. code: str
  1589. # How many times this component is referenced in the app.
  1590. references: int = 0
  1591. # Whether the component has already been rendered to a shared file.
  1592. rendered_as_shared: bool = False
  1593. @classmethod
  1594. def create(cls, component: Component) -> StatefulComponent | None:
  1595. """Create a stateful component from a component.
  1596. Args:
  1597. component: The component to memoize.
  1598. Returns:
  1599. The stateful component or None if the component should not be memoized.
  1600. """
  1601. from reflex.components.core.foreach import Foreach
  1602. if component._memoization_mode.disposition == MemoizationDisposition.NEVER:
  1603. # Never memoize this component.
  1604. return None
  1605. if component.tag is None:
  1606. # Only memoize components with a tag.
  1607. return None
  1608. # If _var_data is found in this component, it is a candidate for auto-memoization.
  1609. should_memoize = False
  1610. # If the component requests to be memoized, then ignore other checks.
  1611. if component._memoization_mode.disposition == MemoizationDisposition.ALWAYS:
  1612. should_memoize = True
  1613. if not should_memoize:
  1614. # Determine if any Vars have associated data.
  1615. for prop_var in component._get_vars():
  1616. if prop_var._get_all_var_data():
  1617. should_memoize = True
  1618. break
  1619. if not should_memoize:
  1620. # Check for special-cases in child components.
  1621. for child in component.children:
  1622. # Skip BaseComponent and StatefulComponent children.
  1623. if not isinstance(child, Component):
  1624. continue
  1625. # Always consider Foreach something that must be memoized by the parent.
  1626. if isinstance(child, Foreach):
  1627. should_memoize = True
  1628. break
  1629. child = cls._child_var(child)
  1630. if isinstance(child, Var) and child._get_all_var_data():
  1631. should_memoize = True
  1632. break
  1633. if should_memoize or component.event_triggers:
  1634. # Render the component to determine tag+hash based on component code.
  1635. tag_name = cls._get_tag_name(component)
  1636. if tag_name is None:
  1637. return None
  1638. # Look up the tag in the cache
  1639. stateful_component = cls.tag_to_stateful_component.get(tag_name)
  1640. if stateful_component is None:
  1641. # Render the component as a string of javascript code.
  1642. code = cls._render_stateful_code(component, tag_name=tag_name)
  1643. # Set the stateful component in the cache for the given tag.
  1644. stateful_component = cls.tag_to_stateful_component.setdefault(
  1645. tag_name,
  1646. cls(
  1647. children=component.children,
  1648. component=component,
  1649. tag=tag_name,
  1650. code=code,
  1651. ),
  1652. )
  1653. # Bump the reference count -- multiple pages referencing the same component
  1654. # will result in writing it to a common file.
  1655. stateful_component.references += 1
  1656. return stateful_component
  1657. # Return None to indicate this component should not be memoized.
  1658. return None
  1659. @staticmethod
  1660. def _child_var(child: Component) -> Var | Component:
  1661. """Get the Var from a child component.
  1662. This method is used for special cases when the StatefulComponent should actually
  1663. wrap the parent component of the child instead of recursing into the children
  1664. and memoizing them independently.
  1665. Args:
  1666. child: The child component.
  1667. Returns:
  1668. The Var from the child component or the child itself (for regular cases).
  1669. """
  1670. from reflex.components.base.bare import Bare
  1671. from reflex.components.core.cond import Cond
  1672. from reflex.components.core.foreach import Foreach
  1673. from reflex.components.core.match import Match
  1674. if isinstance(child, Bare):
  1675. return child.contents
  1676. if isinstance(child, Cond):
  1677. return child.cond
  1678. if isinstance(child, Foreach):
  1679. return child.iterable
  1680. if isinstance(child, Match):
  1681. return child.cond
  1682. return child
  1683. @classmethod
  1684. def _get_tag_name(cls, component: Component) -> str | None:
  1685. """Get the tag based on rendering the given component.
  1686. Args:
  1687. component: The component to render.
  1688. Returns:
  1689. The tag for the stateful component.
  1690. """
  1691. # Get the render dict for the component.
  1692. rendered_code = component.render()
  1693. if not rendered_code:
  1694. # Never memoize non-visual components.
  1695. return None
  1696. # Compute the hash based on the rendered code.
  1697. code_hash = md5(str(rendered_code).encode("utf-8")).hexdigest()
  1698. # Format the tag name including the hash.
  1699. return format.format_state_name(
  1700. f"{component.tag or 'Comp'}_{code_hash}"
  1701. ).capitalize()
  1702. @classmethod
  1703. def _render_stateful_code(
  1704. cls,
  1705. component: Component,
  1706. tag_name: str,
  1707. ) -> str:
  1708. """Render the code for a stateful component.
  1709. Args:
  1710. component: The component to render.
  1711. tag_name: The tag name for the stateful component (see _get_tag_name).
  1712. Returns:
  1713. The rendered code.
  1714. """
  1715. # Memoize event triggers useCallback to avoid unnecessary re-renders.
  1716. memo_event_triggers = tuple(cls._get_memoized_event_triggers(component).items())
  1717. # Trigger hooks stored separately to write after the normal hooks (see stateful_component.js.jinja2)
  1718. memo_trigger_hooks = []
  1719. if memo_event_triggers:
  1720. # Copy the component to avoid mutating the original.
  1721. component = copy.copy(component)
  1722. for event_trigger, (
  1723. memo_trigger,
  1724. memo_trigger_hook,
  1725. ) in memo_event_triggers:
  1726. # Replace the event trigger with the memoized version.
  1727. memo_trigger_hooks.append(memo_trigger_hook)
  1728. component.event_triggers[event_trigger] = memo_trigger
  1729. # Render the code for this component and hooks.
  1730. return STATEFUL_COMPONENT.render(
  1731. tag_name=tag_name,
  1732. memo_trigger_hooks=memo_trigger_hooks,
  1733. component=component,
  1734. )
  1735. @staticmethod
  1736. def _get_hook_deps(hook: str) -> list[str]:
  1737. """Extract var deps from a hook.
  1738. Args:
  1739. hook: The hook line to extract deps from.
  1740. Returns:
  1741. A list of var names created by the hook declaration.
  1742. """
  1743. # Ensure that the hook is a var declaration.
  1744. var_decl = hook.partition("=")[0].strip()
  1745. if not any(var_decl.startswith(kw) for kw in ["const ", "let ", "var "]):
  1746. return []
  1747. # Extract the var name from the declaration.
  1748. _, _, var_name = var_decl.partition(" ")
  1749. var_name = var_name.strip()
  1750. # Break up array and object destructuring if used.
  1751. if var_name.startswith("[") or var_name.startswith("{"):
  1752. return [
  1753. v.strip().replace("...", "") for v in var_name.strip("[]{}").split(",")
  1754. ]
  1755. return [var_name]
  1756. @classmethod
  1757. def _get_memoized_event_triggers(
  1758. cls,
  1759. component: Component,
  1760. ) -> dict[str, tuple[Var, str]]:
  1761. """Memoize event handler functions with useCallback to avoid unnecessary re-renders.
  1762. Args:
  1763. component: The component with events to memoize.
  1764. Returns:
  1765. A dict of event trigger name to a tuple of the memoized event trigger Var and
  1766. the hook code that memoizes the event handler.
  1767. """
  1768. trigger_memo = {}
  1769. for event_trigger, event_args in component._get_vars_from_event_triggers(
  1770. component.event_triggers
  1771. ):
  1772. if event_trigger in {
  1773. EventTriggers.ON_MOUNT,
  1774. EventTriggers.ON_UNMOUNT,
  1775. EventTriggers.ON_SUBMIT,
  1776. }:
  1777. # Do not memoize lifecycle or submit events.
  1778. continue
  1779. # Get the actual EventSpec and render it.
  1780. event = component.event_triggers[event_trigger]
  1781. rendered_chain = str(LiteralVar.create(event))
  1782. # Hash the rendered EventChain to get a deterministic function name.
  1783. chain_hash = md5(str(rendered_chain).encode("utf-8")).hexdigest()
  1784. memo_name = f"{event_trigger}_{chain_hash}"
  1785. # Calculate Var dependencies accessed by the handler for useCallback dep array.
  1786. var_deps = ["addEvents", "Event"]
  1787. for arg in event_args:
  1788. var_data = arg._get_all_var_data()
  1789. if var_data is None:
  1790. continue
  1791. for hook in var_data.hooks:
  1792. var_deps.extend(cls._get_hook_deps(hook))
  1793. memo_var_data = VarData.merge(
  1794. *[var._get_all_var_data() for var in event_args],
  1795. VarData(
  1796. imports={"react": [ImportVar(tag="useCallback")]},
  1797. ),
  1798. )
  1799. # Store the memoized function name and hook code for this event trigger.
  1800. trigger_memo[event_trigger] = (
  1801. Var(_js_expr=memo_name)._replace(
  1802. _var_type=EventChain, merge_var_data=memo_var_data
  1803. ),
  1804. f"const {memo_name} = useCallback({rendered_chain}, [{', '.join(var_deps)}])",
  1805. )
  1806. return trigger_memo
  1807. def _get_all_hooks_internal(self) -> dict[str, None]:
  1808. """Get the reflex internal hooks for the component and its children.
  1809. Returns:
  1810. The code that should appear just before user-defined hooks.
  1811. """
  1812. return {}
  1813. def _get_all_hooks(self) -> dict[str, None]:
  1814. """Get the React hooks for this component.
  1815. Returns:
  1816. The code that should appear just before returning the rendered component.
  1817. """
  1818. return {}
  1819. def _get_all_imports(self) -> ParsedImportDict:
  1820. """Get all the libraries and fields that are used by the component.
  1821. Returns:
  1822. The import dict with the required imports.
  1823. """
  1824. if self.rendered_as_shared:
  1825. return {
  1826. f"$/{Dirs.UTILS}/{PageNames.STATEFUL_COMPONENTS}": [
  1827. ImportVar(tag=self.tag)
  1828. ]
  1829. }
  1830. return self.component._get_all_imports()
  1831. def _get_all_dynamic_imports(self) -> set[str]:
  1832. """Get dynamic imports for the component.
  1833. Returns:
  1834. The dynamic imports.
  1835. """
  1836. if self.rendered_as_shared:
  1837. return set()
  1838. return self.component._get_all_dynamic_imports()
  1839. def _get_all_custom_code(self) -> set[str]:
  1840. """Get custom code for the component.
  1841. Returns:
  1842. The custom code.
  1843. """
  1844. if self.rendered_as_shared:
  1845. return set()
  1846. return self.component._get_all_custom_code().union({self.code})
  1847. def _get_all_refs(self) -> set[str]:
  1848. """Get the refs for the children of the component.
  1849. Returns:
  1850. The refs for the children.
  1851. """
  1852. if self.rendered_as_shared:
  1853. return set()
  1854. return self.component._get_all_refs()
  1855. def render(self) -> dict:
  1856. """Define how to render the component in React.
  1857. Returns:
  1858. The tag to render.
  1859. """
  1860. return dict(Tag(name=self.tag or ""))
  1861. def __str__(self) -> str:
  1862. """Represent the component in React.
  1863. Returns:
  1864. The code to render the component.
  1865. """
  1866. from reflex.compiler.compiler import _compile_component
  1867. return _compile_component(self)
  1868. @classmethod
  1869. def compile_from(cls, component: BaseComponent) -> BaseComponent:
  1870. """Walk through the component tree and memoize all stateful components.
  1871. Args:
  1872. component: The component to memoize.
  1873. Returns:
  1874. The memoized component tree.
  1875. """
  1876. if isinstance(component, Component):
  1877. if component._memoization_mode.recursive:
  1878. # Recursively memoize stateful children (default).
  1879. component.children = [
  1880. cls.compile_from(child) for child in component.children
  1881. ]
  1882. # Memoize this component if it depends on state.
  1883. stateful_component = cls.create(component)
  1884. if stateful_component is not None:
  1885. return stateful_component
  1886. return component
  1887. class MemoizationLeaf(Component):
  1888. """A component that does not separately memoize its children.
  1889. Any component which depends on finding the exact names of children
  1890. components within it, should be a memoization leaf so the compiler
  1891. does not replace the provided child tags with memoized tags.
  1892. During creation, a memoization leaf will mark itself as wanting to be
  1893. memoized if any of its children return any hooks.
  1894. """
  1895. _memoization_mode = MemoizationMode(recursive=False)
  1896. @classmethod
  1897. def create(cls, *children, **props) -> Component:
  1898. """Create a new memoization leaf component.
  1899. Args:
  1900. *children: The children of the component.
  1901. **props: The props of the component.
  1902. Returns:
  1903. The memoization leaf
  1904. """
  1905. comp = super().create(*children, **props)
  1906. if comp._get_all_hooks() or comp._get_all_hooks_internal():
  1907. comp._memoization_mode = cls._memoization_mode.copy(
  1908. update={"disposition": MemoizationDisposition.ALWAYS}
  1909. )
  1910. return comp
  1911. load_dynamic_serializer()