component.py 84 KB

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