component.py 98 KB

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