1
0

component.py 97 KB

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