component.py 78 KB

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