component.py 77 KB

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