component.py 88 KB

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