component.py 81 KB

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