component.py 77 KB

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