component.py 84 KB

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