component.py 83 KB

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