component.py 84 KB

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