component.py 84 KB

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