component.py 88 KB

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