component.py 87 KB

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