1
0

component.py 76 KB

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