component.py 85 KB

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