component.py 83 KB

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