component.py 84 KB

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