component.py 87 KB

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