component.py 98 KB

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