1
0

component.py 84 KB

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