component.py 83 KB

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