component.py 87 KB

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