component.py 88 KB

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