component.py 97 KB

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