component.py 77 KB

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