component.py 74 KB

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