component.py 85 KB

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