component.py 88 KB

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