component.py 83 KB

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